Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <iostream> #include <map> #include <random> std::default_random_engine generator; std::uniform_int_distribution<int> dice(1, 6); int rollDice() { return dice(generator); } const bool sixesThrowAgain = true; const std::map<int, int> snl{ {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, ...
const landingtoending = Dict(4 => 14, 9 => 31, 17 => 7, 20 => 38, 28 => 84, 40 => 59, 51 => 67, 54 => 34, 62 => 19, 63 => 81, 64 => 60, 71 => 91, 87 => 24, 93 => 73, 95 => 75, 99 => 78) const sixesrollagain = true function takeaturn(player, square, verbose=true) while true roll = rand(1:6) ...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> #include <map> #include <random> std::default_random_engine generator; std::uniform_int_distribution<int> dice(1, 6); int rollDice() { return dice(generator); } const bool sixesThrowAgain = true; const std::map<int, int> snl{ {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, ...
const landingtoending = Dict(4 => 14, 9 => 31, 17 => 7, 20 => 38, 28 => 84, 40 => 59, 51 => 67, 54 => 34, 62 => 19, 63 => 81, 64 => 60, 71 => 91, 87 => 24, 93 => 73, 95 => 75, 99 => 78) const sixesrollagain = true function takeaturn(player, square, verbose=true) while true roll = rand(1:6) ...
Write the same code in Julia as shown below in C++.
#include <iostream> struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; }; std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; } class farey_sequence { public: explicit ...
using DataStructures function farey(n::Int) rst = SortedSet{Rational}(Rational[0, 1]) for den in 1:n, num in 1:den-1 push!(rst, Rational(num, den)) end return rst end for n in 1:11 print("F_$n: ") for frac in farey(n) print(numerator(frac), "/", denominator(frac), " ") end ...
Write a version of this C++ function in Julia with identical behavior.
#include <iostream> struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; }; std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; } class farey_sequence { public: explicit ...
using DataStructures function farey(n::Int) rst = SortedSet{Rational}(Rational[0, 1]) for den in 1:n, num in 1:den-1 push!(rst, Rational(num, den)) end return rst end for n in 1:11 print("F_$n: ") for frac in farey(n) print(numerator(frac), "/", denominator(frac), " ") end ...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power ...
function aliquotclassifier{T<:Integer}(n::T) a = T[n] b = divisorsum(a[end]) len = 1 while len < 17 && !(b in a) && 0 < b && b < 2^47+1 push!(a, b) b = divisorsum(a[end]) len += 1 end if b in a 1 < len || return ("Perfect", a) if b == a[1] 2 < ...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power ...
function aliquotclassifier{T<:Integer}(n::T) a = T[n] b = divisorsum(a[end]) len = 1 while len < 17 && !(b in a) && 0 < b && b < 2^47+1 push!(a, b) b = divisorsum(a[end]) len += 1 end if b in a 1 < len || return ("Perfect", a) if b == a[1] 2 < ...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <iostream> #include <math.h> struct PolarPoint; struct CartesianPoint { double x; double y; operator PolarPoint(); }; struct PolarPoint { double rho; double theta; operator CartesianPoint(); }; CartesianPoint::operator PolarPoint() { return PolarPoint ...
julia> function testme() ui8::UInt8 = 1 ui16::UInt16 = ui8 ui32::UInt32 = ui8 ui64::UInt64 = ui8 flo::Float64 = ui8 return ui8, sizeof(ui8), ui16, sizeof(ui16), ui32, sizeof(ui32), ui64, sizeof(ui64), flo, sizeof(flo) end testme (generic function with 1 method) ...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> #include <math.h> struct PolarPoint; struct CartesianPoint { double x; double y; operator PolarPoint(); }; struct PolarPoint { double rho; double theta; operator CartesianPoint(); }; CartesianPoint::operator PolarPoint() { return PolarPoint ...
julia> function testme() ui8::UInt8 = 1 ui16::UInt16 = ui8 ui32::UInt32 = ui8 ui64::UInt64 = ui8 flo::Float64 = ui8 return ui8, sizeof(ui8), ui16, sizeof(ui16), ui32, sizeof(ui32), ui64, sizeof(ui64), flo, sizeof(flo) end testme (generic function with 1 method) ...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; ...
using Primes function ismagnanimous(n) n < 10 && return true for i in 1:ndigits(n)-1 q, r = divrem(n, 10^i) !isprime(q + r) && return false end return true end function magnanimous(N) mvec, i = Int[], 0 while length(mvec) < N if ismagnanimous(i) push!(mvec, ...
Please provide an equivalent version of this C++ code in Julia.
#include <iostream> bool isPrime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; uint64_t test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; if (n % test == 0) return false; test += 4;...
using Primes mersenne(n::Integer) = convert(typeof(n), 2) ^ n - one(n) function main(nmax::Integer) n = ith = zero(nmax) while ith ≤ nmax if isprime(mersenne(n)) println("M$n") ith += 1 end n += 1 end end main(big(20))
Write a version of this C++ function in Julia with identical behavior.
#include <iostream> bool isPrime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; uint64_t test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; if (n % test == 0) return false; test += 4;...
using Primes mersenne(n::Integer) = convert(typeof(n), 2) ^ n - one(n) function main(nmax::Integer) n = ith = zero(nmax) while ith ≤ nmax if isprime(mersenne(n)) println("M$n") ith += 1 end n += 1 end end main(big(20))
Port the provided C++ code into Julia while preserving the original functionality.
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_...
using Primes function nextby6(n, a) top = length(a) i = n + 1 j = n + 2 k = n + 3 if n >= top return n end possiblenext = a[n] + 6 if i <= top && possiblenext == a[i] return i elseif j <= top && possiblenext == a[j] return j elseif k <= top && possiblenex...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <sstream> #include <vector> template <typename T> size_t indexOf(const std::vector<T> &v, const T &k) { auto it = std::find(v.cbegin(), v.cend(), k); if (it != v.cend()) { return it - v.cbegin(); } return -1; }...
using Printf, DataStructures, IterTools function findtaxinumbers(nmax::Integer) cube2n = Dict{Int,Int}(x ^ 3 => x for x in 0:nmax) sum2cubes = DefaultDict{Int,Set{NTuple{2,Int}}}(Set{NTuple{2,Int}}) for ((c1, _), (c2, _)) in product(cube2n, cube2n) if c1 ≥ c2 push!(sum2cubes[c1 + c2], (...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostrea...
using Primes, Formatting function parseprimelist() primelist = primes(2, 10000019) strongs = Vector{Int64}() weaks = Vector{Int64}() balanceds = Vector{Int64}() for (n, p) in enumerate(primelist) if n == 1 || n == length(primelist) continue end x = (primelist[n -...
Generate an equivalent Julia version of this C++ code.
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif ...
leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1) @show leftfactorial.(0:10) @show ndigits.(leftfactorial.(big.(1000:1000:10_000)))
Generate an equivalent Julia version of this C++ code.
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif ...
leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1) @show leftfactorial.(0:10) @show ndigits.(leftfactorial.(big.(1000:1000:10_000)))
Produce a functionally identical Julia code for the snippet given in C++.
#include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t ...
using Primes function prime_sum_prime_triplets_to(N, verbose=false) a = primes(3, N) prime_sieve_set = primesmask(1, N * 3) len, triplets, n = length(a), Dict{Tuple{Int64,Int64,Int64}, Int}(), 0 for i in eachindex(a), j in i+1:len, k in j+1:len if prime_sieve_set[a[i] + a[j] + a[k]] ...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t ...
using Primes function prime_sum_prime_triplets_to(N, verbose=false) a = primes(3, N) prime_sieve_set = primesmask(1, N * 3) len, triplets, n = length(a), Dict{Tuple{Int64,Int64,Int64}, Int}(), 0 for i in eachindex(a), j in i+1:len, k in j+1:len if prime_sieve_set[a[i] + a[j] + a[k]] ...
Translate this program into Julia but keep the logic exactly as in C++.
#include <cstdint> #include <iomanip> #include <iostream> 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; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += ...
using Primes function motzkin(N) m = zeros(Int, N) m[1] = m[2] = 1 for i in 3:N m[i] = (m[i - 1] * (2i - 1) + m[i - 2] * (3i - 6)) ÷ (i + 1) end return m end println(" n M[n] Prime?\n-----------------------------------") for (i, m) in enumerate(motzkin(42)) println(lp...
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> #include <vector> const std::vector<bool> p{ false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; bool isStrange(long n) { if (n < 10) { return false; } for (; n >= 10; n /= 10) { ...
let smallprimes = [2, 3, 5, 7, 11, 13, 17] paired_digit_sums(n) = (d = digits(n); [sum(p) for p in zip(d[1:end-1], d[2:end])]) isstrangeplus(n) = all(x -> x ∈ smallprimes, paired_digit_sums(n)) printed = 0 for n in 100:500 isstrangeplus(n) && print(n, (printed += 1) % 13 == 0 ? "\n" : " ...
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> #include <vector> const std::vector<bool> p{ false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; bool isStrange(long n) { if (n < 10) { return false; } for (; n >= 10; n /= 10) { ...
let smallprimes = [2, 3, 5, 7, 11, 13, 17] paired_digit_sums(n) = (d = digits(n); [sum(p) for p in zip(d[1:end-1], d[2:end])]) isstrangeplus(n) = all(x -> x ∈ smallprimes, paired_digit_sums(n)) printed = 0 for n in 100:500 isstrangeplus(n) && print(n, (printed += 1) % 13 == 0 ? "\n" : " ...
Write a version of this C++ function in Julia with identical behavior.
#include <iostream> #include <cstdint> using integer = uint32_t; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; ...
using Combinatorics, Primes combodigits(len) = sort!(unique(map(y -> join(y, ""), with_replacement_combinations("2357", len)))) function getprimes(N, maxdigits=9) ret = [2, 3, 5, 7] perms = Int[] for i in 1:maxdigits-1, combo in combodigits(i), perm in permutations(combo) n = parse(Int64, String(p...
Transform the following C++ implementation into Julia, maintaining the same output and logic.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "D...
using Printf function magicsquaredoubleeven(order::Int) if order % 4 != 0; error("the order must be divisible by 4") end sqr = Matrix{Int}(order, order) mul = div(order, 4) ext = vcat(1:mul, order-mul+1:order) isext(i::Int, j::Int) = (i in ext) == (j in ext) boolsqr = collect(isext(i, j) for i...
Write the same code in Julia as shown below in C++.
#include <windows.h> #include <math.h> #include <string> const int BMP_SIZE = 240, MY_TIMER = 987654; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
using Luxor, Colors Drawing(800, 800) function plasma(wid, hei) for x in 1:wid, y in 1:hei sethue(parse(Colorant, HSV(180 + 45sin(x/19) + 45sin(y/9) + 45sin((x+y)/25) + 45sin(sqrt(x^2 + y^2)/8), 1, 1))) circle(Point(x, y), 1, :fill) end end @png plasma(800, 800)
Keep all operations the same but rewrite the snippet in Julia.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return f...
using Primes const maxrootprime = Int64(floor(sqrt(1000000000145))) const sqprimes = map(x -> x * x, primes(2, maxrootprime)) possdivisorsfor(n) = vcat(filter(x -> x <= n / 2, sqprimes), n in sqprimes ? n : []) issquarefree(n) = all(x -> floor(n / x) != n / x, possdivisorsfor(n)) function squarefreebetween(mn, mx) ...
Produce a functionally identical Julia code for the snippet given in C++.
#include <array> #include <iomanip> #include <iostream> const int MC = 103 * 1000 * 10000 + 11 * 9 + 1; std::array<bool, MC + 1> SV; void sieve() { std::array<int, 10000> dS; for (int a = 9, i = 9999; a >= 0; a--) { for (int b = 9; b >= 0; b--) { for (int c = 9, s = a + b; c >= 0; c--) { ...
gsum(i) = sum(digits(i)) + i isnonself(i) = any(x -> gsum(x) == i, i-1:-1:i-max(1, ndigits(i)*9)) const last81 = filter(isnonself, 1:5000)[1:81] function checkselfnumbers() i, selfcount = 1, 0 while selfcount <= 100_000_000 && i <= 1022727208 if !(i in last81) selfcount += 1 if ...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <cstdint> #include <iomanip> #include <iostream> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false...
using Formatting function findharshadgaps(N) isharshad(i) = i % sum(digits(i)) == 0 println("Gap Index Number Index Niven Number") lastnum, lastnumidx, biggestgap = 1, 1, 0 for i in 2:N if isharshad(i) if (gap = i - lastnum) > biggestgap println(lpad(gap, 5), lpad(...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <iostream> #include <iomanip> using namespace std; class ormConverter { public: ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ), MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {} ...
using DataStructures const unit2mult = Dict( "arshin" => 0.7112, "centimeter" => 0.01, "diuym" => 0.0254, "fut" => 0.3048, "kilometer" => 1000.0, "liniya" => 0.00254, "meter" => 1.0, "milia" => 7467.6, "piad" => 0.1778, "sazhen" => 2.1336, "tochka" => 0.000254, "vershok" ...
Port the provided C++ code into Julia while preserving the original functionality.
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m <<...
minproddigsum(n) = findfirst(i -> sum(digits(n * i)) == n, 1:typemax(Int32)) for j in 1:70 print(lpad(minproddigsum(j), 10), j % 7 == 0 ? "\n" : "") end
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <iomanip> #include <iostream> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = i * 5...
function pancake(len) gap, gapsum, adj = 2, 2, -1 while gapsum < len adj += 1 gap = gap * 2 - 1 gapsum += gap end return len + adj end for i in 1:25 print("pancake(", lpad(i, 2), ") = ", rpad(pancake(i), 5)) i % 5 == 0 && println() end
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { ...
function quadruples(N::Int=2200) r = falses(N) ab = falses(2N ^ 2) for a in 1:N, b in a:N ab[a ^ 2 + b ^ 2] = true end s = 3 for c in 1:N s1, s, s2 = s, s + 2, s + 2 for d in c+1:N if ab[s1] r[d] = true end s1 += s2 s2 += 2 e...
Keep all operations the same but rewrite the snippet in Julia.
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" <...
using Primes function satisfy1(x::Integer) prmslt100 = primes(100) for i in 2:(x ÷ 2) if i ∈ prmslt100 && x - i ∈ prmslt100 return false end end return true end function satisfy2(x::Integer) once = false for i in 2:isqrt(x) if x % i == 0 j = x ÷ ...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <array> #include <iostream> #include <vector> constexpr int MAX = 12; static std::vector<char> sp; static std::array<int, MAX> count; static int pos = 0; int factSum(int n) { int s = 0; int x = 0; int f = 1; while (x < n) { f *= ++x; s += f; } return s; } bool r(int ...
const nmax = 12 function r!(n, s, pos, count) if n == 0 return false end c = s[pos + 1 - n] count[n + 1] -= 1 if count[n + 1] == 0 count[n + 1] = n if r!(n - 1, s, pos, count) == 0 return false end end s[pos + 1] = c pos += 1 true end fun...
Keep all operations the same but rewrite the snippet in Julia.
#include <complex> #include <math.h> #include <iostream> template<class Type> struct Precision { public: static Type GetEps() { return eps; } static void SetEps(Type e) { eps = e; } private: static Type eps; }; template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7); template<class DigT...
@show isinteger(25.000000) @show isinteger(24.999999) @show isinteger(25.000100) @show isinteger(-2.1e120) @show isinteger(-5e-2) @show isinteger(NaN) @show isinteger(Inf) @show isinteger(complex(5.0, 0.0)) @show isinteger(complex(5, 5))
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); const uint64_t limit = 10000000000; uint64_t max_diff = 0; primesieve::iterator pi; uint64_t p1 = pi.next_prime(); for (uint64_t p = 10;;) { uint64_t p2 = pi.next_prime(); ...
using Primes function maxprimeinterval(nmax) pri = primes(nmax) diffs = [pri[i] - pri[i - 1] for i in 2:length(pri)] diff, idx = findmax(diffs) println("The maximum prime interval in primes up to $nmax is $diff: for example at [$(pri[idx]), $(pri[idx + 1])].") end foreach(n -> maxprimeinterval(10^n), ...
Write a version of this C++ function in Julia with identical behavior.
#include <fstream> #include <iostream> #include <numeric> #include <unistd.h> #include <vector> std::vector<size_t> get_cpu_times() { std::ifstream proc_stat("/proc/stat"); proc_stat.ignore(5, ' '); std::vector<size_t> times; for (size_t time; proc_stat >> time; times.push_back(time)); return time...
function main() lastidle = lasttotal = 0 while true ln = readline("/proc/stat") fields = parse.(Float64, split(ln)[2:end]) idle, total = fields[4], sum(fields) Δidle, Δtotal = idle - lastidle, total - lasttotal lastidle, lasttotal = idle, total utilization = 100 *...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <algorithm> #include <chrono> #include <iostream> #include <vector> int ulam(int n) { std::vector<int> ulams{1, 2}; std::vector<int> sieve{1, 1}; for (int u = 2; ulams.size() < n; ) { sieve.resize(u + ulams[ulams.size() - 2], 0); for (int i = 0; i < ulams.size() - 1; ++i) ...
function nthUlam(n) ulams = [1, 2] memoized = Set([1, 2]) i = 3 while true count = 0 for j in 1:length(ulams) if i - ulams[j] in memoized && ulams[j] != i - ulams[j] (count += 1) > 2 && break end end if count == 2 push!(...
Write the same code in Julia as shown below in C++.
#include <iostream> #include <iomanip> #include <string> #include <gmpxx.h> std::string smallest_six(unsigned int n) { mpz_class pow = 1; std::string goal = std::to_string(n); while (pow.get_str().find(goal) == std::string::npos) { pow *= 6; } return pow.get_str(); } int main() {...
using Formatting digcontains(n, dig) = contains(String(Char.(digits(n))), String(Char.(dig))) function findpow6containing(needle) dig = digits(needle) for i in 0:1000 p = big"6"^i digcontains(p, dig) && return p end error("could not find a power of 6 containing $dig") end for n in 0:...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> template <typename T> auto typeString(const T&) { return typeid(T).name(); } class C {}; struct S {}; int main() { std::cout << typeString(1) << '\n'; std::cout << typeString(1L) << '\n'; std::cout << typeString(1.0f) << '\n'; std::cout << typeString(1.0) << '\n'; std::cou...
julia> a = 1 1 julia> typeof(a) Int32 julia> b = 1.0 1.0 julia> typeof(b) Float64 julia> 1.0 isa Number true julia> 1.0 isa Int false julia> 1 isa Int true julia> typeof("hello") String julia> typeof(typeof("hello")) DataType julia> typeof(Set([1,3,4])) Set{Int64} julia> 1 isa String false julia> "1" isa Num...
Write the same algorithm in Julia as shown in this C++ implementation.
#include <iostream> using namespace std; bool steady(int n) { int mask = 1; for (int d = n; d != 0; d /= 10) mask *= 10; return (n * n) % mask == n; } int main() { for (int i = 1; i < 10000; i++) if (steady(i)) printf("%4d^2 = %8d\n", i, i * i); }
issteadysquare(n) = (s = "$n"; s == "$(n * n)"[end+1-length(s):end]) println(filter(issteadysquare, 1:10000))
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostrea...
using Primes, Formatting function parseprimelist() primelist = primes(2, 10000000) safeprimes = Vector{Int64}() unsafeprimes = Vector{Int64}() for p in primelist if isprime(div(p - 1, 2)) push!(safeprimes, p) else push!(unsafeprimes, p) end end pr...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"...
using DataFrames A = DataFrame(Age = [27, 18, 28, 18, 28], Name = ["Jonah", "Alan", "Glory", "Popeye", "Alan"]) B = DataFrame(Name = ["Jonah", "Jonah", "Alan", "Alan", "Glory"], Nemesis = ["Whales", "Spiders", "Ghosts", "Zombies", "Buffy"]) AB = join(A, B, on = :Name) @show A B AB
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t p = 3; ; p += 2) { ...
using Primes const pmask = primesmask(1, 1000) function isA085823(n, base = 10, sieve = pmask) dig = digits(n; base=base) for i in 1:length(dig), j in i:length(dig) k = evalpoly(base, dig[i:j]) (k == 0 || !sieve[k]) && return false end return true end println(filter(isA085823, 1:1000)...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t p = 3; ; p += 2) { ...
using Primes const pmask = primesmask(1, 1000) function isA085823(n, base = 10, sieve = pmask) dig = digits(n; base=base) for i in 1:length(dig), j in i:length(dig) k = evalpoly(base, dig[i:j]) (k == 0 || !sieve[k]) && return false end return true end println(filter(isA085823, 1:1000)...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <cmath> #include <cstdlib> #include <iomanip> #include <iostream> int divisor_count(int n) { int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (int p = 3; p * p <= n; p += 2) { int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; ...
using Primes ispdc(n) = (ndivs = prod(collect(values(factor(n))).+ 1); ndivs > 2 && isprime(ndivs)) foreach(p -> print(rpad(p[2], 8), p[1] % 10 == 0 ? "\n" : ""), enumerate(filter(ispdc, 1:100000)))
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iostream> bool is_giuga(unsigned int n) { unsigned int m = n / 2; auto test_factor = [&m, n](unsigned int p) -> bool { if (m % p != 0) return true; m /= p; return m % p != 0 && (n / p - 1) % p == 0; }; if (!test_factor(3) || !test_factor(5)) return...
using Primes isGiuga(n) = all(f -> f != n && rem(n ÷ f - 1, f) == 0, factor(Vector, n)) function getGiuga(N) gcount = 0 for i in 4:typemax(Int) if isGiuga(i) println(i) (gcount += 1) >= N && break end end end getGiuga(4)
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main() { std::vector<std::string> words; std::ifstream in("words.txt"); if (!in) { std::cerr << "Cannot open file words.txt.\n"; return EXIT_FAILURE; ...
function anadromes(minsize, csense = true, fname = "words.txt") words = Set(filter(w -> length(w) >= minsize, split((csense ? identity : lowercase)(read(fname, String)), r"\s+"))) found = [(w, reverse(w)) for w in words if (r = reverse(w)) in words && w < r] println("Total $(length(found)) case $(csense ? "...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <gmpxx.h> #include <algorithm> #include <cassert> #include <functional> #include <iostream> #include <vector> using big_int = mpz_class; const unsigned int small_primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, ...
using Primes, Printf function addmsdigit(p::Integer, b::Integer, s::Integer) a = Vector{typeof(p)}() q = p for i in 1:(b-1) q += s isprime(q) || continue push!(a, q) end return a end function lefttruncprime(pbase::Integer) a = Vector{BigInt}() append!(a, primes(pb...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::...
function solve24(nums) length(nums) != 4 && error("Input must be a 4-element Array") syms = [+,-,*,/] for x in syms, y in syms, z in syms for i = 1:24 a,b,c,d = nthperm(nums,i) if round(x(y(a,b),z(c,d)),5) == 24 return "($a$y$b)$x($c$z$d)" elseif r...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::...
function solve24(nums) length(nums) != 4 && error("Input must be a 4-element Array") syms = [+,-,*,/] for x in syms, y in syms, z in syms for i = 1:24 a,b,c,d = nthperm(nums,i) if round(x(y(a,b),z(c,d)),5) == 24 return "($a$y$b)$x($c$z$d)" elseif r...
Please provide an equivalent version of this C++ code in Julia.
UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2) { UINT_64 N; N = N1; N = (N<<32)|N2; return UINT_64(N); } UINT_32 TGost::ReplaceBlock(UINT_32 x) { register i; UINT_32 res = 0UL; for(i=7;i>=0;i--) { ui4_0 = x>>(i*4); ui4_0 = BS[ui4_0][i]; res = (res<<4)|ui4_0; } retu...
const k8 = [ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3] const k7 = [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9] const k6 = [ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11] const k5 = [ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3] const k4 = [ 6, ...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); numbers.insert(numbers.end(), 4); auto it = std::next(numbers.begin(), numbers.size() / 2); numbers.insert(it, 6); for(const auto& i: numbers) std::cout <...
show(DLNode)
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|...
module TruthTable using Printf using MacroTools isvariablename(::Any) = false isvariablename(s::Symbol) = all(x -> isletter(x) || x == '_', string(s)) function table(expr) if !isvariablename(expr) && !Meta.isexpr(expr, :call) throw(ArgumentError("expr must be a boolean expression")) end exprstr ...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|...
module TruthTable using Printf using MacroTools isvariablename(::Any) = false isvariablename(s::Symbol) = all(x -> isletter(x) || x == '_', string(s)) function table(expr) if !isvariablename(expr) && !Meta.isexpr(expr, :call) throw(ArgumentError("expr must be a boolean expression")) end exprstr ...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <cassert> #include <functional> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }; class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate; public: R...
""" struct ConvexRealSet Convex real set (similar to a line segment). Parameters: lower bound, upper bound: floating point numbers includelower, includeupper: boolean true or false to indicate whether the set has a closed boundary (set to true) or open (set to false). """ mutable struct Conv...
Please provide an equivalent version of this C++ code in Julia.
#include <cassert> #include <functional> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }; class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate; public: R...
""" struct ConvexRealSet Convex real set (similar to a line segment). Parameters: lower bound, upper bound: floating point numbers includelower, includeupper: boolean true or false to indicate whether the set has a closed boundary (set to true) or open (set to false). """ mutable struct Conv...
Translate this program into Julia but keep the logic exactly as in C++.
#include <algorithm> #include <iostream> #include <string> #include <array> #include <vector> template<typename T> T unique(T&& src) { T retval(std::move(src)); std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>()); retval.erase(std::unique(retval.begin(), retval.end()), retval.end()...
module StateNamePuzzle const realnames = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississip...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <array> #include <cmath> #include <iomanip> #include <iostream> double ByVaccaSeries(int numTerms) { double gamma = 0; size_t next = 4; for(double numerator = 1; numerator < numTerms; ++numerator) { double delta = 0; for(size_t denominato...
display(MathConstants.γ)
Produce a functionally identical Julia code for the snippet given in C++.
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; v...
function superd(N) println("First 10 super-$N numbers:") count, j = 0, BigInt(3) target = Char('0' + N)^N while count < 10 if occursin(target, string(j^N * N)) count += 1 print("$j ") end j += 1 end println() end for n in 2:9 @time superd(n) e...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; v...
function superd(N) println("First 10 super-$N numbers:") count, j = 0, BigInt(3) target = Char('0' + N)^N while count < 10 if occursin(target, string(j^N * N)) count += 1 print("$j ") end j += 1 end println() end for n in 2:9 @time superd(n) e...
Please provide an equivalent version of this C++ code in Julia.
#include <iostream> #include <map> #include <cmath> int pRec(int n) { static std::map<int,int> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n <= 2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); return memo[n]; } int pFloor(int n) { long const double ...
""" Recursive Padovan """ rPadovan(n) = (n < 4) ? one(n) : rPadovan(n - 3) + rPadovan(n - 2) """ Floor function calculation Padovan """ function fPadovan(n)::Int p, s = big"1.324717957244746025960908854", big"1.0453567932525329623" return Int(floor(p^(n-2) / s + .5)) end """ LSystem Padovan """ function list_...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <iostream> #include <cmath> #include <optional> #include <vector> using namespace std; template <typename T> auto operator>>(const optional<T>& monad, auto f) { if(!monad.has_value()) { return optional<remove_reference_t<decltype(*f(*monad))>>(); } return f(*monad)...
struct maybe x::Union{Real, Missing}; end Base.show(io::IO, m::maybe) = print(io, m.x) unit(x) = maybe(x) bind(f, x) = unit(f(x.x)) f1(x) = 5x f2(x) = x + 4 a = unit(3) b = unit(missing) println(a, " -> ", bind(f2, bind(f1, a))) println(b, " -> ", bind(f2, bind(f1, b)))
Produce a functionally identical Julia code for the snippet given in C++.
#include <iostream> #include <vector> using namespace std; template <typename T> auto operator>>(const vector<T>& monad, auto f) { vector<remove_reference_t<decltype(f(monad.front()).front())>> result; for(auto& item : monad) { const auto r = f(item); resul...
julia> unit(v) = [v...] unit (generic function with 1 method) julia> import Base.bind julia> bind(v, f) = f.(v) bind (generic function with 5 methods) julia> f1(x) = x + 1 f1 (generic function with 1 method) julia> f2(x) = 2x f2 (generic function with 1 method) julia> bind(bind(unit([2, 3, 4]), f1), f2) 3-element ...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mappin...
using Printf const tcode = (Regex=>Char)[r"A|B|C|Ä|Å|Á|Â|Ç" => '2', r"D|E|F|È|Ê|É" => '3', r"G|H|I|Í" => '4', r"J|K|L" => '5', r"M|N|O|Ó|Ö|Ô|Ñ" => '6', r"P|Q|R|S" => '7', ...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <iostream> #include <string> #include <windows.h> using namespace std; typedef unsigned char byte; enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR }; class fieldData { public: fieldData() : value( CLOSED ), open( false ) {} byte value; bool open, mine; }; class game { publi...
mutable struct Field size::Tuple{Int, Int} numbers::Array{Int, 2} possible_mines::Array{Bool, 2} actual_mines::Array{Bool, 2} visible::Array{Bool, 2} end function Field(x, y) size = (x, y) actual_mines = convert(Array{Bool, 2}, rand(x, y) .< 0.15) possible_mines = zeros(Bool, x, y) ...
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; ...
id(x) = x -> x zero() = x -> id(x) add(m) = n -> (f -> (x -> n(f)(m(f)(x)))) mult(m) = n -> (f -> (x -> n(m(f))(x))) exp(m) = n -> n(m) succ(i::Int) = i + 1 succ(cn) = f -> (x -> f(cn(f)(x))) church2int(cn) = cn(succ)(0) int2church(n) = n < 0 ? throw("negative Church numeral") : (n == 0 ? zero() : succ(int2church(n - 1...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; ...
id(x) = x -> x zero() = x -> id(x) add(m) = n -> (f -> (x -> n(f)(m(f)(x)))) mult(m) = n -> (f -> (x -> n(m(f))(x))) exp(m) = n -> n(m) succ(i::Int) = i + 1 succ(cn) = f -> (x -> f(cn(f)(x))) church2int(cn) = cn(succ)(0) int2church(n) = n < 0 ? throw("negative Church numeral") : (n == 0 ? zero() : succ(int2church(n - 1...
Port the provided C++ code into Julia while preserving the original functionality.
#include <iostream> struct SpecialVariables { int i = 0; SpecialVariables& operator++() { this->i++; return *this; } }; int main() { SpecialVariables sv; auto sv2 = ++sv; std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n...
join(sort(filter(sym -> let n=eval(sym); !(isa(n, Function) || isa(n, Type) || isa(n, Module)); end, names(Base))), ", ")
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsi...
using Sockets function canonCIDR(cidr::String) cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") ip = split(cidr, "/") dig = length(ip) > 1 ? 2^(32 - parse(UInt8, ip[2])) : 1 ip4 = IPv4(UInt64(IPv4(ip[1])) & (0xffffffff - dig + 1)) return length(ip) =...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsi...
using Sockets function canonCIDR(cidr::String) cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") ip = split(cidr, "/") dig = length(ip) > 1 ? 2^(32 - parse(UInt8, ip[2])) : 1 ip4 = IPv4(UInt64(IPv4(ip[1])) & (0xffffffff - dig + 1)) return length(ip) =...
Write the same code in Julia as shown below in C++.
#include <cstdint> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_probably_prime(const integer& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; ...
using Primes function primordials(N) print("The first $N primorial indices sequentially producing primorial primes are: 1 ") primorial = 1 count = 1 p = 3 prod = BigInt(2) while true if isprime(p) prod *= p primorial += 1 if isprime(prod + 1) || ispr...
Write the same algorithm in Julia as shown in this C++ implementation.
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return ...
function Base.binomial{T<:FloatingPoint}(n::T, k::T) exp(lfact(n) - lfact(n - k) - lfact(k)) end function Base.factorial{T<:FloatingPoint}(n::T, k::T) exp(lfact(n) - lfact(k)) end ⊞{T<:Real}(n::T, k::T) = binomial(n, k) ⊠{T<:Real}(n::T, k::T) = factorial(n, n-k)
Write a version of this C++ function in Julia with identical behavior.
#include <gmpxx.h> #include <chrono> using namespace std; using namespace chrono; void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, const mpf_class& op2) { rop1 = (op1 + op2) / 2; rop2 = op1 * op2; mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); } int main(void) { auto st = ste...
using Printf agm1step(x, y) = (x + y) / 2, sqrt(x * y) function approxπstep(x, y, z, n::Integer) a, g = agm1step(x, y) k = n + 1 s = z + 2 ^ (k + 1) * (a ^ 2 - g ^ 2) return a, g, s, k end approxπ(a, g, s) = 4a ^ 2 / (1 - s) function testmakepi() setprecision(512) a, g, s, k = BigFloat(1.0), 1 /...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <gmpxx.h> #include <chrono> using namespace std; using namespace chrono; void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, const mpf_class& op2) { rop1 = (op1 + op2) / 2; rop2 = op1 * op2; mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); } int main(void) { auto st = ste...
using Printf agm1step(x, y) = (x + y) / 2, sqrt(x * y) function approxπstep(x, y, z, n::Integer) a, g = agm1step(x, y) k = n + 1 s = z + 2 ^ (k + 1) * (a ^ 2 - g ^ 2) return a, g, s, k end approxπ(a, g, s) = 4a ^ 2 / (1 - s) function testmakepi() setprecision(512) a, g, s, k = BigFloat(1.0), 1 /...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <iomanip> #include <iostream> #include <list> using namespace std; void sieve(int limit, list<int> &primes) { bool *c = new bool[limit + 1]; for (int i = 0; i <= limit; i++) c[i] = false; int p = 3, n = 0; int p2 = p * p; while (p2 <= limit) { for (int i = p2; i <= limit; i += 2 * p) ...
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 islongprime(p) for i in divisors(p-1) if powermod(10, i, p) == 1 return i + 1 == p ...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
using System; class Program { static int l; static int[] gp(int n) { var c = new bool[n]; var r = new int[(int)(1.28 * n)]; l = 0; r[l++] = 2; r[l++] = 3; int j, d, lim = (int)Math.Sqrt(n); for (int i = 9; i < n; i += 6) c[i] = true; for (j = 5, d = 4; j < lim; j += (d = 6 - ...
using Primes primelist = primes(300000001) primorial(n) = foldr(*, primelist[1:n], init=BigInt(1)) println("The first ten primorials are: $([primorial(n) for n in 1:10])") for i in 1:6 n = 10^i p = primorial(n) plen = Int(floor(log10(p))) + 1 println("primorial($n) has length $plen digits in base 1...
Port the provided C++ code into Julia while preserving the original functionality.
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; int...
struct EgyptianFraction{T<:Integer} <: Real int::T frac::NTuple{N,Rational{T}} where N end Base.show(io::IO, ef::EgyptianFraction) = println(io, "[", ef.int, "] ", join(ef.frac, " + ")) Base.length(ef::EgyptianFraction) = !iszero(ef.int) + length(ef.frac) function Base.convert(::Type{EgyptianFraction{T}}, fr::...
Port the provided C++ code into Julia while preserving the original functionality.
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; int...
struct EgyptianFraction{T<:Integer} <: Real int::T frac::NTuple{N,Rational{T}} where N end Base.show(io::IO, ef::EgyptianFraction) = println(io, "[", ef.int, "] ", join(ef.frac, " + ")) Base.length(ef::EgyptianFraction) = !iszero(ef.int) + length(ef.frac) function Base.convert(::Type{EgyptianFraction{T}}, fr::...
Produce a functionally identical Julia code for the snippet given in C++.
#include <iostream> #include <iomanip> #include <cmath> namespace Rosetta { template <int N> class GaussLegendreQuadrature { public: enum {eDEGREE = N}; template <typename Function> double integrate(double a, double b, Function f) { double p = (b - a) / 2...
using LinearAlgebra function gauss(a, b, N) λ, Q = eigen(SymTridiagonal(zeros(N), [n / sqrt(4n^2 - 1) for n = 1:N-1])) @. (λ + 1) * (b - a) / 2 + a, [2Q[1, i]^2 for i = 1:N] * (b - a) / 2 end
Translate this program into Julia but keep the logic exactly as in C++.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { ...
ENV["NN_DEBUG"] = true using NearestNeighbors const data = [[2, 3] [5, 4] [9, 6] [4, 7] [8, 1] [7, 2]] NearestNeighbors.reset_stats() const kdtree = KDTree(Float64.(data)) const indexpoint = [9,2] idx, dist = knn(kdtree, indexpoint, 1) println("Wikipedia example: The nearest neighbor to $indexpoint is ", "$(dat...
Write a version of this C++ function in Julia with identical behavior.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { ...
ENV["NN_DEBUG"] = true using NearestNeighbors const data = [[2, 3] [5, 4] [9, 6] [4, 7] [8, 1] [7, 2]] NearestNeighbors.reset_stats() const kdtree = KDTree(Float64.(data)) const indexpoint = [9,2] idx, dist = knn(kdtree, indexpoint, 1) println("Wikipedia example: The nearest neighbor to $indexpoint is ", "$(dat...
Produce a functionally identical Julia code for the snippet given in C++.
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) {...
const count = [0] const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]] function walk(y, x, h, w, grid, len, next) if y == 0 || y == h || x == 0 || x == w count[1] += 2 return end t = y * (w + 1) + x grid[t + 1] += UInt8(1) grid[len - t + 1] += UInt8(1) for i in 1:4 if grid[t +...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) {...
const count = [0] const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]] function walk(y, x, h, w, grid, len, next) if y == 0 || y == h || x == 0 || x == w count[1] += 2 return end t = y * (w + 1) + x grid[t + 1] += UInt8(1) grid[len - t + 1] += UInt8(1) for i in 1:4 if grid[t +...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <iostream> #include <vector> #include <chrono> #include <climits> #include <cmath> using namespace std; vector <long long> primes{ 3, 5 }; int main() { cout.imbue(locale("")); const int cutOff = 200, bigUn = 100000, chunks = 50, little = bigUn / chunks; const char tn[] = " cuban prime"; ...
using Primes function cubanprimes(N) cubans = zeros(Int, N) cube100k, cube1, count = 0, 1, 1 for i in Iterators.countfrom(1) j = BigInt(i + 1) cube2 = j^3 diff = cube2 - cube1 if isprime(diff) count ≤ N && (cubans[count] = diff) if count == 100000 ...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
using Luxor function chaos() width = 1000 height = 1000 Drawing(width, height, "./chaos.png") t = Turtle(0, 0, true, 0, (0., 0., 0.)) x = rand(1:width) y = rand(1:height) for l in 1:30_000 v = rand(1:3) if v == 1 x /= 2 y /= 2 elseif v == 2 ...
Port the provided C++ code into Julia while preserving the original functionality.
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
using Luxor function chaos() width = 1000 height = 1000 Drawing(width, height, "./chaos.png") t = Turtle(0, 0, true, 0, (0., 0., 0.)) x = rand(1:width) y = rand(1:height) for l in 1:30_000 v = rand(1:3) if v == 1 x /= 2 y /= 2 elseif v == 2 ...
Produce a functionally identical Julia code for the snippet given in C++.
#include <algorithm> #include <array> #include <iomanip> #include <iostream> #include <sstream> std::array<std::string, 6> games{ "12", "13", "14", "23", "24", "34" }; std::string results = "000000"; int fromBase3(std::string num) { int out = 0; for (auto c : num) { int d = c - '0'; out = 3 * ...
function worldcupstages() games = ["12", "13", "14", "23", "24", "34"] results = "000000" function nextresult() if (results == "222222") return false end results = lpad(string(parse(Int, results, base=3) + 1, base=3), 6, '0') true end points = zeros(Int,...
Keep all operations the same but rewrite the snippet in Julia.
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return st...
function parseinfix2rpn(s) outputq = [] opstack = [] infix = split(s) for tok in infix if all(isnumber, tok) push!(outputq, tok) elseif tok == "(" push!(opstack, tok) elseif tok == ")" while !isempty(opstack) && (op = pop!(opstack)) != "(" ...
Keep all operations the same but rewrite the snippet in Julia.
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: ...
using LightGraphs, SimpleWeightedGraphs const chessboardsize = 8 const givenobstacles = [(2,4), (2,5), (2,6), (3,6), (4,6), (5,6), (5,5), (5,4), (5,3), (5,2), (4,2), (3,2)] vfromcart(p, n) = (p[1] - 1) * n + p[2] const obstacles = [vfromcart(o .+ 1, chessboardsize) for o in givenobstacles] zbasedpath(path, n) = [(div(...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
using Base.Iterators struct NonogramPuzzle nrows::Int ncols::Int xhints::Vector{Vector{Int}} yhints::Vector{Vector{Int}} solutions:: Vector{Any} NonogramPuzzle(xh, yh) = new(length(xh), length(yh), xh, yh, Vector{NTuple{4,Array{Int64,1}}}()) end ycols2xrows(ycols) = [[ycols[i][j] for i in each...
Write a version of this C++ function in Julia with identical behavior.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
using Base.Iterators struct NonogramPuzzle nrows::Int ncols::Int xhints::Vector{Vector{Int}} yhints::Vector{Vector{Int}} solutions:: Vector{Any} NonogramPuzzle(xh, yh) = new(length(xh), length(yh), xh, yh, Vector{NTuple{4,Array{Int64,1}}}()) end ycols2xrows(ycols) = [[ycols[i][j] for i in each...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result ...
using Formatting setprecision(BigFloat, 300) function integerterm(n) p = BigInt(532) * n * n + BigInt(126) * n + 9 return (p * BigInt(2)^5 * factorial(BigInt(6) * n)) ÷ (3 * factorial(BigInt(n))^6) end exponentterm(n) = -(6n + 3) nthterm(n) = integerterm(n) * big"10.0"^exponentterm(n) println(" N ...
Write the same code in Julia as shown below in C++.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result ...
using Formatting setprecision(BigFloat, 300) function integerterm(n) p = BigInt(532) * n * n + BigInt(126) * n + 9 return (p * BigInt(2)^5 * factorial(BigInt(6) * n)) ÷ (3 * factorial(BigInt(n))^6) end exponentterm(n) = -(6n + 3) nthterm(n) = integerterm(n) * big"10.0"^exponentterm(n) println(" N ...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <gmpxx.h> #include <iomanip> #include <iostream> #include <map> #include <string> using big_int = mpz_class; std::pair<std::string, size_t> divide(const big_int& n, const big_int& d) { assert(n >= 0); assert(d > 0); std::string result = big_int(n / d).get_str(); result += '.'; big_int c ...
function f2d(numr, denr) dpart, remainders, r = "", Dict{BigInt, Int}(), BigInt(numr) % denr while (r != 0) && !haskey(remainders, r) remainders[r] = length(dpart) r *= 10 partrem, r = divrem(r, denr) dpart *= string(partrem) end return r == 0 ? (0, 0) : (dpart[remainders...
Please provide an equivalent version of this C++ code in Julia.
#include <gmpxx.h> #include <iomanip> #include <iostream> #include <map> #include <string> using big_int = mpz_class; std::pair<std::string, size_t> divide(const big_int& n, const big_int& d) { assert(n >= 0); assert(d > 0); std::string result = big_int(n / d).get_str(); result += '.'; big_int c ...
function f2d(numr, denr) dpart, remainders, r = "", Dict{BigInt, Int}(), BigInt(numr) % denr while (r != 0) && !haskey(remainders, r) remainders[r] = length(dpart) r *= 10 partrem, r = divrem(r, denr) dpart *= string(partrem) end return r == 0 ? (0, 0) : (dpart[remainders...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
const cache = Dict{BigInt, Tuple{Bool, BigInt}}() Base.reverse(n::Integer) = parse(BigInt, string(n) |> reverse) function lychrel(n::BigInt)::Tuple{Bool, BigInt} if haskey(cache, n) return cache[n] end r = reverse(n) rst = (true, n) seen = Set{BigInt}() for i in 0:500 n += r ...
Generate an equivalent Julia version of this C++ code.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
const cache = Dict{BigInt, Tuple{Bool, BigInt}}() Base.reverse(n::Integer) = parse(BigInt, string(n) |> reverse) function lychrel(n::BigInt)::Tuple{Bool, BigInt} if haskey(cache, n) return cache[n] end r = reverse(n) rst = (true, n) seen = Set{BigInt}() for i in 0:500 n += r ...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <iomanip> #include <iostream> #include <sstream> using namespace std; enum CipherMode {ENCRYPT, DECRYPT}; uint32_t randRsl[256]; uint32_t randCnt; uint32_t mm[256]; uint32_t aa = 0, bb = 0, cc = 0; void isaac() { ++cc; bb += cc; for (uint32_t i = 0; i < 256; ++i) { uin...
""" Julia translation of code from the following: ------------------------------------------------------------------------------ readable.c: My random number generator, ISAAC. (c) Bob Jenkins, March 1996, Public Domain You may use this code in any way you wish, and it is free. No warrantee. ---------------------------...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <iomanip> #include <iostream> #include <sstream> using namespace std; enum CipherMode {ENCRYPT, DECRYPT}; uint32_t randRsl[256]; uint32_t randCnt; uint32_t mm[256]; uint32_t aa = 0, bb = 0, cc = 0; void isaac() { ++cc; bb += cc; for (uint32_t i = 0; i < 256; ++i) { uin...
""" Julia translation of code from the following: ------------------------------------------------------------------------------ readable.c: My random number generator, ISAAC. (c) Bob Jenkins, March 1996, Public Domain You may use this code in any way you wish, and it is free. No warrantee. ---------------------------...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <string> #include <chrono> #include <cmath> #include <locale> using namespace std; using namespace chrono; unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * pow(10, modf(++res * ...
function p(L, n) @assert(L > 0 && n > 0) places, logof2, nfound = trunc(log(10, L)), log(10, 2), 0 for i in 1:typemax(Int) if L == trunc(10^(((i * logof2) % 1) + places)) && (nfound += 1) == n return i end end end for (L, n) in [(12, 1), (12, 2), (123, 45), (123, 12345), (12...