Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() != s2.size())
return false;
bool result = false;
... | const dict = Set(split(read("unixdict.txt", String), r"\s+"))
function targeted_mutations(str::AbstractString, target::AbstractString)
working, tried = [[str]], Set{String}()
while all(a -> a[end] != target, working)
newworking = Vector{Vector{String}}()
for arr in working
s = arr[e... |
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version. | #include <cstdint>
#include <iomanip>
#include <iostream>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (b... | using Primes
ispseudo(n, base) = !isprime(n) && BigInt(base)^(n - 1) % n == 1
for b in 1:20
pseudos = filter(n -> ispseudo(n, b), 1:50000)
println("Base ", lpad(b, 2), " up to 50000: ", lpad(length(pseudos), 5), " First 20: ", pseudos[1:20])
end
|
Write the same algorithm in Julia as shown in this C++ implementation. | #include <iostream>
#include <cstdint>
struct Date {
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
};
constexpr bool leap(int year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const std::string& weekday(const Date& date) {
static const std::uint8_t leapdoom[] = {4,1,7,2,4,6... | module DoomsdayRule
export get_weekday
const weekdaynames = ["Sunday", "Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
const leapyear_firstdoomsdays = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
const nonleapyear_firstdoomsdays = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
"""
get_weekday(year::Int, month::... |
Rewrite the snippet below in Julia so it works the same as the original C++ code. | #include <iostream>
#include <cstdint>
struct Date {
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
};
constexpr bool leap(int year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const std::string& weekday(const Date& date) {
static const std::uint8_t leapdoom[] = {4,1,7,2,4,6... | module DoomsdayRule
export get_weekday
const weekdaynames = ["Sunday", "Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
const leapyear_firstdoomsdays = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
const nonleapyear_firstdoomsdays = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
"""
get_weekday(year::Int, month::... |
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... | A = [1 2 3; 4 1 6; 7 8 9]
@show I / A
@show inv(A)
|
Keep all operations the same but rewrite the snippet in Julia. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... | A = [1 2 3; 4 1 6; 7 8 9]
@show I / A
@show inv(A)
|
Preserve the algorithm and functionality while converting the code from C++ to Julia. | #include <ctime>
#include <iostream>
#include <string>
#include <algorithm>
class chessBoard {
public:
void generateRNDBoard( int brds ) {
int a, b, i; char c;
for( int cc = 0; cc < brds; cc++ ) {
memset( brd, 0, 64 );
std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";... | module Chess
using Printf
struct King end
struct Pawn end
function placepieces!(grid, ::King)
axis = axes(grid, 1)
while true
r1, c1, r2, c2 = rand(axis, 4)
if r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1
grid[r1, c1] = '♚'
grid[r2, c2] = '♔'
return gri... |
Please provide an equivalent version of this C++ code in Julia. | #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= ... | using Printf
function proper_divisors(n::Integer)
uptosqr = 1:isqrt(n)
divs = Iterators.filter(uptosqr) do m
n % m == 0
end
pd_pairs = Iterators.map(divs) do d1
d2 = div(n, d1)
(d1 == d2 || d1 == 1) ? (d1,) : (d1, d2)
end
return Iterators.flatten(pd_pairs)
end
function ... |
Translate this program into Julia but keep the logic exactly as in C++. | #include <iomanip>
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
template <typename IntegerType>
IntegerType arithmetic_derivative(IntegerType n) {
bool negative = n < 0;
if (negative)
n = -n;
if (n < 2)
return 0;
IntegerType sum = 0, count = 0, m = n;
while ((m &... | using Primes
D(n) = n < 0 ? -D(-n) : n < 2 ? zero(n) : isprime(n) ? one(n) : typeof(n)(sum(e * n ÷ p for (p, e) in eachfactor(n)))
foreach(p -> print(lpad(p[2], 5), p[1] % 10 == 0 ? "\n" : ""), pairs(map(D, -99:100)))
println()
for m in 1:20
println("D for 10^", rpad(m, 3), "divided by 7 is ", D(Int128(10)^m) ÷ ... |
Keep all operations the same but rewrite the snippet in Julia. | #include <iomanip>
#include <iostream>
#include <utility>
auto min_max_prime_factors(unsigned int n) {
unsigned int min_factor = 1;
unsigned int max_factor = 1;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
min_factor = 2;
max_factor = 2;
}
for (unsigned int ... | using Primes
function firstlastprimeprod(number_wanted)
for num in 1:number_wanted
fac = collect(factor(num))
product = isempty(fac) ? 1 : fac[begin][begin] * fac[end][begin]
print(rpad(product, 6), num % 10 == 0 ? "\n" : "")
end
end
firstlastprimeprod(100)
|
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <cmath>
#include <cstdint>
#include <iostream>
#include <functional>
uint64_t factorial(int n) {
uint64_t result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int inverse_factorial(uint64_t f) {
int p = 1;
int i = 1;
if (f == 1) {
return 0;... | superfactorial(n) = n < 1 ? 1 : mapreduce(factorial, *, 1:n)
sf(n) = superfactorial(n)
hyperfactorial(n) = n < 1 ? 1 : mapreduce(i -> i^i, *, 1:n)
H(n) = hyperfactorial(n)
alternating_factorial(n) = n < 1 ? 0 : mapreduce(i -> (-1)^(n - i) * factorial(i), +, 1:n)
af(n) = alternating_factorial(n)
exponential_factorial... |
Write the same algorithm in Julia as shown in this C++ implementation. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_square {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std... | using Lindenmayer
scurve = LSystem(Dict("X" => "XF-F+F-XF+F+XF-F+F-X"), "F+XF+F+XF")
drawLSystem(scurve,
forward = 3,
turn = 90,
startingy = -400,
iterations = 6,
filename = "sierpinski_square_curve.png",
showpreview = true
)
|
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <windows.h>
#include <iostream>
#include <ctime>
const int WID = 79, HEI = 22;
const float NCOUNT = ( float )( WID * HEI );
class coord : public COORD {
public:
coord( short x = 0, short y = 0 ) { set( x, y ); }
void set( short x, short y ) { X = x; Y = y; }
};
class winConsole {
public:
static w... | using Gtk
struct BState
board::Matrix{Int}
row::Int
col::Int
end
function greedapp(r, c)
rows, cols = c, r
win = GtkWindow("Greed Game", 1200, 400) |> (GtkFrame() |> (box = GtkBox(:v)))
toolbar = GtkToolbar()
newgame = GtkToolButton("New Game")
set_gtk_property!(newgame, :label, "New... |
Write a version of this C++ function in Julia with identical behavior. | #include <windows.h>
#include <iostream>
#include <ctime>
const int WID = 79, HEI = 22;
const float NCOUNT = ( float )( WID * HEI );
class coord : public COORD {
public:
coord( short x = 0, short y = 0 ) { set( x, y ); }
void set( short x, short y ) { X = x; Y = y; }
};
class winConsole {
public:
static w... | using Gtk
struct BState
board::Matrix{Int}
row::Int
col::Int
end
function greedapp(r, c)
rows, cols = c, r
win = GtkWindow("Greed Game", 1200, 400) |> (GtkFrame() |> (box = GtkBox(:v)))
toolbar = GtkToolbar()
newgame = GtkToolButton("New Game")
set_gtk_property!(newgame, :label, "New... |
Convert this C++ block to Julia, preserving its control flow and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int digit_product(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
... | using Primes
isRhonda(n, b) = prod(digits(n, base=b)) == b * sum([prod(pair) for pair in factor(n).pe])
function displayrhondas(low, high, nshow)
for b in filter(!isprime, low:high)
n, rhondas = 1, Int[]
while length(rhondas) < nshow
isRhonda(n, b) && push!(rhondas, n)
n +=... |
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <iostream>
#include <optional>
using namespace std;
class TropicalAlgebra
{
optional<double> m_value;
public:
friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);
friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;
Tr... | ⊕(x, y) = max(x, y)
⊗(x, y) = x + y
↑(x, y) = (@assert round(y) == y && y > 0; x * y)
@show 2 ⊗ -2
@show -0.001 ⊕ -Inf
@show 0 ⊗ -Inf
@show 1.5 ⊕ -1
@show -0.5 ⊗ 0
@show 5↑7
@show 5 ⊗ (8 ⊕ 7)
@show 5 ⊗ 8 ⊕ 5 ⊗ 7
@show 5 ⊗ (8 ⊕ 7) == 5 ⊗ 8 ⊕ 5 ⊗ 7
|
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <iomanip>
#include <iostream>
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3, sq = 9; sq <= n; p += 2) {
for (; n % p == 0; n /= p)
sum += p;
sq += (p + 1) << 2;
}
if (n > 1)
sum += n;
return... | using Lazy
using Primes
sumprimedivisors(n) = sum([p[1] for p in factor(n)])
ruthaaron(n) = sumprimedivisors(n) == sumprimedivisors(n + 1)
ruthaarontriple(n) = sumprimedivisors(n) == sumprimedivisors(n + 1) ==
sumprimedivisors(n + 2)
sumprimefactors(n) = sum([p[1] * p[2] for p in factor(n)])
ruthaaronfactors(n) = ... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <algorithm>
#include <iostream>
#include <vector>
std::vector<unsigned int> divisors(unsigned int n) {
std::vector<unsigned int> result{1};
unsigned int power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
result.push_back(power);
for (unsigned int p = 3; p * p <= n; p += 2) {
... | using Primes
divisors(n) = @view sort!(vec(map(prod, Iterators.product((p.^(0:m) for (p, m) in eachfactor(n))...))))[begin:end-1]
issuperPoulet(n) = !isprime(n) && big"2"^(n - 1) % n == 1 && all(d -> (big"2"^d - 2) % d == 0, divisors(n))
spoulets = filter(issuperPoulet, 1:12_000_000)
println("The first 20 super-Pou... |
Write the same code in Julia as shown below in C++. | #include <algorithm>
#include <iostream>
int main() {
std::string str("AABBBC");
int count = 0;
do {
std::cout << str << (++count % 10 == 0 ? '\n' : ' ');
} while (std::next_permutation(str.begin(), str.end()));
}
| using Combinatorics
catlist(spec) = mapreduce(i -> repeat([i], spec[i]), vcat, 1:length(spec))
alphastringfromintvector(v) = String([Char(Int('A') + i - 1) for i in v])
function testpermwithident(spec)
println("\nTesting $spec yielding:")
for (i, p) in enumerate(unique(collect(permutations(catlist(spec)))))
... |
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version. | #include <cassert>
#include <cstdint>
#include <iostream>
class bcd64 {
public:
constexpr explicit bcd64(uint64_t bits = 0) : bits_(bits) {}
constexpr bcd64& operator+=(bcd64 other) {
uint64_t t1 = bits_ + 0x0666666666666666;
uint64_t t2 = t1 + other.bits_;
uint64_t t3 = t1 ^ other.bits... | const nibs = [0b0, 0b1, 0b10, 0b11, 0b100, 0b101, 0b110, 0b111, 0b1000, 0b1001]
"""
function bcd_decode(data::Vector{codeunit}, sgn, decimalplaces; table = nibs)
Decode BCD number
bcd: packed BCD data as vector of bytes
sgn: sign(positive 1, negative -1, zero 0)
decimalplaces: decimal places from end ... |
Generate an equivalent Julia version of this C++ code. | #include <cctype>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct number_names {
const char* cardinal;
const char* ordinal;
};
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "fou... | using DataStructures
const seed = "Four is the number of letters in the first word of this sentence, "
const (word2, word3) = ("in", "the")
lettercount(w) = length(w) - length(collect(eachmatch(r"-", w)))
splits(txt) = [x.match for x in eachmatch(r"[\w\-]+", txt)]
todq(sentence) = (d = Deque{String}(); map(x->push!... |
Port the provided C++ code into Julia while preserving the original functionality. |
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return tr... | abstract type MatrixNG end
mutable struct NG4 <: MatrixNG
cfn::Int
thisterm::Int
haveterm::Bool
a1::Int
a::Int
b1::Int
b::Int
NG4(a1, a, b1, b) = new(0, 0, false, a1, a, b1, b)
end
mutable struct NG8 <: MatrixNG
cfn::Int
thisterm::Int
haveterm::Bool
a12::Int
a1::Int... |
Convert the following code from C++ to Julia, ensuring the logic remains intact. |
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return tr... | abstract type MatrixNG end
mutable struct NG4 <: MatrixNG
cfn::Int
thisterm::Int
haveterm::Bool
a1::Int
a::Int
b1::Int
b::Int
NG4(a1, a, b1, b) = new(0, 0, false, a1, a, b1, b)
end
mutable struct NG8 <: MatrixNG
cfn::Int
thisterm::Int
haveterm::Bool
a12::Int
a1::Int... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) ... | julia> a = BigFloat(MathConstants.e^(BigFloat(pi)))^(BigFloat(163.0)^0.5)
2.625374126407687439999999999992500725971981856888793538563373369908627075373427e+17
julia> 262537412640768744 - a
7.499274028018143111206461436626630091372924626572825942241598957614307213309258e-13
|
Translate the given C++ code snippet into Julia without altering its behavior. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) ... | julia> a = BigFloat(MathConstants.e^(BigFloat(pi)))^(BigFloat(163.0)^0.5)
2.625374126407687439999999999992500725971981856888793538563373369908627075373427e+17
julia> 262537412640768744 - a
7.499274028018143111206461436626630091372924626572825942241598957614307213309258e-13
|
Change the following C++ code into Julia without altering its purpose. | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
{
if(*first == depth)
{
... | function makenested(list)
nesting = 0
str = isempty(list) ? "[]" : ""
for n in list
if n > nesting
str *= "["^(n - nesting)
nesting = n
elseif n < nesting
str *= "]"^(nesting - n) * ", "
nesting = n
end
str *= "$n, "
end
... |
Change the programming language of this snippet from C++ to Julia without modifying what it does. | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
{
if(*first == depth)
{
... | function makenested(list)
nesting = 0
str = isempty(list) ? "[]" : ""
for n in list
if n > nesting
str *= "["^(n - nesting)
nesting = n
elseif n < nesting
str *= "]"^(nesting - n) * ", "
nesting = n
end
str *= "$n, "
end
... |
Rewrite the snippet below in Julia so it works the same as the original C++ code. | #include <iomanip>
#include <iostream>
#include <list>
#include <string>
#include <vector>
#include <utility>
#include <vector>
class nest_tree;
bool operator==(const nest_tree&, const nest_tree&);
class nest_tree {
public:
explicit nest_tree(const std::string& name) : name_(name) {}
nest_tree& add_child(con... | const nesttext = """
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
"""
function nesttoindent(txt)
ret = ""
windent = gcd(length.([x.match for x in eachmatch(r"\s+", txt)]) .- 1)
for lin in split(txt, "\n")
ret *= isempty(lin) ? "\n" : isspace(lin[1]) ... |
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version. | #include <algorithm>
#include <cassert>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
bool is_prime(uint64_t n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
retur... | using Primes
ispanbasecomposite(n) = (d = digits(n); all(b -> !isprime(evalpoly(b, d)), maximum(d)+1:max(10, n)))
panbase2500 = filter(ispanbasecomposite, 2:2500)
oddpanbase2500 = filter(isodd, panbase2500)
ratio = length(oddpanbase2500) // length(panbase2500)
println("First 50 pan base non-primes:")
foreach(p -> pr... |
Convert this C++ block to Julia, preserving its control flow and logic. | #include <cmath>
#include <fstream>
#include <iostream>
bool sunflower(const char* filename) {
std::ofstream out(filename);
if (!out)
return false;
constexpr int size = 600;
constexpr int seeds = 5 * size;
constexpr double pi = 3.14159265359;
constexpr double phi = 1.61803398875;
... | using Makie
function sunflowerplot()
len = 2000
ϕ = 0.5 + sqrt(5) / 2
r = LinRange(0.0, 100.0, len)
θ = zeros(len)
markersizes = zeros(Int, len)
for i in 2:length(r)
θ[i] = θ[i - 1] + 2π * ϕ
markersizes[i] = div(i, 500) + 3
end
x = r .* cos.(θ)
y = r .* sin.(θ)
s... |
Change the following C++ code into Julia without altering its purpose. |
#include <cstring>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctime>
void Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) {
uint32_t i, j, x;
i = 0; j = w_end;
x = length + 1;
while (x <= n) {
... | """ Rosetta Code task rosettacode.org/wiki/Sieve_of_Pritchard """
""" Pritchard sieve of primes up to limit. Uses type of `limit` arg for type of primes """
function pritchard(limit::T, verbose=false) where {T<:Integer}
members = falses(limit)
members[1] = true
steplength = 1
prime = T(2)
primes =... |
Please provide an equivalent version of this C++ code in Julia. | #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
template <typename iterator>
bool sum_of_any_subset(int n, iterator begin, iterator end) {
if (begin == end)
return false;
if (std::find(begin, end, n) != end)
return true;
int total = std::acc... | using Primes
""" proper divisors of n """
function proper_divisors(n)
f = [one(n)]
for (p,e) in factor(n)
f = reduce(vcat, [f*p^j for j in 1:e], init=f)
end
pop!(f)
return f
end
""" return true if any subset of f sums to n. """
function sumofanysubset(n, f)
n in f && return true
to... |
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <numeric>
#include <string>
#include <vector>
#include <cfloat>
using namespace std;
class Shipment {
public:
double costPerUnit;
int r, c;
double quantity;
Shipment() : quantity(0), costPerUnit(0), r(-1), c(-1) {... | using JuMP, GLPK
c = [3, 5, 7, 3, 2, 5];
N = size(c,1);
A = [1 1 1 0 0 0
0 0 0 1 1 1
1 0 0 1 0 0
0 1 0 0 1 0
0 0 1 0 0 1];
b = [ 25, 35, 20, 30, 10];
s = ['<', '<', '=', '=', '='];
model = Model(GLPK.Optimizer)
@variable(model, x[i=1:N] >= 0, base_name="traded quantities")
cost_fn = @expre... |
Write the same code in Julia as shown below in C++. |
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
int main(int argc, char* argv[]);
void write_vals(int* const, const size_t, const size_t);
std::string mergeFiles(size_t);
struct Compare
{
bool operator() ( std::pair<int, int>& p1, std::... | intfile = open("/tmp/mmap.bin", "r+")
arr = Mmap.mmap(intfile, Vector{Int64}, (div(stat(intfile).size, 8)))
sort!(arr)
|
Write the same code in Julia as shown below in C++. | #include <iostream>
#include <vector>
class Outer
{
int m_privateField;
public:
Outer(int value) : m_privateField{value}{}
class Inner
{
int m_innerValue;
public:
Inner(int innerValue) : m_innerValue{innerValue}{}
int A... | """ see the Outer class in C++ example """
struct Outer
m_privateField::Int
""" Inner class in example """
struct Inner
m_innerValue::Int
end
end
""" adds the values from the outer and inner class objects """
addouter(inner::Inner, outer::Outer) = outer.m_privateField + inner.m_innerValue
"""... |
Maintain the same structure and functionality when rewriting this code in Julia. | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq... | using Primes
""" Even numbers which cannot be expressed as the sum of two twin primes """
function nonpairsums(;include1=false, limit=20_000)
tpri = primesmask(limit + 2)
for i in 1:limit
tpri[i] && (i > 2 && !tpri[i - 2]) && !tpri[i + 2] && (tpri[i] = false)
end
tpri[2] = false
include1 &&... |
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version. | #include <algorithm>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
std::vector<uint64_t> divisors(uint64_t n) {
std::vector<uint64_t> result{1};
uint64_t power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
result.push_back(power);
for (uint64_t p = 3; p * p <= n;... | """ Rosetta code task: rosettacode.org/wiki/Zsigmondy_numbers """
using Primes
function divisors(n)
f = [one(n)]
for (p,e) in factor(n)
f = reduce(vcat, [f*p^j for j in 1:e], init=f)
end
return length(f) == 1 ? [one(n), n] : sort!(f)
end
function Zs(n, a, b)
@assert a > b
dexpms = map... |
Change the following C++ code into Julia without altering its purpose. | #include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
int main() {
std::ofstream out("penrose_tiling.svg");
if (!out) {
std::cerr << "Cannot open output file.\n";
return... | using Printf
function drawpenrose()
lindenmayer_rules = Dict("A" => "",
"M" => "OA++PA----NA[-OA----MA]++", "N" => "+OA--PA[---MA--NA]+",
"O" => "-MA++NA[+++OA++PA]-", "P" => "--OA++++MA[+PA++++NA]--NA")
rul(x) = lindenmayer_rules[x]
penrose = replace(replace(replace(replace("[N]++[N]++[N... |
Please provide an equivalent version of this C++ code in Julia. | #include <fstream>
#include <iostream>
#include <map>
#include <regex>
#include <set>
#include <sstream>
#include <string>
using namespace std;
map<string, string> terminals;
map<string, vector<vector<string>>> nonterminalRules;
map<string, set<string>> nonterminalFirst;
map<string, vector<string>> nonterminalCode;
i... | const one, two, three, four, five, six, seven, eight, nine = collect(1:9)
function testparser(s)
cod = Meta.parse(s)
println(Meta.lower(Main, cod))
end
testparser("(one + two) * three - four * five")
|
Keep all operations the same but rewrite the snippet in Julia. | #include <chrono>
#include <iostream>
#include <locale>
#include <numeric>
#include <sstream>
#include <primesieve.hpp>
bool is_prime(uint64_t n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
... | using Primes
function calmo_prime_sequence(N)
pri = primes(N)
for w in lastindex(pri):-1:2
psum = sum(pri[1:w])
for d in 0:lastindex(pri)-w
if d > 0
psum -= pri[d]
psum += pri[w + d]
end
if isprime(psum)
println... |
Generate a Julia translation of this C++ snippet without changing its computational steps. |
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
#include <vector>
struct noncopyable {
noncopyable() {}
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
};
template <typename T>
class tarjan;
template <typename T>
class vertex :... | using LightGraphs
edge_list=[(1,2),(3,1),(6,3),(6,7),(7,6),(2,3),(4,2),(4,3),(4,5),(5,6),(5,4),(8,5),(8,8),(8,7)]
grph = SimpleDiGraph(Edge.(edge_list))
tarj = strongly_connected_components(grph)
inzerobase(arrarr) = map(x -> sort(x .- 1, rev=true), arrarr)
println("Results in the zero-base scheme: $(inzerobase(ta... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (au... | using Primes
is_kpowerful(n, k) = all(x -> x[2] >= k, factor(n))
is_squarefree(n) = all(x -> x[2] == 1, factor(n))
rootdiv(n, m, r) = Int128(floor(div(n, m)^(1/r) + 0.0000001))
function genkpowerful(n, k)
ret = Int128[]
function inner(m, r)
if r < k
push!(ret, m)
else
... |
Convert this C++ snippet to Julia and keep its semantics consistent. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (au... | using Primes
is_kpowerful(n, k) = all(x -> x[2] >= k, factor(n))
is_squarefree(n) = all(x -> x[2] == 1, factor(n))
rootdiv(n, m, r) = Int128(floor(div(n, m)^(1/r) + 0.0000001))
function genkpowerful(n, k)
ret = Int128[]
function inner(m, r)
if r < k
push!(ret, m)
else
... |
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <array>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
auto init_zc() {
std::array<int, 1000> zc;
zc.fill(0);
zc[0] = 3;
for (int x = 1; x <= 9; ++x) {
zc[x] = 2;
zc[10 * x] = 2;
zc[100 * x] = 2;
for (int y = 10; y <= 90; y += 10) {
... | function meanfactorialdigits(N, goal = 0.0)
factoril, proportionsum = big"1", 0.0
for i in 1:N
factoril *= i
d = digits(factoril)
zero_proportion_in_fac = count(x -> x == 0, d) / length(d)
proportionsum += zero_proportion_in_fac
propmean = proportionsum / i
if i >... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <SDL2/SDL.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <random>
#include <tuple>
#include <vector>
auto now() {
using namespace std::chrono;
auto time = system_clock::now();
return duration_cast<milliseconds>(time.time_since_epoch()).co... | using Dates, Colors, SimpleDirectMediaLayer.LibSDL2
mutable struct ParticleFountain
particlenum::Int
positions::Vector{Float64}
velocities::Vector{Float64}
lifetimes::Vector{Float64}
points::Vector{SDL_Point}
numpoints::Int
saturation::Float64
spread::Float64
range::Float64
reci... |
Produce a language-to-language conversion: from C++ to Julia, same semantics. | #include <fstream>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>
#include <stdlib.h>
using namespace std;
void fatal_error(string errtext, char *argv[])
{
cout << "%" << errtext << endl;
cout << "usage: " << argv[0] << " [filename.cp]" << endl;
exit(1);
}
string& ltrim(string& ... | function interpretCopyPasta()
clipboard = String[]
if isempty(ARGS)
println("Usage: interpretcopypasta <filename>")
exit(1)
end
thecode = read(ARGS[1], String)
codelines = String.(strip.(split(thecode, "\n")))
nextline() = popfirst!(codelines)
Copy() = push!(clipboard,... |
Write a version of this Java function in Lua with identical behavior. | public class McNuggets {
public static void main(String... args) {
int[] SIZES = new int[] { 6, 9, 20 };
int MAX_TOTAL = 100;
int numSizes = SIZES.length;
int[] counts = new int[numSizes];
int maxFound = MAX_TOTAL + 1;
boolean[] found = new boolean[maxFound]... | function range(A,B)
return function()
return coroutine.wrap(function()
for i = A, B do coroutine.yield(i) end
end)
end
end
function filter(stream, f)
return function()
return coroutine.wrap(function()
for i in stream() do
if f(i) then coroutin... |
Port the following code from Java to Lua with equivalent syntax and logic. | import java.util.stream.IntStream;
public class Letters {
public static void main(String[] args) throws Exception {
System.out.print("Upper case: ");
IntStream.rangeClosed(0, 0x10FFFF)
.filter(Character::isUpperCase)
.limit(72)
.forEach(n -> System... | function ASCIIstring (pattern)
local matchString, ch = ""
for charNum = 0, 255 do
ch = string.char(charNum)
if string.match(ch, pattern) then
matchString = matchString .. ch
end
end
return matchString
end
print(ASCIIstring("%l"))
print(ASCIIstring("%u"))
|
Rewrite the snippet below in Lua so it works the same as the original Java code. | import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Di... | local abs,cos,floor,pi,pow,sin = math.abs,math.cos,math.floor,math.pi,math.pow,math.sin
local bitmap = {
init = function(self, w, h, value)
self.w, self.h, self.pixels = w, h, {}
for y=1,h do self.pixels[y]={} end
self:clear(value)
end,
clear = function(self, value)
for y=1,self.h do
for x=1... |
Please provide an equivalent version of this Java code in Lua. | public class OddWord {
interface CharHandler {
CharHandler handle(char c) throws Exception;
}
final CharHandler fwd = new CharHandler() {
public CharHandler handle(char c) {
System.out.print(c);
return (Character.isLetter(c) ? fwd : rev);
}
};
class Reverser extends Thread implements Ch... | function reverse()
local ch = io.read(1)
if ch:find("%w") then
local rc = reverse()
io.write(ch)
return rc
end
return ch
end
function forward()
ch = io.read(1)
io.write(ch)
if ch == "." then return false end
if not ch:find("%w") then
ch = reverse()
if ch then io.write(ch) end
if... |
Produce a language-to-language conversion: from Java to Lua, same semantics. | public class PCG32 {
private static final long N = 6364136223846793005L;
private long state = 0x853c49e6748fea9bL;
private long inc = 0xda3e39cb94b95bdbL;
public void seed(long seedState, long seedSequence) {
state = 0;
inc = (seedSequence << 1) | 1;
nextInt();
state = ... | function uint32(n)
return n & 0xffffffff
end
function uint64(n)
return n & 0xffffffffffffffff
end
N = 6364136223846793005
state = 0x853c49e6748fea9b
inc = 0xda3e39cb94b95bdb
function pcg32_seed(seed_state, seed_sequence)
state = 0
inc = (seed_sequence << 1) | 1
pcg32_int()
state = state + ... |
Translate the given Java code snippet into Lua without altering its behavior. | import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
... |
function findNext (nStr)
local nTab, outStr, pos, count = {}, "", 1, 1
for i = 1, #nStr do nTab[i] = nStr:sub(i, i) end
table.sort(nTab, function (a, b) return a > b end)
while pos <= #nTab do
if nTab[pos] == nTab[pos + 1] then
count = count + 1
else
outStr = out... |
Convert this Java block to Lua, preserving its control flow and logic. | int l = 300;
void setup() {
size(400, 400);
background(0, 0, 255);
stroke(255);
translate(width/2.0, height/2.0);
translate(-l/2.0, l*sqrt(3)/6.0);
for (int i = 1; i <= 3; i++) {
kcurve(0, l);
rotate(radians(120));
translate(-l, 0);
}
}
void kcurve(float x1, float x2) {
float s = (x2... | local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
function Bitmap:render()
for y = 1, self.height do
print(table.concat(self.pixels[y]))
end
end
function Bitmap:drawKochPath(path, x, y, angle, speed, color)
local rules = {
["+"] = function() angle = angle + pi/3 end,
["-"] = functi... |
Keep all operations the same but rewrite the snippet in Lua. | public class XorShiftStar {
private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16);
private long state;
public void seed(long num) {
state = num;
}
public int nextInt() {
long x;
int answer;
x = state;
x = x ^ (x >>> 12);
x... | function create()
local g = {
magic = 0x2545F4914F6CDD1D,
state = 0,
seed = function(self, num)
self.state = num
end,
next_int = function(self)
local x = self.state
x = x ~ (x >> 12)
x = x ~ (x << 25)
x = x ~ (x >> 2... |
Rewrite this program in Lua while keeping its functionality equivalent to the Java version. | public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0);
int count = 0;
for(int j = 0; j < s.len... | function Is_self_describing( n )
local s = tostring( n )
local t = {}
for i = 0, 9 do t[i] = 0 end
for i = 1, s:len() do
local idx = tonumber( s:sub(i,i) )
t[idx] = t[idx] + 1
end
for i = 1, s:len() do
if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end
end
ret... |
Rewrite the snippet below in Lua so it works the same as the original Java code. | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Objects;
public class DecisionTables {
private static class Pair<T, U> {
private final T t;
private final U u;
public static <T, U> Pair<T, U> of(T t, U u) {... | function promptYN(q)
local ans = '?'
repeat
io.write(q..'? ')
ans = string.upper(io.read())
until ans == 'Y' or ans == 'N'
return ans == 'Y'
end
function getCharAt(s,i)
return string.sub(s,i,i)
end
conditions = {
{"Printer prints", "NNNNYYYY"},
{"A red light is flashing", "... |
Change the following Java code into Lua without altering its purpose. | import java.util.Scanner;
public class Main {
public static void doStuff(String word){
System.out.println(word);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
for(int i=0; i<n; i++){
String word = in.nextLine();
doStuff(... | function show (t)
for _, line in pairs(t) do print(line) end
end
local lineTable, numLines = {}, io.read()
for i = 1, numLines do table.insert(lineTable, io.read()) end
show(lineTable)
|
Change the following Java code into Lua without altering its purpose. | public static double arcLength(double r, double a1, double a2){
return (360.0 - Math.abs(a2-a1))*Math.PI/180.0 * r;
}
| function arcLength(radius, angle1, angle2)
return (360.0 - math.abs(angle2 - angle1)) * math.pi * radius / 180.0
end
function main()
print("arc length: " .. arcLength(10.0, 10.0, 120.0))
end
main()
|
Produce a language-to-language conversion: from Java to Lua, same semantics. | public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
| io.write("Hello world, from ",_VERSION,"!\n")
|
Convert this Java block to Lua, preserving its control flow and logic. | public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
| io.write("Hello world, from ",_VERSION,"!\n")
|
Preserve the algorithm and functionality while converting the code from Java to Lua. | public class AVLtree {
private Node root;
private static class Node {
private int key;
private int balance;
private int height;
private Node left;
private Node right;
private Node parent;
Node(int key, Node parent) {
this.key = key;
... | AVL={balance=0}
AVL.__mt={__index = AVL}
function AVL:new(list)
local o={}
setmetatable(o, AVL.__mt)
for _,v in ipairs(list or {}) do
o=o:insert(v)
end
return o
end
function AVL:rebalance()
local rotated=false
if self.balance>1 then
if self.right.balance<0 then
self.right, self.right.... |
Change the programming language of this snippet from Java to Lua without modifying what it does. | public class AVLtree {
private Node root;
private static class Node {
private int key;
private int balance;
private int height;
private Node left;
private Node right;
private Node parent;
Node(int key, Node parent) {
this.key = key;
... | AVL={balance=0}
AVL.__mt={__index = AVL}
function AVL:new(list)
local o={}
setmetatable(o, AVL.__mt)
for _,v in ipairs(list or {}) do
o=o:insert(v)
end
return o
end
function AVL:rebalance()
local rotated=false
if self.balance>1 then
if self.right.balance<0 then
self.right, self.right.... |
Produce a language-to-language conversion: from Java to Lua, same semantics. | package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
| print([[
This is a long paragraph of text
it is the simplest while using it
with lua, however it will have the
same line breaks and spacing as
you set in this block.
]])
print([=[by using equals signs, ]] may be embedded.]=])
local msg = [[this is a message that spans
multiple lines and will have the next lines
... |
Write the same algorithm in Lua as shown in this Java implementation. | package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
| print([[
This is a long paragraph of text
it is the simplest while using it
with lua, however it will have the
same line breaks and spacing as
you set in this block.
]])
print([=[by using equals signs, ]] may be embedded.]=])
local msg = [[this is a message that spans
multiple lines and will have the next lines
... |
Write a version of this Java function in Lua with identical behavior. | import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class Game2048 extends JPanel {
enum State {
start, won, running, over
}
final Color[] colorTable = {
new Color(0x701710), new Color(0xFFE4C3), new Color(0xfff4d3),
new Color(0xffdac3... |
local unpack = unpack or table.unpack
game = {
cell = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
best = 0,
draw = function(self)
local t = self.cell
print("+
for r=0,12,4 do
print(string.format("|%4d|%4d|%4d|%4d|\n+
end
end,
incr = function(self)
local t,open = self.cell,{}
for i=1,16 ... |
Please provide an equivalent version of this Java code in Lua. | import java.io.*;
import java.util.*;
public class OddWords {
public static void main(String[] args) {
try {
Set<String> dictionary = new TreeSet<>();
final int minLength = 5;
String fileName = "unixdict.txt";
if (args.length != 0)
fileName = ... | minOddWordLength = 5
minWordLength = minOddWordLength*2-1
dict = {}
for word in io.lines('unixdict.txt') do
local n = #word
if n >= minOddWordLength then
dict[word] = n
end
end
for word, len in pairs(dict) do
if len >= minWordLength then
local odd = ""
for o, _ in word:gmatch("(.)(.?)") do
... |
Ensure the translated Lua code behaves exactly like the original Java snippet. | while (true) {
System.out.println("SPAM");
}
| while true do
print("SPAM")
end
repeat
print("SPAM")
until false
|
Convert the following code from Java to Lua, ensuring the logic remains intact. | class MD5
{
private static final int INIT_A = 0x67452301;
private static final int INIT_B = (int)0xEFCDAB89L;
private static final int INIT_C = (int)0x98BADCFEL;
private static final int INIT_D = 0x10325476;
private static final int[] SHIFT_AMTS = {
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,... |
local s = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
}
local K = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bd... |
Produce a language-to-language conversion: from Java to Lua, same semantics. | public class HistoryVariable
{
private Object value;
public HistoryVariable(Object v)
{
value = v;
}
public void update(Object v)
{
value = v;
}
public Object undo()
{
return value;
}
@Override
public String toString()
{
return valu... |
local HistoryVariable = {
new = function(self)
return setmetatable({history={}},self)
end,
get = function(self)
return self.history[#self.history]
end,
set = function(self, value)
self.history[#self.history+1] = value
end,
undo = function(self)
self.history[#self.history] = nil
end,
}
H... |
Keep all operations the same but rewrite the snippet in Lua. | module MultiplyExample
{
static <Value extends Number> Value multiply(Value n1, Value n2)
{
return n1 * n2;
}
void run()
{
(Int i1, Int i2) = (7, 3);
Int i3 = multiply(i1, i2);
(Double d1, Double d2) = (2.7182818, 3.1415);
Double d3 = multiply... | function multiply( a, b )
return a * b
end
|
Write the same code in Lua as shown below in Java. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SuccessivePrimeDifferences {
private static Integer[] sieve(int limit) {
List<Integer> primes = new ArrayList<>();
primes.add(2);
boolean[] c = new boolean[limit + 1];
int p = 3;
... | function findspds(primelist, diffs)
local results = {}
for i = 1, #primelist-#diffs do
result = {primelist[i]}
for j = 1, #diffs do
if primelist[i+j] - primelist[i+j-1] == diffs[j] then
result[j+1] = primelist[i+j]
else
result = nil
break
end
end
results[#re... |
Ensure the translated Lua code behaves exactly like the original Java snippet. | public class LynchBell {
static String s = "";
public static void main(String args[]) {
int i = 98764321;
boolean isUnique = true;
boolean canBeDivided = true;
while (i>0) {
s = String.valueOf(i);
isUnique = uniqueDigits(i);
... | function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
end... |
Can you help me rewrite this code in Lua instead of Java, keeping it the same logically? | public class LynchBell {
static String s = "";
public static void main(String args[]) {
int i = 98764321;
boolean isUnique = true;
boolean canBeDivided = true;
while (i>0) {
s = String.valueOf(i);
isUnique = uniqueDigits(i);
... | function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
end... |
Translate this program into Lua but keep the logic exactly as in Java. | import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j... |
_JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
setmetatable(n,{__index=_JT})
for i=1,dim do
n.values[i]=i
n.positions[i]=i
n.directions[i]=-1
end
return n
end
function _JT:largestMobile()
for i=#self.values,1,-1 do
local loc=self.positions[i]+self.direct... |
Convert this Java snippet to Lua and keep its semantics consistent. | import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j... |
_JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
setmetatable(n,{__index=_JT})
for i=1,dim do
n.values[i]=i
n.positions[i]=i
n.directions[i]=-1
end
return n
end
function _JT:largestMobile()
for i=#self.values,1,-1 do
local loc=self.positions[i]+self.direct... |
Change the following Java code into Lua without altering its purpose. | private static final Random rng = new Random();
void sattoloCycle(Object[] items) {
for (int i = items.length-1; i > 0; i--) {
int j = rng.nextInt(i);
Object tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
| function sattolo (items)
local j
for i = #items, 2, -1 do
j = math.random(i - 1)
items[i], items[j] = items[j], items[i]
end
end
math.randomseed(os.time())
local testCases = {
{},
{10},
{10, 20},
{10, 20, 30},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}
}
for _, arr... |
Convert the following code from Java to Lua, ensuring the logic remains intact. | private static final Random rng = new Random();
void sattoloCycle(Object[] items) {
for (int i = items.length-1; i > 0; i--) {
int j = rng.nextInt(i);
Object tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
| function sattolo (items)
local j
for i = #items, 2, -1 do
j = math.random(i - 1)
items[i], items[j] = items[j], items[i]
end
end
math.randomseed(os.time())
local testCases = {
{},
{10},
{10, 20},
{10, 20, 30},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}
}
for _, arr... |
Please provide an equivalent version of this Java code in Lua. | import java.util.Arrays;
public class CycleSort {
public static void main(String[] args) {
int[] arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1};
System.out.println(Arrays.toString(arr));
int writes = cycleSort(arr);
System.out.println(Arrays.toString(arr));
System... | function printa(a)
io.write("[")
for i,v in ipairs(a) do
if i > 1 then
io.write(", ")
end
io.write(v)
end
io.write("]")
end
function cycle_sort(a)
local writes = 0
local cycle_start = 0
while cycle_start < #a - 1 do
local val = a[cycle_start + 1]... |
Write the same code in Lua as shown below in Java. | import java.util.Arrays;
public class CycleSort {
public static void main(String[] args) {
int[] arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1};
System.out.println(Arrays.toString(arr));
int writes = cycleSort(arr);
System.out.println(Arrays.toString(arr));
System... | function printa(a)
io.write("[")
for i,v in ipairs(a) do
if i > 1 then
io.write(", ")
end
io.write(v)
end
io.write("]")
end
function cycle_sort(a)
local writes = 0
local cycle_start = 0
while cycle_start < #a - 1 do
local val = a[cycle_start + 1]... |
Produce a functionally identical Lua code for the snippet given in Java. | import java.math.BigInteger;
import java.util.List;
public class Brazilian {
private static final List<Integer> primeList = List.of(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 16... | function sameDigits(n,b)
local f = n % b
n = math.floor(n / b)
while n > 0 do
if n % b ~= f then
return false
end
n = math.floor(n / b)
end
return true
end
function isBrazilian(n)
if n < 7 then
return false
end
if (n % 2 == 0) and (n >= 8) the... |
Write a version of this Java function in Lua with identical behavior. | import java.math.BigInteger;
import java.util.List;
public class Brazilian {
private static final List<Integer> primeList = List.of(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 16... | function sameDigits(n,b)
local f = n % b
n = math.floor(n / b)
while n > 0 do
if n % b ~= f then
return false
end
n = math.floor(n / b)
end
return true
end
function isBrazilian(n)
if n < 7 then
return false
end
if (n % 2 == 0) and (n >= 8) the... |
Ensure the translated Lua code behaves exactly like the original Java snippet. | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
public class CreateFile {
public static void main(String[] args) throws IOException {
String os = System.getProperty("os.name");
if (os.contains("Windows")) {... | require "lfs"
local out
if lfs.attributes('/dev/tape') then
out = '/dev/tape'
else
out = 'tape.file'
end
file = io.open(out, 'w')
file:write('Hello world')
io.close(file)
|
Preserve the algorithm and functionality while converting the code from Java to Lua. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<I... | local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1
while n<=15 or not foundDup or #used1000<1001 do
local nxt = a[n - 1] - n
if nxt<1 or used[nxt] ~= nil then
nxt = nxt + 2 * n
end
local alreadyUsed = used[nxt] ~= nil
table.insert(a, nxt... |
Write a version of this Java function in Lua with identical behavior. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<I... | local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1
while n<=15 or not foundDup or #used1000<1001 do
local nxt = a[n - 1] - n
if nxt<1 or used[nxt] ~= nil then
nxt = nxt + 2 * n
end
local alreadyUsed = used[nxt] ~= nil
table.insert(a, nxt... |
Write a version of this Java function in Lua with identical behavior. | import java.util.function.Function;
public interface YCombinator {
interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }
public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {
RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));
return... | Y = function (f)
return function(...)
return (function(x) return x(x) end)(function(x) return f(function(y) return x(x)(y) end) end)(...)
end
end
|
Maintain the same structure and functionality when rewriting this code in Lua. | import java.util.*;
public class SortComp1 {
public static void main(String[] args) {
List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
List<String> sortedItems = new ArrayList<>();
Comparator<String> interactiveCompare = new Comparator<Stri... | colors = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }
print("unsorted: " .. table.concat(colors," "))
known, notyn, nc, nq = {}, {n="y",y="n"}, 0, 0
table.sort(colors, function(a,b)
nc = nc + 1
if not known[a] then known[a]={[a]="n"} end
if not known[b] then known[b]={[b]="n"} end
if not ... |
Ensure the translated Lua code behaves exactly like the original Java snippet. | public class BeadSort
{
public static void main(String[] args)
{
BeadSort now=new BeadSort();
int[] arr=new int[(int)(Math.random()*11)+5];
for(int i=0;i<arr.length;i++)
arr[i]=(int)(Math.random()*10);
System.out.print("Unsorted: ");
now.display1D(arr);
int[] sort=now.beadSort(arr);
System.out.pr... |
function show (msg, t)
io.write(msg .. ":\t")
for _, v in pairs(t) do io.write(v .. " ") end
print()
end
function randList (length, lo, hi)
local t = {}
for i = 1, length do table.insert(t, math.random(lo, hi)) end
return t
end
function tally (list)
local tal = {}
for k, v in pairs(... |
Change the programming language of this snippet from Java to Lua without modifying what it does. | import java.util.*;
import java.util.stream.IntStream;
public class CastingOutNines {
public static void main(String[] args) {
System.out.println(castOut(16, 1, 255));
System.out.println(castOut(10, 1, 99));
System.out.println(castOut(17, 1, 288));
}
static List<Integer> castOut(i... | local N = 2
local base = 10
local c1 = 0
local c2 = 0
for k = 1, math.pow(base, N) - 1 do
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
io.write(k .. ' ')
end
end
print()
print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.... |
Convert this Java snippet to Lua and keep its semantics consistent. | import java.util.*;
import java.util.stream.IntStream;
public class CastingOutNines {
public static void main(String[] args) {
System.out.println(castOut(16, 1, 255));
System.out.println(castOut(10, 1, 99));
System.out.println(castOut(17, 1, 288));
}
static List<Integer> castOut(i... | local N = 2
local base = 10
local c1 = 0
local c2 = 0
for k = 1, math.pow(base, N) - 1 do
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
io.write(k .. ' ')
end
end
print()
print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.... |
Please provide an equivalent version of this Java code in Lua. | public class TauFunction {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
+... | function divisorCount(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = tot... |
Rewrite this program in Lua while keeping its functionality equivalent to the Java version. | public class TauFunction {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
+... | function divisorCount(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = tot... |
Translate this program into Lua but keep the logic exactly as in Java. | public class MöbiusFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the möbius function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", möbiusFunction(n));
if ( (n+1) % 20 == 0 ) {
... | function buildArray(size, value)
local tbl = {}
for i=1, size do
table.insert(tbl, value)
end
return tbl
end
MU_MAX = 1000000
sqroot = math.sqrt(MU_MAX)
mu = buildArray(MU_MAX, 1)
for i=2, sqroot do
if mu[i] == 1 then
for j=i, MU_MAX, i do
mu[j] = mu[j] * -i
... |
Produce a functionally identical Lua code for the snippet given in Java. | import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
mem... | local funs = {
['>'] = 'ptr = ptr + 1; ',
['<'] = 'ptr = ptr - 1; ',
['+'] = 'mem[ptr] = mem[ptr] + 1; ',
['-'] = 'mem[ptr] = mem[ptr] - 1; ',
['['] = 'while mem[ptr] ~= 0 do ',
[']'] = 'end; ',
['.'] = 'io.write(string.char(mem[ptr])); ',
[','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ',
}
local prog = [[
local ... |
Write the same code in Lua as shown below in Java. | import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
mem... | local funs = {
['>'] = 'ptr = ptr + 1; ',
['<'] = 'ptr = ptr - 1; ',
['+'] = 'mem[ptr] = mem[ptr] + 1; ',
['-'] = 'mem[ptr] = mem[ptr] - 1; ',
['['] = 'while mem[ptr] ~= 0 do ',
[']'] = 'end; ',
['.'] = 'io.write(string.char(mem[ptr])); ',
[','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ',
}
local prog = [[
local ... |
Maintain the same structure and functionality when rewriting this code in Lua. | public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace }
| suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"}
stack = setmetatable({
__unm = function(z)
local ret = {}
for i = #z, 1, -1 do
ret[#ret + 1] = table.remove(z,math.random(i))
end
return setmetatable(ret, stack)
end,
__add = function(z, z2)
for ... |
Translate this program into Lua but keep the logic exactly as in Java. | import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Intege... | local function phi(n)
assert(type(n) == 'number', 'n must be a number!')
local result, i = n, 2
while i <= n do
if n % i == 0 then
while n % i == 0 do n = n // i end
result = result - (result // i)
end
if i == 2 then i = 1 end
i = i + 2
end
if n > 1 then result = result - (res... |
Generate a Lua translation of this Java snippet without changing its computational steps. | import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Intege... | local function phi(n)
assert(type(n) == 'number', 'n must be a number!')
local result, i = n, 2
while i <= n do
if n % i == 0 then
while n % i == 0 do n = n // i end
result = result - (result // i)
end
if i == 2 then i = 1 end
i = i + 2
end
if n > 1 then result = result - (res... |
Convert the following code from Java to Lua, ensuring the logic remains intact. | import java.util.Arrays;
public class TwoSum {
public static void main(String[] args) {
long sum = 21;
int[] arr = {0, 2, 11, 19, 90};
System.out.println(Arrays.toString(twoSum(arr, sum)));
}
public static int[] twoSum(int[] a, long target) {
int i = 0, j = a.length - 1;
... | function twoSum (numbers, sum)
local i, j, s = 1, #numbers
while i < j do
s = numbers[i] + numbers[j]
if s == sum then
return {i, j}
elseif s < sum then
i = i + 1
else
j = j - 1
end
end
return {}
end
print(table.concat(twoSum({... |
Write the same algorithm in Lua as shown in this Java implementation. | import java.util.Arrays;
public class TwoSum {
public static void main(String[] args) {
long sum = 21;
int[] arr = {0, 2, 11, 19, 90};
System.out.println(Arrays.toString(twoSum(arr, sum)));
}
public static int[] twoSum(int[] a, long target) {
int i = 0, j = a.length - 1;
... | function twoSum (numbers, sum)
local i, j, s = 1, #numbers
while i < j do
s = numbers[i] + numbers[j]
if s == sum then
return {i, j}
elseif s < sum then
i = i + 1
else
j = j - 1
end
end
return {}
end
print(table.concat(twoSum({... |
Produce a language-to-language conversion: from Java to Lua, same semantics. | public class UnprimeableNumbers {
private static int MAX = 10_000_000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 35 unprimeable numbers:");
displayUnprimeableNumbers(35);
int n = 600;
... |
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end
local sieve, S = {}, 10000000
for i = 2,S ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.