Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following Go implementation into Ruby, maintaining the same output and logic.
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}
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import "fmt" func möbius(to int) []int { if to < 1 { to = 1 } mobs := make([]int, to+1) primes := []int{2} for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break ...
require 'prime' def μ(n) pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even? ? 1 : -1 end ([" "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }
Port the provided Go code into Ruby while preserving the original functionality.
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byt...
define tape_length = 50_000; define eof_val = -1; define unbalanced_exit_code = 1; var cmd = 0; var cell = 0; var code = []; var loops = []; var tape = tape_length.of(0); func get_input { static input_buffer = []; input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord}));...
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byt...
define tape_length = 50_000; define eof_val = -1; define unbalanced_exit_code = 1; var cmd = 0; var cell = 0; var code = []; var loops = []; var tape = tape_length.of(0); func get_input { static input_buffer = []; input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord}));...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, ...
list = [1, 2] available = (1..50).to_a - list loop do i = available.index{|a| list.last(2).all?{|b| a.gcd(b) == 1}} break if i.nil? list << available.delete_at(i) end puts list.join(" ")
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, ...
list = [1, 2] available = (1..50).to_a - list loop do i = available.index{|a| list.last(2).all?{|b| a.gcd(b) == 1}} break if i.nil? list << available.delete_at(i) end puts list.join(" ")
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func main() { zero := big.NewInt(0) one := big.NewInt(1) for k := int64(2); k <= 10; k += 2 { bk := big.NewInt(k) fmt.Println("The first 50 Curzon numbers using a base of", k, ":") count := 0 n := int64(1) pow := big....
def curzons(k) Enumerator.new do |y| (1..).each do |n| r = k * n y << n if k.pow(n, r + 1) == r end end end [2,4,6,8,10].each do |base| puts "Curzon numbers with k = puts curzons(base).take(50).join(", ") puts "Thousandth Curzon with k = end
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/big" ) func main() { zero := big.NewInt(0) one := big.NewInt(1) for k := int64(2); k <= 10; k += 2 { bk := big.NewInt(k) fmt.Println("The first 50 Curzon numbers using a base of", k, ":") count := 0 n := int64(1) pow := big....
def curzons(k) Enumerator.new do |y| (1..).each do |n| r = k * n y << n if k.pow(n, r + 1) == r end end end [2,4,6,8,10].each do |base| puts "Curzon numbers with k = puts curzons(base).take(50).join(", ") puts "Thousandth Curzon with k = end
Translate the given Go code snippet into Ruby without altering its behavior.
package main import "fmt" func mertens(to int) ([]int, int, int) { if to < 1 { to = 1 } merts := make([]int, to+1) primes := []int{2} var sum, zeros, crosses int for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { ...
require 'prime' def μ(n) return 1 if self == 1 pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even? ? 1 : -1 end def M(n) (1..n).sum{|n| μ(n)} end ([" "] + (1..199).map{|n|"%2s" % M(n)}).each_slice(20){|line| puts line.join(" ") } ar = (1..1000).map{|n| M(n)} puts "\nThe Mertens fun...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } re...
def divisor_count(n) total = 1 while n % 2 == 0 do total = total + 1 n = n >> 1 end p = 3 while p * p <= n do count = 1 while n % p == 0 do count = count + 1 n = n / p end total = total * count p = p + 2 en...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } re...
def divisor_count(n) total = 1 while n % 2 == 0 do total = total + 1 n = n >> 1 end p = 3 while p * p <= n do count = 1 while n % p == 0 do count = count + 1 n = n / p end total = total * count p = p + 2 en...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e6) lowerLimit := 2500 c := rcu.PrimeSieve(limit-1, true) var erdos []int lastErdos := 0 ec := 0 for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { ...
func is_erdos_prime(p) { return true if p==2 return false if !p.is_prime var f = 1 for (var k = 2; f < p; k++) { p - f -> is_composite || return false f *= k } return true } say ("Erdős primes <= 2500: ", 1..2500 -> grep(is_erdos_prime)) say ("The 7875th Erdős prime is: ", ...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e6) lowerLimit := 2500 c := rcu.PrimeSieve(limit-1, true) var erdos []int lastErdos := 0 ec := 0 for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { ...
func is_erdos_prime(p) { return true if p==2 return false if !p.is_prime var f = 1 for (var k = 2; f < p; k++) { p - f -> is_composite || return false f *= k } return true } say ("Erdős primes <= 2500: ", 1..2500 -> grep(is_erdos_prime)) say ("The 7875th Erdős prime is: ", ...
Please provide an equivalent version of this Go code in Ruby.
package cards import ( "math/rand" ) type Suit uint8 const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 ) func (s Suit) String() string { const suites = "CDHS" return suites[s : s+1] } type Rank uint8 const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Fiv...
class Card SUITS = %i[ Clubs Hearts Spades Diamonds ] PIPS = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ] @@suit_value = Hash[ SUITS.each_with_index.to_a ] @@pip_value = Hash[ PIPS.each_with_index.to_a ] attr_reader :pip, :suit def initialize(pip,suit) @pip = pip @suit = suit end ...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main;func main(){print("Code Golf")}
$><<"Code Golf" puts $><<['436F646520476F6C66'].pack('H*')
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main;func main(){print("Code Golf")}
$><<"Code Golf" puts $><<['436F646520476F6C66'].pack('H*')
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "rcu" ) func main() { pairs := [][2]int{{21, 15}, {17, 23}, {36, 12}, {18, 29}, {60, 15}} fmt.Println("The following pairs of numbers are coprime:") for _, pair := range pairs { if rcu.Gcd(pair[0], pair[1]) == 1 { fmt.Println(pair) } } }
pairs = [[21,15],[17,23],[36,12],[18,29],[60,15]] pairs.select{|p, q| p.gcd(q) == 1}.each{|pair| p pair}
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "rcu" ) func main() { pairs := [][2]int{{21, 15}, {17, 23}, {36, 12}, {18, 29}, {60, 15}} fmt.Println("The following pairs of numbers are coprime:") for _, pair := range pairs { if rcu.Gcd(pair[0], pair[1]) == 1 { fmt.Println(pair) } } }
pairs = [[21,15],[17,23],[36,12],[18,29],[60,15]] pairs.select{|p, q| p.gcd(q) == 1}.each{|pair| p pair}
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { ...
require "prime" class Integer def φ prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end def perfect_totient? f, sum = self, 0 until f == 1 do f = f.φ sum += f end self == sum end end puts (1..).lazy.select(&:perfect_totient?).first(20).join(", ")
Translate the given Go code snippet into Ruby without altering its behavior.
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { ...
require "prime" class Integer def φ prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end def perfect_totient? f, sum = self, 0 until f == 1 do f = f.φ sum += f end self == sum end end puts (1..).lazy.select(&:perfect_totient?).first(20).join(", ")
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" big "github.com/ncw/gmp" ) var two = big.NewInt(2) func a(n uint) int { one := big.NewInt(1) p := new(big.Int).Lsh(one, 1 << n) p.Sub(p, one) for k := 1; ; k += 2 { if p.ProbablyPrime(15) { return k } p.Sub(p, two) } } func ...
require 'openssl' (1..10).each do |n| pow = 2 ** (2 ** n) print " puts (1..).step(2).detect{|k| OpenSSL::BN.new(pow-k).prime?} end
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" big "github.com/ncw/gmp" ) var two = big.NewInt(2) func a(n uint) int { one := big.NewInt(1) p := new(big.Int).Lsh(one, 1 << n) p.Sub(p, one) for k := 1; ; k += 2 { if p.ProbablyPrime(15) { return k } p.Sub(p, two) } } func ...
require 'openssl' (1..10).each do |n| pow = 2 ** (2 ** n) print " puts (1..).step(2).detect{|k| OpenSSL::BN.new(pow-k).prime?} end
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*) def lah(n, k) case k when 1 then fact(n) when n then 1 when (..1),(n..) then 0 else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k) end end r = (0..12) puts "Unsigned Lah numbers: L(n, k):" puts "n/k r.each do |row| print...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*) def lah(n, k) case k when 1 then fact(n) when n then 1 when (..1),(n..) then 0 else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k) end end r = (0..12) puts "Unsigned Lah numbers: L(n, k):" puts "n/k r.each do |row| print...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import "fmt" func twoSum(a []int, targetSum int) (int, int, bool) { len := len(a) if len < 2 { return 0, 0, false } for i := 0; i < len - 1; i++ { if a[i] <= targetSum { for j := i + 1; j < len; j++ { sum := a[i] + a[j] if sum ==...
def two_sum(numbers, sum) numbers.each_with_index do |x,i| if j = numbers.index(sum - x) then return [i,j] end end [] end numbers = [0, 2, 11, 19, 90] p two_sum(numbers, 21) p two_sum(numbers, 25)
Translate the given Go code snippet into Ruby without altering its behavior.
package main import "fmt" func twoSum(a []int, targetSum int) (int, int, bool) { len := len(a) if len < 2 { return 0, 0, false } for i := 0; i < len - 1; i++ { if a[i] <= targetSum { for j := i + 1; j < len; j++ { sum := a[i] + a[j] if sum ==...
def two_sum(numbers, sum) numbers.each_with_index do |x,i| if j = numbers.index(sum - x) then return [i,j] end end [] end numbers = [0, 2, 11, 19, 90] p two_sum(numbers, 21) p two_sum(numbers, 25)
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") ...
if ENV.values_at("LC_ALL","LC_CTYPE","LANG").compact.first.include?("UTF-8") puts "△" else raise "Terminal can't handle UTF-8" end
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") ...
if ENV.values_at("LC_ALL","LC_CTYPE","LANG").compact.first.include?("UTF-8") puts "△" else raise "Terminal can't handle UTF-8" end
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "fmt" "strconv" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false ...
require 'prime' def unprimable?(n) digits = %w(0 1 2 3 4 5 6 7 8 9) s = n.to_s size = s.size (size-1).downto(0) do |i| digits.each do |d| cand = s.dup cand[i]=d return false if cand.to_i.prime? end end true end ups = Enumerator.new {|y| (1..).each{|n| y << n if unprimable?(n)} } ...
Please provide an equivalent version of this Go 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' taus = Enumerator.new do |y| (1..).each do |n| num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 } y << n if n % num_divisors == 0 end end p taus.take(100)
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) 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...
require 'prime' def digitSum(n) sum = 0 while n > 0 sum += n % 10 n /= 10 end return sum end for p in Prime.take_while { |p| p < 5000 } if digitSum(p) == 25 then print p, " " end end
Please provide an equivalent version of this Go code in Ruby.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) 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...
require 'prime' def digitSum(n) sum = 0 while n > 0 sum += n % 10 n /= 10 end return sum end for p in Prime.take_while { |p| p < 5000 } if digitSum(p) == 25 then print p, " " end end
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) }...
def primeDigitsSum13(n) sum = 0 while n > 0 r = n % 10 if r != 2 and r != 3 and r != 5 and r != 7 then return false end n = (n / 10).floor sum = sum + r end return sum == 13 end c = 0 for i in 1 .. 1000000 if primeDigitsSum13(i) then print...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) }...
def primeDigitsSum13(n) sum = 0 while n > 0 r = n % 10 if r != 2 and r != 3 and r != 5 and r != 7 then return false end n = (n / 10).floor sum = sum + r end return sum == 13 end c = 0 for i in 1 .. 1000000 if primeDigitsSum13(i) then print...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import "fmt" type cds struct { i int s string b []byte m map[int]bool } func (c cds) deepcopy() *cds { r := &cds{c.i, c.s, append([]byte{}, c.b...), make(map[int]bool)} for k, v := range c.m { r.m[k] = v } return r } ...
orig = { :num => 1, :ary => [2, 3] } orig[:cycle] = orig copy = Marshal.load(Marshal.dump orig) orig[:ary] << 4 orig[:rng] = (5..6) p orig p copy p [(orig.equal? orig[:cycle]), (copy.equal? copy[:cycle]), (not orig.equal? copy)]
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import "fmt" type cds struct { i int s string b []byte m map[int]bool } func (c cds) deepcopy() *cds { r := &cds{c.i, c.s, append([]byte{}, c.b...), make(map[int]bool)} for k, v := range c.m { r.m[k] = v } return r } ...
orig = { :num => 1, :ary => [2, 3] } orig[:cycle] = orig copy = Marshal.load(Marshal.dump orig) orig[:ary] << 4 orig[:rng] = (5..6) p orig p copy p [(orig.equal? orig[:cycle]), (copy.equal? copy[:cycle]), (not orig.equal? copy)]
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { ...
require 'gmp' require 'prime' candidate_primes = Enumerator.new do |y| DIGS = [1,3,7,9] [2,3,5,7].each{|n| y << n.to_s} (2..).each do |size| DIGS.repeated_permutation(size) do |perm| y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0 end end end def min_rotation...
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(101) var frobenius []int for i := 0; i < len(primes)-1; i++ { frob := primes[i]*primes[i+1] - primes[i] - primes[i+1] if frob >= 10000 { break } frobenius = append(frobenius, frob) ...
require 'prime' Prime.each_cons(2) do |p1, p2| f = p1*p2-p1-p2 break if f > 10_000 puts f end
Produce a functionally identical Ruby code for the snippet given in Go.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(101) var frobenius []int for i := 0; i < len(primes)-1; i++ { frob := primes[i]*primes[i+1] - primes[i] - primes[i+1] if frob >= 10000 { break } frobenius = append(frobenius, frob) ...
require 'prime' Prime.each_cons(2) do |p1, p2| f = p1*p2-p1-p2 break if f > 10_000 puts f end
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) if len(a) > 1 && !recurse(len(a) - 1) { panic("sorted permutation not found!") } fmt.Println("after: ", a) } func recurse(last int) bool { ...
class Array def permutationsort permutation.each{|perm| return perm if perm.sorted?} end def sorted? each_cons(2).all? {|a, b| a <= b} end end
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import "fmt" func main() { fmt.Println(root(3, 8)) fmt.Println(root(3, 9)) fmt.Println(root(2, 2e18)) } func root(N, X int) int { for r := 1; ; { x := X for i := 1; i < N; i++ { x /= r } x -= r Δ...
def root(a,b) return b if b<2 a1, c = a-1, 1 f = -> x {(a1*x+b/(x**a1))/a} d = f[c] e = f[d] c, d, e = d, e, f[e] until [d,e].include?(c) [d,e].min end puts "First 2,001 digits of the square root of two:" puts root(2, 2*100**2000)
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import "fmt" func main() { fmt.Println(root(3, 8)) fmt.Println(root(3, 9)) fmt.Println(root(2, 2e18)) } func root(N, X int) int { for r := 1; ; { x := X for i := 1; i < N; i++ { x /= r } x -= r Δ...
def root(a,b) return b if b<2 a1, c = a-1, 1 f = -> x {(a1*x+b/(x**a1))/a} d = f[c] e = f[d] c, d, e = d, e, f[e] until [d,e].include?(c) [d,e].min end puts "First 2,001 digits of the square root of two:" puts root(2, 2*100**2000)
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "math/big" "rcu" "sort" ) func main() { primes := rcu.Primes(379) primorial := big.NewInt(1) var fortunates []int bPrime := new(big.Int) for _, prime := range primes { bPrime.SetUint64(uint64(prime)) primorial.Mul(primorial, bPrime) ...
require "gmp" primorials = Enumerator.new do |y| cur = prod = 1 loop {y << prod *= (cur = GMP::Z(cur).nextprime)} end limit = 50 fortunates = [] while fortunates.size < limit*2 do prim = primorials.next fortunates << (GMP::Z(prim+2).nextprime - prim) fortunates = fortunates.uniq.sort end p fortunates[0, ...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
def meaning_of_life 42 end if __FILE__ == $0 puts "Main: The meaning of life is end
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
def meaning_of_life 42 end if __FILE__ == $0 puts "Main: The meaning of life is end
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) ...
func foo { } func bar { } foo(); foo(); foo() bar(); bar(); var data = Perl.to_sidef(Parser{:vars}{:main}).flatten data.sort_by { |v| -v{:count} }.first(10).each { |entry| if (entry{:type} == :func) { say ("Function ` " } }
Port the provided Go code into Ruby while preserving the original functionality.
package main import ( "encoding/binary" "encoding/json" "fmt" "github.com/boltdb/bolt" "log" ) type StockTrans struct { Id int Date string Trans string Symbol string Quantity int Price float32 Settled bool } func (st *StockTrans) save(db *bolt.DB, ...
require 'pstore' db = PStore.new "filename.pstore"
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "encoding/binary" "encoding/json" "fmt" "github.com/boltdb/bolt" "log" ) type StockTrans struct { Id int Date string Trans string Symbol string Quantity int Price float32 Settled bool } func (st *StockTrans) save(db *bolt.DB, ...
require 'pstore' db = PStore.new "filename.pstore"
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
require 'prime' class Integer def dig_root = (1+(self-1).remainder(9)) def nice? = prime? && dig_root.prime? end p (500..1000).select(&:nice?)
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
require 'prime' class Integer def dig_root = (1+(self-1).remainder(9)) def nice? = prime? && dig_root.prime? end p (500..1000).select(&:nice?)
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "time" ) func main() { var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } } fmt.Prin...
require 'date' def last_sundays_of_year(year = Date.today.year) (1..12).map do |month| d = Date.new(year, month, -1) d - d.wday end end puts last_sundays_of_year(2013)
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "time" ) func main() { var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } } fmt.Prin...
require 'date' def last_sundays_of_year(year = Date.today.year) (1..12).map do |month| d = Date.new(year, month, -1) d - d.wday end end puts last_sundays_of_year(2013)
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "math/rand" "time" ) type matrix [][]int func shuffle(row []int, n int) { rand.Shuffle(n, func(i, j int) { row[i], row[j] = row[j], row[i] }) } func latinSquare(n int) { if n <= 0 { fmt.Println("[]\n") return } latin := make(matrix,...
N = 5 def generate_square perms = (1..N).to_a.permutation(N).to_a.shuffle square = [] N.times do square << perms.pop perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} } end square end def print_square(square) cell_size = N.digits.size + 1 strings = square.map!{|row| row.ma...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "bufio" "fmt" "log" "os" "sort" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner :...
lists = ["unixdict.txt", "wordlist.10000", "woordenlijst.txt"] lists.each do |list| words = open(list).readlines( chomp: true).reject{|w| w.size < 3 } grouped_by_size = words.group_by(&:size) tea_words = words.filter_map do |word| chars = word.chars next unless chars.none?{|c| c < chars.first } next ...
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } retu...
def turn(base, n) sum = 0 while n != 0 do rem = n % base n = n / base sum = sum + rem end return sum % base end def fairshare(base, count) print "Base %2d: " % [base] for i in 0 .. count - 1 do t = turn(base, i) print " %2d" % [t] end print "\n" e...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strconv" ) func uabs(a, b uint64) uint64 { if a > b { return a - b } return b - a } func isEsthetic(n, b uint64) bool { if n == 0 { return false } i := n % b n /= b for n > 0 { j := n % b if uabs(i, j) != 1 { ...
def isEsthetic(n, b) if n == 0 then return false end i = n % b n2 = (n / b).floor while n2 > 0 j = n2 % b if (i - j).abs != 1 then return false end n2 = n2 / b i = j end return true end def listEsths(n, n2, m, m2, perLine, all) ...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, le...
require 'prime' digits = [9,8,7,6,5,4,3,2,1].to_a res = 1.upto(digits.size).flat_map do |n| digits.combination(n).filter_map do |set| candidate = set.join.to_i candidate if candidate.prime? end.reverse end puts res.join(",")
Maintain the same structure and functionality when rewriting this code in Ruby.
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
str = "你好" str.include?("好")
Translate this program into Ruby but keep the logic exactly as in Go.
package permute func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } } func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } defa...
def perms(n) p = Array.new(n+1){|i| -i} s = 1 loop do yield p[1..-1].map(&:abs), s k = 0 for i in 2..n k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs end for i in 1...n k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs end break if k....
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "fmt" "math/rand" "sort" "time" ) func main() { s := rand.NewSource(time.Now().UnixNano()) r := rand.New(s) for { var values [6]int vsum := 0 for i := range values { var numbers [4]int for j := range numbers { ...
def roll_stat dices = Array(Int32).new(4) { rand(1..6) } dices.sum - dices.min end def roll_character loop do stats = Array(Int32).new(6) { roll_stat } return stats if stats.sum >= 75 && stats.count(&.>=(15)) >= 2 end end 10.times do stats = roll_character puts "stats: end
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import "fmt" func nextInCycle(c []int, index int) int { return c[index % len(c)] } func kolakoski(c []int, slen int) []int { s := make([]int, slen) i, k := 0, 0 for { s[i] = nextInCycle(c, k) if s[k] > 1 { for j := 1; j < s[k]; j++ { i++ ...
def create_generator(ar) Enumerator.new do |y| cycle = ar.cycle s = [] loop do t = cycle.next s.push(t) v = s.shift y << v (v-1).times{s.push(t)} end end end def rle(ar) ar.slice_when{|a,b| a != b}.map(&:size) end [[20, [1,2]], [20, [2,1]], [30, [1,3,1,2]], [30...
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 seq :=...
require 'prime' def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end def first_with_num_divs(n) (1..).detect{|i| num_divisors(i) == n } end p (1..15).map{|n| first_with_num_divs(n) }
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "bufio" "errors" "fmt" "math" "os" "regexp" "strconv" "strings" ) func main() { fmt.Println("Numbers please separated by space/commas:") sc := bufio.NewScanner(os.Stdin) sc.Scan() s, n, min, max, err := spark(sc.Text()) if err != nil { ...
bar = ('▁'..'█').to_a loop {print 'Numbers please separated by space/commas: ' numbers = gets.split(/[\s,]+/).map(&:to_f) min, max = numbers.minmax puts "min: %5f; max: %5f"% [min, max] div = (max - min) / (bar.size - 1) puts min == max ? bar.last*numbers.size : numbers.map{|num| bar[((num - min) / div).to_i...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "github.com/biogo/biogo/align" ab "github.com/biogo/biogo/alphabet" "github.com/biogo/biogo/feat" "github.com/biogo/biogo/seq/linear" ) func main() { lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz", feat.Undefined, '-', 0, true)) ...
require 'lcs' def levenshtein_align(a, b) apos, bpos = LCS.new(a, b).backtrack2 c = "" d = "" x0 = y0 = -1 dx = dy = 0 apos.zip(bpos) do |x,y| diff = x + dx - y - dy if diff < 0 dx -= diff c += "-" * (-diff) elsif diff > 0 dy += diff d += "-" * diff end c += a...
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back =...
Node = Struct.new(:val, :back) def lis(n) pileTops = [] for x in n low, high = 0, pileTops.size-1 while low <= high mid = low + (high - low) / 2 if pileTops[mid].val >= x high = mid - 1 else low = mid + 1 end end i = low node = Node.new(x) nod...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import "fmt" type person struct{ name string age int } func copy(p person) person { return person{p.name, p.age} } func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) }
class IDVictim attr_accessor :name, :birthday, :gender, :hometown def self.new_element(element) attr_accessor element end end
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "math" ) func main() { pow := 1 for p := 0; p < 5; p++ { low := int(math.Ceil(math.Sqrt(float64(pow)))) if low%2 == 0 { low++ } pow *= 10 high := int(math.Sqrt(float64(pow))) var oddSq []int for i := low; i...
lo, hi = 100, 1000 (Integer.sqrt(lo)..Integer.sqrt(hi)).each{|n| puts n*n if n.odd?}
Please provide an equivalent version of this Go code in Ruby.
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []strin...
new_word_size = 9 well_sized = File.readlines("unixdict.txt", chomp: true).reject{|word| word.size < new_word_size} list = well_sized.each_cons(new_word_size).filter_map do |slice| candidate = (0...new_word_size).inject(""){|res, idx| res << slice[idx][idx] } candidate if well_sized.include?(candidate) end puts li...
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "rcu" ) func main() { for i := 1; i < 100; i++ { if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) { continue } if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) { fmt.Printf("%d ", i) } } fmt.Println() }
require 'prime' p (1..100).select{|n|(n*n).digits.sum.prime? && (n**3).digits.sum.prime?}
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } ...
func odd_squarefree_almost_primes(upto, k=2) { k.squarefree_almost_primes(upto).grep{.is_odd} } with (1e3) {|n| var list = odd_squarefree_almost_primes(n, 2) say "Found say (list.first(10).join(', '), ', ..., ', list.last(10).join(', ')) }
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } ...
func odd_squarefree_almost_primes(upto, k=2) { k.squarefree_almost_primes(upto).grep{.is_odd} } with (1e3) {|n| var list = odd_squarefree_almost_primes(n, 2) say "Found say (list.first(10).join(', '), ', ..., ', list.last(10).join(', ')) }
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } fun...
require 'prime' base = 10 upto = 1000 res = Prime.each(upto).select do |pr| pr.digits(base).each_cons(2).all?{|p1, p2| p1 >= p2} end puts "There are puts res.join(", ")
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } fun...
require 'prime' base = 10 upto = 1000 res = Prime.each(upto).select do |pr| pr.digits(base).each_cons(2).all?{|p1, p2| p1 >= p2} end puts "There are puts res.join(", ")
Please provide an equivalent version of this Go code in Ruby.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
func is_briliant_number(n) { n.is_semiprime && (n.factor.map{.len}.uniq.len == 1) } func brilliant_numbers_count(n) { var count = 0 var len = n.isqrt.len for k in (1 .. len-1) { var pi = prime_count(10**(k-1), 10**k - 1) count += binomial(pi, 2)+pi } var min = (10**(len - 1))...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
func is_briliant_number(n) { n.is_semiprime && (n.factor.map{.len}.uniq.len == 1) } func brilliant_numbers_count(n) { var count = 0 var len = n.isqrt.len for k in (1 .. len-1) { var pi = prime_count(10**(k-1), 10**k - 1) count += binomial(pi, 2)+pi } var min = (10**(len - 1))...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f...
cw = Enumerator.new do |y| y << a = 1.to_r loop { y << a = 1/(2*a.floor + 1 - a) } end def term_num(rat) num, den, res, pwr, dig = rat.numerator, rat.denominator, 0, 0, 1 while den > 0 num, (digit, den) = den, num.divmod(den) digit.times do res |= dig << pwr pwr += 1 end dig ^= 1 ...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f...
cw = Enumerator.new do |y| y << a = 1.to_r loop { y << a = 1/(2*a.floor + 1 - a) } end def term_num(rat) num, den, res, pwr, dig = rat.numerator, rat.denominator, 0, 0, 1 while den > 0 num, (digit, den) = den, num.divmod(den) digit.times do res |= dig << pwr pwr += 1 end dig ^= 1 ...
Produce a functionally identical Ruby code for the snippet given in Go.
package main import ( "fmt" "sort" "strings" ) type indexSort struct { val sort.Interface ind []int } func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], ...
def order_disjoint(m,n) print " m, n = m.split, n.split from = 0 n.each_slice(2) do |x,y| next unless y sd = m[from..-1] if x > y && (sd.include? x) && (sd.include? y) && (sd.index(x) > sd.index(y)) new_from = m.index(x)+1 m[m.index(x)+from], m[m.index(y)+from] = m[m.index(y)+from], m[m....
Write the same code in Ruby as shown below in Go.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return ...
require 'prime' puts File.open("unixdict.txt").select{|line| line.chomp.chars.all?{|c| c.ord.prime?} }
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return ...
require 'prime' puts File.open("unixdict.txt").select{|line| line.chomp.chars.all?{|c| c.ord.prime?} }
Produce a functionally identical Ruby code for the snippet given in Go.
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
require 'prime' p Prime.each(1000).select{|pr| pr.digits == pr.digits.reverse}
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
require 'prime' p Prime.each(1000).select{|pr| pr.digits == pr.digits.reverse}
Please provide an equivalent version of this Go code in Ruby.
package main import ( "fmt" "math" "rcu" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { limit := 200000 d := rcu.PrimeSieve(limit-1, true) d[1] = false for i := 2; i < limit; i++ { if !d[i] { continue } ...
func is_duffinian(n) { n.is_composite && n.is_coprime(n.sigma) } say "First 50 Duffinian numbers:" say 50.by(is_duffinian) say "\nFirst 15 Duffinian triplets:" 15.by{|n| ^3 -> all {|k| is_duffinian(n+k) } }.each {|n| printf("(%s, %s, %s)\n", n, n+1, n+2) }
Produce a functionally identical Ruby code for the snippet given in Go.
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) two := big.NewInt(2) next := new(big.Int) sylvester := []*big.Int{two} prod := new(big.Int).Set(two) count := 1 for count < 10 { next.Add(prod, one) sylvester = append(sylvester, new(big.Int...
def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 } (0..9).each {|n| puts " puts " Sum of reciprocals of first 10 terms:
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "math/big" ) func harmonic(n int) *big.Rat { sum := new(big.Rat) for i := int64(1); i <= int64(n); i++ { r := big.NewRat(1, i) sum.Add(sum, r) } return sum } func main() { fmt.Println("The first 20 harmonic numbers and the 100th, expressed in ra...
harmonics = Enumerator.new do |y| res = 0 (1..).each {|n| y << res += Rational(1, n) } end n = 20 The first harmonics.take(n).each_slice(5){|slice| puts "%20s"*slice.size % slice } puts milestones = (1..10).to_a harmonics.each.with_index(1) do |h,i| if h > milestones.first then puts "The first harmonic num...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
$ irb irb(main):001:0> def f(string1, string2, separator) irb(main):002:1> [string1, '', string2].join(separator) irb(main):003:1> end => :f irb(main):004:0> f('Rosetta', 'Code', ':') => "Rosetta::Code" irb(main):005:0> exit $
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
def bind_x_to_value(x) binding end def eval_with_x(code, a, b) eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a)) end puts eval_with_x('2 ** x', 3, 5)
Keep all operations the same but rewrite the snippet in Ruby.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
def bind_x_to_value(x) binding end def eval_with_x(code, a, b) eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a)) end puts eval_with_x('2 ** x', 3, 5)
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She wa...
var male2female = <<'EOD' maleS femaleS, maleness femaleness, him her, himself herself, his her, his hers, he she, Mr Mrs, Mister Missus, Ms Mr, Master Miss, MasterS MistressES, uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS, brotherS sisterS, man woman, men women, boyS girlS, paternal m...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She wa...
var male2female = <<'EOD' maleS femaleS, maleness femaleness, him her, himself herself, his her, his hers, he she, Mr Mrs, Mister Missus, Ms Mr, Master Miss, MasterS MistressES, uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS, brotherS sisterS, man woman, men women, boyS girlS, paternal m...
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time er...
a, b = 5, -7 ans = eval "(a * b).abs"
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time er...
a, b = 5, -7 ans = eval "(a * b).abs"
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/big" ) func rank(l []uint) (r big.Int) { for _, n := range l { r.Lsh(&r, n+1) r.SetBit(&r, int(n), 1) } return } func unrank(n big.Int) (l []uint) { m := new(big.Int).Set(&n) for a := m.BitLen(); a > 0; { m.SetBit(m, a-1, 0) ...
def rank(arr) arr.join('a').to_i(11) end def unrank(n) n.to_s(11).split('a').map(&:to_i) end l = [1, 2, 3, 10, 100, 987654321] p l n = rank(l) p n l = unrank(n) p l
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "log" "math/rand" "time" ) func generate(from, to int64) { if to < from || from < 0 { log.Fatal("Invalid range.") } span := to - from + 1 generated := make([]bool, span) count := span for count > 0 { n := from + rand.Int63n(span) ...
nums = (1..20).to_a 5.times{ puts nums.shuffle.join(" ") }
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
^Inf -> lazy.grep{|p| all_prime(p, 2*p + 1) }.first(50).slices(10).each{ .join(', ').say }
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
^Inf -> lazy.grep{|p| all_prime(p, 2*p + 1) }.first(50).slices(10).each{ .join(', ').say }
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "rcu" "strconv" "strings" ) func findFirst(list []int) (int, int) { for i, n := range list { if n > 1e7 { return n, i } } return -1, -1 } func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; ...
require 'prime' NONZEROS = %w(1 2 3 4 5 6 7 8 9) cyclopes = Enumerator.new do |y| (0..).each do |n| NONZEROS.repeated_permutation(n) do |lside| NONZEROS.repeated_permutation(n) do |rside| y << (lside.join + "0" + rside.join).to_i end end end end prime_cyclopes = Enumerator...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
def conjugate(infinitive) return ["Can not conjugate conjugations = case infinitive[-3..-1] when "are" then ["o", "as", "at", "amus", "atis", "ant"] when "ēre" then ["eo", "es", "et", "emus", "etis", "ent"] when "ere" then ["o", "is", "it", "imus", "itis", "unt"] when "ire" then ["io", "is", "it"...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
def conjugate(infinitive) return ["Can not conjugate conjugations = case infinitive[-3..-1] when "are" then ["o", "as", "at", "amus", "atis", "ant"] when "ēre" then ["eo", "es", "et", "emus", "etis", "ent"] when "ere" then ["o", "is", "it", "imus", "itis", "unt"] when "ire" then ["io", "is", "it"...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
require 'prime' RE = /123/ puts Prime.each(100_000).select {|prime| RE.match? prime.to_s}.join(" "), "" puts "