Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true...
using Combinatorics using Primes function descendingprimes() return sort!(filter(isprime, [evalpoly(10, x) for x in powerset([1, 2, 3, 4, 5, 6, 7, 8, 9]) if !isempty(x)])) end foreach(p -> print(rpad(p[2], 10), p[1] % 10 == 0 ? "\n" : ""), enumerate(descendingprimes()))
Port the provided C++ code into Julia while preserving the original functionality.
#include <iostream> #include <vector> using namespace std; vector<int> UpTo(int n, int offset = 0) { vector<int> retval(n); for (int ii = 0; ii < n; ++ii) retval[ii] = ii + offset; return retval; } struct JohnsonTrotterState_ { vector<int> values_; vector<int> positions_; vector<bool> directions_; int sign...
function johnsontrottermove!(ints, isleft) len = length(ints) function ismobile(pos) if isleft[pos] && (pos > 1) && (ints[pos-1] < ints[pos]) return true elseif !isleft[pos] && (pos < len) && (ints[pos+1] < ints[pos]) return true end false end func...
Write the same algorithm in Julia as shown in this C++ implementation.
#include <algorithm> #include <ctime> #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { srand(time(0)); unsigned int attributes_total = 0; unsigned int count = 0; int attributes[6] = {}; int rolls[4] = {}; while(attributes_total < 75 || count ...
roll_skip_lowest(dice, sides) = (r = rand(collect(1:sides), dice); sum(r) - minimum(r)) function rollRPGtoon() attributes = zeros(Int, 6) attsum = 0 gte15 = 0 while attsum < 75 || gte15 < 2 for i in 1:6 attributes[i] = roll_skip_lowest(4, 6) end attsum = sum(attribu...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <iostream> #include <vector> using Sequence = std::vector<int>; std::ostream& operator<<(std::ostream& os, const Sequence& v) { os << "[ "; for (const auto& e : v) { std::cout << e << ", "; } os << "]"; return os; } int next_in_cycle(const Sequence& s, size_t i) { return s[i % s.size()]; } ...
function kolakoski(vec, len) seq = Vector{Int}() k = 0 denom = length(vec) while length(seq) < len n = vec[k % denom + 1] k += 1 seq = vcat(seq, repeat([n], k > length(seq) ? n : seq[k])) end seq[1:len] end function iskolakoski(seq) count = 1 rle = Vector{Int}() ...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <array> #include <iostream> int main() { constexpr std::array s {1,2,2,3,4,4,5}; if(!s.empty()) { int previousValue = s[0]; for(size_t i = 1; i < s.size(); ++i) { const int currentValue = s[i]; if(i > 0 && previousValue == currentValue) { std::cout << i <<...
s = [1, 2, 2, 3, 4, 4, 5] for i in eachindex(s) curr = s[i] i > 1 && curr == prev && println(i) prev = curr end
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { ...
using Primes numfactors(n) = reduce(*, e+1 for (_,e) in factor(n); init=1) A005179(n) = findfirst(k -> numfactors(k) == n, 1:typemax(Int)) println("The first 15 terms of the sequence are:") println(map(A005179, 1:15))
Write the same code in Julia as shown below in C++.
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = "...
function sparklineit(arr) sparkchars = '\u2581':'\u2588' dyn = length(sparkchars) lo, hi = extrema(arr) b = @. max(ceil(Int, dyn * (arr - lo) / (hi - lo)), 1) return join(sparkchars[b]) end v = rand(0:10, 10) println("$v → ", sparklineit(v)) v = 10rand(10) println("$(round.(v, 2)) → ", sparklineit(...
Write a version of this C++ function in Julia with identical behavior.
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename Container> Container lis(const Container& values) { using E = typename Container::value_type; using NodePtr = Node<E>*; using ConstNodePtr ...
function lis(arr::Vector) if length(arr) == 0 return copy(arr) end L = Vector{typeof(arr)}(length(arr)) L[1] = [arr[1]] for i in 2:length(arr) nextL = [] for j in 1:i if arr[j] < arr[i] && length(L[j]) ≥ length(nextL) nextL = L[j] end end ...
Generate an equivalent Julia version of this C++ code.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main(int argc, char** argv) { const int min_length = 9; const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std...
function wordsfromneighbourones(wordfile::String, len = 9, colwidth = 11, numcols = 8) println("Word source: $wordfile\n") words = filter(w -> length(w) >= len, split(read(wordfile, String), r"\s+")) dict, shown, found = Dict(w => 1 for w in words), 0, String[] for position in eachindex(@view words[1:en...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; ...
using Primes twoprimeproduct(n) = (a = factor(n).pe; length(a) == 2 && all(p -> p[2] == 1, a)) special1k = filter(n -> isodd(n) && twoprimeproduct(n), 1:1000) foreach(p -> print(rpad(p[2], 4), p[1] % 20 == 0 ? "\n" : ""), enumerate(special1k))
Maintain the same structure and functionality when rewriting this code in Julia.
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; ...
using Primes twoprimeproduct(n) = (a = factor(n).pe; length(a) == 2 && all(p -> p[2] == 1, a)) special1k = filter(n -> isodd(n) && twoprimeproduct(n), 1:1000) foreach(p -> print(rpad(p[2], 4), p[1] % 20 == 0 ? "\n" : ""), enumerate(special1k))
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
using Primes function isbrilliant(n) p = factor(n).pe return (length(p) == 1 && p[1][2] == 2) || length(p) == 2 && ndigits(p[1][1]) == ndigits(p[2][1]) && p[1][2] == p[2][2] == 1 end function testbrilliants() println("First 100 brilliant numbers:") foreach(p -> print(lpad(p[2], 5), p[1] % 20 ==...
Write the same code in Julia as shown below in C++.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
using Primes function isbrilliant(n) p = factor(n).pe return (length(p) == 1 && p[1][2] == 2) || length(p) == 2 && ndigits(p[1][1]) == ndigits(p[2][1]) && p[1][2] == p[2][2] == 1 end function testbrilliants() println("First 100 brilliant numbers:") foreach(p -> print(lpad(p[2], 5), p[1] % 20 ==...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
function calkin_wilf(n) cw = zeros(Rational, n + 1) for i in 2:n + 1 t = Int(floor(cw[i - 1])) * 2 - cw[i - 1] + 1 cw[i] = 1 // t end return cw[2:end] end function continued(r::Rational) a, b = r.num, r.den res = [] while true push!(res, Int(floor(a / b))) a,...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
function calkin_wilf(n) cw = zeros(Rational, n + 1) for i in 2:n + 1 t = Int(floor(cw[i - 1])) * 2 - cw[i - 1] + 1 cw[i] = 1 // t end return cw[2:end] end function continued(r::Rational) a, b = r.num, r.den res = [] while true push!(res, Int(floor(a / b))) a,...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <vector> #include <algorithm> #include <string> template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; } template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::vector...
function order_disjoint{T<:AbstractArray}(m::T, n::T) rlen = length(n) rdis = zeros(Int, rlen) for (i, e) in enumerate(n) j = findfirst(m, e) while j in rdis && j != 0 j = findnext(m, e, j+1) end rdis[i] = j end if 0 in rdis throw(DomainError()) ...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot ope...
const primelettervalues = [67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113] isprimeword(w, _) = all(c -> Int(c) in primelettervalues, collect(w)) ? w : "" foreachword("unixdict.txt", isprimeword, colwidth=10, numcols=9)
Write the same code in Julia as shown below in C++.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot ope...
const primelettervalues = [67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113] isprimeword(w, _) = all(c -> Int(c) in primelettervalues, collect(w)) ? w : "" foreachword("unixdict.txt", isprimeword, colwidth=10, numcols=9)
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit pal...
using Primes parray = [2, 3, 5, 7, 9, 11] results = vcat(parray, filter(isprime, [100j + 10i + j for i in 0:9, j in 1:9])) println(results)
Write the same code in Julia as shown below in C++.
#include <iomanip> #include <iostream> #include <numeric> #include <sstream> bool duffinian(int n) { if (n == 2) return false; int total = 1, power = 2, m = n; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (int p = 3; p * p <= n; p += 2) { int sum = 1; f...
using Primes function σ(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 sum(f) end isDuffinian(n) = !isprime(n) && gcd(n, σ(n)) == 1 function testDuffinians() println("First 50 Duffinian numbers:") foreach(p -> print(rpad(p[2], 4), p[1]...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> using integer = boost::multiprecision::cpp_int; using rational = boost::rational<integer>; integer sylvester_next(const integer& n) { return n * n - n + 1; } int main() { std::cout << "First 10 el...
sylvester(n) = (n == 1) ? big"2" : prod(sylvester, 1:n-1) + big"1" foreach(n -> println(rpad(n, 3), " => ", sylvester(n)), 1:10) println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))
Keep all operations the same but rewrite the snippet in Julia.
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/gmp.hpp> using integer = boost::multiprecision::mpz_int; using rational = boost::rational<integer>; class harmonic_generator { public: rational next() { rational result = term_; term_ += rational(1,...
const memoizer = [BigFloat(1.0), BigFloat(1.5)] """ harmonic(n::Integer)::BigFloat Calculates harmonic numbers. The integer argument `n` should be positive. """ function harmonic(n::Integer)::BigFloat if n < 0 throw(DomainError(n)) elseif n == 0 return BigFloat(0.0) elseif length(mem...
Write the same code in Julia as shown below in C++.
#include <fstream> #include <iostream> #include <locale> using namespace std; int main(void) { std::locale::global(std::locale("")); std::cout.imbue(std::locale()); ifstream in("input.txt"); wchar_t c; while ((c = in.get()) != in.eof()) wcout<<c; in.close(); return EXIT_...
open("myfilename") do f while !eof(f) c = read(f, Char) println(c) end end
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject(...
using Random function drawball(timer) global r, c, d print("\e[$r;$(c)H ") if (r+=1) > 14 close(timer) b = (bin[(c+2)>>2] += 1) print("\e[$b;$(c)Ho") else r in 3:2:13 && c in 17-r:4:11+r && (d = 2bitrand()-1) print("\e[$r;$(c+=d)Ho") end end print("...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <algorithm> #include <iostream> #include <vector> typedef unsigned long long integer; std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && a != n; ) { n = a; a = ancestor[n]; ...
using Primes function ancestraldecendants(maxsum) aprimes = primes(maxsum) descendants = [Vector{Int}() for _ in 1:maxsum + 1] ancestors = [Vector{Int}() for _ in 1:maxsum + 1] for p in aprimes push!(descendants[p + 1], p) foreach(s -> append!(descendants[s + p], [p * pr for pr in desce...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <iostream> void f(int n) { if (n < 1) { return; } int i = 1; while (true) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int...
function squaresstartingupto(n, verbose=true) res, numfound = zeros(Int, n), 0 p_int = collect(1:n) p_string = string.(p_int) for i in 1:typemax(Int) sq = i * i sq_s = string(sq) for (j, s) in enumerate(p_string) if res[j] == 0 && length(sq_s) >= length(s) && sq_s[1:...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> void f(int n) { if (n < 1) { return; } int i = 1; while (true) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int...
function squaresstartingupto(n, verbose=true) res, numfound = zeros(Int, n), 0 p_int = collect(1:n) p_string = string.(p_int) for i in 1:typemax(Int) sq = i * i sq_s = string(sq) for (j, s) in enumerate(p_string) if res[j] == 0 && length(sq_s) >= length(s) && sq_s[1:...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; a...
function _ciclesort!(arr::Vector, lo::Int, hi::Int, swaps::Int) lo == hi && return swaps high = hi low = lo mid = (hi - lo) ÷ 2 while lo < hi if arr[lo] > arr[hi] arr[lo], arr[hi] = arr[hi], arr[lo] swaps += 1 end lo += 1 hi -= 1 end ...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <array> #include <iostream> #include <fstream> #include <map> #include <string> #include <vector> #include <boost/program_options.hpp> class letterset { public: letterset() { count_.fill(0); } explicit letterset(const std::string& str) { count_.fill(0); for (char c : str)...
using Combinatorics const tfile = download("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") const wordlist = Dict(w => 1 for w in split(read(tfile, String), r"\s+")) function wordwheel(wheel, central) returnlist = String[] for combo in combinations([string(i) for i in wheel]) if central in combo...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> namespace detail { template <typename ForwardIterator> class tokenizer { ForwardIterator _tbegin, _tend, _end; public: tokenizer(ForwardIterator begin, ForwardIterator end) : _tbegin(begin), _tend(begin), _end(end...
function getitem(s, depth=0) out = [""] while s != "" c = s[1] if depth > 0 && (c == ',' || c == '}') return out, s elseif c == '{' x = getgroup(s[2:end], depth+1) if x != "" out, s = [a * b for a in out, b in x[1]], x[2] ...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { } Wheel(std::initializer_list<char> data) : values(data), index(0) { if (values.size() < 1) { ...
const d1 = Dict("A" => [["1", "2", "3"], 1]) const d2 = Dict("A" => [["1", "B", "2"], 1], "B" => [["3", "4"], 1]) const d3 = Dict("A" => [["1", "D", "D"], 1], "D" => [["6", "7", "8"], 1]) const d4 = Dict("A" => [["1", "B", "C"], 1], "B" => [["3", "4"], 1], "C" => [["5", "B"], 1]) function getvalue!(wheelname, allw...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { } Wheel(std::initializer_list<char> data) : values(data), index(0) { if (values.size() < 1) { ...
const d1 = Dict("A" => [["1", "2", "3"], 1]) const d2 = Dict("A" => [["1", "B", "2"], 1], "B" => [["3", "4"], 1]) const d3 = Dict("A" => [["1", "D", "D"], 1], "D" => [["6", "7", "8"], 1]) const d4 = Dict("A" => [["1", "B", "C"], 1], "B" => [["3", "4"], 1], "C" => [["5", "B"], 1]) function getvalue!(wheelname, allw...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; [STAThreadAttribute] int main() { Point^ MousePoint = gcnew Point(); Control^ TempControl = gcnew Control(); MousePoint = TempControl->MousePosition; Bitmap^ TempBitmap = gcnew Bitmap(1,1); Graphics^ g = Graphics::Fro...
function getpixelcolors(x, y) hdc = ccall((:GetDC, "user32.dll"), UInt32, (UInt32,), 0) pxl = ccall((:GetPixel, "gdi32.dll"), UInt32, (UInt32, Cint, Cint), hdc, Cint(x), Cint(y)) return pxl & 0xff, (pxl >> 8) & 0xff, (pxl >> 16) & 0xff end const x = 120 const y = 100 cols = getpixelcolors(x, y) println("A...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
immutable Point{T<:FloatingPoint} x::T y::T end immutable Circle{T<:FloatingPoint} c::Point{T} r::T end Circle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T)) using AffineTransforms function circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T) cp = Circle{T}[] r >= 0 || return (...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
immutable Point{T<:FloatingPoint} x::T y::T end immutable Circle{T<:FloatingPoint} c::Point{T} r::T end Circle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T)) using AffineTransforms function circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T) cp = Circle{T}[] r >= 0 || return (...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> #include <string> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) using namespace std; class recorder { public: void start() { paused = rec = false; action = "IDLE"; while( true ) { cout << endl << "==" << action << "==" << endl << endl; cout <<...
using PortAudio, LibSndFile stream = PortAudioStream("Microphone (USB Microphone)", 1, 0) buf = read(stream, 441000) save("recorded10sec.wav", buf)
Convert this C++ block to Julia, preserving its control flow and logic.
#include <vector> #include <utility> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <cmath> bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) { std::ostringstream numberstream ; numberstream << number ; std::string numberstring( number...
function divisors{T<:Integer}(n::T) !isprime(n) || return [one(T), n] d = [one(T)] for (k, v) in factor(n) e = T[k^i for i in 1:v] append!(d, vec([i*j for i in d, j in e])) end sort(d) end function vampirefangs{T<:Integer}(n::T) fangs = T[] isvampire = false vdcnt = ndig...
Please provide an equivalent version of this C++ code in Julia.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); ...
using Gtk, Cairo const can = GtkCanvas(800, 100) const win = GtkWindow(can, "Canvas") const numbers = [0, 1, 20, 300, 4000, 5555, 6789, 8123] function drawcnum(ctx, xypairs) move_to(ctx, xypairs[1][1], xypairs[1][2]) for p in xypairs[2:end] line_to(ctx, p[1], p[2]) end stroke(ctx) end @guarde...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); ...
using Gtk, Cairo const can = GtkCanvas(800, 100) const win = GtkWindow(can, "Canvas") const numbers = [0, 1, 20, 300, 4000, 5555, 6789, 8123] function drawcnum(ctx, xypairs) move_to(ctx, xypairs[1][1], xypairs[1][2]) for p in xypairs[2:end] line_to(ctx, p[1], p[2]) end stroke(ctx) end @guarde...
Please provide an equivalent version of this C++ code in Julia.
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), ...
sorteddeck = [string(r) * s for s in "♣♦♥♠", r in "23456789TJQKA"] cardlessthan(card1, card2) = indexin(x, sorteddeck)[1] < indexin(y, sorteddeck)[1] decksort(d) = sort(d, lt=cardlessthan) highestrank(d) = string(highestcard(d)[1]) function hasduplicate(d) s = sort(d) for i in 1:length(s)-1 if s[i] ...
Translate this program into Julia but keep the logic exactly as in C++.
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), ...
sorteddeck = [string(r) * s for s in "♣♦♥♠", r in "23456789TJQKA"] cardlessthan(card1, card2) = indexin(x, sorteddeck)[1] < indexin(y, sorteddeck)[1] decksort(d) = sort(d, lt=cardlessthan) highestrank(d) = string(highestcard(d)[1]) function hasduplicate(d) s = sort(d) for i in 1:length(s)-1 if s[i] ...
Translate this program into Julia but keep the logic exactly as in C++.
#include <windows.h> #include <string> using namespace std; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, siz...
using Luxor, Colors function fwfractal!(word::AbstractString, t::Turtle) left = 90 right = -90 for (n, c) in enumerate(word) Forward(t) if c == '0' Turn(t, ifelse(iseven(n), left, right)) end end return t end word = last(fiboword(25)) touch("data/fibonaccifra...
Produce a functionally identical Julia code for the snippet given in C++.
#include <time.h> #include <iostream> #include <string> using namespace std; class penney { public: penney() { pW = cW = 0; } void gameLoop() { string a; while( true ) { playerChoice = computerChoice = ""; if( rand() % 2 ) { computer(); player(); } else { player(); comput...
const SLEN = 3 autobet() = randbool(SLEN) function autobet(ob::BitArray{1}) rlen = length(ob) 2 < rlen || return ~ob 3 < rlen || return [~ob[2], ob[1:2]] opt = falses(rlen) opt[1] = true opt[end-1:end] = true ob != opt || return ~opt return opt end autobet(ob::Array{Bool,1}) = autobet(c...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
using Luxor function sierpinski(txy, levelsyet) nxy = zeros(6) if levelsyet > 0 for i in 1:6 pos = i < 5 ? i + 2 : i - 4 nxy[i] = (txy[i] + txy[pos]) / 2.0 end sierpinski([txy[1],txy[2],nxy[1],nxy[2],nxy[5],nxy[6]], levelsyet-1) sierpinski([nxy[1],nxy[2],...
Write the same algorithm in Julia as shown in this C++ implementation.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
using Luxor function sierpinski(txy, levelsyet) nxy = zeros(6) if levelsyet > 0 for i in 1:6 pos = i < 5 ? i + 2 : i - 4 nxy[i] = (txy[i] + txy[pos]) / 2.0 end sierpinski([txy[1],txy[2],nxy[1],nxy[2],nxy[5],nxy[6]], levelsyet-1) sierpinski([nxy[1],nxy[2],...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { ...
minsized(arr) = join(map(x->" minlen(arr) = sum(arr) + length(arr) - 1 function sequences(blockseq, numblanks) if isempty(blockseq) return ["." ^ numblanks] elseif minlen(blockseq) == numblanks return minsized(blockseq) else result = Vector{String}() allbuthead = blocks...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { ...
minsized(arr) = join(map(x->" minlen(arr) = sum(arr) + length(arr) - 1 function sequences(blockseq, numblanks) if isempty(blockseq) return ["." ^ numblanks] elseif minlen(blockseq) == numblanks return minsized(blockseq) else result = Vector{String}() allbuthead = blocks...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
function iseban(n::Integer) b, r = divrem(n, oftype(n, 10 ^ 9)) m, r = divrem(r, oftype(n, 10 ^ 6)) t, r = divrem(r, oftype(n, 10 ^ 3)) m, t, r = (30 <= x <= 66 ? x % 10 : x for x in (m, t, r)) return all(in((0, 2, 4, 6)), (b, m, t, r)) end println("eban numbers up to and including 1000:") println(...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
function iseban(n::Integer) b, r = divrem(n, oftype(n, 10 ^ 9)) m, r = divrem(r, oftype(n, 10 ^ 6)) t, r = divrem(r, oftype(n, 10 ^ 3)) m, t, r = (30 <= x <= 66 ? x % 10 : x for x in (m, t, r)) return all(in((0, 2, 4, 6)), (b, m, t, r)) end println("eban numbers up to and including 1000:") println(...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
function validnutsforsailors(sailors, finalpile) for i in sailors:-1:1 if finalpile % sailors != 1 return false end finalpile -= Int(floor(finalpile/sailors) + 1) end (finalpile != 0) && (finalpile % sailors == 0) end function runsim() println("Sailors Starting P...
Write the same code in Julia as shown below in C++.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
function validnutsforsailors(sailors, finalpile) for i in sailors:-1:1 if finalpile % sailors != 1 return false end finalpile -= Int(floor(finalpile/sailors) + 1) end (finalpile != 0) && (finalpile % sailors == 0) end function runsim() println("Sailors Starting P...
Change the following C++ code into Julia without altering its purpose.
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
using Dates """ nauticalbells(DateTime) Return a string according to the "simpler system" of nautical bells listed in the table in Wikipedia at en.wikipedia.org/wiki/Ship%27s_bell Note the traditional time zone was determined by local sun position and so should be local time without dayli...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
using Dates """ nauticalbells(DateTime) Return a string according to the "simpler system" of nautical bells listed in the table in Wikipedia at en.wikipedia.org/wiki/Ship%27s_bell Note the traditional time zone was determined by local sun position and so should be local time without dayli...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER...
using PortAudio function paudio() devs = PortAudio.devices() devnum = findfirst(x -> x.maxoutchans > 0, devs) (devnum == nothing) && error("No output device for audio found") return PortAudioStream(devs[devnum].name, 0, 2) end function play(ostream, pitch, durationseconds) sinewave(t) = 0.6sin(t) ...
Write a version of this C++ function in Julia with identical behavior.
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER...
using PortAudio function paudio() devs = PortAudio.devices() devnum = findfirst(x -> x.maxoutchans > 0, devs) (devnum == nothing) && error("No output device for audio found") return PortAudioStream(devs[devnum].name, 0, 2) end function play(ostream, pitch, durationseconds) sinewave(t) = 0.6sin(t) ...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
using Gtk, Graphics, Colors const can = @GtkCanvas() const win = GtkWindow(can, "Polyspiral", 360, 360) const drawiters = 72 const colorseq = [colorant"blue", colorant"red", colorant"green", colorant"black", colorant"gold"] const angleiters = [0, 0, 0] const angles = [75, 100, 135, 160] Base.length(v::Vec2) = sqrt(v...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
using Gtk, Graphics, Colors const can = @GtkCanvas() const win = GtkWindow(can, "Polyspiral", 360, 360) const drawiters = 72 const colorseq = [colorant"blue", colorant"red", colorant"green", colorant"black", colorant"gold"] const angleiters = [0, 0, 0] const angles = [75, 100, 135, 160] Base.length(v::Vec2) = sqrt(v...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <iostream> #include <optional> #include <ranges> #include <string> #include <vector> using namespace std; struct Patient { string ID; string LastName; }; struct Visit { string PatientID; string Date; optional<float> Score; }; int main(void) { auto patients = vector<Patient> { ...
using CSV, DataFrames, Statistics str_patients = IOBuffer("""PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz """) df_patients = CSV.read(str_patients, DataFrame) str_visits = IOBuffer("""PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,202...
Write a version of this C++ function in Julia with identical behavior.
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
using Images function voronoi(w, h, n_centroids) dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2) dots = [rand(1:h, n_centroids) rand(1:w, n_centroids) rand(RGB{N0f8}, n_centroids)] img = zeros(RGB{N0f8}, h, w) for x in 1:h, y in 1:w distances = dist([x,y...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
using Images function voronoi(w, h, n_centroids) dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2) dots = [rand(1:h, n_centroids) rand(1:w, n_centroids) rand(RGB{N0f8}, n_centroids)] img = zeros(RGB{N0f8}, h, w) for x in 1:h, y in 1:w distances = dist([x,y...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <iostream> #include <vector> #include <algorithm> #include <stdexcept> #include <memory> #include <sys/time.h> using std::cout; using std::endl; class StopTimer { public: StopTimer(): begin_(getUsec()) {} unsigned long long getTime() const { return getUsec() - begin_; } private: static unsigned l...
using MathProgBase, Cbc struct KPDSupply{T<:Integer} item::String weight::T value::T quant::T end Base.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, " ", kdps.item, " ($(kdps.weight) kg, $(kdps.value) €)") function solve(gear::Vector{KPDSupply{T}}, capacity::Integer) where T<:Integer w = g...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <sstream> #include <iterator> #include <vector> using namespace std; struct node { int val; unsigned char neighbors; }; class hSolver { public: hSolver() { dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; dy[0] = -1; dy[1] = -...
module Hidato export hidatosolve, printboard, hidatoconfigure function hidatoconfigure(str) lines = split(str, "\n") nrows, ncols = length(lines), length(split(lines[1], r"\s+")) board = fill(-1, (nrows, ncols)) presets = Vector{Int}() starts = Vector{CartesianIndex{2}}() maxmoves = 0 for ...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <iostream> #include <sstream> #include <iterator> #include <vector> using namespace std; struct node { int val; unsigned char neighbors; }; class hSolver { public: hSolver() { dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; dy[0] = -1; dy[1] = -...
module Hidato export hidatosolve, printboard, hidatoconfigure function hidatoconfigure(str) lines = split(str, "\n") nrows, ncols = length(lines), length(split(lines[1], r"\s+")) board = fill(-1, (nrows, ncols)) presets = Vector{Int}() starts = Vector{CartesianIndex{2}}() maxmoves = 0 for ...
Keep all operations the same but rewrite the snippet in Julia.
#include <list> template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.en...
function mergelist(a, b) out = Vector{Int}() while !isempty(a) && !isempty(b) if a[1] < b[1] push!(out, popfirst!(a)) else push!(out, popfirst!(b)) end end append!(out, a) append!(out, b) out end function strand(a) i, s = 1, [popfirst!(a)] ...
Transform the following C++ implementation into Julia, maintaining the same output and logic.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(doub...
using Formatting d2d(d) = d % 360 g2g(g) = g % 400 m2m(m) = m % 6400 r2r(r) = r % 2π d2g(d) = d2d(d) * 10 / 9 d2m(d) = d2d(d) * 160 / 9 d2r(d) = d2d(d) * π / 180 g2d(g) = g2g(g) * 9 / 10 g2m(g) = g2g(g) * 16 g2r(g) = g2g(g) * π / 200 m2d(m) = m2m(m) * 9 / 160 m2g(m) = m2m(m) / 16 m2r(m) = m2m(m) * π / 3200 r2d(r) = r2...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <utility> #include <vector> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <libxml/xmlstring.h> #include <libxml/xmlversion.h> #include <libxml/xpath.h> #ifndef LIBXML_XPATH_ENABLED # e...
using LibExpat xdoc = raw"""<inventory title="OmniCorp Store <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Sa...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& print(std::ostream& os, const T& src) { auto it = src.cbegin(); auto end = src.cend(); os << "["; if (it != end) { os << *it; ...
function ties{T<:Real}(a::Array{T,1}) unique(a[2:end][a[2:end] .== a[1:end-1]]) end
Translate the given C++ code snippet into Julia without altering its behavior.
#include <iostream> #include <string> #include <map> #include <algorithm> using namespace std; class StraddlingCheckerboard { map<char, string> table; char first[10], second[10], third[10]; int rowU, rowV; public: StraddlingCheckerboard(const string &alphabet, int u, int v) { rowU = min(u, v); rowV...
function straddlingcheckerboard(board, msg, doencode) lookup = Dict() reverselookup = Dict() row2 = row3 = slash = -1 function encode(x) s = "" for ch in replace(replace(uppercase(x), r"([01-9])", s";=;\1"), r";=;", slash) c = string(ch) if haskey(lookup, c) ...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string...
open("unixdict.txt") do txtfile rule1, notrule1, rule2, notrule2 = 0, 0, 0, 0 for word in eachline(txtfile) if ismatch(r"ie"i, word) if ismatch(r"cie"i, word) notrule1 += 1 else rule1 += 1 end end if ...
Write the same algorithm in Julia as shown in this C++ implementation.
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string...
open("unixdict.txt") do txtfile rule1, notrule1, rule2, notrule2 = 0, 0, 0, 0 for word in eachline(txtfile) if ismatch(r"ie"i, word) if ismatch(r"cie"i, word) notrule1 += 1 else rule1 += 1 end end if ...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <iostream> #include "xtensor/xarray.hpp" #include "xtensor/xio.hpp" #include "xtensor-io/ximage.hpp" xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim) { xt::xarray<int>::shape_type shape = { x_dim, y_dim }; xt::xarray<int> grid(shape); grid(x_dim/2, y_dim/2) = 64000; r...
module AbelSand using CSV, DataFrames, Images function TrimZeros(A) i1, j1 = 1, 1 i2, j2 = size(A) zz = typeof(A[1, 1])(0) for i = 1:size(A, 1) q = false for k = 1:size(A, 2) if A[i, k] != zz q = true i1 = i ...
Generate an equivalent Julia version of this C++ code.
#include <iostream> #include "xtensor/xarray.hpp" #include "xtensor/xio.hpp" #include "xtensor-io/ximage.hpp" xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim) { xt::xarray<int>::shape_type shape = { x_dim, y_dim }; xt::xarray<int> grid(shape); grid(x_dim/2, y_dim/2) = 64000; r...
module AbelSand using CSV, DataFrames, Images function TrimZeros(A) i1, j1 = 1, 1 i2, j2 = size(A) zz = typeof(A[1, 1])(0) for i = 1:size(A, 1) q = false for k = 1:size(A, 2) if A[i, k] != zz q = true i1 = i ...
Port the provided C++ code into Julia while preserving the original functionality.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
using Combinatorics, BenchmarkTools asint(dig) = foldl((i, j) -> 10i + Int128(j), dig) """ Algorithm 1(A) Generate all the permutations of the digits and sort into numeric order. Find the number in the list. Return the next highest number from the list. """ function nexthighest_1A(N) n = Int128(abs(N)) dig = ...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
using Combinatorics, BenchmarkTools asint(dig) = foldl((i, j) -> 10i + Int128(j), dig) """ Algorithm 1(A) Generate all the permutations of the digits and sort into numeric order. Find the number in the list. Return the next highest number from the list. """ function nexthighest_1A(N) n = Int128(abs(N)) dig = ...
Please provide an equivalent version of this C++ code in Julia.
#include <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen"...
const stext = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] const teentext = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] const tenstext = ["ten", "twenty", "thirty", "forty", "fift...
Translate this program into Julia but keep the logic exactly as in C++.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <sstream> class Roulette { private: std::array<bool, 6> cylinder; std::mt19937 gen; std::uniform_int_distribution<> distrib; int next_int() { return distrib(gen); } void rshift() { std::rotate(...
const cyl = zeros(Bool, 6) function load() while cyl[1] cyl .= circshift(cyl, 1) end cyl[1] = true cyl .= circshift(cyl, 1) end spin() = (cyl .= circshift(cyl, rand(1:6))) fire() = (shot = cyl[1]; cyl .= circshift(cyl, 1); shot) function LSLSFSF() cyl .= 0 load(); spin(); load(); spi...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { doubl...
using Printf const sides = 5 const order = 5 const dim = 250 const scale = (3 - order ^ 0.5) / 2 const τ = 8 * atan(1, 1) const orders = map(x -> ((1 - scale) * dim) * scale ^ x, 0:order-1) cis(x) = Complex(cos(x), sin(x)) const vertices = map(x -> cis(x * τ / sides), 0:sides-1) fh = open("sierpinski_pentagon.svg"...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.#...
const pixelstring = "00000000000000000000000000000000" * "01111111110000000111111110000000" * "01110001111000001111001111000000" * "01110000111000001110000111000000" * "01110001111000001110000000000000" * "01111111110000001110000000000000" * "01110111100000001110000111000000" * "01110011110011101111001111011100" * "011...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> #include <string> #include <time.h> using namespace std; namespace { void placeRandomly(char* p, char c) { int loc = rand() % 8; if (!p[loc]) p[loc] = c; else placeRandomly(p, c); } int placeFirst(char* p, char c, int loc = 0) { while (p[loc]) ++loc; p[loc] = ...
function generateposition() rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] lrank = length(rank) isfree(x::Int) = rank[x] == '♘' rank[indking = rand(2:lrank-1)] = '♔' rank[indrook = rand(filter(isfree, 1:lrank))] = '♖' if indrook > indking rank[rand(filter(isfree, ...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> #include <locale> #include <map> #include <vector> std::string trim(const std::string &str) { auto s = str; auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end()); auto it2 = st...
const pat1 = (" " const pat2 = [replace(x, r"[ const ptod1 = Dict((b => a - 1) for (a, b) in enumerate(pat1)) const ptod2 = Dict((b => a - 1) for (a, b) in enumerate(pat2)) const reg = Regex("^\\s* "){6})\\s* const lines = [ " " " " " ...
Transform the following C++ implementation into Julia, maintaining the same output and logic.
#include <iostream> #include <sstream> int main(int argc, char *argv[]) { using namespace std; #if _WIN32 if (argc != 5) { cout << "Usage : " << argv[0] << " (type) (id) (source string) (description>)\n"; cout << " Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n"; } else { ...
cmd = "eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\"" Base.run(`$cmd`)
Transform the following C++ implementation into Julia, maintaining the same output and logic.
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five...
const irregular = Dict("one" => "first", "two" => "second", "three" => "third", "five" => "fifth", "eight" => "eighth", "nine" => "ninth", "twelve" => "twelfth") const suffix = "th" const ysuffix = "ieth" function numtext2ordinal(s) lastword = split(s)[end] redolast = split(las...
Transform the following C++ implementation into Julia, maintaining the same output and logic.
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boo...
const testdata = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80", "1::", "[1::]:80", "::", "[::]:80"] maybev4(ip) = search(ip, '.') > 0 && length(mat...
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> #include <utility> #include <vector> using Point = std::pair<double, double>; constexpr auto eps = 1e-14; std::ostream &operator<<(std::ostream &os, const Point &p) { auto x = p.first; if (x == 0.0) { x = 0.0; } auto y = p.second; if (y == 0.0) { y = 0.0; } ...
using Luxor const centers = [Point(3, -5), Point(0, 0), Point(4, 2)] const rads = [3, 4, 5] const lins = [ [Point(-10, 11), Point(10, -9)], [Point(-10, 11), Point(-11, 12)], [Point(3, -2), Point(7, -2)], [Point(0, -3), Point(0, 6)], [Point(6, 3), Point(10, 7)], [Point(7, 4), Point(11, 8)], ] println("Ce...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> using namespace std; string redact(const string &source, const string &word, bool partial, bool insensitive, bool overkill) { string temp = source; auto different = [insensitive](char s, char w) { if (insensitive) { return toupper(s) != toupper(w); } else { ...
function doif_equals(word, pattern, insens=false) regex = insens ? Regex("^$pattern\$", "i") : Regex("^$pattern\$") return replace(word, regex => pattern in multichars ? "X" : "X"^length(pattern)) end doif_ci_equals(word, pattern) = doif_equals(word, pattern, true) function doif_includes(word, pattern, insens=...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> #include <cstring> int findNumOfDec(const char *s) { int pos = 0; while (s[pos] && s[pos++] != '.') {} return strlen(s + pos); } void test(const char *s) { int num = findNumOfDec(s); const char *p = num != 1 ? "s" : ""; std::cout << s << " has " << num << " decimal" << p <...
function postprecision(str::String) s = lowercase(str) if 'e' in s s, ex = split(s, "e") expdig = parse(Int, ex) else expdig = 0 end dig = something(findfirst('.', reverse(s)), 1) - 1 - expdig return dig > 0 ? dig : 0 end postprecision(x::Integer) = 0 postprecision(x:...
Write the same code in Julia as shown below in C++.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
using .Hidato const hopid = """ . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . """ const hopidomoves = [[-3, 0], [0, -3], [-2, -2], [-2, 2], [2, -2], [0, 3], [3, 0], [2, 2]] board, maxmoves, fixed, starts = hidatoconfigure(hopid) printboard(board, " 0", " ") hidatos...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
using .Hidato const hopid = """ . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . """ const hopidomoves = [[-3, 0], [0, -3], [-2, -2], [-2, 2], [2, -2], [0, 3], [3, 0], [2, 2]] board, maxmoves, fixed, starts = hidatoconfigure(hopid) printboard(board, " 0", " ") hidatos...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size()...
using .Hidato const numbrixmoves = [[-1, 0], [0, -1], [0, 1], [1, 0]] board, maxmoves, fixed, starts = hidatoconfigure(numbrix1) printboard(board, " 0 ", " ") hidatosolve(board, maxmoves, numbrixmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board) board, maxmoves, fixed, starts = hidatoconfigure(numbrix2...
Please provide an equivalent version of this C++ code in Julia.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size()...
using .Hidato const numbrixmoves = [[-1, 0], [0, -1], [0, 1], [1, 0]] board, maxmoves, fixed, starts = hidatoconfigure(numbrix1) printboard(board, " 0 ", " ") hidatosolve(board, maxmoves, numbrixmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board) board, maxmoves, fixed, starts = hidatoconfigure(numbrix2...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
class animal { public: virtual void bark() { throw "implement me: do not know how to bark"; } }; class elephant : public animal { }; int main() { elephant e; e.bark(); }
function add(a, b) try a + b catch println("caught exception") a * b end end println(add(2, 6)) println(add(1//2, 1//2)) println(add("Hello ", "world"))
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
julia> expr="2 * (3 -1) + 2 * 5" "2 * (3 -1) + 2 * 5" julia> parsed = parse(expr) :(+(*(2,-(3,1)),*(2,5))) julia> t = typeof(parsed) Expr julia> names(t) (:head,:args,:typ) julia> parsed.args 3-element Any Array: :+ :(*(2,-(3,1))) :(*(2,5)) julia> typeof(parsed.args[2]) Expr julia> parsed....
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
julia> expr="2 * (3 -1) + 2 * 5" "2 * (3 -1) + 2 * 5" julia> parsed = parse(expr) :(+(*(2,-(3,1)),*(2,5))) julia> t = typeof(parsed) Expr julia> names(t) (:head,:args,:typ) julia> parsed.args 3-element Any Array: :+ :(*(2,-(3,1))) :(*(2,5)) julia> typeof(parsed.args[2]) Expr julia> parsed....
Produce a functionally identical Julia code for the snippet given in C++.
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { 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 Luxor function sierpinski_curve(x0, y0, h, level) x1, y1 = x0, y0 lineto(x, y) = begin line(Point(x1, y1), Point(x, y), :stroke); x1, y1 = x, y end lineN() = lineto(x1,y1-2*h) lineS() = lineto(x1,y1+2*h) lineE() = lineto(x1+2*h,y1) lineW() = lineto(x1-2*h,y1) lineNW() = lineto(x1-h,y1...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { 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 Luxor function sierpinski_curve(x0, y0, h, level) x1, y1 = x0, y0 lineto(x, y) = begin line(Point(x1, y1), Point(x, y), :stroke); x1, y1 = x, y end lineN() = lineto(x1,y1-2*h) lineS() = lineto(x1,y1+2*h) lineE() = lineto(x1+2*h,y1) lineW() = lineto(x1-2*h,y1) lineNW() = lineto(x1-h,y1...
Generate an equivalent Julia version of this C++ code.
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
rep = Dict('a' => Dict(1 => 'A', 2 => 'B', 4 => 'C', 5 => 'D'), 'b' => Dict(1 => 'E'), 'r' => Dict(2 => 'F')) function trstring(oldstring, repdict) seen, newchars = Dict{Char, Int}(), Char[] for c in oldstring i = get!(seen, c, 1) push!(newchars, haskey(repdict, c) && haskey(repdict[c], i) ? re...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
rep = Dict('a' => Dict(1 => 'A', 2 => 'B', 4 => 'C', 5 => 'D'), 'b' => Dict(1 => 'E'), 'r' => Dict(2 => 'F')) function trstring(oldstring, repdict) seen, newchars = Dict{Char, Int}(), Char[] for c in oldstring i = get!(seen, c, 1) push!(newchars, haskey(repdict, c) && haskey(repdict[c], i) ? re...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <stdio.h> #include <stdlib.h> void clear() { for(int n = 0;n < 10; n++) { printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n"); } } #define UP "00^00\r\n00|00\r\n00000\r\n" #define DOWN "00000\r\n00|00\r\n00v00\r\n" #define LEFT "00000\r\n<--00\r\n00000\r\n" #define RIGHT "00000\r\n00-->\r\n00000\r\...
using CSFML.LibCSFML, Gtk.ShortNames, Colors, Graphics, Cairo mutable struct Joystick devnum::Int isconnected::Bool hasXaxis::Bool nbuttons::Int pressed::Vector{Bool} ypos::Int xpos::Int name::String Joystick(n, b=2, c=false, x=true) = new(n, c, x, b, fill(false, b), 0, 0) end co...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) co...
t = ([Any[Any[1, 2], Any[3, 4, 1], 5]]) p = ["Payload for (i, e) in enumerate(t) if e isa Number t[i] = p[e + 1] else for (j, f) in enumerate(e) if f isa Number e[j] = p[f + 1] else for (k, g) in enumerate(f) ...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iomanip> #include <iostream> #include <list> struct range { range(int lo, int hi) : low(lo), high(hi) {} int low; int high; }; std::ostream& operator<<(std::ostream& out, const range& r) { return out << r.low << '-' << r.high; } class ranges { public: ranges() {} ...
import Base.parse, Base.print, Base.reduce const RangeSequence = Array{UnitRange, 1} function combine!(seq::RangeSequence, r::UnitRange) isempty(seq) && return push!(seq, r) if r.start < seq[end].start reduce!(push!(seq, r)) elseif r.stop > seq[end].stop if r.start <= seq[end].stop + 1 ...