Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the following code from C# to Julia with equivalent syntax and logic. | using System;
using System.Linq;
using System.Text;
namespace ImaginaryBaseNumbers {
class Complex {
private double real, imag;
public Complex(int r, int i) {
real = r;
imag = i;
}
public Complex(double r, double i) {
real = r;
imag ... | import Base.show, Base.parse, Base.+, Base.-, Base.*, Base./, Base.^
function inbase4(charvec::Vector)
if (!all(x -> x in ['-', '0', '1', '2', '3', '.'], charvec)) ||
((x = findlast(x -> x == '-', charvec)) != nothing && x > findfirst(x -> x != '-', charvec)) ||
((x = findall(x -> x == '.', charvec... |
Generate a Julia translation of this C# snippet without changing its computational steps. | using System;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Statistics;
class Program
{
static void RunNormal(int sampleSize)
{
double[] X = new double[sampleSize];
var norm = new Normal(new Random());
norm.Samples(X);
const int numBuckets = 10;
var histo... | using Printf, Distributions, Gadfly
data = rand(Normal(0, 1), 1000)
@printf("N = %i\n", length(data))
@printf("μ = %2.2f\tσ = %2.2f\n", mean(data), std(data))
@printf("range = (%2.2f, %2.2f\n)", minimum(data), maximum(data))
h = plot(x=data, Geom.histogram)
draw(PNG("norm_hist.png", 10cm, 10cm), h)
|
Produce a functionally identical Julia code for the snippet given in C#. | using System;
using System.Collections.Generic;
using static System.Console;
class Program {
static string B10(int n) {
int[] pow = new int[n + 1], val = new int[29];
for (int count = 0, ten = 1, x = 1; x <= n; x++) {
val[x] = ten;
for (int j = 0, t; j <= n; j++)
if (pow[j] != 0 && pow... | function B10(n)
for i in Int128(1):typemax(Int128)
q, b10, place = i, zero(Int128), one(Int128)
while q > 0
q, r = divrem(q, 2)
if r != 0
b10 += place
end
place *= 10
end
if b10 % n == 0
return b10
en... |
Translate the given C# code snippet into Julia without altering its behavior. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WeirdNumbers {
class Program {
static List<int> Divisors(int n) {
List<int> divs = new List<int> { 1 };
List<int> divs2 = new List<int>();
for (... | using Primes
function nosuchsum(revsorted, num)
if sum(revsorted) < num
return true
end
for (i, n) in enumerate(revsorted)
if n > num
continue
elseif n == num
return false
elseif !nosuchsum(revsorted[i+1:end], num - n)
return false
... |
Translate this program into Julia but keep the logic exactly as in C#. | using System;
using System.Collections.Generic;
namespace PeacefulChessQueenArmies {
using Position = Tuple<int, int>;
enum Piece {
Empty,
Black,
White
}
class Program {
static bool IsAttacking(Position queen, Position pos) {
return queen.Item1 == pos.Item1... | using Gtk
struct Position
row::Int
col::Int
end
function place!(numeach, bsize, bqueens, wqueens)
isattack(q, pos) = (q.row == pos.row || q.col == pos.col ||
abs(q.row - pos.row) == abs(q.col - pos.col))
noattack(qs, pos) = !any(x -> isattack(x, pos), qs)
positionopen(bqs, ... |
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.Runtime.CompilerServices;
namespace ReadlineInterface {
class Program {
static LinkedList<string> histArr = new LinkedList<string>();
static void AppendHistory([CallerMemberName] string name = "unknown") {
histArr.AddLast(nam... | function input(prompt::AbstractString)
print(prompt)
r = readline(STDIN)
if isempty(r) || r == "quit"
println("bye.")
elseif r == "help"
println("commands: ls, cat, quit")
elseif r ∈ ("ls", "cat")
println("command `$r` not implemented yet")
else
println("Yes...?"... |
Translate the given C# code snippet into Julia without altering its behavior. | using System;
namespace AdditionChains {
class Program {
static int[] Prepend(int n, int[] seq) {
int[] result = new int[seq.Length + 1];
Array.Copy(seq, 0, result, 1, seq.Length);
result[0] = n;
return result;
}
static Tuple<int, int> CheckS... | checksequence(pos, seq, n, minlen) =
pos > minlen || seq[1] > n ? (minlen, 0) :
seq[1] == n ? (pos, 1) :
pos < minlen ? trypermutation(0, pos, seq, n, minlen) : (minlen, 0)
function trypermutation(i, pos, seq, n, minlen)
if i > pos
return minlen, 0
end
res1 = checksequence(pos + 1, push... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.Linq;
namespace JustInTimeProcessing {
struct UserInput {
public UserInput(string ff, string lf, string tb, string sp) {
FormFeed = (char)int.Parse(ff);
LineFeed = (char)int.Parse(lf);
Tab = (char)int.Parse(tb)... | @enum streamstate GET_FF GET_LF GET_TAB GET_CHAR ABORT
chars = Dict(GET_FF => ['\f'], GET_LF => ['\n'], GET_TAB => ['\t'])
function stream_decode_jit(iostream)
msg, state, ffcount, lfcount, tabcount, charcount = "", GET_FF, 0, 0, 0, 0
while true
if state == ABORT || eof(iostream)
return msg... |
Rewrite this program in Julia while keeping its functionality equivalent to the C# version. | using System;
using System.Numerics;
namespace MontgomeryReduction {
public static class Helper {
public static int BitLength(this BigInteger v) {
if (v < 0) {
v *= -1;
}
int result = 0;
while (v > 0) {
v >>= 1;
... | """ base 2 type Montgomery numbers """
struct Montgomery2
m::BigInt
n::Int64
rrm::BigInt
end
function Montgomery2(x::BigInt)
bitlen = length(string(x, base=2))
r = (x == 0) ? 0 : (BigInt(1) << (bitlen * 2)) % x
Montgomery2(x, bitlen, r)
end
Montgomery2(n) = Montgomery2(BigInt(n))
function redu... |
Produce a functionally identical Julia code for the snippet given in C#. | using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SokobanSolver
{
public class SokobanSolver
{
private class Board
{
public string Cur { get; internal set; }
public string Sol { get; internal set; }
public int X { get; internal... | struct BoardState
board::String
csol::String
position::Int
end
function move(s::BoardState, dpos)
buffer = Vector{UInt8}(deepcopy(s.board))
if s.board[s.position] == '@'
buffer[s.position] = ' '
else
buffer[s.position] = '.'
end
newpos = s.position + dpos
if s.board[... |
Produce a language-to-language conversion: from C# to Julia, same semantics. | using System;
using System.Collections.Generic;
using System.Linq;
namespace ZumkellerNumbers {
class Program {
static List<int> GetDivisors(int n) {
List<int> divs = new List<int> {
1, n
};
for (int i = 2; i * i <= n; i++) {
if (n % i == ... | using Primes
function factorize(n)
f = [one(n)]
for (p, x) in factor(n)
f = reduce(vcat, [f*p^i for i in 1:x], init=f)
end
f
end
function cansum(goal, list)
if goal == 0 || list[1] == goal
return true
elseif length(list) > 1
if list[1] > goal
return cansum(... |
Write a version of this C# function in Julia with identical behavior. | using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using UI = System.UInt64;
using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;
using Lst = System.Collections.Generic.List<sbyte>;
using DT = System.DateTime;
class Program {
const sbyte... | using Formatting, Printf
struct Term
coeff::UInt64
ix1::Int8
ix2::Int8
end
function toUInt64(dgits, reverse)
return reverse ? foldr((i, j) -> i + 10j, UInt64.(dgits)) :
foldl((i, j) -> 10i + j, UInt64.(dgits))
end
function issquare(n)
if 0x202021202030213 & (1 << (UInt64(n) &... |
Write the same code in Julia as shown below in C#. | using System;
using System.Collections.Generic;
namespace SuffixTree {
class Node {
public string sub;
public List<int> ch = new List<int>();
public Node() {
sub = "";
}
public Node(string sub, params int[] children) {
this.sub... | import Base.print
mutable struct Node
sub::String
ch::Vector{Int}
Node(str, v=Int[]) = new(str, v)
end
struct SuffixTree
nodes::Vector{Node}
function SuffixTree(s::String)
nod = [Node("", Int[])]
for i in 1:length(s)
addSuffix!(nod, s[i:end])
end
return ... |
Write the same code in Julia as shown below in C#. | using System;
using System.Collections.Generic;
namespace SuffixTree {
class Node {
public string sub;
public List<int> ch = new List<int>();
public Node() {
sub = "";
}
public Node(string sub, params int[] children) {
this.sub... | import Base.print
mutable struct Node
sub::String
ch::Vector{Int}
Node(str, v=Int[]) = new(str, v)
end
struct SuffixTree
nodes::Vector{Node}
function SuffixTree(s::String)
nod = [Node("", Int[])]
for i in 1:length(s)
addSuffix!(nod, s[i:end])
end
return ... |
Port the provided C# code into Julia while preserving the original functionality. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class Reflection
{
public static void Main() {
var t = new TestClass();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var prop in GetPropert... | for obj in (Int, 1, 1:10, collect(1:10), now())
println("\nObject: $obj\nDescription:")
dump(obj)
end
|
Transform the following C# implementation into Julia, maintaining the same output and logic. | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
t... | mutable struct Node
edges::Dict{Char, Node}
link::Union{Node, Missing}
sz::Int
Node() = new(Dict(), missing, 0)
end
sizednode(x) = (n = Node(); n.sz = x; n)
function eertree(str)
nodes = Vector{Node}()
oddroot = sizednode(-1)
evenroot = sizednode(0)
oddroot.link = evenroot
evenroot... |
Preserve the algorithm and functionality while converting the code from C# to Julia. | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
t... | mutable struct Node
edges::Dict{Char, Node}
link::Union{Node, Missing}
sz::Int
Node() = new(Dict(), missing, 0)
end
sizednode(x) = (n = Node(); n.sz = x; n)
function eertree(str)
nodes = Vector{Node}()
oddroot = sizednode(-1)
evenroot = sizednode(0)
oddroot.link = evenroot
evenroot... |
Produce a language-to-language conversion: from C# to Julia, same semantics. | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
cons... | const alpha = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
function encodebase58(hsh::AbstractString, base::Integer=16)
x = if base == 16 && hsh[1:2] == "0x" parse(BigInt, hsh[3:end], 16)
else parse(BigInt, hsh, base) end
sb = IOBuffer()
while x > 0
x, r = divrem(x, 58)
... |
Translate the given C# code snippet into Julia without altering its behavior. | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
cons... | const alpha = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
function encodebase58(hsh::AbstractString, base::Integer=16)
x = if base == 16 && hsh[1:2] == "0x" parse(BigInt, hsh[3:end], 16)
else parse(BigInt, hsh, base) end
sb = IOBuffer()
while x > 0
x, r = divrem(x, 58)
... |
Transform the following C# implementation into Julia, maintaining the same output and logic. | using System;
using System.Collections.Generic;
using System.Linq;
namespace LatinSquares {
using matrix = List<List<int>>;
class Program {
static void Swap<T>(ref T a, ref T b) {
var t = a;
a = b;
b = t;
}
static matrix DList(int n, int start) {
... | using Combinatorics
clash(row2, row1::Vector{Int}) = any(i -> row1[i] == row2[i], 1:length(row2))
clash(row, rows::Vector{Vector{Int}}) = any(r -> clash(row, r), rows)
permute_onefixed(i, n) = map(vec -> vcat(i, vec), permutations(filter(x -> x != i, 1:n)))
filter_permuted(rows, i, n) = filter(v -> !clash(v, rows),... |
Can you help me rewrite this code in Julia instead of C#, keeping it the same logically? | using System;
using System.Collections.Generic;
class Node
{
public enum Colors
{
Black, White, Gray
}
public Colors color { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
color = Colors.White;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>> A... | function korasaju(g::Vector{Vector{T}}) where T<:Integer
vis = falses(length(g))
L = Vector{T}(length(g))
x = length(L) + 1
t = collect(T[] for _ in eachindex(g))
function visit(u::T)
if !vis[u]
vis[u] = true
for v in g[u]
visit(v)
... |
Keep all operations the same but rewrite the snippet in Julia. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Wordseach
{
static class Program
{
readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
class Grid
{
... | using Random
const stepdirections = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
const nrows = 10
const ncols = nrows
const gridsize = nrows * ncols
const minwords = 25
const minwordsize = 3
mutable struct LetterGrid
nattempts::Int
nrows::Int
ncols::Int
cells::Matrix{Ch... |
Maintain the same structure and functionality when rewriting this code in Julia. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MarkovChainTextGenerator {
class Program {
static string Join(string a, string b) {
return a + " " + b;
}
static string Markov(string filePath, int keySize, int outputSize) {
... | function markovtext(txt::AbstractString, klen::Integer, maxchlen::Integer)
words = matchall(r"\w+", txt)
dict = Dict()
for i in 1:length(words)-klen
k = join(words[i:i+klen-1], " ")
v = words[i+klen]
if haskey(dict, k)
dict[k] = push!(dict[k], v)
else
... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace AruthmeticCoding {
using Freq = Dictionary<char, long>;
using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;
class Program {
static Freq CumulativeFreq(Freq freq) {
... | function charfreq(s)
d = Dict()
for c in s
if haskey(d, c)
d[c] += 1
else
d[c] = 1
end
end
d
end
function charcumfreq(dfreq)
lastval = 0
d = Dict()
for c in sort!(collect(keys(dfreq)))
d[c] = lastval
lastval += dfreq[c]
end... |
Write the same algorithm in Julia as shown in this C# implementation. | using System;
using System.Text;
namespace GeometricAlgebra {
struct Vector {
private readonly double[] dims;
public Vector(double[] da) {
dims = da;
}
public static Vector operator -(Vector v) {
return v * -1.0;
}
public static Vector oper... | using GeometryTypes
import Base.*
CliffordVector = Point{32, Float64}
e(n) = (v = zeros(32); v[(1 << n) + 1] = 1.0; CliffordVector(v))
randommultivector() = CliffordVector(rand(32))
randomvector() = sum(i -> rand() * e(i), 0:4)
bitcount(n) = (count = 0; while n != 0 n &= n - 1; count += 1 end; count)
function reo... |
Generate an equivalent Julia version of this C# code. | using System;
namespace ParticleSwarmOptimization {
public struct Parameters {
public double omega, phip, phig;
public Parameters(double omega, double phip, double phig) : this() {
this.omega = omega;
this.phip = phip;
this.phig = phig;
}
}
publ... | using Optim
const mcclow = [-1.5, -3.0]
const mccupp = [4.0, 4.0]
const miclow = [0.0, 0.0]
const micupp = Float64.([pi, pi])
const npar = [100, 1000]
const x0 = [0.0, 0.0]
michalewicz(x, m=10) = -sum(i -> sin(x[i]) * (i * sin( x[i]^2/pi))^(2*m), 1:length(x))
mccormick(x) = sin(x[1] + x[2]) + (x[1] - x[2])^2 - 1.5 *... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using System;
class Program {
const long Lm = (long)1e18;
const string Fm = "D18";
struct LI { public long lo, ml, mh, hi, tp; }
static void inc(ref LI d, LI s) {
if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
if ((d.... | using Memoize
function partDiffDiff(n::Int)::Int
isodd(n) ? (n+1)÷2 : n+1
end
@memoize function partDiff(n::Int)::Int
n<2 ? 1 : partDiff(n-1)+partDiffDiff(n-1)
end
@memoize function partitionsP(n::Int)
T=BigInt
if n<2
one(T)
else
psum = zero(T)
for i ∈ 1:n
pd =... |
Can you help me rewrite this code in Julia instead of C#, keeping it the same logically? | using System;
namespace SpecialDivisors {
class Program {
static int Reverse(int n) {
int result = 0;
while (n > 0) {
result = 10 * result + n % 10;
n /= 10;
}
return result;
}
static void Main() {
... | 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 f[1:end-1]
end
function isspecialdivisor(n)::Bool
isprime(n) && return true
nreverse = evalpoly(10, reverse(digits(n)))
for d in divisors(n)
dreve... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyntheticDivision
{
class Program
{
static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
{
List<int> output = dividend.ToList();
int normalizer = divisor... | function divrem(dividend::Vector, divisor::Vector)
result = copy(dividend)
quotientlen = length(divisor) - 1
for i in 1:length(dividend)-quotientlen
if result[i] != 0
result[i] /= divisor[1]
for j in 1:quotientlen
result[i + j] -= divisor[j + 1] * result[i]
... |
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 SyntheticDivision
{
class Program
{
static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
{
List<int> output = dividend.ToList();
int normalizer = divisor... | function divrem(dividend::Vector, divisor::Vector)
result = copy(dividend)
quotientlen = length(divisor) - 1
for i in 1:length(dividend)-quotientlen
if result[i] != 0
result[i] /= divisor[1]
for j in 1:quotientlen
result[i + j] -= divisor[j + 1] * result[i]
... |
Change the programming language of this snippet from C# to Julia without modifying what it does. |
public MainWindow()
{
InitializeComponent();
RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);
imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);
DrawHue(100);
}
void DrawHue(int saturation)
{
var bmp = (WriteableBitmap)imgMain.Source;... | using Gtk, Graphics, Colors
const win = GtkWindow("Color Wheel", 450, 450) |> (const can = @GtkCanvas())
set_gtk_property!(can, :expand, true)
@guarded draw(can) do widget
ctx = getgc(can)
h = height(can)
w = width(can)
center = (x = w / 2, y = h / 2)
anglestep = 1/w
for θ in 0:0.1:360
... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
class Program
{
static string fmt(int[] a)
{
var sb = new System.Text.StringBuilder();
for (int i = 0; i < a.Length; i++)
sb.Append(string.Format("{0,5}{1}",
a[i], i % 10 ==... | """
The sieve of Sundaram is a simple deterministic algorithm for finding all the
prime numbers up to a specified integer. This function is modified from the
Python example Wikipedia entry wiki/Sieve_of_Sundaram, to give primes to the
nth prime rather than the Wikipedia function that gives primes less than n.
"""
funct... |
Rewrite this program in Julia while keeping its functionality equivalent to the C# version. | using System.Linq;
using System.Collections.Generic;
using TG = System.Tuple<int, int>;
using static System.Console;
class Program
{
static void Main(string[] args)
{
const int mil = (int)1e6;
foreach (var amt in new int[] { 1, 2, 6, 12, 18 })
{
int lmt = mil * amt, lg = 0, ... | using Primes
function primediffseqs(maxnum = 1_000_000)
mprimes = primes(maxnum)
diffs = map(p -> mprimes[p[1] + 1] - p[2], enumerate(@view mprimes[begin:end-1]))
incstart, decstart, bestinclength, bestdeclength = 1, 1, 0, 0
for i in 1:length(diffs)-1
foundinc, founddec = false, false
f... |
Write a version of this C# function in Julia with identical behavior. | using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class Test
{
public static void Main()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, "http:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc... | using LightXML
const Xptr = LightXML.Xptr
function validate(url::String, schemafile::String)
ctxt = ccall((:xmlSchemaNewParserCtxt, LightXML.libxml2), Xptr, (Cstring,), schemafile)
ctxt != C_NULL || throw(LightXML.XMLNoRootError())
schema = ccall((:xmlSchemaParse, LightXML.libxml2), Xptr, (Xptr,), ctxt)
... |
Maintain the same structure and functionality when rewriting this code in Julia. | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static stri... | using Formatting
import Base.iterate, Base.IteratorSize, Base.IteratorEltype, Base.Iterators.take
const metallicnames = ["Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel",
"Aluminium", "Iron", "Tin", "Lead"]
struct Lucas b::Int end
Base.IteratorSize(s::Lucas) = Base.IsInfinite()
Base.IteratorEltype(s::... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static stri... | using Formatting
import Base.iterate, Base.IteratorSize, Base.IteratorEltype, Base.Iterators.take
const metallicnames = ["Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel",
"Aluminium", "Iron", "Tin", "Lead"]
struct Lucas b::Int end
Base.IteratorSize(s::Lucas) = Base.IsInfinite()
Base.IteratorEltype(s::... |
Preserve the algorithm and functionality while converting the code from C# to Julia. | using System;
using System.Runtime.InteropServices;
static unsafe class Program
{
ref struct LinkedListNode
{
public int Value;
public LinkedListNode* Next;
public override string ToString() => this.Value + (this.Next == null ? string.Empty : " -> " + this.Next->ToString());
}
... | function Base.deleteat!(ll::LinkedList, index::Integer)
if isempty(ll) throw(BoundsError()) end
if index == 1
ll.head = ll.head.next
else
nd = ll.head
index -= 1
while index > 1 && !isa(nd.next, EmptyNode)
nd = nd.next
index -= 1
end
if... |
Generate an equivalent Julia version of this C# code. | using System;
using System.IO;
using System.Security.Cryptography;
namespace DES {
class Program {
static string ByteArrayToString(byte[] ba) {
return BitConverter.ToString(ba).Replace("-", "");
}
static byte[] Encrypt(byte[] messageBytes, byte[] pass... | using MbedTLS
const testdata = [
[[0x13, 0x34, 0x57, 0x79, 0x9B, 0xBC, 0xDF, 0xF1],
[0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF]],
[[0x0E, 0x32, 0x92, 0x32, 0xEA, 0x6D, 0x0D, 0x73],
[0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87]],
[[0x0E, 0x32, 0x92, 0x32, 0xEA, 0x6D, 0x0D, 0x73],
[0x59, ... |
Change the programming language of this snippet from C# to Julia without modifying what it does. | using System;
namespace Rosetta
{
internal class Vector
{
private double[] b;
internal readonly int rows;
internal Vector(int rows)
{
this.rows = rows;
b = new double[rows];
}
internal Vector(double[] initArray)
{
b =... | A = [1 2 3; 4 1 6; 7 8 9]
@show I / A
@show inv(A)
|
Produce a functionally identical Julia code for the snippet given in C#. | using System;
namespace Rosetta
{
internal class Vector
{
private double[] b;
internal readonly int rows;
internal Vector(int rows)
{
this.rows = rows;
b = new double[rows];
}
internal Vector(double[] initArray)
{
b =... | A = [1 2 3; 4 1 6; 7 8 9]
@show I / A
@show inv(A)
|
Port the following code from C# to Julia with equivalent syntax and logic. | using System;
class Program {
static bool dc8(uint n) {
uint res = 1, count, p, d;
for ( ; (n & 1) == 0; n >>= 1) res++;
for (count = 1; n % 3 == 0; n /= 3) count++;
for (p = 5, d = 4; p * p <= n; p += d = 6 - d)
for (res *= count, count = 1; n % p == 0; n /= p) count++;
return n > 1 ? re... | using Printf
function proper_divisors(n::Integer)
uptosqr = 1:isqrt(n)
divs = Iterators.filter(uptosqr) do m
n % m == 0
end
pd_pairs = Iterators.map(divs) do d1
d2 = div(n, d1)
(d1 == d2 || d1 == 1) ? (d1,) : (d1, d2)
end
return Iterators.flatten(pd_pairs)
end
function ... |
Write the same algorithm in Julia as shown in this C# implementation. | using System;
class Program {
static void fun(char sp) {
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {
var s = x.ToString();
for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0)... | using Primes
function pandigitals(firstdig, lastdig)
mask = primesmask(10^(lastdig - firstdig + 1))
for j in lastdig:-1:firstdig
n = j - firstdig + 1
for i in evalpoly(10, firstdig:j):-1:evalpoly(10, j:-1:firstdig)
if mask[i]
d = digits(i)
if length(d... |
Change the following C# code into Julia without altering its purpose. | using System;
class Program {
static void fun(char sp) {
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {
var s = x.ToString();
for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0)... | using Primes
function pandigitals(firstdig, lastdig)
mask = primesmask(10^(lastdig - firstdig + 1))
for j in lastdig:-1:firstdig
n = j - firstdig + 1
for i in evalpoly(10, firstdig:j):-1:evalpoly(10, j:-1:firstdig)
if mask[i]
d = digits(i)
if length(d... |
Write the same code in Julia as shown below in C#. | using System;
using System.IO;
using System.Numerics;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
namespace Fibonacci {
class Program
{
private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };
privat... |
const b = [big"1" 1; 1 0]
matrixfibonacci(n) = n == 0 ? 0 : n == 1 ? 1 : (b^(n+1))[2,2]
binetfibonacci(n) = ((1+sqrt(big"5"))^n-(1-sqrt(big"5"))^n)/(sqrt(big"5")*big"2"^n)
function firstbinet(bits, ndig=20)
logφ = big"2"^bits * log(10, (1 + sqrt(BigFloat(5.0))) / 2)
mantissa = logφ - trunc(logφ) + ndig + ... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using System;
using System.IO;
using System.Numerics;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
namespace Fibonacci {
class Program
{
private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };
privat... |
const b = [big"1" 1; 1 0]
matrixfibonacci(n) = n == 0 ? 0 : n == 1 ? 1 : (b^(n+1))[2,2]
binetfibonacci(n) = ((1+sqrt(big"5"))^n-(1-sqrt(big"5"))^n)/(sqrt(big"5")*big"2"^n)
function firstbinet(bits, ndig=20)
logφ = big"2"^bits * log(10, (1 + sqrt(BigFloat(5.0))) / 2)
mantissa = logφ - trunc(logφ) + ndig + ... |
Convert the following code from C# to Julia, ensuring the logic remains intact. | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using IntMap = System.Collections.Generic.Dictionary<int, int>;
public static class CyclotomicPolynomial
{
public static void Main2() {
Console.WriteLine("Task 1: Cyclotomic polynomials for n <= 30:");
for ... | using Primes, Polynomials
const cyclotomics = Dict([1 => Poly([big"-1", big"1"]), 2 => Poly([big"1", big"1"])])
function divisors(n::Integer)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init=f)
end
return resize!(f, length(f) - 1)
end
"""
cyclotomic(... |
Transform the following C# implementation into Julia, maintaining the same output and logic. | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using IntMap = System.Collections.Generic.Dictionary<int, int>;
public static class CyclotomicPolynomial
{
public static void Main2() {
Console.WriteLine("Task 1: Cyclotomic polynomials for n <= 30:");
for ... | using Primes, Polynomials
const cyclotomics = Dict([1 => Poly([big"-1", big"1"]), 2 => Poly([big"1", big"1"])])
function divisors(n::Integer)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init=f)
end
return resize!(f, length(f) - 1)
end
"""
cyclotomic(... |
Produce a functionally identical Julia code for the snippet given in C#. | using System;
using System.Collections.Generic;
using System.Linq;
public static class MinimalSteps
{
public static void Main() {
var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });
var lookup = CreateLookup(2_000, divisors, subtractors);
Console.WriteLine($"Divisors: [{diviso... | import Base.print
struct Action{T}
f::Function
i::T
end
struct ActionOutcome{T}
act::Action{T}
out::T
end
Base.print(io::IO, ao::ActionOutcome) = print(io, "$(ao.act.f) $(ao.act.i) yields $(ao.out)")
memoized = Dict{Int, Int}()
function findshortest(start, goal, fails, actions, verbose=true, m... |
Rewrite this program in Julia while keeping its functionality equivalent to the C# version. | using System;
using System.Collections.Generic;
class Program {
static List<int> PrimesUpTo(int limit, bool verbose = false) {
var sw = System.Diagnostics.Stopwatch.StartNew();
var members = new SortedSet<int>{ 1 };
int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), ... | """ Rosetta Code task rosettacode.org/wiki/Sieve_of_Pritchard """
""" Pritchard sieve of primes up to limit. Uses type of `limit` arg for type of primes """
function pritchard(limit::T, verbose=false) where {T<:Integer}
members = falses(limit)
members[1] = true
steplength = 1
prime = T(2)
primes =... |
Please provide an equivalent version of this C# code in Julia. | using System.Collections.Generic; using System.Linq; using static System.Console;
class Program {
static bool soas(int n, IEnumerable<int> f) {
if (n <= 0) return false; if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;
case -1: v... | using Primes
""" proper divisors of n """
function proper_divisors(n)
f = [one(n)]
for (p,e) in factor(n)
f = reduce(vcat, [f*p^j for j in 1:e], init=f)
end
pop!(f)
return f
end
""" return true if any subset of f sums to n. """
function sumofanysubset(n, f)
n in f && return true
to... |
Write the same code in Julia as shown below in C#. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace TransportationProblem {
class Shipment {
public Shipment(double q, double cpu, int r, int c) {
Quantity = q;
CostPerUnit = cpu;
R = r;
C = c;
}
publ... | using JuMP, GLPK
c = [3, 5, 7, 3, 2, 5];
N = size(c,1);
A = [1 1 1 0 0 0
0 0 0 1 1 1
1 0 0 1 0 0
0 1 0 0 1 0
0 0 1 0 0 1];
b = [ 25, 35, 20, 30, 10];
s = ['<', '<', '=', '=', '='];
model = Model(GLPK.Optimizer)
@variable(model, x[i=1:N] >= 0, base_name="traded quantities")
cost_fn = @expre... |
Generate an equivalent Julia version of this C# code. | using System;
using System.Net;
class Program
{
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.ClientCertificates.Add(new X509Certificate());
... | using HTTP, MbedTLS
conf = MbedTLS.SSLConfig(true, log_secrets="/utl/secret_key_log.log")
resp = HTTP.get("https://httpbin.org/ip", sslconfig=conf)
println(resp)
|
Port the provided C# code into Julia while preserving the original functionality. | using System.Security.Cryptography;
using System.Text;
namespace rosettaMySQL
{
class Hasher
{
private static string _BytesToHex(byte[] input)
{
var strBuilder = new StringBuilder();
foreach (byte _byte in input)
{
strBuilder.Append(_byte.ToSt... | using MySQL
using Nettle
function connect_db(uri, user, pw, dbname)
mydb = mysql_connect(uri, user, pw, dbname)
const command = """CREATE TABLE IF NOT EXISTS users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
... |
Translate the given C# code snippet into Julia without altering its behavior. | using System;
using System.Collections.Generic;
class Node
{
public int LowLink { get; set; }
public int Index { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
Index = -1;
LowLink = 0;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dict... | using LightGraphs
edge_list=[(1,2),(3,1),(6,3),(6,7),(7,6),(2,3),(4,2),(4,3),(4,5),(5,6),(5,4),(8,5),(8,8),(8,7)]
grph = SimpleDiGraph(Edge.(edge_list))
tarj = strongly_connected_components(grph)
inzerobase(arrarr) = map(x -> sort(x .- 1, rev=true), arrarr)
println("Results in the zero-base scheme: $(inzerobase(ta... |
Transform the following C# implementation into Julia, maintaining the same output and logic. | using System;
namespace Rosetta
{
internal interface IFun
{
double F(int index, Vector x);
double df(int index, int derivative, Vector x);
double[] weights();
}
class Newton
{
internal Vector Do(int size, IFun fun, Vector start)
{
... |
using NLsolve
function f!(F, x)
F[1] = (x[1]+3)*(x[2]^3-7)+18
F[2] = sin(x[2]*exp(x[1])-1)
end
function j!(J, x)
J[1, 1] = x[2]^3-7
J[1, 2] = 3*x[2]^2*(x[1]+3)
u = exp(x[1])*cos(x[2]*exp(x[1])-1)
J[2, 1] = x[2]*u
J[2, 2] = u
end
println(nlsolve(f!, j!, [ 0.1; 1.2], method = :newton))
|
Can you help me rewrite this code in Julia instead of C#, keeping it the same logically? | using System;
namespace Rosetta
{
internal interface IFun
{
double F(int index, Vector x);
double df(int index, int derivative, Vector x);
double[] weights();
}
class Newton
{
internal Vector Do(int size, IFun fun, Vector start)
{
... |
using NLsolve
function f!(F, x)
F[1] = (x[1]+3)*(x[2]^3-7)+18
F[2] = sin(x[2]*exp(x[1])-1)
end
function j!(J, x)
J[1, 1] = x[2]^3-7
J[1, 2] = 3*x[2]^2*(x[1]+3)
u = exp(x[1])*cos(x[2]*exp(x[1])-1)
J[2, 1] = x[2]*u
J[2, 2] = u
end
println(nlsolve(f!, j!, [ 0.1; 1.2], method = :newton))
|
Preserve the algorithm and functionality while converting the code from C# to Julia. | using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static bool soms(int n, IEnumerable<int> f) {
if (n <= 0) return false;
if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) {
case 1: return false;
case 0: return true;
case -1:
var... |
Here we show all the 128 < numbers < 400 can be expressed as a sum of distinct squares. Now
11 * 11 < 128 < 12 * 12. It is also true that we need no square less than 144 (12 * 12) to
reduce via subtraction of squares all the numbers above 400 to a number > 128 and < 400 by
subtracting discrete squares of numbers over ... |
Write the same algorithm in Julia as shown in this C# implementation. | using System;
using System.Security.Cryptography;
namespace RosettaTOTP
{
public class TOTP_SHA1
{
private byte[] K;
public TOTP_SHA1()
{
GenerateKey();
}
public void GenerateKey()
{
using (RandomNumberGenerator rng = new RNGCryptoServiceP... | using CodecBase
using SHA
function hmac(key, msg, hashfunction, blocksize=64)
key = hashfunction(key)
paddingneeded = blocksize - length(key)
if paddingneeded > 0
resize!(key, blocksize)
key[end-paddingneeded+1:end] .= 0
end
return hashfunction([key .⊻ 0x5c; hashfunction([key .⊻ 0x3... |
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
}
| def winsize
require 'io/console'
IO.console.winsize
rescue LoadError
[Integer(`tput li`), Integer(`tput co`)]
end
rows, cols = winsize
printf "%d rows by %d columns\n", rows, cols
|
Port the provided Go code into Ruby while preserving the original functionality. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
... | func special_primes(upto) {
var gap = 0
var prev = 2
var list = [[prev, gap]]
loop {
var n = prev+gap
n = n.next_prime
break if (n > upto)
gap = n-prev
list << [n, gap]
prev = n
}
return list
}
special_primes(1050).each_2d {|p,gap|
say "
}... |
Generate a Ruby translation of this Go snippet without changing its computational steps. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
... | func special_primes(upto) {
var gap = 0
var prev = 2
var list = [[prev, gap]]
loop {
var n = prev+gap
n = n.next_prime
break if (n > upto)
gap = n-prev
list << [n, gap]
prev = n
}
return list
}
special_primes(1050).each_2d {|p,gap|
say "
}... |
Write the same code in Ruby as shown below in Go. | package main
import (
"fmt"
"strconv"
"strings"
)
func divByAll(num int, digits []byte) bool {
for _, digit := range digits {
if num%int(digit-'0') != 0 {
return false
}
}
return true
}
func main() {
magic := 9 * 8 * 7
high := 9876432 / magic * magic
fo... | magic_number = 9*8*7
div = (9876432 // magic_number) * magic_number
candidates = div.step(to: 0, by: -magic_number)
res = candidates.find do |c|
digits = c.to_s.chars.map(&.to_i)
(digits & [0,5]).empty? && digits == digits.uniq
end
puts "Largest decimal number is
|
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import (
"fmt"
"strconv"
"strings"
)
func divByAll(num int, digits []byte) bool {
for _, digit := range digits {
if num%int(digit-'0') != 0 {
return false
}
}
return true
}
func main() {
magic := 9 * 8 * 7
high := 9876432 / magic * magic
fo... | magic_number = 9*8*7
div = (9876432 // magic_number) * magic_number
candidates = div.step(to: 0, by: -magic_number)
res = candidates.find do |c|
digits = c.to_s.chars.map(&.to_i)
(digits & [0,5]).empty? && digits == digits.uniq
end
puts "Largest decimal number is
|
Port the provided Go code into Ruby while preserving the original functionality. | package main
import (
"fmt"
"log"
"math/big"
)
func jacobi(a, n uint64) int {
if n%2 == 0 {
log.Fatal("'n' must be a positive odd integer")
}
a %= n
result := 1
for a != 0 {
for a%2 == 0 {
a /= 2
nn := n % 8
if nn == 3 || nn == 5 {
... | def jacobi(a, n)
raise ArgumentError.new "n must b positive and odd" if n < 1 || n.even?
res = 1
until (a %= n) == 0
while a.even?
a >>= 1
res = -res if [3, 5].includes? n % 8
end
a, n = n, a
res = -res if a % 4 == n % 4 == 3
end
n == 1 ? res : 0
end
puts "Jacobian symbols for jac... |
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import (
"fmt"
"log"
"math/big"
)
func jacobi(a, n uint64) int {
if n%2 == 0 {
log.Fatal("'n' must be a positive odd integer")
}
a %= n
result := 1
for a != 0 {
for a%2 == 0 {
a /= 2
nn := n % 8
if nn == 3 || nn == 5 {
... | def jacobi(a, n)
raise ArgumentError.new "n must b positive and odd" if n < 1 || n.even?
res = 1
until (a %= n) == 0
while a.even?
a >>= 1
res = -res if [3, 5].includes? n % 8
end
a, n = n, a
res = -res if a % 4 == n % 4 == 3
end
n == 1 ? res : 0
end
puts "Jacobian symbols for jac... |
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
... | require 'matrix'
class Matrix
def permanent
r = (0...row_count).to_a
r.permutation.inject(0) do |sum, sigma|
sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] }
end
end
end
m1 = Matrix[[1,2],[3,4]]
m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 1... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
... | require 'matrix'
class Matrix
def permanent
r = (0...row_count).to_a
r.permutation.inject(0) do |sum, sigma|
sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] }
end
end
end
m1 = Matrix[[1,2],[3,4]]
m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 1... |
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
count := 0
limit := 25
n := int64(17)
repunit := big.NewInt(1111111111111111)
t := new(big.Int)
zero := new(big.Int)
eleven := big.NewInt(11)
hundred := big.NewInt(100)
var deceptive []int64
for count < li... | require 'prime'
deceptives = Enumerator.new do |y|
10.step(by: 10) do |n|
[1,3,7,9].each do |digit|
cand = n + digit
next if cand % 3 == 0 || cand.prime?
repunit = ("1"*(cand-1)).to_i
y << cand if (repunit % cand) == 0
end
end
end
p deceptives.take(25).to_a
|
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
count := 0
limit := 25
n := int64(17)
repunit := big.NewInt(1111111111111111)
t := new(big.Int)
zero := new(big.Int)
eleven := big.NewInt(11)
hundred := big.NewInt(100)
var deceptive []int64
for count < li... | require 'prime'
deceptives = Enumerator.new do |y|
10.step(by: 10) do |n|
[1,3,7,9].each do |digit|
cand = n + digit
next if cand % 3 == 0 || cand.prime?
repunit = ("1"*(cand-1)).to_i
y << cand if (repunit % cand) == 0
end
end
end
p deceptives.take(25).to_a
|
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import (
"fmt"
"rcu"
"strings"
)
func main() {
var numbers []int
for n := 0; n < 1000; n++ {
ns := fmt.Sprintf("%d", n)
ds := fmt.Sprintf("%d", rcu.DigitSum(n, 10))
if strings.Contains(ns, ds) {
numbers = append(numbers, n)
}
}
fmt.P... | p (0...1000).select{|n| n.to_s.match? n.digits.sum.to_s}
|
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"fmt"
"rcu"
"strings"
)
func main() {
var numbers []int
for n := 0; n < 1000; n++ {
ns := fmt.Sprintf("%d", n)
ds := fmt.Sprintf("%d", rcu.DigitSum(n, 10))
if strings.Contains(ns, ds) {
numbers = append(numbers, n)
}
}
fmt.P... | p (0...1000).select{|n| n.to_s.match? n.digits.sum.to_s}
|
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"math/rand"
"fmt"
)
func main() {
list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for i := 1; i <= 10; i++ {
sattoloCycle(list)
fmt.Println(list)
}
}
func sattoloCycle(list []int) {
for x := len(list) -1; x > 0; x-- {
j := rand.Intn(x)
list[x], list[j] = list[j], list[x]
}
}
| > class Array
> def sattolo_cycle!
> (length - 1).downto(1) do |i|
* j = rand(i)
> self[i], self[j] = self[j], self[i]
> end
> self
> end
> end
=> :sattolo_cycle!
>
> 10.times do
* p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sattolo_cycle!
> end
[10, 6, 9, 7, 8, 1, 3, 2, 5, 4]
[3, 7, 5, 10, 4, 8, ... |
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"math/rand"
"fmt"
)
func main() {
list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for i := 1; i <= 10; i++ {
sattoloCycle(list)
fmt.Println(list)
}
}
func sattoloCycle(list []int) {
for x := len(list) -1; x > 0; x-- {
j := rand.Intn(x)
list[x], list[j] = list[j], list[x]
}
}
| > class Array
> def sattolo_cycle!
> (length - 1).downto(1) do |i|
* j = rand(i)
> self[i], self[j] = self[j], self[i]
> end
> self
> end
> end
=> :sattolo_cycle!
>
> 10.times do
* p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sattolo_cycle!
> end
[10, 6, 9, 7, 8, 1, 3, 2, 5, 4]
[3, 7, 5, 10, 4, 8, ... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Q... | require 'net/ftp'
Net::FTP.open('ftp.ed.ac.uk', "anonymous","aaa@gmail.com" ) do |ftp|
ftp.passive = true
ftp.chdir('pub/courses')
puts ftp.list
ftp.getbinaryfile("make.notes.tar")
end
|
Change the following Go code into Ruby without altering its purpose. | package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "rc.db")
if err != nil {
log.Print(err)
return
}
defer db.Close()
_, err = db.Exec(`create table addr (
id int uniq... | require 'pstore'
require 'set'
Address = Struct.new :id, :street, :city, :state, :zip
db = PStore.new("addresses.pstore")
db.transaction do
db[:next] ||= 0
db[:ids] ||= Set[]
end
|
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import (
"fmt"
"math/rand"
"time"
)
func cyclesort(ints []int) int {
writes := 0
for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ {
item := ints[cyclestart]
pos := cyclestart
for i := cyclestart + 1; i < len(ints); i++ {
if ints[i] < item {
pos++
}
}
if pos == cycl... | def cycleSort!(array)
writes = 0
for cycleStart in 0 .. array.size-2
item = array[cycleStart]
pos = cycleStart
for i in cycleStart+1 ... array.size
pos += 1 if array[i] < item
end
next if pos == cycleStart
pos += 1 while item == array[pos]
arr... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"math/rand"
"time"
)
func cyclesort(ints []int) int {
writes := 0
for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ {
item := ints[cyclestart]
pos := cyclestart
for i := cyclestart + 1; i < len(ints); i++ {
if ints[i] < item {
pos++
}
}
if pos == cycl... | def cycleSort!(array)
writes = 0
for cycleStart in 0 .. array.size-2
item = array[cycleStart]
pos = cycleStart
for i in cycleStart+1 ... array.size
pos += 1 if array[i] < item
end
next if pos == cycleStart
pos += 1 while item == array[pos]
arr... |
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := uint64(3)
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
... | require 'prime'
(1..8).each do |n|
count = Prime.each(10**n).each_cons(2).count{|p1, p2| p2-p1 == 2}
puts "Twin primes below 10**
end
|
Write a version of this Go function in Ruby with identical behavior. | package main
import "fmt"
func sameDigits(n, b int) bool {
f := n % b
n /= b
for n > 0 {
if n%b != f {
return false
}
n /= b
}
return true
}
func isBrazilian(n int) bool {
if n < 7 {
return false
}
if n%2 == 0 && n >= 8 {
return true... | def sameDigits(n,b)
f = n % b
while (n /= b) > 0 do
if n % b != f then
return false
end
end
return true
end
def isBrazilian(n)
if n < 7 then
return false
end
if n % 2 == 0 then
return true
end
for b in 2 .. n - 2 do
if sameDigits(n... |
Please provide an equivalent version of this Go code in Ruby. | package main
import "fmt"
func sameDigits(n, b int) bool {
f := n % b
n /= b
for n > 0 {
if n%b != f {
return false
}
n /= b
}
return true
}
func isBrazilian(n int) bool {
if n < 7 {
return false
}
if n%2 == 0 && n >= 8 {
return true... | def sameDigits(n,b)
f = n % b
while (n /= b) > 0 do
if n % b != f then
return false
end
end
return true
end
def isBrazilian(n)
if n < 7 then
return false
end
if n % 2 == 0 then
return true
end
for b in 2 .. n - 2 do
if sameDigits(n... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String(... | filename = {% if flag?(:win32) %}
"TAPE.FILE"
{% else %}
"/dev/tape"
{% end %}
File.write filename, "howdy, planet!"
|
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[... | require 'set'
a = [0]
used = Set[0]
used1000 = Set[0]
foundDup = false
n = 1
while n <= 15 or not foundDup or used1000.size < 1001
nxt = a[n - 1] - n
if nxt < 1 or used === nxt then
nxt = nxt + 2 * n
end
alreadyUsed = used === nxt
a << nxt
if not alreadyUsed then
used << nxt
... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[... | require 'set'
a = [0]
used = Set[0]
used1000 = Set[0]
foundDup = false
n = 1
while n <= 15 or not foundDup or used1000.size < 1001
nxt = a[n - 1] - n
if nxt < 1 or used === nxt then
nxt = nxt + 2 * n
end
alreadyUsed = used === nxt
a << nxt
if not alreadyUsed then
used << nxt
... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import "fmt"
type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func
func main() {
fac := Y(almost_fac)
fib := Y(almost_fib)
fmt.Println("fac(10) = ", fac(10))
fmt.Println("fib(10) = ", fib(10))
}
func Y(f FuncFunc) Func {
g := func(r RecursiveFunc) Func ... | y = lambda do |f|
lambda {|g| g[g]}[lambda do |g|
f[lambda {|*args| g[g][*args]}]
end]
end
fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}}
p Array.new(10) {|i| y[fac][i]}
fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}}
p Array.new(10) {|i| y[fib][i]}
|
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"flag"
"fmt"
"math"
"runtime"
"sort"
)
type Circle struct{ X, Y, R, rsq float64 }
func NewCircle(x, y, r float64) Circle {
return Circle{x, y, r, r * r}
}
func (c Circle) ContainsPt(x, y float64) bool {
return distSq(x, y, c.... | circles = [
[ 1.6417233788, 1.6121789534, 0.0848270516],
[-1.4944608174, 1.2077959613, 1.1039549836],
[ 0.6110294452, -0.6907087527, 0.9089162485],
[ 0.3844862411, 0.2923344616, 0.2375743054],
[-0.2495892950, -0.3832854473, 1.0845181219],
[ 1.7813504266, 1.6178237031, 0.8162655711],
[-0.1985249206, -0... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"flag"
"fmt"
"math"
"runtime"
"sort"
)
type Circle struct{ X, Y, R, rsq float64 }
func NewCircle(x, y, r float64) Circle {
return Circle{x, y, r, r * r}
}
func (c Circle) ContainsPt(x, y float64) bool {
return distSq(x, y, c.... | circles = [
[ 1.6417233788, 1.6121789534, 0.0848270516],
[-1.4944608174, 1.2077959613, 1.1039549836],
[ 0.6110294452, -0.6907087527, 0.9089162485],
[ 0.3844862411, 0.2923344616, 0.2375743054],
[-0.2495892950, -0.3832854473, 1.0845181219],
[ 1.7813504266, 1.6178237031, 0.8162655711],
[-0.1985249206, -0... |
Produce a language-to-language conversion: from Go to Ruby, same semantics. | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++... | def factorion?(n, base)
n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n
end
(9..12).each do |base|
puts "Base
end
|
Change the following Go code into Ruby without altering its purpose. | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++... | def factorion?(n, base)
n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n
end
(9..12).each do |base|
puts "Base
end
|
Change the following Go code into Ruby without altering its purpose. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return... | def divisor_sum(n)
total = 1
power = 2
while (n & 1) == 0
total = total + power
power = power << 1
n = n >> 1
end
p = 3
while p * p <= n
sum = 1
power = p
while n % p == 0
sum = sum + power
power = power * p
... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(79)
ix := 0
n := 1
count := 0
var pi []int
for {
if primes[ix] <= n {
count++
if count == 22 {
break
}
ix++
}
n++
pi =... | 1..(prime(22)-1) -> map { .prime_count }.say
|
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(79)
ix := 0
n := 1
count := 0
var pi []int
for {
if primes[ix] <= n {
count++
if count == 22 {
break
}
ix++
}
n++
pi =... | 1..(prime(22)-1) -> map { .prime_count }.say
|
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"sort"
"strings"
)
var count int = 0
func interactiveCompare(s1, s2 string) bool {
count++
fmt.Printf("(%d) Is %s < %s? ", count, s1, s2)
var response string
_, err := fmt.Scanln(&response)
return err == nil && strings.HasPrefix(response, "y")
}
func main... | items = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
count = 0
sortedItems = []
items.each {|item|
puts "Inserting '
spotToInsert = sortedItems.bsearch_index{|x|
count += 1
print "(
gets.start_with?('y')
} || sortedItems.length
sortedItems.insert(spotToInsert, item)
}
p sortedIt... |
Convert the following code from Go to Ruby, ensuring the logic remains intact. | package main
import (
"fmt"
"github.com/jbarham/primegen"
"math"
"math/big"
"math/rand"
"sort"
"time"
)
const (
maxCurves = 10000
maxRnd = 1 << 31
maxB1 = uint64(43 * 1e7)
maxB2 = uint64(2 * 1e10)
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
t... | require "big"
def factors(n)
factors = `factor
factors.group_by(&.itself).map { |prime, exp| [prime, exp.size] }
end
def fermat(n); (1.to_big_i << (1 << n)) | 1 end
puts "Value for each Fermat Number F0 .. F9."
(0..9).each { |n| puts "F
puts
puts "Factors for each Fermat Number F0 .. F8."
(0..8).each { |n| ... |
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, ... | class Array
def beadsort
map {|e| [1] * e}.columns.columns.map(&:length)
end
def columns
y = length
x = map(&:length).max
Array.new(x) do |row|
Array.new(y) { |column| self[column][row] }.compact
end
end
end
p [5,3,1,7,4,1,1].beadsort
|
Port the provided Go code into Ruby while preserving the original functionality. | package main
import (
"fmt"
"log"
"strconv"
)
func co9Peterson(base int) (cob func(string) (byte, error), err error) {
if base < 2 || base > 36 {
return nil, fmt.Errorf("co9Peterson: %d invalid base", base)
}
addDigits := func(a, b byte) (string, error) {... | N = 2
base = 10
c1 = 0
c2 = 0
for k in 1 .. (base ** N) - 1
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
print "%d " % [k]
end
end
puts
print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
|
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"log"
"strconv"
)
func co9Peterson(base int) (cob func(string) (byte, error), err error) {
if base < 2 || base > 36 {
return nil, fmt.Errorf("co9Peterson: %d invalid base", base)
}
addDigits := func(a, b byte) (string, error) {... | N = 2
base = 10
c1 = 0
c2 = 0
for k in 1 .. (base ** N) - 1
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
print "%d " % [k]
end
end
puts
print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
|
Translate the given Go code snippet into Ruby without altering its behavior. |
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}
|
say ARGV.join(" ")
|
Convert this Go block to Ruby, preserving its control flow and logic. |
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}
|
say ARGV.join(" ")
|
Write the same code in Ruby as shown below in Go. | package main
import "C"
import "fmt"
import "unsafe"
func main() {
d := C.XOpenDisplay(nil)
f7, f6 := C.CString("F7"), C.CString("F6")
defer C.free(unsafe.Pointer(f7))
defer C.free(unsafe.Pointer(f6))
if d != nil {
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
... | Shoes.app do
@info = para "NO KEY is PRESSED."
keypress do |k|
@info.replace "
end
end
|
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
retu... | require 'prime'
def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1}
(1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.