Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a language-to-language conversion: from C# to Julia, same semantics.
using System; class program { static void Main() { knapSack(40); var sw = System.Diagnostics.Stopwatch.StartNew(); Console.Write(knapSack(400) + "\n" + sw.Elapsed); Console.Read(); } static string knapSack(uint w1) { init(); change(); uint n = (ui...
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...
Port the provided C# code into Julia while preserving the original functionality.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)}; priva...
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 ...
Convert this C# snippet to Julia and keep its semantics consistent.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)}; priva...
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 ...
Change the programming language of this snippet from C# to Julia without modifying what it does.
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Mat...
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...
Port the provided C# code into Julia while preserving the original functionality.
XmlReader XReader; XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>")); XReader = XmlReader.Create("xmlfile.xml"); IXPathNavigable XDocument = new XPathDocument(XReader); XPathNavigator Nav = XDocument.CreateNavigator(); Nav = Nav.SelectSingleNode(" if(Nav.MoveToFirst()) { ...
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...
Convert this C# snippet to Julia and keep its semantics consistent.
using System; using System.Net; class Program { static void Main(string[] args) { var client = new WebClient(); client.Credentials = CredentialCache.DefaultCredentials; client.Credentials = new NetworkCredential("User", "Password"); var data = client.Download...
using HTTP, HTTP.IOExtras, JSON, MusicProcessing HTTP.open("POST", "http://music.com/play") do io write(io, JSON.json([ "auth" => "12345XXXX", "song_id" => 7, ])) r = startread(io) @show r.status while !eof(io) bytes = readavailable(io) play(bytes) end end
Convert the following code from C# to Julia, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.Linq; namespace RankingMethods { class Program { static void Main(string[] args) { Dictionary<string, int> scores = new Dictionary<string, int> { ["Solomon"] = 44, ["Jason"] = 42, ["Erro...
function ties{T<:Real}(a::Array{T,1}) unique(a[2:end][a[2:end] .== a[1:end-1]]) end
Write a version of this C# function in Julia with identical behavior.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace StraddlingCheckerboard { class Program { public readonly static IReadOnlyDictionary<char, string> val2Key; public readonly static IReadOnlyDictionary<string, char> key2Val; ...
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) ...
Write a version of this C# function in Julia with identical behavior.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
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 ...
Convert this C# snippet to Julia and keep its semantics consistent.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
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 functionally identical Julia code for the snippet given in C#.
using System.Diagnostics; namespace RC { internal class Program { public static void Main() { string sSource = "Sample App"; string sLog = "Application"; string sEvent = "Hello from RC!"; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);...
cmd = "eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\"" Base.run(`$cmd`)
Preserve the algorithm and functionality while converting the code from C# to Julia.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { Circle circle = ((3, -5), 3); Line[] lines = { ((-10, 11), (10, -9)), ((-10, 11), (-11, 12), true), ((3, -2), (7, -2)) }; Pri...
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...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, priva...
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...
Maintain the same structure and functionality when rewriting this code in Julia.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, priva...
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...
Translate this program into Julia but keep the logic exactly as in C#.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves...
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...
Port the provided C# code into Julia while preserving the original functionality.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves...
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.
using System; using System.Dynamic; class Example : DynamicObject { public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = null; Console.WriteLine("This is {0}.", binder.Name); return true; } } class Program { static void M...
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.
using System; using System.Collections.Generic; namespace SnakeAndLadder { class Program { private static Dictionary<int, int> snl = new Dictionary<int, int>() { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51,...
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) ...
Port the following code from C# to Julia with equivalent syntax and logic.
using System; using System.Collections.Generic; namespace SnakeAndLadder { class Program { private static Dictionary<int, int> snl = new Dictionary<int, int>() { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51,...
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) ...
Translate this program into Julia but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Linq; public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i...
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 ...
Port the following code from C# to Julia with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i...
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 ...
Rewrite this program in Julia while keeping its functionality equivalent to the C# version.
byte aByte = 2; short aShort = aByte; int anInt = aShort; long aLong = anInt; float aFloat = 1.2f; double aDouble = aFloat; BigInteger b = 5; Complex c = 2.5;
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) ...
Translate this program into Julia but keep the logic exactly as in C#.
byte aByte = 2; short aShort = aByte; int anInt = aShort; long aLong = anInt; float aFloat = 1.2f; double aDouble = aFloat; BigInteger b = 5; Complex c = 2.5;
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) ...
Write the same algorithm in Julia as shown in this C# implementation.
using System; using static System.Console; class Program { static bool[] np; static void ms(long lmt) { np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt; k += n) np[k] = true; } static bool is_Mag(long n) { lon...
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, ...
Write the same algorithm in Julia as shown in this C# implementation.
using System; using System.Numerics; namespace MersennePrimes { class Program { static BigInteger Sqrt(BigInteger x) { if (x < 0) throw new ArgumentException("Negative argument."); if (x < 2) return x; BigInteger y = x / 2; while (y > x / y) { ...
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))
Convert this C# block to Julia, preserving its control flow and logic.
using System; using System.Numerics; namespace MersennePrimes { class Program { static BigInteger Sqrt(BigInteger x) { if (x < 0) throw new ArgumentException("Negative argument."); if (x < 2) return x; BigInteger y = x / 2; while (y > x / y) { ...
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))
Produce a language-to-language conversion: from C# to Julia, same semantics.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TaxicabNumber { class Program { static void Main(string[] args) { IDictionary<long, IList<Tuple<int, int>>> taxicabNumbers = GetTaxicabNumbers(2006); PrintTaxicabNumbers(taxic...
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], (...
Keep all operations the same but rewrite the snippet in Julia.
using static System.Console; using static System.Linq.Enumerable; using System; public static class StrongAndWeakPrimes { public static void Main() { var primes = PrimeGenerator(10_000_100).ToList(); var strongPrimes = from i in Range(1, primes.Count - 2) where primes[i] > (primes[i-1] + primes[i+1...
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 -...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 2...
leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1) @show leftfactorial.(0:10) @show ndigits.(leftfactorial.(big.(1000:1000:10_000)))
Port the provided C# code into Julia while preserving the original functionality.
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 2...
leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1) @show leftfactorial.(0:10) @show ndigits.(leftfactorial.(big.(1000:1000:10_000)))
Write a version of this C# function in Julia with identical behavior.
using System; using System.Collections.Generic; using static System.Console; using System.Linq; using DT = System.DateTime; class Program { static void Main(string[] args) { string s; foreach (int lmt in new int[]{ 90, 300, 3000, 30000, 111000 }) { var pr = PG.Primes(lmt).Skip(1).ToList(); DT st = DT.Now; in...
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]] ...
Can you help me rewrite this code in Julia instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using static System.Console; using System.Linq; using DT = System.DateTime; class Program { static void Main(string[] args) { string s; foreach (int lmt in new int[]{ 90, 300, 3000, 30000, 111000 }) { var pr = PG.Primes(lmt).Skip(1).ToList(); DT st = DT.Now; in...
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 the given C# code snippet into Julia without altering its behavior.
using System; using BI = System.Numerics.BigInteger; class Program { static bool hmf(BI x) { if (x < 4) return x == 1; if ((x & 1) == 0 || x % 3 == 0) return true; int l = (int)Math.Sqrt((double)x); for (int j = 5, d = 4; j <= l; j += d = 6 - d) if (x % j == 0) return x > j; return f...
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...
Convert this C# block to Julia, preserving its control flow and logic.
using System; namespace MagicSquareDoublyEven { class Program { static void Main(string[] args) { int n = 8; var result = MagicSquareDoublyEven(n); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLengt...
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...
Port the following code from C# to Julia with equivalent syntax and logic.
using System; using static System.Console; class Program { const int mc = 103 * 1000 * 10000 + 11 * 9 + 1; static bool[] sv = new bool[mc + 1]; static void sieve() { int[] dS = new int[10000]; for (int a = 9, i = 9999; a >= 0; a--) for (int b = 9; b >= 0; b--) for (int c = 9, s = a + b; 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 ...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2; static void Main(string[] args) { bool[] found = new bool[MAX + 1]; bool[] a2b2 = new bool[MAX2 + 1]; int s = 3; for(int ...
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...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { const int maxSum = 100; var pairs = ( from X in 2.To(maxSum / 2 - 1) from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum) select ...
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 ÷ ...
Generate an equivalent Julia version of this C# code.
using System; using System.Linq; using static System.Console; class Program { static int nxtPrime(int x) { int j = 2; do { if (x % j == 0) { j = 2; x++; } else j += j < 3 ? 1 : 2; } while (j * j <= x); return x; } static void Main(string[] args) { WriteLine("working..."); int[] Nu...
using Primes println(nextprime.(maximum(hcat([5,45,23,21,67], [43,22,78,46,38], [9,98,12,54,53]), dims=2)))
Preserve the algorithm and functionality while converting the code from C# to Julia.
var prevIdle = 0f; var prevTotal = 0f; while (true) { var cpuLine = File .ReadAllLines("/proc/stat") .First() .Split(' ', StringSplitOptions.RemoveEmptyEntries) .Skip(1) .Select(float.Parse) .ToArray(); var idle = cpuLine[3]; var total = cpuLine.Sum(); ...
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 *...
Rewrite the snippet below in Julia so it works the same as the original C# code.
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); S...
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...
Keep all operations the same but rewrite the snippet in Julia.
using System; using System.Collections.Generic; class Program { static List<uint> sieve(uint max, bool ordinary = false) { uint k = ((max - 3) >> 1) + 1, lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1; var pl = new List<uint> { }; var ic = new bool[k]; for (u...
using Primes function isoneoddprime(n, base = 10) d = digits(n ÷ base, base = base) return n != 2 && all(iseven, d) end found = filter(isoneoddprime, primes(1000)) println("Found $(length(found)) primes with one odd digit in base 10:") foreach(p -> print(rpad(last(p), 5), first(p) % 9 == 0 ? "\n" : ""), enume...
Convert the following code from C# to Julia, ensuring the logic remains intact.
using System; using System.Collections.Generic; class Program { static List<uint> sieve(uint max, bool ordinary = false) { uint k = ((max - 3) >> 1) + 1, lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1; var pl = new List<uint> { }; var ic = new bool[k]; for (u...
using Primes function isoneoddprime(n, base = 10) d = digits(n ÷ base, base = base) return n != 2 && all(iseven, d) end found = filter(isoneoddprime, primes(1000)) println("Found $(length(found)) primes with one odd digit in base 10:") foreach(p -> print(rpad(last(p), 5), first(p) % 9 == 0 ? "\n" : ""), enume...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using static System.Console; using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class SafePrimes { public static void Main() { HashSet<int> primes = Primes(10_000_000).ToHashSet(); WriteLine("First 35 safe primes:"); WriteLine(string.J...
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...
Port the provided C# code into Julia while preserving the original functionality.
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; privat...
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
Convert this C# snippet to Julia and keep its semantics consistent.
using Mpir.NET; using System; using System.Collections.Generic; class MaxLftTrP_B { static void Main() { mpz_t p; var sw = System.Diagnostics.Stopwatch.StartNew(); L(3); for (uint b = 3; b < 13; b++) { sw.Restart(); p = L(b); Console.WriteLine("{0} {1,2} {...
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.
using SpeechLib; namespace Speaking_Computer { public class Program { private static void Main() { var voice = new SpVoice(); voice.Speak("This is an example of speech synthesis."); } } }
julia> a = "hello world" "hello world" julia> run(`espeak $a`)
Generate a Julia translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Numerics; namespace TonelliShanks { class Solution { private readonly BigInteger root1, root2; private readonly bool exists; public Solution(BigInteger root1, BigInteger root2, bool exists) { this.root1 = root1; ...
module TonelliShanks legendre(a, p) = powermod(a, (p - 1) ÷ 2, p) function solve(n::T, p::T) where T <: Union{Int, Int128, BigInt} legendre(n, p) != 1 && throw(ArgumentError("$n not a square (mod $p)")) local q::T = p - one(p) local s::T = 0 while iszero(q % 2) q ÷= 2 s += one(s) e...
Rewrite this program in Julia while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; using System.Numerics; namespace TonelliShanks { class Solution { private readonly BigInteger root1, root2; private readonly bool exists; public Solution(BigInteger root1, BigInteger root2, bool exists) { this.root1 = root1; ...
module TonelliShanks legendre(a, p) = powermod(a, (p - 1) ÷ 2, p) function solve(n::T, p::T) where T <: Union{Int, Int128, BigInt} legendre(n, p) != 1 && throw(ArgumentError("$n not a square (mod $p)")) local q::T = p - one(p) local s::T = 0 while iszero(q % 2) q ÷= 2 s += one(s) e...
Write the same algorithm in Julia as shown in this C# implementation.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; public class TruthTable { enum TokenType { Unknown, WhiteSpace, Constant, Operand, Operator, LeftParenthesis, RightParenthesis } readonly char trueConstant, falseConstant; readonly IDictionary<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 ...
Preserve the algorithm and functionality while converting the code from C# to Julia.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; public class TruthTable { enum TokenType { Unknown, WhiteSpace, Constant, Operand, Operator, LeftParenthesis, RightParenthesis } readonly char trueConstant, falseConstant; readonly IDictionary<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 ...
Rewrite the snippet below in Julia so it works the same as the original C# code.
using System; namespace RosettaCode.SetOfRealNumbers { public class Set<TValue> { public Set(Predicate<TValue> contains) { Contains = contains; } public Predicate<TValue> Contains { get; private set; } public Set<TVal...
""" 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...
Change the following C# code into Julia without altering its purpose.
using System; namespace RosettaCode.SetOfRealNumbers { public class Set<TValue> { public Set(Predicate<TValue> contains) { Contains = contains; } public Predicate<TValue> Contains { get; private set; } public Set<TVal...
""" 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...
Change the following C# code into Julia without altering its purpose.
using System; using System.Collections.Generic; using BI = System.Numerics.BigInteger; using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>; using static System.Console; class Program { struct LI { public UInt64 lo, ml, mh, hi, tp; } const UInt64 Lm = 1_000_000_000_000_000_000UL; ...
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...
Translate this program into Julia but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using BI = System.Numerics.BigInteger; using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>; using static System.Console; class Program { struct LI { public UInt64 lo, ml, mh, hi, tp; } const UInt64 Lm = 1_000_000_000_000_000_000UL; ...
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...
Produce a language-to-language conversion: from C# to Julia, same semantics.
using System; namespace RosettaMaybe { public abstract class Maybe<T> { public sealed class Some : Maybe<T> { public Some(T value) => Value = value; public T Value { get; } } public sealed class None : Maybe<T> { } } class Program { ...
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)))
Can you help me rewrite this code in Julia instead of C#, keeping it the same logically?
using System; using System.Drawing; using System.Windows.Forms; class MineFieldModel { public int RemainingMinesCount{ get{ var count = 0; ForEachCell((i,j)=>{ if (Mines[i,j] && !Marked[i,j]) count++; }); return count; ...
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) ...
Generate a Julia translation of this C# snippet without changing its computational steps.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this ...
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...
Change the programming language of this snippet from C# to Julia without modifying what it does.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this ...
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...
Rewrite the snippet below in Julia so it works the same as the original C# code.
using System; using System.Reflection; public class Rosetta { public static void Main() { BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; foreach (var method in typeof(...
methods(methods) methods(println)
Convert this C# snippet to Julia and keep its semantics consistent.
using System; class Example { public int foo(int x) { return 42 + x; } } class Program { static void Main(string[] args) { var example = new Example(); var method = "foo"; var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5...
const functions = Dict{String,Function}( "foo" => x -> 42 + x, "bar" => x -> 42 * x) @show functions["foo"](3) @show functions["bar"](3)
Transform the following C# implementation into Julia, maintaining the same output and logic.
using System; using System.Net; using System.Linq; public class Program { public static void Main() { string[] tests = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", ...
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) =...
Rewrite this program in Julia while keeping its functionality equivalent to the C# version.
using System; using System.Net; using System.Linq; public class Program { public static void Main() { string[] tests = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", ...
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) =...
Change the programming language of this snippet from C# to Julia without modifying what it does.
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } ...
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 /...
Please provide an equivalent version of this C# code in Julia.
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } ...
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.
using System; using System.Collections.Generic; using System.Linq; public static class LongPrimes { public static void Main() { var primes = SomePrimeGenerator.Primes(64000).Skip(1).Where(p => Period(p) == p - 1).Append(99999); Console.WriteLine(string.Join(" ", primes.TakeWhile(p => p <= 500))); ...
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 ...
Translate this program into Julia but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public B...
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::...
Rewrite the snippet below in Julia so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public B...
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::...
Generate a Julia translation of this C# snippet without changing its computational steps.
using System; public class Program { public static double[][] legeCoef(int N) { double[][] lcoef = new double[N+1][]; for (int i=0; i < lcoef.Length; ++i) lcoef[i] = new double[N+1]; lcoef[0][0] = lcoef[1][1] = 1; for (int n = 2; n <= N...
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
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<long> primes = new List<long>() { 3, 5 }; static void Main(string[] args) { const int cutOff = 200; const int bigUn = 100000; const int chunks = 50; const int little = big...
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 ...
Produce a language-to-language conversion: from C# to Julia, same semantics.
using System.Diagnostics; using System.Drawing; namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600); var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), ...
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 ...
Generate an equivalent Julia version of this C# code.
using System.Diagnostics; using System.Drawing; namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600); var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), ...
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.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; using static System.Linq.Enumerable; namespace WorldCupGroupStage { public static class WorldCupGroupStage { static int[][] _histogram; static WorldCupGroupStage() { ...
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,...
Convert the following code from C# to Julia, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (str...
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)) != "(" ...
Write the same code in Julia as shown below in C#.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordina...
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(...
Convert this C# block to Julia, preserving its control flow and logic.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordina...
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(...
Please provide an equivalent version of this C# code in Julia.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", ...
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...
Translate the given C# code snippet into Julia without altering its behavior.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", ...
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...
Translate the given C# code snippet into Julia without altering its behavior.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) {...
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 ...
Convert this C# block to Julia, preserving its control flow and logic.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) {...
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 ...
Rewrite the snippet below in Julia so it works the same as the original C# code.
using System; class Program { static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; } static ...
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...
Rewrite this program in Julia while keeping its functionality equivalent to the C# version.
using System; class Program { static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; } static ...
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...
Change the following C# code into Julia without altering its purpose.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ...
using Primes function legendre(n, p) if p != 2 && isprime(p) x = powermod(BigInt(n), div(p - 1, 2), p) return x == 0 ? 0 : x == 1 ? 1 : -1 end return -1 end function cipolla(n, p) if legendre(n, p) != 1 return NaN end a, w2 = BigInt(0), BigInt(0) while true ...
Preserve the algorithm and functionality while converting the code from C# to Julia.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ...
using Primes function legendre(n, p) if p != 2 && isprime(p) x = powermod(BigInt(n), div(p - 1, 2), p) return x == 0 ? 0 : x == 1 ? 1 : -1 end return -1 end function cipolla(n, p) if legendre(n, p) != 1 return NaN end a, w2 = BigInt(0), BigInt(0) while true ...
Please provide an equivalent version of this C# code in Julia.
using System; using System.Collections.Generic; using System.Numerics; namespace PierpontPrimes { public static class Helper { private static readonly Random rand = new Random(); private static readonly List<int> primeList = new List<int>() { 2, 3, 5, 7, 11, 13, 17, 19, 23,...
using Primes function pierponts(N, firstkind = true) ret, incdec = BigInt[], firstkind ? 1 : -1 for k2 in 0:10000, k3 in 0:k2, switch in false:true i, j = switch ? (k3, k2) : (k2, k3) n = BigInt(2)^i * BigInt(3)^j + incdec if isprime(n) && !(n in ret) push!(ret, n) ...
Translate the given C# code snippet into Julia without altering its behavior.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; namespace NSmooth { class Program { static readonly List<BigInteger> primes = new List<BigInteger>(); static readonly List<int> smallPrimes = new List<int>(); static Program() { primes.Add...
using Primes function nsmooth(N, needed) nexts, smooths = [BigInt(i) for i in 2:N if isprime(i)], [BigInt(1)] prim, count = deepcopy(nexts), 1 indices = ones(Int, length(nexts)) while count < needed x = minimum(nexts) push!(smooths, x) count += 1 for j in 1:length(nexts)...
Rewrite the snippet below in Julia so it works the same as the original C# code.
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class Rosetta { static void Main() { foreach ((int x, int n) in new [] { (99809, 1), (18, 2), (19, 3), (20, 4), (2017,...
using Primes, Combinatorics function primepartition(x::Int64, n::Int64) if n == oftype(n, 1) return isprime(x) ? [x] : Int64[] else for combo in combinations(primes(x), n) if sum(combo) == x return combo end end end return Int64[] end for...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; using System.Text; namespace ZeckendorfArithmetic { class Zeckendorf : IComparable<Zeckendorf> { private static readonly string[] dig = { "00", "01", "10" }; private static readonly string[] dig1 = { "", "1", "10" }; private int dVal = 0; private int dLen = 0; ...
import Base.*, Base.+, Base.-, Base./, Base.show, Base.!=, Base.==, Base.<=, Base.<, Base.>, Base.>=, Base.divrem const z0 = "0" const z1 = "1" const flipordered = (z1 < z0) mutable struct Z s::String end Z() = Z(z0) Z(z::Z) = Z(z.s) pairlen(x::Z, y::Z) = max(length(x.s), length(y.s)) tolen(x::Z, n::Int) = (s = x.s;...
Change the programming language of this snippet from C# to Julia without modifying what it does.
using System; using System.Collections.Generic; using System.Linq; namespace LineSimplification { using Point = Tuple<double, double>; class Program { static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.Item1 - lineStart.Item1; do...
const Point = Vector{Float64} function perpdist(pt::Point, lnstart::Point, lnend::Point) d = normalize!(lnend .- lnstart) pv = pt .- lnstart pvdot = dot(d, pv) ds = pvdot .* d return norm(pv .- ds) end function rdp(plist::Vector{Point}, ϵ::Float64 = 1.0) if length(plist) < 2 ...
Produce a language-to-language conversion: from C# to Julia, same semantics.
using System; using System.Collections.Generic; using System.Linq; namespace LineSimplification { using Point = Tuple<double, double>; class Program { static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.Item1 - lineStart.Item1; do...
const Point = Vector{Float64} function perpdist(pt::Point, lnstart::Point, lnend::Point) d = normalize!(lnend .- lnstart) pv = pt .- lnstart pvdot = dot(d, pv) ds = pvdot .* d return norm(pv .- ds) end function rdp(plist::Vector{Point}, ϵ::Float64 = 1.0) if length(plist) < 2 ...
Port the provided C# code into Julia while preserving the original functionality.
using System; using System.Drawing; namespace BilinearInterpolation { class Program { private static float Lerp(float s, float e, float t) { return s + (e - s) * t; } private static float Blerp(float c00, float c10, float c01, float c11, float tx, float ty) { return...
using Images, FileIO, Interpolations function enlarge(A::Matrix, factor::AbstractFloat) lx, ly = size(A) nx, ny = round.(Int, factor .* (lx, ly)) vx, vy = LinRange(1, lx, nx), LinRange(1, ly, ny) itp = interpolate(A, BSpline(Linear())) return itp(vx, vy) end A = load("data/lenna100.jpg") |> Matr...
Change the programming language of this snippet from C# to Julia without modifying what it does.
using System; using System.Drawing; namespace BilinearInterpolation { class Program { private static float Lerp(float s, float e, float t) { return s + (e - s) * t; } private static float Blerp(float c00, float c10, float c01, float c11, float tx, float ty) { return...
using Images, FileIO, Interpolations function enlarge(A::Matrix, factor::AbstractFloat) lx, ly = size(A) nx, ny = round.(Int, factor .* (lx, ly)) vx, vy = LinRange(1, lx, nx), LinRange(1, ly, ny) itp = interpolate(A, BSpline(Linear())) return itp(vx, vy) end A = load("data/lenna100.jpg") |> Matr...
Write a version of this C# function in Julia with identical behavior.
using System; using System.Collections.Generic; using System.Linq; namespace RosettaVectors { public class Vector { public double[] store; public Vector(IEnumerable<double> init) { store = init.ToArray(); } public Vector(double x, double y) { ...
module SpatialVectors export SpatialVector struct SpatialVector{N, T} coord::NTuple{N, T} end SpatialVector(s::NTuple{N,T}, e::NTuple{N,T}) where {N,T} = SpatialVector{N, T}(e .- s) function SpatialVector(∠::T, val::T) where T θ = atan(∠) x = val * cos(θ) y = val * sin(θ) return SpatialVector...
Maintain the same structure and functionality when rewriting this code in Julia.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chebyshev { class Program { struct ChebyshevApprox { public readonly List<double> coeffs; public readonly Tuple<double, double> domain; public C...
mutable struct Cheb c::Vector{Float64} min::Float64 max::Float64 end function Cheb(min::Float64, max::Float64, ncoeff::Int, nnodes::Int, fn::Function)::Cheb c = Cheb(Vector{Float64}(ncoeff), min, max) f = Vector{Float64}(nnodes) p = Vector{Float64}(nnodes) z = (max + min) / 2 r = (max -...
Translate this program into Julia but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Linq; namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03; private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --...
bwsort(vec) = sort(vec, lt = (a, b) -> string(a) < string(b)) function burrowswheeler_encode(s) if match(r"\x02|\x03", s) != nothing throw("String for Burrows-Wheeler input cannot contain STX or ETX") end s = "\x02" * s * "\x03" String([t[end] for t in bwsort([circshift([c for c in s], n) for n...
Can you help me rewrite this code in Julia instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using System.Linq; namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03; private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --...
bwsort(vec) = sort(vec, lt = (a, b) -> string(a) < string(b)) function burrowswheeler_encode(s) if match(r"\x02|\x03", s) != nothing throw("String for Burrows-Wheeler input cannot contain STX or ETX") end s = "\x02" * s * "\x03" String([t[end] for t in bwsort([circshift([c for c in s], n) for n...
Port the following code from C# to Julia with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CardShuffles { public static class Helper { public static string AsString<T>(this ICollection<T> c) { StringBuilder sb = new StringBuilder("["); sb.Append(string.Join(", ", c)); ...
function riffleshuffle!(list::Vector, flips::Integer) len = length(list) llist = similar(list, len÷2 + fld(len, 10)) rlist = similar(list, len÷2 + fld(len, 10)) for _ in Base.OneTo(flips) cut = len ÷ 2 + rand(-1:2:1) * rand(0:fld(len, 10)) copy!(llist, 1,...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CardShuffles { public static class Helper { public static string AsString<T>(this ICollection<T> c) { StringBuilder sb = new StringBuilder("["); sb.Append(string.Join(", ", c)); ...
function riffleshuffle!(list::Vector, flips::Integer) len = length(list) llist = similar(list, len÷2 + fld(len, 10)) rlist = similar(list, len÷2 + fld(len, 10)) for _ in Base.OneTo(flips) cut = len ÷ 2 + rand(-1:2:1) * rand(0:fld(len, 10)) copy!(llist, 1,...
Translate this program into Julia but keep the logic exactly as in C#.
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { ...
function bernoulli(n) A = Vector{Rational{BigInt}}(undef, n + 1) for i in 0:n A[i + 1] = 1 // (i + 1) for j = i:-1:1 A[j] = j * (A[j] - A[j + 1]) end end return n == 1 ? -A[1] : A[1] end function faulhabercoeffs(p) coeffs = Vector{Rational{BigInt}}(undef, p + 1) ...
Change the programming language of this snippet from C# to Julia without modifying what it does.
using System; namespace FaulhabersFormula { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { ...
module Faulhaber function bernoulli(n::Integer) n ≥ 0 || throw(DomainError(n, "n must be a positive-or-0 number")) a = fill(0 // 1, n + 1) for m in 1:n a[m] = 1 // (m + 1) for j in m:-1:2 a[j - 1] = (a[j - 1] - a[j]) * j end end return ifelse(n != 1, a[1], -a[1])...
Port the provided C# code into Julia while preserving the original functionality.
using System; namespace PrimeConspiracy { class Program { static void Main(string[] args) { const int limit = 1_000_000; const int sieveLimit = 15_500_000; int[,] buckets = new int[10, 10]; int prevDigit = 2; bool[] notPrime = Sieve(sieveLimit); ...
using Printf, Primes using DataStructures function counttransitions(upto::Integer) cnt = counter(Pair{Int,Int}) tot = 0 prv, nxt = 2, 3 while nxt ≤ upto push!(cnt, prv % 10 => nxt % 10) prv = nxt nxt = nextprime(nxt + 1) tot += 1 end return sort(Dict(cnt)), tot -...