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"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
... | def backup_and_open(filename)
filename = File.realpath(filename)
bkup = filename + ".backup"
backup_files = Dir.glob(bkup + "*").sort_by do |f|
f.match(/\d+$/)
$&.nil? ? 0 : $&.to_i
end
backup_files.reverse.each do |fname|
if m = fname.match(/\.backup\.(\d+)$/)
File.rename(fname, "%s.%d" % [... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
... | def backup_and_open(filename)
filename = File.realpath(filename)
bkup = filename + ".backup"
backup_files = Dir.glob(bkup + "*").sort_by do |f|
f.match(/\d+$/)
$&.nil? ? 0 : $&.to_i
end
backup_files.reverse.each do |fname|
if m = fname.match(/\.backup\.(\d+)$/)
File.rename(fname, "%s.%d" % [... |
Change the following Go code into Ruby without altering its purpose. | package main
import "fmt"
import "io/ioutil"
import "log"
import "os"
import "regexp"
import "strings"
func main() {
err := fix()
if err != nil {
log.Fatalln(err)
}
}
func fix() (err error) {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
out, err := Lang(string(buf))
if err != nil {
... |
text = DATA.read
slash_lang = '/lang'
langs = %w(foo bar baz)
for lang in langs
text.gsub!(Regexp.new("<(
text.gsub!(Regexp.new("</
end
text.gsub!(/<code (.*?)>/, '<lang \1>')
text.gsub!(/<\/code>/, "<
print text
__END__
Lorem ipsum <code foo>saepe audire</code> elaboraret ne quo, id equidem
atomorum inciderin... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103}
var primes []int
for _, e := range list {
if rcu.IsPrime(e) {
primes = append(primes, e)
}
}
sort.Ints(primes)
fmt.Println(primes)
}
| require 'prime'
p [2,43,81,122,63,13,7,95,103].select(&:prime?).sort
|
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"fmt"
"sort"
)
func firstMissingPositive(a []int) int {
var b []int
for _, e := range a {
if e > 0 {
b = append(b, e)
}
}
sort.Ints(b)
le := len(b)
if le == 0 || b[0] > 1 {
return 1
}
for i := 1; i < le; i++ {
if... | nums = [1,2,0], [3,4,-1,1], [7,8,9,11,12]
puts nums.map{|ar|(1..).find{|candidate| !ar.include?(candidate) }}.join(", ")
|
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
limit := 999999
primes := rcu.Primes(limit)
fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:")
for i := 1; i < len(primes); i++ {
diff := primes[i] - primes[i-1]
if diff > 36 {
... | require "prime"
Prime.each(1_000_000).each_cons(2) do |a, b|
diff = b - a
next unless diff > 36
isqrt = Integer.sqrt(diff)
puts "
end
|
Convert this Go block to Ruby, preserving its control flow and logic. | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
limit := 999999
primes := rcu.Primes(limit)
fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:")
for i := 1; i < len(primes); i++ {
diff := primes[i] - primes[i-1]
if diff > 36 {
... | require "prime"
Prime.each(1_000_000).each_cons(2) do |a, b|
diff = b - a
next unless diff > 36
isqrt = Integer.sqrt(diff)
puts "
end
|
Convert the following code from Go to Ruby, ensuring the logic remains intact. | package main
import (
"fmt"
"math/rand"
"time"
)
var snl = map[int]int{
4: 14, 9: 31, 17: 7, 20: 38, 28: 84, 40: 59, 51: 67, 54: 34,
62: 19, 63: 81, 64: 60, 71: 91, 87: 24, 93: 73, 95: 75, 99: 78,
}
const sixThrowsAgain = true
func turn(player, square int) int {
for {
roll := 1 + ran... | NONE = 0; LADDER = 1; SNAKE = 2; STAY = 1; MOVE = 2; WIN = 3
class Cell
@type; @to; attr_reader :type, :to
def initialize; @type = NONE; @to = 0; end
def set( t, o ); @type = t; @to = o; end
end
class Player
@pos; @name; attr_accessor :pos; attr_reader :name
def initialize( n ); @pos = 0; @name = n... |
Generate a Ruby translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/rand"
"time"
)
var snl = map[int]int{
4: 14, 9: 31, 17: 7, 20: 38, 28: 84, 40: 59, 51: 67, 54: 34,
62: 19, 63: 81, 64: 60, 71: 91, 87: 24, 93: 73, 95: 75, 99: 78,
}
const sixThrowsAgain = true
func turn(player, square int) int {
for {
roll := 1 + ran... | NONE = 0; LADDER = 1; SNAKE = 2; STAY = 1; MOVE = 2; WIN = 3
class Cell
@type; @to; attr_reader :type, :to
def initialize; @type = NONE; @to = 0; end
def set( t, o ); @type = t; @to = o; end
end
class Player
@pos; @name; attr_accessor :pos; attr_reader :name
def initialize( n ); @pos = 0; @name = n... |
Please provide an equivalent version of this Go code in Ruby. | package main
import "fmt"
type frac struct{ num, den int }
func (f frac) String() string {
return fmt.Sprintf("%d/%d", f.num, f.den)
}
func f(l, r frac, n int) {
m := frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
fmt.Print(m, " ")
f(m, r, n)
}
}
func main() {... | require "big"
def farey(n)
a, b, c, d = 0, 1, 1, n
fracs = [] of BigRational
fracs << BigRational.new(0,1)
while c <= n
k = (n + b) // d
a, b, c, d = c, d, k * c - a, k * d - b
fracs << BigRational.new(a,b)
end
fracs.uniq.sort
end
puts "Farey sequence for order 1 throug... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import "fmt"
type frac struct{ num, den int }
func (f frac) String() string {
return fmt.Sprintf("%d/%d", f.num, f.den)
}
func f(l, r frac, n int) {
m := frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
fmt.Print(m, " ")
f(m, r, n)
}
}
func main() {... | require "big"
def farey(n)
a, b, c, d = 0, 1, 1, n
fracs = [] of BigRational
fracs << BigRational.new(0,1)
while c <= n
k = (n + b) // d
a, b, c, d = c, d, k * c - a, k * d - b
fracs << BigRational.new(a,b)
end
fracs.uniq.sort
end
puts "Farey sequence for order 1 throug... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum := 0
fmt.Println(" i p[i] Σp[i]")
fmt.Println("----------------")
for i := 0; i < len(primes); i += 2 {
sum += primes[i]
if rcu.IsPrime(sum) {
fmt.Printf("%3d %3d %6s\n", i+1, p... | require 'prime'
sum = 0
Prime.each(1000).with_index(1).each_slice(2) do |(odd_i, i),(_)|
puts "%6d%6d%6d" % [i, odd_i, sum] if (sum += odd_i).prime?
end
|
Please provide an equivalent version of this Go code in Ruby. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum := 0
fmt.Println(" i p[i] Σp[i]")
fmt.Println("----------------")
for i := 0; i < len(primes); i += 2 {
sum += primes[i]
if rcu.IsPrime(sum) {
fmt.Printf("%3d %3d %6s\n", i+1, p... | require 'prime'
sum = 0
Prime.each(1000).with_index(1).each_slice(2) do |(odd_i, i),(_)|
puts "%6d%6d%6d" % [i, odd_i, sum] if (sum += odd_i).prime?
end
|
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, sea... | def aliquot(n, maxlen=16, maxterm=2**47)
return "terminating", [0] if n == 0
s = []
while (s << n).size <= maxlen and n < maxterm
n = n.proper_divisors.inject(0, :+)
if s.include?(n)
case n
when s[0]
case s.size
when 1 then return "perfect", s
when 2 then return... |
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, sea... | def aliquot(n, maxlen=16, maxterm=2**47)
return "terminating", [0] if n == 0
s = []
while (s << n).size <= maxlen and n < maxterm
n = n.proper_divisors.inject(0, :+)
if s.include?(n)
case n
when s[0]
case s.size
when 1 then return "perfect", s
when 2 then return... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import "fmt"
func main() {
var i int32 = 1
fmt.Printf("i : type %-7T value %d\n", i, i)
j := 2
fmt.Printf("j : type %-7T value %d\n", j, j)
var k int64 = int64(i) + int64(j)
fmt.Printf("k : type %-7T value %d\n", k, k)
... | > 1+"2"
> "1"+2
> sqrt(-4)
> ("a" + [1,2])
> ('ha' * '3')
> ('ha' * true)
|
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import "fmt"
func main() {
var i int32 = 1
fmt.Printf("i : type %-7T value %d\n", i, i)
j := 2
fmt.Printf("j : type %-7T value %d\n", j, j)
var k int64 = int64(i) + int64(j)
fmt.Printf("k : type %-7T value %d\n", k, k)
... | > 1+"2"
> "1"+2
> sqrt(-4)
> ("a" + [1,2])
> ('ha' * '3')
> ('ha' * true)
|
Generate an equivalent Ruby version of this Go code. | package main
import "fmt"
func isPrime(n uint64) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint64(5)
for d*d <= n {
if n%d == 0 {
return false
}
... | require "prime"
magnanimouses = Enumerator.new do |y|
(0..).each {|n| y << n if (1..n.digits.size-1).all? {|k| n.divmod(10**k).sum.prime?} }
end
puts "First 45 magnanimous numbers:"
puts magnanimouses.first(45).join(' ')
puts "\n241st through 250th magnanimous numbers:"
puts magnanimouses.first(250).last(10).join... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"time"
"math/big"
)
func main() {
start := time.Now()
one := big.NewInt(1)
mp := big.NewInt(0)
bp := big.NewInt(0)
const max = 22
for count, p := 0, uint(2); count < max; {
mp.Lsh(one, p)
mp.Sub(mp, one)
if mp.ProbablyPrime(0) {
elapsed := time.Since(start).Seconds()... | require 'openssl'
(0..).each{|n| puts "2**
|
Change the programming language of this snippet from Go to Ruby without modifying what it does. | package main
import (
"fmt"
"time"
"math/big"
)
func main() {
start := time.Now()
one := big.NewInt(1)
mp := big.NewInt(0)
bp := big.NewInt(0)
const max = 22
for count, p := 0, uint(2); count < max; {
mp.Lsh(one, p)
mp.Sub(mp, one)
if mp.ProbablyPrime(0) {
elapsed := time.Since(start).Seconds()... | require 'openssl'
(0..).each{|n| puts "2**
|
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"math"
)
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] =... | require 'prime'
res = [2]
until res.last > 15000 do
res << (1..).detect{|n| (res.last + n**3).prime? } ** 3 + res.last
end
puts res[..-2].join(" ")
|
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"math"
)
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] =... | require 'prime'
res = [2]
until res.last > 15000 do
res << (1..).detect{|n| (res.last + n**3).prime? } ** 3 + res.last
end
puts res[..-2].join(" ")
|
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
... | require 'prime'
prime_array, sppair2, sppair3, sppair4, sppair5 = Array.new(5) {Array.new()}
unsexy, i, start = [2], 0, Time.now
Prime.each(1_000_100) {|prime| prime_array.push prime}
while prime_array[i] < 1_000_035
i+=1
unsexy.push(i) if prime_array[(i+1)..(i+2)].include?(prime_array[i]+6) == false && prime_ar... |
Convert the following code from Go to Ruby, ensuring the logic remains intact. | package main
import (
"container/heap"
"fmt"
"strings"
)
type CubeSum struct {
x, y uint16
value uint64
}
func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] }
type CubeSumHeap []*CubeSum
func (h CubeSumHeap) Len() int { return len(h) }
func (h CubeSumHeap) Less(i, j int) bool { retu... | def taxicab_number(nmax=1200)
[*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort
end
t = [0] + taxicab_number
[*1..25, *2000...2007].each do |i|
puts "%4d: %10d" % [i, t[i][0]] + t[i][1].map{|a| " = %4d**3 + %4d**3" % a}.join
end
|
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
... | require 'prime'
strong_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b<b} }
weak_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b>b} }
puts "First 36 strong primes:"
puts strong_gen.take(36).join(" "), "\n"
puts "First 37 weak primes:"
puts weak_gen.take(37).join(" "), "\n"
[1_... |
Generate a Ruby translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Print("!0 through !10: 0")
one := big.NewInt(1)
n := big.NewInt(1)
f := big.NewInt(1)
l := big.NewInt(1)
next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) }
for ; ; next() {
fmt.Print(" ", l)
if n.Int... | left_fact = Enumerator.new do |y|
f, lf = 1, 0
1.step do |n|
y << lf
lf += f
f *= n
end
end
|
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Print("!0 through !10: 0")
one := big.NewInt(1)
n := big.NewInt(1)
f := big.NewInt(1)
l := big.NewInt(1)
next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) }
for ; ; next() {
fmt.Print(" ", l)
if n.Int... | left_fact = Enumerator.new do |y|
f, lf = 1, 0
1.step do |n|
y << lf
lf += f
f *= n
end
end
|
Generate a Ruby translation of this Go snippet without changing its computational steps. | 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'
Prime.each(30).to_a.combination(3).select{|trio| trio.sum.prime? }.each do |a,b,c|
puts "
end
m = 1000
count = Prime.each(m).to_a.combination(3).count{|trio| trio.sum.prime? }
puts "Count of strange unique prime triplets <
|
Write the same algorithm in Ruby as shown in this Go implementation. | 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'
Prime.each(30).to_a.combination(3).select{|trio| trio.sum.prime? }.each do |a,b,c|
puts "
end
m = 1000
count = Prime.each(m).to_a.combination(3).count{|trio| trio.sum.prime? }
puts "Count of strange unique prime triplets <
|
Convert this Go block to Ruby, preserving its control flow and logic. | package main
import (
"fmt"
"rcu"
)
func motzkin(n int) []int {
m := make([]int, n+1)
m[0] = 1
m[1] = 1
for i := 2; i <= n; i++ {
m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2)
}
return m
}
func main() {
fmt.Println(" n M[n] Prime?")
fmt.Printl... | require "prime"
motzkin = Enumerator.new do |y|
m = [1,1]
m.each{|m| y << m }
2.step do |i|
m << (m.last*(2*i+1) + m[-2]*(3*i-3)) / (i+2)
m.unshift
y << m.last
end
end
motzkin.take(42).each_with_index do |m, i|
puts "
end
|
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"runtime"
"ex"
)
func main() {
f := func() {
pc, _, _, _ := runtime.Caller(0)
fmt.Println(runtime.FuncForPC(pc).Name(), "here!")
}
ex.X(f)
}
| def welcome(name)
puts "hello
end
puts "What is your name?"
$name = STDIN.gets
welcome($name)
return
|
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"rcu"
)
func main() {
var primes []int
candidates := []int{3, 33}
for i := 303; i <= 393; i += 10 {
candidates = append(candidates, i)
}
for i := 3003; i <= 3993; i += 10 {
candidates = append(candidates, i)
}
for _, cand := range candida... | func numbers_with_edges(upto, base = 10, s = [3]) {
Enumerator({|callback|
callback(s.digits2num(base))
for k in (0 .. base**(upto.len(base) - 2*s.len)) {
break if (s + k.digits(base) + s -> digits2num(base) > upto)
Inf.times { |j|
var d = (s + k.digits(bas... |
Produce a language-to-language conversion: from Go to Ruby, same semantics. | package main
import (
"fmt"
"rcu"
)
func main() {
var primes []int
candidates := []int{3, 33}
for i := 303; i <= 393; i += 10 {
candidates = append(candidates, i)
}
for i := 3003; i <= 3993; i += 10 {
candidates = append(candidates, i)
}
for _, cand := range candida... | func numbers_with_edges(upto, base = 10, s = [3]) {
Enumerator({|callback|
callback(s.digits2num(base))
for k in (0 .. base**(upto.len(base) - 2*s.len)) {
break if (s + k.digits(base) + s -> digits2num(base) > upto)
Inf.times { |j|
var d = (s + k.digits(bas... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"fmt"
"rcu"
)
const MAX = 1e7 - 1
var primes = rcu.Primes(MAX)
func specialNP(limit int, showAll bool) {
if showAll {
fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:")
}
count := 0
for i := 1; i < len(primes); i++ {
p2 := primes[i]
... | require 'prime'
Prime.each(100).each_cons(2).select{|p1, p2|(p1+p2-1).prime?}.each{|ar| p ar}
|
Change the following Go code into Ruby without altering its purpose. | package main
import (
"fmt"
"rcu"
)
const MAX = 1e7 - 1
var primes = rcu.Primes(MAX)
func specialNP(limit int, showAll bool) {
if showAll {
fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:")
}
count := 0
for i := 1; i < len(primes); i++ {
p2 := primes[i]
... | require 'prime'
Prime.each(100).each_cons(2).select{|p1, p2|(p1+p2-1).prime?}.each{|ar| p ar}
|
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import "fmt"
func isPrime(n int) bool {
return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17
}
func main() {
count := 0
var d []int
fmt.Println("Strange plus numbers in the open interval (100, 500) are:\n")
for i := 101; i < 500; i++ {
d = d[:0]
... | $p = [
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
]
def isStrange(n)
if n < 10 then
return false
end
while n >= 10 do
if not $p[n % 10 + (n / 10).floor % 10] then
return false
... |
Generate an equivalent Ruby version of this Go code. | package main
import "fmt"
func isPrime(n int) bool {
return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17
}
func main() {
count := 0
var d []int
fmt.Println("Strange plus numbers in the open interval (100, 500) are:\n")
for i := 101; i < 500; i++ {
d = d[:0]
... | $p = [
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
]
def isStrange(n)
if n < 10 then
return false
end
while n >= 10 do
if not $p[n % 10 + (n / 10).floor % 10] then
return false
... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"math/big"
)
var b = new(big.Int)
func isSPDSPrime(n uint64) bool {
nn := n
for nn > 0 {
r := nn % 10
if r != 2 && r != 3 && r != 5 && r != 7 {
return false
}
nn /= 10
}
b.SetUint64(n)
if b.ProbablyPrime(0) {
... | require "prime"
smarandache = Enumerator.new do|y|
prime_digits = [2,3,5,7]
prime_digits.each{|pr| y << pr}
(1..).each do |n|
prime_digits.repeated_permutation(n).each do |perm|
c = perm.join.to_i * 10
y << c + 3 if (c+3).prime?
y << c + 7 if (c+7).prime?
end
end
end
seq = smarand... |
Convert the following code from Go to Ruby, ensuring the logic remains intact. | package main
import (
"fmt"
"log"
"strings"
)
const dimensions int = 8
func setupMagicSquareData(d int) ([][]int, error) {
var output [][]int
if d < 4 || d%4 != 0 {
return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
}
var bits uint = 0x9669
size := d * d
mu... | def double_even_magic_square(n)
raise ArgumentError, "Need multiple of four" if n%4 > 0
block_size, max = n/4, n*n
pre_pat = [true, false, false, true,
false, true, true, false]
pre_pat += pre_pat.reverse
pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size
flat_ar = pattern.each_with_... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"image"
"image/color"
"image/gif"
"log"
"math"
"os"
)
func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
img.SetColorIndex(x, y, ci)
}
}
}
func hsb2rgb(hue, sat, bri flo... | attr_reader :buffer, :palette, :r, :g, :b, :rd, :gd, :bd, :dim
def settings
size(600, 600)
end
def setup
sketch_title 'Plasma Effect'
frame_rate 25
@r = 42
@g = 84
@b = 126
@rd = true
@gd = true
@bd = true
@dim = width * height
@buffer = Array.new(dim)
grid(width, height) do |x, y|
buffer[... |
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1)
p := uint64(3)
for {
p2 := p * p
if p2 > limit {
break
}
for i := p2; i <= limit; i += 2 * p {
c[i] = true
... | require "prime"
class Integer
def square_free?
prime_division.none?{|pr, exp| exp > 1}
end
end
puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(" ")}
puts
m = 10**12
puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(" ")}
puts
markers = [100, 1000, 10_000, 100_000, 1_000_... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"fmt"
"time"
)
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func main() {
st := time.Now()
count := 0
var selfs []int
i... | func is_self_number(n) {
if (n < 30) {
return (((n < 10) && (n.is_odd)) || (n == 20))
}
var qd = (1 + n.ilog10)
var r = (1 + (n-1)%9)
var h = (r + 9*(r%2))/2
var ld = 10
while (h + 9*qd >= n%ld) {
ld *= 10
}
var vs = idiv(n, ld).sumdigits
n %= ld
0..qd ... |
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import "fmt"
type is func() uint64
func newSum() is {
var ms is
ms = func() uint64 {
ms = newSum()
return ms()
}
var msd, d uint64
return func() uint64 {
if d < 9 {
d++
} else {
d = 0
msd = ms()
}
ret... | nivens = Enumerator.new {|y| (1..).each {|n| y << n if n.remainder(n.digits.sum).zero?} }
cur_gap = 0
puts 'Gap Index of gap Starting Niven'
nivens.each_cons(2).with_index(1) do |(n1, n2), i|
break if i > 10_000_000
if n2-n1 > cur_gap then
printf "%3d %15s %15s\n", n2-n1, i, n1
cur_gap = n2-n1
end
e... |
Please provide an equivalent version of this Go code in Ruby. | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
units := []string{
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer",
}
convs := []float32{
0.025... | module Distances
RATIOS =
{arshin: 0.7112, centimeter: 0.01, diuym: 0.0254,
fut: 0.3048, kilometer: 1000.0, liniya: 0.00254,
meter: 1.0, milia: 7467.6, piad: 0.1778,
sazhen: 2.1336, tochka: 0.000254, vershok: 0.04445,
versta: 1066.8}
def self.method_missing(meth, arg)... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import "rcu"
func main() {
var res []int
for n := 1; n <= 70; n++ {
m := 1
for rcu.DigitSum(m*n, 10) != n {
m++
}
res = append(res, m)
}
rcu.PrintTable(res, 7, 10, true)
}
| a131382 = (0..).lazy.map{|n| (1..).detect{|m|(n*m).digits.sum == n} }
a131382.take(70).each_slice(10){|slice| puts "%8d"*slice.size % slice }
|
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import "fmt"
func pancake(n int) int {
gap, sum, adj := 2, 2, -1
for sum < n {
adj++
gap = gap*2 - 1
sum += gap
}
return n + adj
}
func main() {
for i := 0; i < 4; i++ {
for j := 1; j < 6; j++ {
n := i*5 + j
fmt.Printf("p(%2d) =... | def pancake(n)
gap = 2
sum = 2
adj = -1
while sum < n
adj = adj + 1
gap = gap * 2 - 1
sum = sum + gap
end
return n + adj
end
for i in 0 .. 3
for j in 1 .. 5
n = i * 5 + j
print "p(%2d) = %2d " % [n, pancake(n)]
end
print "\n"
end
|
Write the same code in Ruby as shown below in Go. | package main
import "fmt"
const (
N = 2200
N2 = N * N * 2
)
func main() {
s := 3
var s1, s2 int
var r [N + 1]bool
var ab [N2 + 1]bool
for a := 1; a <= N; a++ {
a2 := a * a
for b := a; b <= N; b++ {
ab[a2 + b * b] = true
}
}
for c := 1; ... | n = 2200
l_add, l = Hash(Int32, Bool).new(false), Hash(Int32, Bool).new(false)
(1..n).each do |x|
x2 = x * x
(x..n).each { |y| l_add[x2 + y * y] = true }
end
s = 3
(1..n).each do |x|
s1 = s
s += 2
s2 = s
((x+1)..n).each do |y|
l[y] = true if l_add[s1]
s1 += s2
s2 += 2
end
end
puts (1..n).r... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import "fmt"
type pair struct{ x, y int }
func main() {
const max = 1685
var all []pair
for a := 2; a < max; a++ {
for b := a + 1; b < max-a; b++ {
all = append(all, pair{a, b})
}
}
fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
products := countProducts(all... | def add(x,y) x + y end
def mul(x,y) x * y end
def sumEq(s,p) s.select{|q| add(*p) == add(*q)} end
def mulEq(s,p) s.select{|q| mul(*p) == mul(*q)} end
s1 = (a = *2...100).product(a).select{|x,y| x<y && x+y<100}
s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size != 1} }
s3 = s2.select{|p| (mulEq(s1,p) & s2).size ... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
)
func factSum(n int) int {
s := 0
for x, f := 0, 1; x < n; {
x++
f *= x
s += f
}
return s
}
func r(n int) bool {
if n == 0 {
return false
}
c := super[pos-n... |
l = []
(1..6).each{|e|
a, i = [], e-2
(0..l.length-e+1).each{|g|
if not (n = l[g..g+e-2]).uniq!
a.concat(n[(a[0]? i : 0)..-1]).push(e).concat(n)
i = e-2
else
i -= 1
end
}
a.each{|n| print n}; puts "\n\n"
l = a
}
|
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
)
func Float64IsInt(f float64) bool {
_, frac := math.Modf(f)
return frac == 0
}
func Float32IsInt(f float32) bool {
return Float64IsInt(float64(f))
}
func Complex128IsInt(c complex128) bool {
return imag(c) == 0 && Float6... | class Numeric
def to_i?
self == self.to_i rescue false
end
end
ar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2,
Float::NAN, Float::INFINITY,
2r, 2.5r,
2+0i, 2+0.0i, 5-5i]
ar.each{|nu... |
Port the provided Go code into Ruby while preserving the original functionality. | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
limit := int(math.Log(1e7) * 1e7 * 1.2)
primes := rcu.Primes(limit)
fmt.Println("The first 20 pairs of natural numbers whose sum is prime are:")
for i := 1; i <= 20; i++ {
p := primes[i]
hp := p / 2
fmt.Print... | var wanted = (1..Inf -> lazy.map {|n| [n, n+1, n+(n+1)] }\
.grep { .tail.is_prime })
wanted.first(20).each_2d {|a,b,c|
printf("%2d + %2d = %2d\n", a,b,c)
}
|
Generate a Ruby translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"rcu"
)
func main() {
limit := int(1e10 - 1)
primes := rcu.Primes(limit)
maxI := 0
maxDiff := 0
nextStop := 10
fmt.Println("The largest differences between adjacent primes under the following limits is:")
for i := 1; i < len(primes); i++ {
diff :... | func prime_gap_records(upto) {
var gaps = []
var p = 2
each_prime(p.next_prime, upto, {|q|
gaps[q-p] := p
p = q
})
gaps.grep { defined(_) }
}
var upto = 1e8
var primes = prime_gap_records(upto)
for n in (2 .. upto.ilog10) {
var b = primes.last_by {|p| p < 10**n } \\ break... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"rcu"
)
func main() {
numbers1 := [5]int{5, 45, 23, 21, 67}
numbers2 := [5]int{43, 22, 78, 46, 38}
numbers3 := [5]int{9, 98, 12, 54, 53}
primes := [5]int{}
for n := 0; n < 5; n++ {
max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])
if... | require "prime"
numbers1 = [ 5, 45, 23, 21, 67]
numbers2 = [43, 22, 78, 46, 38]
numbers3 = [ 9, 98, 12, 54, 53]
p [numbers1, numbers2, numbers3].transpose.map{|ar| (ar.max..).find(&:prime?) }
|
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import "fmt"
func ulam(n int) int {
ulams := []int{1, 2}
set := map[int]bool{1: true, 2: true}
i := 3
for {
count := 0
for j := 0; j < len(ulams); j++ {
_, ok := set[i-ulams[j]]
if ok && ulams[j] != (i-ulams[j]) {
count++
... | func ulam(n) {
static u = Set(1,2)
static ulams = [0, 1, 2]
return ulams[n] if (ulams.end >= n)
++n
for(var i = 3; true; ++i) {
var count = 0
ulams.each {|v|
if (u.has(i - v) && (v != i-v)) {
break if (count++ > 2)
}
}
... |
Change the following Go code into Ruby without altering its purpose. | package main
import "fmt"
var (
a [17][17]int
idx [4]int
)
func findGroup(ctype, min, max, depth int) bool {
if depth == 4 {
cs := ""
if ctype == 0 {
cs = "un"
}
fmt.Printf("Totally %sconnected group:", cs)
for i := 0; i < 4; i++ {
fmt.Pri... | a = Array.new(17){['0'] * 17}
17.times{|i| a[i][i] = '-'}
4.times do |k|
17.times do |i|
j = (i + 2 ** k) % 17
a[i][j] = a[j][i] = '1'
end
end
a.each {|row| puts row.join(' ')}
(0...17).to_a.combination(4) do |quartet|
links = quartet.combination(2).map{|i,j| a[i][j].to_i}.reduce(:+)
abort "Bogus" unle... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
func commatize(s string) string {
neg := false
if strings.HasPrefix(s, "-") {
s = s[1:]
neg = true
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if !neg {
... | def smallest_6(n)
i = 1
c = 0
s = n.to_s
until i.to_s.match?(s)
c += 1
i *= 6
end
[n, c, i]
end
(0..21).each{|n| puts "%3d**%-3d: %d" % smallest_6(n) }
|
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import "fmt"
type any = interface{}
func showType(a any) {
switch a.(type) {
case rune:
fmt.Printf("The type of '%c' is %T\n", a, a)
default:
fmt.Printf("The type of '%v' is %T\n", a, a)
}
}
func main() {
values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"}
for ... | def print_type(x)
puts "Compile-time type of
puts " Actual runtime type is
end
print_type 123
print_type 123.45
print_type rand < 0.5 ? "1" : 0
print_type rand < 1.5
print_type nil
print_type 'c'
print_type "str"
print_type [1,2]
print_type({ 2, "two" })
print_type({a: 1, b: 2})
print_type ->(x : Int32){ x+... |
Port the provided Go code into Ruby while preserving the original functionality. | package main
import (
"fmt"
"rcu"
)
func main() {
sum := 0
for _, p := range rcu.Primes(2e6 - 1) {
sum += p
}
fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum))
}
| def prime?(n)
return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5
sqrt = Math.isqrt(n)
pc = typeof(n).new(5)
while pc <= sqrt
return false if n % pc == 0 || n % (pc + 2) == 0
pc += 6
end
true
end
puts "The sum of all primes below 2 million is
puts "The sum of all primes below 2 milli... |
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically? | package main
import (
"fmt"
"rcu"
"strconv"
"strings"
)
func contains(list []int, s int) bool {
for _, e := range list {
if e == s {
return true
}
}
return false
}
func main() {
fmt.Println("Steady squares under 10,000:")
finalDigits := []int{1, 5, 6}
... | p (0..10_000).select{|n| (n*n).to_s.end_with? n.to_s }
|
Generate an equivalent Ruby version of this Go code. | package main
import (
"fmt"
"rcu"
)
func allButOneEven(prime int) bool {
digits := rcu.Digits(prime, 10)
digits = digits[:len(digits)-1]
allEven := true
for _, d := range digits {
if d&1 == 1 {
allEven = false
break
}
}
return allEven
}
func mai... | func primes_with_one_odd_digit(upto, base = 10) {
upto = prev_prime(upto+1)
var list = []
var digits = @(^base)
var even_digits = digits.grep { .is_even }
var odd_digits = digits.grep { .is_odd && .is_coprime(base) }
list << digits.grep { .is_odd && .is_prime && !.is_coprime(base) }...
... |
Generate an equivalent Ruby version of this Go code. | package main
import (
"fmt"
"rcu"
)
func allButOneEven(prime int) bool {
digits := rcu.Digits(prime, 10)
digits = digits[:len(digits)-1]
allEven := true
for _, d := range digits {
if d&1 == 1 {
allEven = false
break
}
}
return allEven
}
func mai... | func primes_with_one_odd_digit(upto, base = 10) {
upto = prev_prime(upto+1)
var list = []
var digits = @(^base)
var even_digits = digits.grep { .is_even }
var odd_digits = digits.grep { .is_odd && .is_coprime(base) }
list << digits.grep { .is_odd && .is_prime && !.is_coprime(base) }...
... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := uint64(4); i < limit; i += 2 {
c[i] = true
}
p := uint64(3)
for {
p2 := p * p
if p2 >= limit {
break
}
... | require "prime"
class Integer
def safe_prime?
((self-1)/2).prime?
end
end
def format_parts(n)
partitions = Prime.each(n).partition(&:safe_prime?).map(&:count)
"There are %d safes and %d unsafes below
end
puts "First 35 safe-primes:"
p Prime.each.lazy.select(&:safe_prime?).take(35).to_a
puts format_parts... |
Port the provided Go code into Ruby while preserving the original functionality. | package main
import "fmt"
func main() {
tableA := []struct {
value int
key string
}{
{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
{28, "Alan"},
}
tableB := []struct {
key string
value string
}{
{"Jonah", "Whales"}, {"Jonah"... | def hashJoin(table1, index1, table2, index2)
h = table1.group_by {|s| s[index1]}
h.default = []
table2.collect {|r|
h[r[index2]].collect {|s| [s, r]}
}.flatten(1)
end
table1 = [[27, "Jonah"],
[18, "Alan"],
[28, "Glory"],
[18, "Popeye"],
[28, "Alan"]]
table2 = [... |
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically? | package main
import "fmt"
func reverse(n uint64) uint64 {
r := uint64(0)
for n > 0 {
r = n%10 + r*10
n /= 10
}
return r
}
func main() {
pow := uint64(10)
nextN:
for n := 2; n < 10; n++ {
low := pow * 9
pow *= 10
high := pow - 1
fmt.Printf("Large... | func largest_palindrome_product (n) {
for k in ((10**n - 1) `downto` 10**(n-1)) {
var t = Num("
t.divisors.each {|d|
if ((d.len == n) && ((t/d).len == n)) {
return (d, t/d)
}
}
}
}
for n in (2..9) {
var (a,b) = largest_palindrome_product(n)
... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(499)
var sprimes []int
for _, p := range primes {
digits := rcu.Digits(p, 10)
var b1 = true
for _, d := range digits {
if !rcu.IsPrime(d) {
b1 = false
break
... | func split_at_indices(array, indices) {
var parts = []
var i = 0
for j in (indices) {
parts << array.slice(i, j)
i = j+1
}
parts
}
func consecutive_partitions(array, callback) {
for k in (0..array.len) {
combinations(array.len, k, {|*indices|
var t = split... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(499)
var sprimes []int
for _, p := range primes {
digits := rcu.Digits(p, 10)
var b1 = true
for _, d := range digits {
if !rcu.IsPrime(d) {
b1 = false
break
... | func split_at_indices(array, indices) {
var parts = []
var i = 0
for j in (indices) {
parts << array.slice(i, j)
i = j+1
}
parts
}
func consecutive_partitions(array, callback) {
for k in (0..array.len) {
combinations(array.len, k, {|*indices|
var t = split... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"rcu"
)
func countDivisors(n int) int {
count := 0
i := 1
k := 1
if n%2 == 1 {
k = 2
}
for ; i*i <= n; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
... | require 'prime'
def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp+1}
res = (1..Integer.sqrt(100_000)).filter_map{|n| sqr = n*n; sqr if tau(sqr).prime? }
res.each_slice(10){|slice| puts "%10d"*slice.size % slice}
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version. | package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
... | rp = [1,2,3].repeated_permutation(2)
p rp.to_a
p rp.take_while{|(a, b)| a + b < 5}
|
Generate an equivalent Ruby version of this Go code. | package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
... | rp = [1,2,3].repeated_permutation(2)
p rp.to_a
p rp.take_while{|(a, b)| a + b < 5}
|
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
"time"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
number := 0
for number < 1 {
fmt.Print("Enter number of seconds delay > 0 : ")
scanner.Scan()
input := scanner.Text()
... | puts "Enter a number of seconds:"
seconds = gets.chomp.to_i
puts "Enter a MP3 file to be played"
mp3filepath = File.dirname(__FILE__) + "/" + gets.chomp + ".mp3"
sleep(seconds)
pid = fork{ exec 'mpg123','-q', mp3filepath }
|
Please provide an equivalent version of this Go code in Ruby. | package main
import (
"fmt"
"math"
)
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] =... | require 'prime'
res = [2]
until res.last > 16000 do
res << (1..).detect{|n| (res.last + n**2).prime? } ** 2 + res.last
end
puts res[..-2].join(" ")
|
Generate an equivalent Ruby version of this Go code. | package main
import (
"fmt"
"math"
)
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] =... | require 'prime'
res = [2]
until res.last > 16000 do
res << (1..).detect{|n| (res.last + n**2).prime? } ** 2 + res.last
end
puts res[..-2].join(" ")
|
Change the following Go code into Ruby without altering its purpose. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"log"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
two = big.NewInt(2)
three = big.NewInt(3)
four = big.NewInt(4)
five = big.NewInt(5)
six = big.NewInt(6)
ten = big.NewInt(10)
max = big.NewInt(100000)... | func f(n) is cached {
return 2 if (n == 1)
lpf(1 + prod(1..^n, {|k| f(k) }))
}
say f.map(1..16)
say f.map(17..27)
|
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically? | package main
import (
"fmt"
big "github.com/ncw/gmp"
"log"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
two = big.NewInt(2)
three = big.NewInt(3)
four = big.NewInt(4)
five = big.NewInt(5)
six = big.NewInt(6)
ten = big.NewInt(10)
max = big.NewInt(100000)... | func f(n) is cached {
return 2 if (n == 1)
lpf(1 + prod(1..^n, {|k| f(k) }))
}
say f.map(1..16)
say f.map(17..27)
|
Write a version of this Go function in Ruby with identical behavior. | package main
import "fmt"
func rotate(lst []int) {
len := len(lst)
last := lst[len-1]
for i := len - 1; i >= 1; i-- {
lst[i] = lst[i-1]
}
lst[0] = last
}
func roundRobin(n int) {
lst := make([]int, n-1)
for i := 0; i < len(lst); i++ {
lst[i] = i + 2
}
if n%2 == 1 {... | def round_robin( n )
rotating_players = (2..n).map(&:to_s)
rotating_players << "bye" if n.odd?
Array.new(rotating_players.size) do |r|
all = ["1"] + rotating_players.rotate(-r)
[all[0, all.size/2], all[all.size/2..].reverse]
end
end
round_robin(12).each.with_index(1) do |round, i|
puts "Round
ro... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"rcu"
"strings"
)
var grid = [][]int {
{ 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8},
{49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0},
{81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3... | gridstr =
"08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 ... |
Write the same code in Ruby as shown below in Go. | package main
import (
"fmt"
"time"
)
func main() {
fmt.Print("\033[?1049h\033[H")
fmt.Println("Alternate screen buffer\n")
s := "s"
for i := 5; i > 0; i-- {
if i == 1 {
s = ""
}
fmt.Printf("\rgoing back in %d second%s...", i, s)
time.Sleep(time.Secon... | print "\e[?1049h\e[H";
say "Alternate buffer!";
3.downto(1).each { |i|
say "Going back in:
Sys.sleep(1);
}
print "\e[?1049l";
|
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"fmt"
"math/big"
)
var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
const maxStack = 128
var (
tens, values [maxStack]big.Int
bigTemp, answer = new(big.Int), new(big.Int)
base, seenDepth int
)
func addDigit(i int) {
for d := 1; d < base; d++ {
... |
require 'prime'
BASE = 3
MAX = 500
stems = Prime.each(BASE-1).to_a
(1..MAX-1).each {|i|
print "
t = []
b = BASE ** i
stems.each {|z|
(1..BASE-1).each {|n|
c = n*b+z
t.push(c) if c.prime?
}}
break if t.empty?
stems = t
}
puts "The largest left truncatable prime
|
Change the following Go code into Ruby without altering its purpose. | package main
import (
"go/build"
"log"
"path/filepath"
"github.com/unixpickle/gospeech"
"github.com/unixpickle/wav"
)
const pkgPath = "github.com/unixpickle/gospeech"
const input = "This is an example of speech synthesis."
func main() {
p, err := build.Import(pkgPath, ".", build.FindOnly)
... | module OperatingSystem
require 'rbconfig'
module_function
def operating_system
case RbConfig::CONFIG["host_os"]
when /linux/i
:linux
when /cygwin|mswin|mingw|windows/i
:windows
when /darwin/i
:mac
when /solaris/i
:solaris
else
nil
end
end
def linux?; ... |
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import (
"log"
"math/rand"
"testing"
"time"
"github.com/gonum/plot"
"github.com/gonum/plot/plotter"
"github.com/gonum/plot/plotutil"
"github.com/gonum/plot/vg"
)
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
... | class Array
def radix_sort(base=10)
ary = dup
rounds = (Math.log(ary.max)/Math.log(base)).ceil
rounds.times do |i|
buckets = Array.new(base){[]}
base_i = base**i
ary.each do |n|
digit = (n/base_i) % base
buckets[digit] << n
end
ary = buckets.flatten
... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"math/rand"
"time"
)
const (
op_num = iota
op_add
op_sub
op_mul
op_div
)
type frac struct {
num, denom int
}
type Expr struct {
op int
left, right *Expr
value frac
}
var n_cards = 4
var goal = 24
var digit_range = 9
func (x *Expr) String() string {
if x.op... | class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
'(%dr %s (%dr %s %dr)) %s %dr',
'(%dr %s %dr) %s (%dr %s %dr)',
'%dr %s ((%dr %s %dr) %s %dr)',
'%dr %s (%dr %s (%dr %s %dr))',
]
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
def self.solve(digits)
so... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"math/rand"
"time"
)
const (
op_num = iota
op_add
op_sub
op_mul
op_div
)
type frac struct {
num, denom int
}
type Expr struct {
op int
left, right *Expr
value frac
}
var n_cards = 4
var goal = 24
var digit_range = 9
func (x *Expr) String() string {
if x.op... | class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
'(%dr %s (%dr %s %dr)) %s %dr',
'(%dr %s %dr) %s (%dr %s %dr)',
'%dr %s ((%dr %s %dr) %s %dr)',
'%dr %s (%dr %s (%dr %s %dr))',
]
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
def self.solve(digits)
so... |
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
)
func hough(im image.Image, ntx, mry int) draw.Image {
nimx := im.Bounds().Max.X
mimy := im.Bounds().Max.Y
him := image.NewGray(image.Rect(0, 0, ntx, mry))
draw.Draw(him, him.Bounds(), ... | require 'mathn'
require 'rubygems'
require 'gd2'
include GD2
def hough_transform(img)
mx, my = img.w*0.5, img.h*0.5
max_d = Math.sqrt(mx**2 + my**2)
min_d = max_d * -1
hough = Hash.new(0)
(0..img.w).each do |x|
puts "
(0..img.h).each do |y|
if img.pixel2color(img.get_pixel(x,y)).g > 32
... |
Write a version of this Go function in Ruby with identical behavior. | package main
import "fmt"
const jobs = 12
type environment struct{ seq, cnt int }
var (
env [jobs]environment
seq, cnt *int
)
func hail() {
fmt.Printf("% 4d", *seq)
if *seq == 1 {
return
}
(*cnt)++
if *seq&1 != 0 {
*seq = 3*(*seq) + 1
} else {
*seq /= 2
... |
envs = (1..12).map do |n|
Object.new.instance_eval {@n = n; @cnt = 0; self}
end
until envs.all? {|e| e.instance_eval{@n} == 1}
envs.each do |e|
e.instance_eval do
printf "%4s", @n
if @n > 1
@cnt += 1
@n = if @n.odd?
@n * 3 + 1
... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var (
gregorianStr = []string{"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"}
gregorian = []int{31, 28, 31, 30, 31, 30, 31, 3... | require('DateTime')
var month_names = %w(
Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse
Germinal Floréal Prairial Messidor Thermidor Fructidor
)
var intercalary = [
'Fête de la vertu',
'Fête du génie',
'Fête du travail',
... |
Convert the following code from Go to Ruby, ensuring the logic remains intact. | package main
import "fmt"
func ts(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 {
... | func tonelli(n, p) {
legendre(n, p) == 1 || die "not a square (mod p)"
var q = p-1
var s = valuation(q, 2)
s == 1 ? return(powmod(n, (p + 1) >> 2, p)) : (q >>= s)
var c = powmod(2 ..^ p -> first {|z| legendre(z, p) == -1}, q, p)
var r = powmod(n, (q + 1) >> 1, p)
var t = powmod(n, q, p)
... |
Change the following Go code into Ruby without altering its purpose. | package main
import "fmt"
func ts(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 {
... | func tonelli(n, p) {
legendre(n, p) == 1 || die "not a square (mod p)"
var q = p-1
var s = valuation(q, 2)
s == 1 ? return(powmod(n, (p + 1) >> 2, p)) : (q >>= s)
var c = powmod(2 ..^ p -> first {|z| legendre(z, p) == -1}, q, p)
var r = powmod(n, (q + 1) >> 1, p)
var t = powmod(n, q, p)
... |
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"bufio"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"reflect"
)
func main() {
in := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Expr: ")
in.Scan()
if err := in.Err(); err != nil {
fmt.Println(err)
re... | loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
break if expr.empty?
vars = expr.scan(/\p{Alpha}+/)
if vars.empty?
puts "no variables detected in your boolean expression"
next
end
vars.each {|v| print "
puts "|
prefix = []
suffix = []
vars.each... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import (
"bufio"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"reflect"
)
func main() {
in := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Expr: ")
in.Scan()
if err := in.Err(); err != nil {
fmt.Println(err)
re... | loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
break if expr.empty?
vars = expr.scan(/\p{Alpha}+/)
if vars.empty?
puts "no variables detected in your boolean expression"
next
end
vars.each {|v| print "
puts "|
prefix = []
suffix = []
vars.each... |
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import "fmt"
type Set func(float64) bool
func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } }
func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } }
func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } }
func... | class Rset
Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do
def include?(x)
(inc_lo ? lo<=x : lo<x) and (inc_hi ? x<=hi : x<hi)
end
def length
hi - lo
end
def to_s
"
end
end
def initialize(lo=nil, hi=nil, inc_lo=false, inc_hi=false)
if lo.nil? and hi.nil?
@set... |
Please provide an equivalent version of this Go code in Ruby. | package main
import "fmt"
type Set func(float64) bool
func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } }
func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } }
func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } }
func... | class Rset
Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do
def include?(x)
(inc_lo ? lo<=x : lo<x) and (inc_hi ? x<=hi : x<hi)
end
def length
hi - lo
end
def to_s
"
end
end
def initialize(lo=nil, hi=nil, inc_lo=false, inc_hi=false)
if lo.nil? and hi.nil?
@set... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"unicode"
)
var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland",... | require 'set'
Primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
States = [
"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indi... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ... | (2..8).each do |d|
rep = d.to_s * d
print "
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ")
end
|
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ... | (2..8).each do |d|
rep = d.to_s * d
print "
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ")
end
|
Generate an equivalent Ruby version of this Go code. | package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(bi... | padovan = Enumerator.new do |y|
ar = [1, 1, 1]
loop do
ar << ar.first(2).sum
y << ar.shift
end
end
P, S = 1.324717957244746025960908854, 1.0453567932525329623
def padovan_f(n) = (P**(n-1) / S + 0.5).floor
puts "Recurrence Padovan:
puts "Floor function:
n = 63
bool = (0...n).map{|n| padovan_f(... |
Generate an equivalent Ruby version of this Go code. | package main
import (
"fmt"
"strconv"
)
type maybe struct{ value *int }
func (m maybe) bind(f func(p *int) maybe) maybe {
return f(m.value)
}
func unit(p *int) maybe {
return maybe{p}
}
func decrement(p *int) maybe {
if p == nil {
return unit(nil)
} else {
q := *p - 1
... | class Maybe
def initialize(value)
@value = value
end
def map
if @value.nil?
self
else
Maybe.new(yield @value)
end
end
end
Maybe.new(3).map { |n| 2*n }.map { |n| n+1 }
Maybe.new(nil).map { |n| 2*n }.map { |n| n+1 }
Maybe.new(3).map { |n| nil }.map { |n| n+1 }
class Maybe
c... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import "fmt"
type mlist struct{ value []int }
func (m mlist) bind(f func(lst []int) mlist) mlist {
return f(m.value)
}
func unit(lst []int) mlist {
return mlist{lst}
}
func increment(lst []int) mlist {
lst2 := make([]int, len(lst))
for i, v := range lst {
lst2[i] = v + 1
}
... | class Array
def bind(f)
flat_map(&f)
end
def self.unit(*args)
args
end
def self.lift(f)
-> e { self.unit(f[e]) }
end
end
inc = -> n { n + 1 }
str = -> n { n.to_s }
listy_inc = Array.lift(inc)
listy_str = Array.lift(str)
Array.unit(3,4,5).bind(listy_inc).bind(listy_str)
doub = -> n... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
func main() {
log.SetFlags(0)
log.SetPrefix("textonyms: ")
wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
t ... | CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
NUMS = "22233344455566677778889999" * 2
dict = "unixdict.txt"
textonyms = File.open(dict){|f| f.map(&:chomp).group_by {|word| word.tr(CHARS, NUMS) } }
puts "There are
They require
puts "\n25287876746242:
|
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import (
"bufio"
"fmt"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type cell struct {
isMine bool
display byte
}
const lMargin = 4
var (
grid [][]cell
mineCount int
minesMarked int
isGameOver bool
)
var scanner = bufio.NewSca... | puts <<EOS
Minesweeper game.
There is an n by m grid that has a random number of between 20% to 60%
of randomly hidden mines that need to be found.
Positions in the grid are modified by entering their coordinates
where the first coordinate is horizontal in the grid and the second
vertical. Th... |
Convert this Go block to Ruby, preserving its control flow and logic. | 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) } }... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.