Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided Go code into Ruby while preserving the original functionality.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } fun...
def zero(f) return lambda {|x| x} end Zero = lambda { |f| zero(f) } def succ(n) return lambda { |f| lambda { |x| f.(n.(f).(x)) } } end Three = succ(succ(succ(Zero))) def add(n, m) return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } } end def mult(n, m) return lambda { |f| lambda { |x| m.(n.(f)).(x) } }...
Please provide an equivalent version of this Go code in Ruby.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := ...
class Super CLASSNAME = 'super' def initialize(name) @name = name def self.superOwn 'super owned' end end def to_s "Super( end def doSup 'did super stuff' end def self.superClassStuff 'did super class stuff' end protected def protSup "Super's prote...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
class Example def foo 42 end def bar(arg1, arg2, &block) block.call arg1, arg2 end end symbol = :foo Example.new.send symbol Example.new.send( :bar, 1, 2 ) { |x,y| x+y } args = [1, 2] Example.new.send( "bar", *args ) { |x,y| x+y }
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) i...
while DATA.gets print end __END__ This is line one This is line two This is line three
Write a version of this Go function in Ruby with identical behavior.
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) i...
while DATA.gets print end __END__ This is line one This is line two This is line three
Translate the given Go code snippet into Ruby without altering its behavior.
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
require 'digest/sha2' def convert g i,e = '',[] (0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'} e.pack(i) end X = '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352' Y = '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6' n = '00'+Digest::RMD160.hexdigest(Digest::SHA256...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
require 'digest/sha2' def convert g i,e = '',[] (0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'} e.pack(i) end X = '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352' Y = '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6' n = '00'+Digest::RMD160.hexdigest(Digest::SHA256...
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "fmt" "log" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func canonicalize(cidr string) string { split := strings.Split(cidr, "/") dotted := split[0] size, err := strconv.Atoi(split[1]) check(err) ...
if ARGV.length == 0 then ARGV = $stdin.readlines.map(&:chomp) end ARGV.each do |cidr| dotted, size_str = cidr.split('/') size = size_str.to_i binary = dotted.split('.').map { |o| "%08b" % o }.join binary[size .. -1] = '0' * (32 - size) canon = binary.chars.each_slice(8).map { |a| a.joi...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "fmt" "log" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func canonicalize(cidr string) string { split := strings.Split(cidr, "/") dotted := split[0] size, err := strconv.Atoi(split[1]) check(err) ...
if ARGV.length == 0 then ARGV = $stdin.readlines.map(&:chomp) end ARGV.each do |cidr| dotted, size_str = cidr.split('/') size = size_str.to_i binary = dotted.split('.').map { |o| "%08b" % o }.join binary[size .. -1] = '0' * (32 - size) canon = binary.chars.each_slice(8).map { |a| a.joi...
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) pm := big.NewInt(1) var px, nx int var pb big.Int primes(4000, func(p int64) bool { pm.Mul(pm, pb.SetInt64(p)) px++ if pb.Add(pm, one).ProbablyPrime(0) || pb.Sub(pm, one).Pro...
require 'prime' require 'openssl' i, urutan, primorial_number = 1, 1, OpenSSL::BN.new(1) start = Time.now prime_array = Prime.first (500) until urutan > 20 primorial_number *= prime_array[i-1] if (primorial_number - 1).prime_fasttest? || (primorial_number + 1).prime_fasttest? puts " urutan += 1 en...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n ...
require "big" include Math struct Int def permutation(k) (self-k+1..self).product(1.to_big_i) end def combination(k) self.permutation(k) // (1..k).product(1.to_big_i) end def big_permutation(k) exp(lgamma_plus(self) - lgamma_plus(self-k)) end def big_combination(k) exp( lgamma_p...
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) t := new(big.Float).SetPrec(prec) u := new(big.Float).SetP...
require 'flt' Flt::BinNum.Context.precision = 8192 a = n = 1 g = 1 / Flt::BinNum(2).sqrt z = 0.25 (0..17).each{ x = [(a + g) * 0.5, (a * g).sqrt] var = x[0] - a z -= var * var * n n += n a = x[0] g = x[1] } puts a * a / z
Please provide an equivalent version of this Go code in Ruby.
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) t := new(big.Float).SetPrec(prec) u := new(big.Float).SetP...
require 'flt' Flt::BinNum.Context.precision = 8192 a = n = 1 g = 1 / Flt::BinNum(2).sqrt z = 0.25 (0..17).each{ x = [(a + g) * 0.5, (a * g).sqrt] var = x[0] - a z -= var * var * n n += n a = x[0] g = x[1] } puts a * a / z
Please provide an equivalent version of this Go code in Ruby.
package main import "fmt" func sieve(limit int) []int { var primes []int c := make([]bool, limit + 1) p := 3 p2 := p * p for p2 <= limit { for i := p2; i <= limit; i += 2 * p { c[i] = true } for ok := true; ok; ok = c[p] { p += 2 } ...
require "big" def prime?(n) return n | 1 == 3 if n < 5 return false if n.gcd(6) != 1 pc = typeof(n).new(5) until pc*pc > n return false if n % pc == 0 || n % (pc + 2) == 0 pc += 6 end true end def long_prime?(p) return false unl...
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and f...
require 'date' CYCLES = {physical: 23, emotional: 28, mental: 33} def biorhythms(date_of_birth, target_date = Date.today.to_s) days_alive = Date.parse(target_date) - Date.parse(date_of_birth) CYCLES.each do |name, num_days| cycle_day = days_alive % num_days state = case cycle_day when 0, num_days/2 ...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and f...
require 'date' CYCLES = {physical: 23, emotional: 28, mental: 33} def biorhythms(date_of_birth, target_date = Date.today.to_s) days_alive = Date.parse(target_date) - Date.parse(date_of_birth) CYCLES.each do |name, num_days| cycle_day = days_alive % num_days state = case cycle_day when 0, num_days/2 ...
Keep all operations the same but rewrite the snippet in Ruby.
package main import ( "fmt" "math/big" "time" "github.com/jbarham/primegen.go" ) func main() { start := time.Now() pg := primegen.New() var i uint64 p := big.NewInt(1) tmp := new(big.Int) for i <= 9 { fmt.Printf("primorial(%v) = %v\n", i, p) i++ p = p.Mul(p, tmp.SetUint64(pg.Next())) } for _, j := ...
require 'prime' def primorial_number(n) pgen = Prime.each (1..n).inject(1){|p,_| p*pgen.next} end puts "First ten primorials: (1..5).each do |n| puts "primorial(10** end
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
def ef(fr) ans = [] if fr >= 1 return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1 intfr = fr.to_i ans, fr = [intfr], fr - intfr end x, y = fr.numerator, fr.denominator while x != 1 ans << Rational(1, (1/fr).ceil) fr = Rational(-y % x, y * (1/fr).ceil) x, y = fr.numerator, fr.de...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
def ef(fr) ans = [] if fr >= 1 return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1 intfr = fr.to_i ans, fr = [intfr], fr - intfr end x, y = fr.numerator, fr.denominator while x != 1 ans << Rational(1, (1/fr).ceil) fr = Rational(-y % x, y * (1/fr).ceil) x, y = fr.numerator, fr.de...
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "math" ) type cFunc func(float64) float64 func main() { fmt.Println("integral:", glq(math.Exp, -3, 3, 5)) } func glq(f cFunc, a, b float64, n int) float64 { x, w := glqNodes(n, f) show := func(label string, vs []float64) { fmt.Printf("%8s: ", label) ...
func legendre_pair((1), x) { (x, 1) } func legendre_pair( n, x) { var (m1, m2) = legendre_pair(n - 1, x) var u = (1 - 1/n) ((1 + u)*x*m1 - u*m2, m1) } func legendre((0), _) { 1 } func legendre( n, x) { [legendre_pair(n, x)][0] } func legendre_prime({ .is_zero }, _) { 0 } func legendre_prime({ .is_one }...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt poi...
struct Kd_node { d, split, left, right, } struct Orthotope { min, max, } class Kd_tree(n, bounds) { method init { n = self.nk2(0, n); } method nk2(split, e) { return(nil) if (e.len <= 0); var exset = e.sort_by { _[split] } var m = (exset.len // 2);...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt poi...
struct Kd_node { d, split, left, right, } struct Orthotope { min, max, } class Kd_tree(n, bounds) { method init { n = self.nk2(0, n); } method nk2(split, e) { return(nil) if (e.len <= 0); var exset = e.sort_by { _[split] } var m = (exset.len // 2);...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "container/heap" "image" "image/color" "image/png" "log" "math" "os" "sort" ) func main() { f, err := os.Open("Quantum_frog.png") if err != nil { log.Fatal(err) } img, err := png.Decode(f) if ec := f.Close(); err != nil { log.Fa...
require('Image::Magick') func quantize_image(n = 16, input, output='output.png') { var im = %O<Image::Magick>.new im.Read(input) im.Quantize(colors => n, dither => 1) im.Write(output) } quantize_image(input: 'Quantum_frog.png')
Write the same code in Ruby as shown below in Go.
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d :...
def cut_it(h, w) if h.odd? return 0 if w.odd? h, w = w, h end return 1 if w == 1 nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] blen = (h + 1) * (w + 1) - 1 grid = [false] * (blen + 1) walk = lambda do |y, x, count=0| return count+1 if y==0 or y==h or x==0 or x==w t ...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "fmt" "math/big" ) func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { var z big.Int var cube1, cube2, cube100k, diff uint64 cubans := make(...
require "openssl" RE = /(\d)(?=(\d\d\d)+(?!\d))/ cuban_primes = Enumerator.new do |y| (1..).each do |n| cand = 3*n*(n+1) + 1 y << cand if OpenSSL::BN.new(cand).prime? end end def commatize(num) num.to_s.gsub(RE, "\\1,") end cbs = cuban_primes.take(200) formatted = cbs.map{|cb| commatize(cb).rjust(1...
Translate the given Go code snippet into Ruby without altering its behavior.
package main import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" ) var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, } func main() { const ( width ...
require('Imager') var width = 600 var height = 600 var points = [ [width//2, 0], [ 0, height-1], [height-1, height-1], ] var img = %O|Imager|.new( xsize => width, ysize => height, ) var color = %O|Imager::Color|.new(' var r =...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" ) var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, } func main() { const ( width ...
require('Imager') var width = 600 var height = 600 var points = [ [width//2, 0], [ 0, height-1], [height-1, height-1], ] var img = %O|Imager|.new( xsize => width, ysize => height, ) var color = %O|Imager::Color|.new(' var r =...
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "sort" "strconv" ) var games = [6]string{"12", "13", "14", "23", "24", "34"} var results = "000000" func nextResult() bool { if results == "222222" { return false } res, _ := strconv.ParseUint(results, 3, 32) results = fmt.Sprintf("%06s", strconv.Format...
teams = [:a, :b, :c, :d] matches = teams.combination(2).to_a outcomes = [:win, :draw, :loss] gains = {win:[3,0], draw:[1,1], loss:[0,3]} places_histogram = Array.new(4) {Array.new(10,0)} outcomes.repeated_permutation(6).each do |outcome| results = Hash.new(0) outcome.zip(matches).each do |decision, (team1,...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) f...
rpn = RPNExpression.from_infix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fa...
const p = (%w'47 4G 3T 2J 2I F 3N D 5L 2N 2O 1H 5E 6H 7 69 3W 10 2V U 1X 3Y 8 2R 11 6O L A N 5A 6 44 6V 3C 6I 23 0 Q 5H 1Q 2M 70 63 5N 39 Z B W 1L 4X X 2G 6L 45 1K 2F 4U K 3H 3S 4R 4O 1W 4V 22 4L 1Z 3Q 3V 1C R 4M 25 42 4E 6F 2B 33 6D 3E 1O 5V 3P 6E 64 2X 2K 15 1J 1A 6T 14 6S 2U 3Z 1I 1T P 1R 4H 1 60 28 21 5T 24 3O 57 5...
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func...
class AStarGraph { has barriers = [ [2,4],[2,5],[2,6],[3,6],[4,6],[5,6],[5,5],[5,4],[5,3],[5,2],[4,2],[3,2] ] method heuristic(start, goal) { var (D1 = 1, D2 = 1) var dx = abs(start[0] - goal[0]) var dy = abs(start[1] - goal[1]) (D1 * (dx + dy)) + ((D2 - 2*D1) * Mat...
Keep all operations the same but rewrite the snippet in Ruby.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func...
class AStarGraph { has barriers = [ [2,4],[2,5],[2,6],[3,6],[4,6],[5,6],[5,5],[5,4],[5,3],[5,2],[4,2],[3,2] ] method heuristic(start, goal) { var (D1 = 1, D2 = 1) var dx = abs(start[0] - goal[0]) var dy = abs(start[1] - goal[1]) (D1 * (dx + dy)) + ((D2 - 2*D1) * Mat...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool)...
func almkvist_giullera(n) { (32 * (14*n * (38*n + 9) + 9) * (6*n)!) / (3 * n!**6) } func almkvist_giullera_pi(prec = 70) { local Num!PREC = (4*(prec+1)).numify var sum = 0 var target = -1 for n in (0..Inf) { sum += (almkvist_giullera(n) / (10**(6*n + 3))) var curr = (sum**-.5).as...
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool)...
func almkvist_giullera(n) { (32 * (14*n * (38*n + 9) + 9) * (6*n)!) / (3 * n!**6) } func almkvist_giullera_pi(prec = 70) { local Num!PREC = (4*(prec+1)).numify var sum = 0 var target = -1 for n in (0..Inf) { sum += (almkvist_giullera(n) / (10**(6*n + 3))) var curr = (sum**-.5).as...
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
require "set" require "big" def add_reverse(num, max_iter=1000) num = num.to_big_i nums = [] of BigInt (1..max_iter).each_with_object(Set.new([num])) do |_, nums| num += reverse_int(num) nums << num return nums if palindrome?(num) end end def palindrome?(num) num == reverse_int(num) end def ...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
var equationtext = <<'EOT' pi/4 = arctan(1/2) + arctan(1/3) pi/4 = 2*arctan(1/3) + arctan(1/7) pi/4 = 4*arctan(1/5) - arctan(1/239) pi/4 = 5*arctan(1/7) + 2*arctan(3/79) pi/4 = 5*arctan(29/278) + 7*arctan(3/79) pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8) pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/9...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
var equationtext = <<'EOT' pi/4 = arctan(1/2) + arctan(1/3) pi/4 = 2*arctan(1/3) + arctan(1/7) pi/4 = 4*arctan(1/5) - arctan(1/239) pi/4 = 5*arctan(1/7) + 2*arctan(3/79) pi/4 = 5*arctan(29/278) + 7*arctan(3/79) pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8) pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/9...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "log" "strings" ) var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔") var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"} var g2lMap = map[rune]string{ '♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K", '♖': "R", '♘': "N", '♗': "B", '♕': "Q", ...
CHESS_PIECES = %w<♖♘♗♕♔ ♜♞♝♛♚> def chess960_to_spid(pos) start_str = pos.tr(CHESS_PIECES.join, "RNBQKRNBQK") s = start_str.delete("QB") n = [0,1,2,3,4].combination(2).to_a.index( [s.index("N"), s.rindex("N")] ) q = start_str.delete("B").index("Q") bs = start_str.index("B"), start_str.rindex("B") d ...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "regexp" "strings" ) var names = map[string]int64{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": ...
require 'number_names' def int_from_words(num) words = num.downcase.gsub(/(,| and |-)/,' ').split if words[0] =~ /(minus|negative)/ negmult = -1 words.shift else negmult = 1 end small, total = 0, 0 for word in words case word when *SMALL small += SMALL.index(word) when *TENS ...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import "fmt" const ( msg = "a Top Secret secret" key = "this is my secret key" ) func main() { var z state z.seed(key) fmt.Println("Message: ", msg) fmt.Println("Key  : ", key) fmt.Println("XOR  : ", z.vernam(msg)) } type state struct { aa, bb, cc uint32 mm ...
require('Math::Random::ISAAC') func xor_isaac(key, msg) { var rng = %O<Math::Random::ISAAC>.new(unpack('C*', key)) msg.chars»ord()» \ -> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).flip \ -> «%« '%02X' -> join } var msg = 'a Top Secret secret' var key = 'this ...
Translate the given Go code snippet into Ruby without altering its behavior.
package main import "fmt" const ( msg = "a Top Secret secret" key = "this is my secret key" ) func main() { var z state z.seed(key) fmt.Println("Message: ", msg) fmt.Println("Key  : ", key) fmt.Println("XOR  : ", z.vernam(msg)) } type state struct { aa, bb, cc uint32 mm ...
require('Math::Random::ISAAC') func xor_isaac(key, msg) { var rng = %O<Math::Random::ISAAC>.new(unpack('C*', key)) msg.chars»ord()» \ -> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).flip \ -> «%« '%02X' -> join } var msg = 'a Top Secret secret' var key = 'this ...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } ...
class Permutation include Enumerable attr_reader :num_elements, :size def initialize(num_elements) @num_elements = num_elements @size = fact(num_elements) end def each return self.to_enum unless block_given? (0...@size).each{|i| yield unrank(i)} end def unrank(r) pi = (0...n...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } ...
class Permutation include Enumerable attr_reader :num_elements, :size def initialize(num_elements) @num_elements = num_elements @size = fact(num_elements) end def each return self.to_enum unless block_given? (0...@size).each{|i| yield unrank(i)} end def unrank(r) pi = (0...n...
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
def p(l, n) test = 0 logv = Math.log(2.0) / Math.log(10.0) factor = 1 loopv = l while loopv > 10 do factor = factor * 10 loopv = loopv / 10 end while n > 0 do test = test + 1 val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor if val == l then...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
def p(l, n) test = 0 logv = Math.log(2.0) / Math.log(10.0) factor = 1 loopv = l while loopv > 10 do factor = factor * 10 loopv = loopv / 10 end while n > 0 do test = test + 1 val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor if val == l then...
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
@memo = {} def sterling2(n, k) key = [n,k] return @memo[key] if @memo.key?(key) return 1 if n.zero? and k.zero? return 0 if n.zero? or k.zero? return 1 if n == k return 0 if k > n res = k * sterling2(n-1, k) + sterling2(n - 1, k-1) @memo[key] = res end r = (0..12) puts "Sterling2 numbers:" puts "n/k ...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
@memo = {} def sterling2(n, k) key = [n,k] return @memo[key] if @memo.key?(key) return 1 if n.zero? and k.zero? return 0 if n.zero? or k.zero? return 1 if n == k return 0 if k > n res = k * sterling2(n-1, k) + sterling2(n - 1, k-1) @memo[key] = res end r = (0..12) puts "Sterling2 numbers:" puts "n/k ...
Port the provided Go code into Ruby while preserving the original functionality.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
func cipolla(n, p) { legendre(n, p) == 1 || return nil var (a = 0, ω2 = 0) loop { ω2 = ((a*a - n) % p) if (legendre(ω2, p) == -1) { break } ++a } struct point { x, y } func mul(a, b) { point((a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) %...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
func cipolla(n, p) { legendre(n, p) == 1 || return nil var (a = 0, ω2 = 0) loop { ω2 = ((a*a - n) % p) if (legendre(ω2, p) == -1) { break } ++a } struct point { x, y } func mul(a, b) { point((a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) %...
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "fmt" big "github.com/ncw/gmp" "sort" ) var ( one = new(big.Int).SetUint64(1) two = new(big.Int).SetUint64(2) three = new(big.Int).SetUint64(3) ) func pierpont(ulim, vlim int, first bool) []*big.Int { p := new(big.Int) p2 := new(big.Int).Set(one) p3 := ne...
require 'gmp' def smooth_generator(ar) return to_enum(__method__, ar) unless block_given? next_smooth = 1 queues = ar.map{|num| [num, []] } loop do yield next_smooth queues.each {|m, queue| queue << next_smooth * m} next_smooth = queues.collect{|m, queue| queue.first}.min queues.each{|m, queue...
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "log" "math/big" ) var ( primes []*big.Int smallPrimes []int ) func init() { two := big.NewInt(2) three := big.NewInt(3) p521 := big.NewInt(521) p29 := big.NewInt(29) primes = append(primes, two) smallPrimes = append(smallPrimes, 2) fo...
require "big" def prime?(n) return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5 sqrt_n = Math.isqrt(n) pc = typeof(n).new(5) while pc <= sqrt_n return false if n % pc == 0 || n % (pc + 2) == 0 pc += 6 end true end def gen_primes(a, b) (a..b).select { |pc| pc if prime? pc } end de...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "log" ) var ( primes = sieve(100000) foundCombo = false ) func sieve(limit uint) []uint { primes := []uint{2} c := make([]bool, limit+1) p := uint(3) for { p2 := p * p if p2 > limit { break } for i := p2...
require "prime" def prime_partition(x, n) Prime.each(x).to_a.combination(n).detect{|primes| primes.sum == x} end TESTCASES = [[99809, 1], [18, 2], [19, 3], [20, 4], [2017, 24], [22699, 1], [22699, 2], [22699, 3], [22699, 4], [40355, 3]] TESTCASES.each do |prime, num| res = prime_partition(prime, nu...
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
$cache = {} def sterling1(n, k) if n == 0 and k == 0 then return 1 end if n > 0 and k == 0 then return 0 end if k > n then return 0 end key = [n, k] if $cache[key] then return $cache[key] end value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n ...
Port the provided Go code into Ruby while preserving the original functionality.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
$cache = {} def sterling1(n, k) if n == 0 and k == 0 then return 1 end if n > 0 and k == 0 then return 0 end if k > n then return 0 end key = [n, k] if $cache[key] then return $cache[key] end value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n ...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x -...
func perpendicular_distance(Arr start, Arr end, Arr point) { ((point == start) || (point == end)) && return 0 var (Δx, Δy ) = ( end »-« start)... var (Δpx, Δpy) = (point »-« start)... var h = hypot(Δx, Δy) [\Δx, \Δy].map { *_ /= h } (([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).su...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x -...
func perpendicular_distance(Arr start, Arr end, Arr point) { ((point == start) || (point == end)) && return 0 var (Δx, Δy ) = ( end »-« start)... var (Δpx, Δpy) = (point »-« start)... var h = hypot(Δx, Δy) [\Δx, \Δy].map { *_ /= h } (([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).su...
Generate an equivalent Ruby version of this Go code.
package main import ( "image" "image/color" "image/jpeg" "log" "math" "os" "golang.org/x/image/draw" ) func scale(dst draw.Image, src image.Image) { sr := src.Bounds() dr := dst.Bounds() mx := float64(sr.Dx()-1) / float64(dr.Dx()) my := float64(sr.Dy()-1) / float64(dr.Dy()) for x := dr.Min.X; x < dr.Max....
require('Imager') func scale(img, scaleX, scaleY) { var (width, height) = (img.getwidth, img.getheight) var (newWidth, newHeight) = (int(width*scaleX), int(height*scaleY)) var out = %O<Imager>.new(xsize => newWidth, ysize => newHeight) var lerp = { |s, e, t| s + t*(e-s) } var blerp =...
Change the following Go code into Ruby without altering its purpose.
package main import ( "image" "image/color" "image/jpeg" "log" "math" "os" "golang.org/x/image/draw" ) func scale(dst draw.Image, src image.Image) { sr := src.Bounds() dr := dst.Bounds() mx := float64(sr.Dx()-1) / float64(dr.Dx()) my := float64(sr.Dy()-1) / float64(dr.Dy()) for x := dr.Min.X; x < dr.Max....
require('Imager') func scale(img, scaleX, scaleY) { var (width, height) = (img.getwidth, img.getheight) var (newWidth, newHeight) = (int(width*scaleX), int(height*scaleY)) var out = %O<Imager>.new(xsize => newWidth, ysize => newHeight) var lerp = { |s, e, t| s + t*(e-s) } var blerp =...
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import "fmt" type vector []float64 func (v vector) add(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi + v2[i] } return r } func (v vector) sub(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi - v...
class Vector def self.polar(r, angle=0) new(r*Math.cos(angle), r*Math.sin(angle)) end attr_reader :x, :y def initialize(x, y) raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric) @x, @y = x, y end def +(other) raise TypeError if self.class != other.class self.class.new(@...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { r...
module EC { var A = 0 var B = 7 class Horizon { method to_s { "EC Point at horizon" } method *(_) { self } method -(_) { self } } class Point(Number x, Number y) { method to_s { "EC Point at ...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { r...
module EC { var A = 0 var B = 7 class Horizon { method to_s { "EC Point at horizon" } method *(_) { self } method -(_) { self } } class Point(Number x, Number y) { method to_s { "EC Point at ...
Keep all operations the same but rewrite the snippet in Ruby.
package main import ( "fmt" "math" ) type cheb struct { c []float64 min, max float64 } func main() { fn := math.Cos c := newCheb(0, 1, 10, 10, fn) fmt.Println("coefficients:") for _, c := range c.c { fmt.Printf("% .15f\n", c) } fmt.Println("\nx computed a...
def mapp(x, min_x, max_x, min_to, max_to) return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to end def chebyshevCoef(func, min, max, coef) n = coef.length for i in 0 .. n-1 do m = mapp(Math.cos(Math::PI * (i + 0.5) / n), -1, 1, min, max) f = func.call(m) * 2 / n for j...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) type cheb struct { c []float64 min, max float64 } func main() { fn := math.Cos c := newCheb(0, 1, 10, 10, fn) fmt.Println("coefficients:") for _, c := range c.c { fmt.Printf("% .15f\n", c) } fmt.Println("\nx computed a...
def mapp(x, min_x, max_x, min_to, max_to) return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to end def chebyshevCoef(func, min, max, coef) n = coef.length for i in 0 .. n-1 do m = mapp(Math.cos(Math::PI * (i + 0.5) / n), -1, 1, min, max) f = func.call(m) * 2 / n for j...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) tab...
STX = "\u0002" ETX = "\u0003" def bwt(s) for c in s.split('') if c == STX or c == ETX then raise ArgumentError.new("Input can't contain STX or ETX") end end ss = ("%s%s%s" % [STX, s, ETX]).split('') table = [] for i in 0 .. ss.length - 1 table.append(ss.join) ...
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) tab...
STX = "\u0002" ETX = "\u0003" def bwt(s) for c in s.split('') if c == STX or c == ETX then raise ArgumentError.new("Input can't contain STX or ETX") end end ss = ("%s%s%s" % [STX, s, ETX]).split('') table = [] for i in 0 .. ss.length - 1 table.append(ss.join) ...
Generate an equivalent Ruby version of this Go code.
package main import "fmt" type vList struct { base *vSeg offset int } type vSeg struct { next *vSeg ele []vEle } type vEle string func (v vList) index(i int) (r vEle) { if i >= 0 { i += v.offset for sg := v.base; sg != nil; sg = sg.next { if i < len(sg.ele...
""" Rosetta Code task rosettacode.org/wiki/VList """ import Base.length, Base.string using BenchmarkTools abstract type VNode end struct VNil <: VNode end const nil = VNil() mutable struct VSeg{T} <: VNode next::VNode ele::Vector{T} end mutable struct VList base::VNode offset::Int VList(b = ni...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import "fmt" type vList struct { base *vSeg offset int } type vSeg struct { next *vSeg ele []vEle } type vEle string func (v vList) index(i int) (r vEle) { if i >= 0 { i += v.offset for sg := v.base; sg != nil; sg = sg.next { if i < len(sg.ele...
""" Rosetta Code task rosettacode.org/wiki/VList """ import Base.length, Base.string using BenchmarkTools abstract type VNode end struct VNil <: VNode end const nil = VNil() mutable struct VSeg{T} <: VNode next::VNode ele::Vector{T} end mutable struct VList base::VNode offset::Int VList(b = ni...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "fmt" "math/rand" "time" ) func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func riffle(deck []int, iterations int) []int { le := len(deck) pile := make([]int, le) copy(pile, deck) for i := 0; i < i...
def riffle deck left, right = deck.partition{rand(10).odd?} new_deck = [] until ((left_card=left.pop).to_i + (right_card=right.shift).to_i).zero? do new_deck << left_card if left_card new_deck << right_card if right_card end new_deck end def overhand deck deck, new_deck = deck.dup, [] s ...
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "math/rand" "time" ) func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func riffle(deck []int, iterations int) []int { le := len(deck) pile := make([]int, le) copy(pile, deck) for i := 0; i < i...
def riffle deck left, right = deck.partition{rand(10).odd?} new_deck = [] until ((left_card=left.pop).to_i + (right_card=right.shift).to_i).zero? do new_deck << left_card if left_card new_deck << right_card if right_card end new_deck end def overhand deck deck, new_deck = deck.dup, [] s ...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) ...
class Frac attr_accessor:num attr_accessor:denom def initialize(n,d) if d == 0 then raise ArgumentError.new('d cannot be zero') end nn = n dd = d if nn == 0 then dd = 1 elsif dd < 0 then nn = -nn dd = -dd ...
Port the provided Go code into Ruby while preserving the original functionality.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
MAX_N = 500 BRANCH = 4 def tree(br, n, l=n, sum=1, cnt=1) for b in br+1 .. BRANCH sum += n return if sum >= MAX_N return if l * 2 >= sum and b >= BRANCH if b == br + 1 c = $ra[n] * cnt else c = c * ($ra[n] + (b - br - 1)) / (b - br) end $unrooted[sum] += c if l * 2 < sum ...
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
MAX_N = 500 BRANCH = 4 def tree(br, n, l=n, sum=1, cnt=1) for b in br+1 .. BRANCH sum += n return if sum >= MAX_N return if l * 2 >= sum and b >= BRANCH if b == br + 1 c = $ra[n] * cnt else c = c * ($ra[n] + (b - br - 1)) / (b - br) end $unrooted[sum] += c if l * 2 < sum ...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "math/big" ) func bernoulli(z *big.Rat, n int64) *big.Rat { if z == nil { z = new(big.Rat) } a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return z.Set...
def binomial(n,k) if n < 0 or k < 0 or n < k then return -1 end if n == 0 or k == 0 then return 1 end num = 1 for i in k+1 .. n do num = num * i end denom = 1 for i in 2 .. n-k do denom = denom * i end return num / denom end def bernoulli(n...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Co...
require 'rubygems' require 'net/ldap' ldap = Net::LDAP.new(:host => 'hostname', :base => 'base') ldap.authenticate('bind_dn', 'bind_pass') filter = Net::LDAP::Filter.pres('objectclass') filter &= Net::LDAP::Filter.eq('sn','Jackman') filter = Net::LDAP::Filter.construct('(&(objectclass=*)(sn=Jackman))') results = ld...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "sort" ) 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 } for { p += 2 if !c[p] { break } } ...
require "prime" def prime_conspiracy(m) conspiracy = Hash.new(0) Prime.take(m).map{|n| n%10}.each_cons(2){|a,b| conspiracy[[a,b]] += 1} puts " conspiracy.sort.each do |(a,b),v| puts "%d → %d count:%10d frequency:%7.4f %" % [a, b, v, 100.0*v/m] end end prime_conspiracy(1_000_000)
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "log" "os" "strconv" ) type tree uint64 var ( list []tree offset = [32]uint{1: 1} ) func add(t tree) { list = append(list, 1|t<<1) } func show(t tree, l uint) { for ; l > 0; t >>= 1 { l-- var paren byte if (t & 1) != 0 { ...
TREE_LIST = [] OFFSET = [] for i in 0..31 if i == 1 then OFFSET << 1 else OFFSET << 0 end end def append(t) TREE_LIST << (1 | (t << 1)) end def show(t, l) while l > 0 l = l - 1 if t % 2 == 1 then print '(' else print ')' end ...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 fo...
size = 100 eca = ElemCellAutomat.new("1"+"0"*(size-1), 30) eca.take(80).map{|line| line[0]}.each_slice(8){|bin| p bin.join.to_i(2)}
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLu...
def generator(even=false, nmax=1000000) start = even ? 2 : 1 Enumerator.new do |y| n = 1 ary = [0] + (start..nmax).step(2).to_a y << ary[n] while (m = ary[n+=1]) < ary.size y << m (m...ary.size).step(m){|i| ary[i]=nil} ary.compact! end ...
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "math" "strconv" "strings" ) const ( twoI = 2.0i invTwoI = 1.0 / twoI ) type quaterImaginary struct { b2i string } func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i...
def base2i_decode(qi) return 0 if qi == '0' md = qi.match(/^(?<int>[0-3]+)(?:\.(?<frc>[0-3]+))?$/) raise 'ill-formed quarter-imaginary base value' if !md ls_pow = md[:frc] ? -(md[:frc].length) : 0 value = 0 (md[:int] + (md[:frc] ? md[:frc] : '')).reverse.each_char.with_index do |dig, inx| value += dig...
Keep all operations the same but rewrite the snippet in Ruby.
package main import ( "fmt" "math" "math/rand" "strings" ) func norm2() (s, c float64) { r := math.Sqrt(-2 * math.Log(rand.Float64())) s, c = math.Sincos(2 * math.Pi * rand.Float64()) return s * r, c * r } func main() { const ( n = 10000 bins = 12 sig =...
class NormalFromUniform def initialize() @next = nil end def rand() if @next retval, @next = @next, nil return retval else u = v = s = nil loop do u = Random.rand(-1.0..1.0) v = Random.rand(-1.0..1.0) s = u**2 + v**2 break if (s > 0.0) &...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 5 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 461, 277, 356, 488, 393 }; int demand[N_COLS] = { 278, 60, 461, 116, 1060 }; int costs[N_ROWS][N_COLS] = { { 46, 74, 9, 28, 99 }, { 12, 75, 6, 36, 48 }, ...
COSTS = {W: {A: 16, B: 16, C: 13, D: 22, E: 17}, X: {A: 14, B: 14, C: 13, D: 19, E: 15}, Y: {A: 19, B: 19, C: 20, D: 23, E: 50}, Z: {A: 50, B: 12, C: 50, D: 15, E: 11}} demand = {A: 30, B: 20, C: 70, D: 30, E: 60} supply = {W: 50, X: 60, Y: 50, Z: 50} COLS = demand.keys res = {}; COST...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "github.com/shabbyrobe/go-num" "strings" "time" ) func b10(n int64) { if n == 1 { fmt.Printf("%4d: %28s  %-24d\n", 1, "1", 1) return } n1 := n + 1 pow := make([]int64, n1) val := make([]int64, n1) var count, ten, x int64 = 0, 1, 1 ...
def mod(m, n) result = m % n if result < 0 then result = result + n end return result end def getA004290(n) if n == 1 then return 1 end arr = Array.new(n) { Array.new(n, 0) } arr[0][0] = 1 arr[0][1] = 1 m = 0 while true m = m + 1 if arr[m - 1]...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] =...
def odd_magic_square(n) n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} } end def single_even_magic_square(n) raise ArgumentError, "must be even, but not divisible by 4." unless (n-2) % 4 == 0 raise ArgumentError, "2x2 magic square not possible." if n == 2 order = (n-2)/4 odd_square ...
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import "fmt" func divisors(n int) []int { divs := []int{1} divs2 := []int{} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs2 = append(divs2, j) } } } for i := l...
def divisors(n : Int32) : Array(Int32) divs = [1] divs2 = [] of Int32 i = 2 while i * i < n if n % i == 0 j = n // i divs << i divs2 << j if i != j end i += 1 end i = divs.size - 1 while i >= 0 divs2 << divs[i] i -= 1 end divs2 end def abundant(n : Int32,...
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { ...
header = <<HEADER +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +-...
Keep all operations the same but rewrite the snippet in Ruby.
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *...
class Position attr_reader :x, :y def initialize(x, y) @x = x @y = y end def ==(other) self.x == other.x && self.y == other.y end def to_s '(%d, %d)' % [@x, @y] end def to_str to_s end end def isAttacking(queen, pos) return que...
Port the provided Go code into Ruby while preserving the original functionality.
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if is...
def isPrime(n) return false if n < 2 return n == 2 if n % 2 == 0 return n == 3 if n % 3 == 0 k = 5 while k * k <= n return false if n % k == 0 k = k + 2 end return true end def getSmallPrimes(numPrimes) smallPrimes = [2] count = 0 n = 3 while count < numPri...
Translate the given Go code snippet into Ruby without altering its behavior.
package main import ( "bufio" "fmt" "log" "os" "strings" ) type vf = func() var history []string func hello() { fmt.Println("Hello World!") history = append(history, "hello") } func hist() { if len(history) == 0 { fmt.Println("No history") } else { for _, cmd := ...
require "readline" require "abbrev" commands = %w[search download open help history quit url prev past] Readline.completion_proc = commands.abbrev.to_proc while buf = Readline.readline(">", true) exit if buf.strip == "quit" p buf end
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import "fmt" var example []int func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func checkSeq(pos, n, minLen int, seq []int) (int, int) { switch { case pos > minLen || seq[0] > n: return minLen, 0 case seq[0] == n:...
def check_seq(pos, seq, n, min_len) if pos > min_len or seq[0] > n then return min_len, 0 elsif seq[0] == n then return pos, 1 elsif pos < min_len then return try_perm(0, pos, seq, n, min_len) else return min_len, 0 end end def try_perm(i, pos, seq, n, min_len) i...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "math/big" "math/rand" "time" ) type mont struct { n uint m *big.Int r2 *big.Int } func newMont(m *big.Int) *mont { if m.Bit(0) != 1 { return nil } n := uint(m.BitLen()) x := big.NewInt(1) x.Sub(x.Lsh(x, n), m) return ...
func montgomeryReduce(m, a) { { a += m if a.is_odd a >>= 1 } * m.as_bin.len a % m } var m = 750791094644726559640638407699 var t1 = 323165824550862327179367294465482435542970161392400401329100 var r1 = 440160025148131680164261562101 var r2 = 435362628198191204145287283255 var x1 = 54001...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "strings" ) func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) } func solve(board string) string { buffer = make([]byte, len(board)) width ...
require 'set' class Sokoban def initialize(level) board = level.each_line.map(&:rstrip) @nrows = board.map(&:size).max board.map!{|line| line.ljust(@nrows)} board.each_with_index do |row, r| row.each_char.with_index do |ch, c| @px, @py = c, r if ch == '@' or ch == '+' end end...
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(div...
class Integer def divisors res = [1, self] (2..Integer.sqrt(self)).each do |n| div, mod = divmod(n) res << n << div if mod.zero? end res.uniq.sort end def zumkeller? divs = divisors sum = divs.sum return false unless sum.even? && sum >= self*2 half = sum / 2 ...
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import ( "fmt" "math" "sort" "time" ) type term struct { coeff uint64 ix1, ix2 int8 } const maxDigits = 19 func toUint64(digits []int8, reverse bool) uint64 { sum := uint64(0) if !reverse { for i := 0; i < len(digits); i++ { sum = sum*10 + uint64(d...
Term = Struct.new(:coeff, :ix1, :ix2) do end MAX_DIGITS = 16 def toLong(digits, reverse) sum = 0 if reverse then i = digits.length - 1 while i >=0 sum = sum *10 + digits[i] i = i - 1 end else i = 0 while i < digits.length sum = s...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree {...
func suffix_tree(Str t) { suffix_tree(^t.len -> map { t.substr(_) }) } func suffix_tree(a {.len == 1}) { Hash(a[0] => nil) } func suffix_tree(Arr a) { var h = Hash() for k,v in (a.group_by { .char(0) }) { var subtree = suffix_tree(v.map { .substr(1) }) var subkeys = subtree.keys ...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree {...
func suffix_tree(Str t) { suffix_tree(^t.len -> map { t.substr(_) }) } func suffix_tree(a {.len == 1}) { Hash(a[0] => nil) } func suffix_tree(Arr a) { var h = Hash() for k,v in (a.group_by { .char(0) }) { var subtree = suffix_tree(v.map { .substr(1) }) var subkeys = subtree.keys ...
Translate the given Go code snippet into Ruby without altering its behavior.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i...
class Foo @@xyz = nil def initialize(name, age) @name, @age = name, age end def add_sex(sex) @sex = sex end end p foo = Foo.new("Angel", 18) p foo.instance_variables p foo.instance_variable_defined?(:@age) p foo.instance_variable_get(:@age) p foo.instance_variable_s...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {le...
class Node def initialize(length, edges = {}, suffix = 0) @length = length @edges = edges @suffix = suffix end attr_reader :length attr_reader :edges attr_accessor :suffix end EVEN_ROOT = 0 ODD_ROOT = 1 def eertree(s) tree = [ Node.new(0, {}, ODD_ROOT), ...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {le...
class Node def initialize(length, edges = {}, suffix = 0) @length = length @edges = edges @suffix = suffix end attr_reader :length attr_reader :edges attr_accessor :suffix end EVEN_ROOT = 0 ODD_ROOT = 1 def eertree(s) tree = [ Node.new(0, {}, ODD_ROOT), ...
Translate the given Go code snippet into Ruby without altering its behavior.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { ...
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" nums = [25420294593250030202636073700053352635053786165627414518, 0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, ...
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { ...
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" nums = [25420294593250030202636073700053352635053786165627414518, 0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, ...