Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"sort"
)
type matrix [][]int
func dList(n, start int) (r matrix) {
start--
a := make([]int, n)
for i := range a {
a[i] = i
}
a[0], a[start] = start, a[0]
sort.Ints(a[1:])
first := a[1]
var recurse func(last int)
recurse = func(las... | def printSquare(a)
for row in a
print row, "\n"
end
print "\n"
end
def dList(n, start)
start = start - 1
a = Array.new(n) {|i| i}
a[0], a[start] = a[start], a[0]
a[1..] = a[1..].sort
first = a[1]
r = []
recurse = lambda {|last|
if last == first then
... |
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
vis := make([]bool, len(g))
L := make([]int, len(g))
x := len(... | func korasaju(Array g) {
var vis = g.len.of(false)
var L = []
var x = g.end
var t = g.len.of { [] }
func visit(u) {
if (!vis[u]) {
vis[u] = true
g[u].each {|v|
visit(v)
t[v] << u
}
L[x--] = u
... |
Generate a Ruby translation of this Go snippet without changing its computational steps. | package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"math/rand"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
)
func main() {
log.SetFlags(0)
log.SetPrefix("markov: ")
input := flag.String("in", "alice_oz.txt", "input file")
n := flag.Int("n", 2, "number of words to use as prefix")
runs := flag.Int... | class Markov(N)
@dictionary = Hash(StaticArray(String, N), Array(String)).new { [] of String }
def parse(filename : String)
File.open(filename) do |file|
parse(file)
end
end
private def prefix_from(array)
StaticArray(String, N).new { |i| array[-(N - i)] }
end
def parse(input : IO)
s... |
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"fmt"
"math/big"
)
func cumulative_freq(freq map[byte]int64) map[byte]int64 {
total := int64(0)
cf := make(map[byte]int64)
for i := 0; i < 256; i++ {
b := byte(i)
if v, ok := freq[b]; ok {
cf[b] = total
total += v
}
}
re... | def cumulative_freq(freq)
cf = {}
total = 0
freq.keys.sort.each do |b|
cf[b] = total
total += freq[b]
end
return cf
end
def arithmethic_coding(bytes, radix)
freq = Hash.new(0)
bytes.each { |b| freq[b] += 1 }
cf = cumulative_freq(freq)
base = bytes.size
lower = 0
pf = 1... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type playfairOption int
const (
noQ playfairOption = iota
iEqualsJ
)
type playfair struct {
keyword string
pfo playfairOption
table [5][5]byte
}
func (p *playfair) init() {
var used [26]bool
if p.pfo == noQ... | class Playfair
Size = 5
def initialize(key, missing)
@missing = missing.upcase
alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''
extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet
grid = extended.uniq[0...Size*Size].each_slice(Size).to_a
coords = {}
grid.each_with_ind... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type playfairOption int
const (
noQ playfairOption = iota
iEqualsJ
)
type playfair struct {
keyword string
pfo playfairOption
table [5][5]byte
}
func (p *playfair) init() {
var used [26]bool
if p.pfo == noQ... | class Playfair
Size = 5
def initialize(key, missing)
@missing = missing.upcase
alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''
extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet
grid = extended.uniq[0...Size*Size].each_slice(Size).to_a
coords = {}
grid.each_with_ind... |
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"strings"
)
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func evolve(l, rule int) {
fmt.Printf(" Rule #%d:\n", rule)
cells := "O"
for x := 0; x < l; x++ {
cells = addNoCells(cells)
width := 40 + (len(cells) >> 1)
fmt.... | def notcell(c)
c.tr('01','10')
end
def eca_infinite(cells, rule)
neighbours2next = Hash[8.times.map{|i|["%03b"%i, "01"[rule[i]]]}]
c = cells
Enumerator.new do |y|
loop do
y << c
c = notcell(c[0])*2 + c + notcell(c[-1])*2
c = (1..c.size-2).map{|i| neighbours2next[c[i-1..i+1]]}.join... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package romap
type Romap struct{ imap map[byte]int }
func New(m map[byte]int) *Romap {
if m == nil {
return nil
}
return &Romap{m}
}
func (rom *Romap) Get(key byte) (int, bool) {
i, ok := rom.imap[key]
return i, ok
}
func (rom *Romap) Reset(key byte) {
_, ok := rom.imap[key]
i... |
class FencedHash
def initialize(hash, obj=nil)
@default = obj
@hash = {}
hash.each_pair do |key, value|
@hash[key] = [value, value]
end
end
def initialize_clone(orig)
super
copy = {}
@hash.each_pair {|key, values| copy[key] =... |
Generate an equivalent Ruby version of this Go code. | package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func decToBin(d float64) string {
whole := int64(math.Floor(d))
binary := strconv.FormatInt(whole, 2) + "."
dd := d - float64(whole)
for dd > 0.0 {
r := dd * 2.0
if r >= 1.0 {
binary += "1"
... | def dec2bin(dec, precision=16)
int, df = dec.split(".")
minus = int.delete!("-")
bin = (minus ? "-" : "") + int.to_i.to_s(2) + "."
if df and df.to_i>0
fp = ("."+df).to_f
digit = 1
until fp.zero? or digit>precision
fp *= 2
n = fp.to_i
bin << n.to_s
fp -= n
digit += 1... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func decToBin(d float64) string {
whole := int64(math.Floor(d))
binary := strconv.FormatInt(whole, 2) + "."
dd := d - float64(whole)
for dd > 0.0 {
r := dd * 2.0
if r >= 1.0 {
binary += "1"
... | def dec2bin(dec, precision=16)
int, df = dec.split(".")
minus = int.delete!("-")
bin = (minus ? "-" : "") + int.to_i.to_s(2) + "."
if df and df.to_i>0
fp = ("."+df).to_f
digit = 1
until fp.zero? or digit>precision
fp *= 2
n = fp.to_i
bin << n.to_s
fp -= n
digit += 1... |
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import (
"fmt"
"sort"
)
type point struct{ x, y int }
type polyomino []point
type pointset map[point]bool
func (p point) rotate90() point { return point{p.y, -p.x} }
func (p point) rotate180() point { return point{-p.x, -p.y} }
func (p point) rotate270() point { return point{-p.y, p.x} }
func (... | require 'set'
def translate2origin(poly)
minx = poly.map(&:first).min
miny = poly.map(&:last).min
poly.map{|x,y| [x - minx, y - miny]}.sort
end
def rotate90(x,y) [y, -x] end
def reflect(x,y) [-x, y] end
def rotations_and_reflections(poly)
[poly,
poly = poly.map{|x,y| rotate90(x,y)},
poly = poly.ma... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
)
var tests = []struct {
descr string
list []string
}{
{"Ignoring leading spaces", []string{
"ignore leading spaces: 2-2",
" ignore leading spaces: 2-1",
" ignore leading spaces: 2+0",
" ... | ar.sort_by{|str| str.downcase.gsub(/\Athe |\Aa |\Aan /, "").lstrip.gsub(/\s+/, " ")}
|
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import "fmt"
type solution struct{ peg, over, land int }
type move struct{ from, to int }
var emptyStart = 1
var board [16]bool
var jumpMoves = [16][]move{
{},
{{2, 4}, {3, 6}},
{{4, 7}, {5, 9}},
{{5, 8}, {6, 10}},
{{2, 1}, {5, 6}, {7, 11}, {8, 13}},
{{8, 12}, {9, 14}},
{{... |
G = [[0,1,3],[0,2,5],[1,3,6],[1,4,8],[2,4,7],[2,5,9],[3,4,5],[3,6,10],[3,7,12],[4,7,11],[4,8,13],[5,8,12],[5,9,14],[6,7,8],[7,8,9],[10,11,12],[11,12,13],[12,13,14],
[3,1,0],[5,2,0],[6,3,1],[8,4,1],[7,4,2],[9,5,2],[5,4,3],[10,6,3],[12,7,3],[11,7,4],[13,8,4],[12,8,5],[14,9,5],[8,7,6],[9,8,7],[12,11,10],[13,12,11],[... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"math/big"
"time"
)
var p []*big.Int
var pd []int
func partDiffDiff(n int) int {
if n&1 == 1 {
return (n + 1) / 2
}
return n + 1
}
func partDiff(n int) int {
if n < 2 {
return 1
}
pd[n] = pd[n-1] + partDiffDiff(n-1)
return pd[n]
}
... | say partitions(6666)
|
Change the following Go code into Ruby without altering its purpose. | package main
import (
"fmt"
"rcu"
)
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n = n / 10
}
return rev
}
func main() {
var special []int
for n := 1; n < 200; n++ {
divs := rcu.Divisors(n)
revN := reversed(n)
all := true
... | class Integer
def reverse
to_s.reverse.to_i
end
def divisors
res = []
(1..Integer.sqrt(self)).each do |cand|
div, mod = self.divmod(cand)
res << cand << div if mod == 0
end
res.uniq.sort
end
def special_divisors?
r = self.reverse
divisors.all?{|d| r % d.rev... |
Produce a language-to-language conversion: from Go to Ruby, same semantics. | package main
import (
"fmt"
"rcu"
)
func main() {
p := rcu.Primes(1000)
fmt.Println("Double twin primes under 1,000:")
for i := 1; i < len(p)-3; i++ {
if p[i+1]-p[i] == 2 && p[i+2]-p[i+1] == 4 && p[i+3]-p[i+2] == 2 {
fmt.Printf("%4d\n", p[i:i+4])
}
}
}
| require 'prime'
res = Prime.each(1000).each_cons(4).select do |p1, p2, p3, p4|
p1+2 == p2 && p2+4 == p3 && p3+2 == p4
end
res.each{|slice| puts slice.join(", ")}
|
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo... | func extended_synthetic_division(dividend, divisor) {
var end = divisor.end
var out = dividend.clone
var normalizer = divisor[0]
for i in ^(dividend.len - end) {
out[i] /= normalizer
var coef = out[i]
if (coef != 0) {
for j in (1 .. end) {
out[i+j] +=... |
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo... | func extended_synthetic_division(dividend, divisor) {
var end = divisor.end
var out = dividend.clone
var normalizer = divisor[0]
for i in ^(dividend.len - end) {
out[i] /= normalizer
var coef = out[i]
if (coef != 0) {
for j in (1 .. end) {
out[i+j] +=... |
Change the programming language of this snippet from Go to Ruby without modifying what it does. | package main
import (
"github.com/fogleman/gg"
"math"
)
const tau = 2 * math.Pi
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri... | def settings
size(300, 300)
end
def setup
sketch_title 'Color Wheel'
background(0)
radius = width / 2.0
center = width / 2
grid(width, height) do |x, y|
rx = x - center
ry = y - center
sat = Math.hypot(rx, ry) / radius
if sat <= 1.0
hue = ((Math.atan2(ry, rx) / PI) + 1) / 2.0
co... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
)
const (
chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
host = "localhost:8000"
)
type database map[string]string
type shortener struct {
Long string `json... | require "kemal"
CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".chars
entries = Hash(String, String).new
post "/" do |env|
short = Random::Secure.random_bytes(8).map{|b| CHARS[b % CHARS.size]}.join
entries[short] = env.params.json["long"].as(String)
"http://localhost:3000/
end
get "/:s... |
Port the following code from Go to Ruby with equivalent syntax and logic. |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
)
const (
chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
host = "localhost:8000"
)
type database map[string]string
type shortener struct {
Long string `json... | require "kemal"
CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".chars
entries = Hash(String, String).new
post "/" do |env|
short = Random::Secure.random_bytes(8).map{|b| CHARS[b % CHARS.size]}.join
entries[short] = env.params.json["long"].as(String)
"http://localhost:3000/
end
get "/:s... |
Maintain the same structure and functionality when rewriting this code in Ruby. | package main
import (
"fmt"
"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)
var pattern =
"(*UTF)(*UCP)" +
"[a-z][-a-z0-9+.]*:" +
"(?=[/\\w])" +
"(?:
"[-\\w.~/%!$&'()*+,;=]*" +
"(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" ... | require 'uri'
str = 'this URI contains an illegal character, parentheses and a misplaced full stop:
http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).
and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)
")" is handled the wrong way by the... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)
var pattern =
"(*UTF)(*UCP)" +
"[a-z][-a-z0-9+.]*:" +
"(?=[/\\w])" +
"(?:
"[-\\w.~/%!$&'()*+,;=]*" +
"(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" ... | require 'uri'
str = 'this URI contains an illegal character, parentheses and a misplaced full stop:
http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).
and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)
")" is handled the wrong way by the... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"image"
"image/color"
"image/png"
"log"
"math/rand"
"os"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
img := image.NewNRGBA(image.Rect(0, 0, 1000, 1000))
for x := 0; x < 1000; x++ {
for y := 0; y < 1000; y++ {
col := color.RG... | require('GD')
var img = %O<GD::Image>.new(500, 500, 1)
for y in (0..500), x in (0..500) {
var color = img.colorAllocate(255.irand, 255.irand, 255.irand)
img.setPixel(x, y, color)
}
File("image500.png").write(img.png, :raw)
|
Write the same algorithm in Ruby as shown in this Go implementation. | package main
import (
"fmt"
"crypto/md5"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"time"
)
type fileData struct {
filePath string
info os.FileInfo
}
type hash [16]byte
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func checksum(filePath ... | require 'digest/md5'
def find_duplicate_files(dir)
puts "\nDirectory :
Dir.chdir(dir) do
file_size = Dir.foreach('.').select{|f| FileTest.file?(f)}.group_by{|f| File.size(f)}
file_size.each do |size, files|
next if files.size==1
files.group_by{|f| Digest::MD5.file(f).to_s}.each do |md5,fs|
... |
Convert this Go block to Ruby, preserving its control flow and logic. | package main
import (
"fmt"
"log"
"math"
"rcu"
)
func cantorPair(x, y int) int {
if x < 0 || y < 0 {
log.Fatal("Arguments must be non-negative integers.")
}
return (x*x + 3*x + 2*x*y + y + y*y) / 2
}
func pi(n int) int {
if n < 2 {
return 0
}
if n == 2 {
... | require 'prime'
def pi(n)
@pr = Prime.each(Integer.sqrt(n)).to_a
a = @pr.size
case n
when 0,1 then 0
when 2 then 1
else phi(n,a) + a - 1
end
end
def phi(x,a)
case a
when 0 then x
when 1 then x-(x>>1)
else
pa = @pr[a-1]
return 1 if x <= pa
phi(x, a-1)- phi(x/pa, a-1)
e... |
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
type header struct {
start, end int
lang string
}
type data struct {
count int
names *[]string
}
func newData(count int, name string) *data {
return &data{count, &[]string{name}}
}
var bmap = m... | require "open-uri"
require "cgi"
tasks = ["Greatest_common_divisor", "Greatest_element_of_a_list", "Greatest_subsequential_sum"]
part_uri = "http://rosettacode.org/wiki?action=raw&title="
Report = Struct.new(:count, :tasks)
result = Hash.new{|h,k| h[k] = Report.new(0, [])}
tasks.each do |task|
puts "processing
... |
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"
"rcu"
)
func main() {
const limit = 29
count := 0
p := 1
one := big.NewInt(1)
three := big.NewInt(3)
w := new(big.Int)
for count < limit {
for {
p += 2
if rcu.IsPrime(p) {
break... | require 'prime'
require 'gmp'
wagstaffs = Enumerator.new do |y|
odd_primes = Prime.each
odd_primes.next
loop do
p = odd_primes.next
candidate = (2 ** p + 1)/3
y << [p, candidate] unless GMP::Z.new(candidate).probab_prime?.zero?
end
end
10.times{puts "%5d - %s" % wagstaffs.next}
14.times{puts "%5d... |
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
func main() {
const limit = 29
count := 0
p := 1
one := big.NewInt(1)
three := big.NewInt(3)
w := new(big.Int)
for count < limit {
for {
p += 2
if rcu.IsPrime(p) {
break... | require 'prime'
require 'gmp'
wagstaffs = Enumerator.new do |y|
odd_primes = Prime.each
odd_primes.next
loop do
p = odd_primes.next
candidate = (2 ** p + 1)/3
y << [p, candidate] unless GMP::Z.new(candidate).probab_prime?.zero?
end
end
10.times{puts "%5d - %s" % wagstaffs.next}
14.times{puts "%5d... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
var p, p2, q *big.Int
func isPentaPowerPrimeSeed(n uint64) bool {
nn := new(big.Int).SetUint64(n)
p.Set(nn)
k := new(big.Int).SetUint64(n + 1)
p2.Add(q, k)
if !p2.ProbablyPrime(15) {
return false
}
p2.Add(p, ... | require 'openssl'
pent_pow_primes = (1..).lazy.select{|n| (0..4).all?{|exp| OpenSSL::BN.new(n**exp + n + 1).prime?} }
n = 30
puts "The first
pent_pow_primes.take(n).each_slice(10){|s| puts "%8s"*s.size % s}
|
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
var p, p2, q *big.Int
func isPentaPowerPrimeSeed(n uint64) bool {
nn := new(big.Int).SetUint64(n)
p.Set(nn)
k := new(big.Int).SetUint64(n + 1)
p2.Add(q, k)
if !p2.ProbablyPrime(15) {
return false
}
p2.Add(p, ... | require 'openssl'
pent_pow_primes = (1..).lazy.select{|n| (0..4).all?{|exp| OpenSSL::BN.new(n**exp + n + 1).prime?} }
n = 30
puts "The first
pent_pow_primes.take(n).each_slice(10){|s| puts "%8s"*s.size % s}
|
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
... | def palindromesgapful(digit, pow)
r1 = (10_u64**pow + 1) * digit
r2 = 10_u64**pow * (digit + 1)
nn = digit * 11
(r1...r2).select { |i| n = i.to_s; n == n.reverse && i.divisible_by?(nn) }
end
def digitscount(digit, count)
pow = 2
nums = [] of UInt64
while nums.size < count
nums += palindromesgapful(d... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
... | def palindromesgapful(digit, pow)
r1 = (10_u64**pow + 1) * digit
r2 = 10_u64**pow * (digit + 1)
nn = digit * 11
(r1...r2).select { |i| n = i.to_s; n == n.reverse && i.divisible_by?(nn) }
end
def digitscount(digit, count)
pow = 2
nums = [] of UInt64
while nums.size < count
nums += palindromesgapful(d... |
Convert this Go block to Ruby, preserving its control flow and logic. | package main
import (
"fmt"
"math/big"
)
var (
zero = new(big.Int)
prod = new(big.Int)
fact = new(big.Int)
)
func ccFactors(n, m uint64) (*big.Int, bool) {
prod.SetUint64(6*m + 1)
if !prod.ProbablyPrime(0) {
return zero, false
}
fact.SetUint64(12*m + 1)
if !fact.Probab... | func chernick_carmichael_factors (n, m) {
[6*m + 1, 12*m + 1, {|i| 2**i * 9*m + 1 }.map(1 .. n-2)...]
}
func is_chernick_carmichael (n, m) {
(n == 2) ? (is_prime(6*m + 1) && is_prime(12*m + 1))
: (is_prime(2**(n-2) * 9*m + 1) && __FUNC__(n-1, m))
}
func chernick_carmichael_number(n, callback) {
... |
Write the same code in Ruby as shown below in Go. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
var p, p2 *big.Int
func isQuadPowerPrimeSeed(n uint64) bool {
nn := new(big.Int).SetUint64(n)
p.Set(nn)
k := new(big.Int).SetUint64(n + 1)
p2.Add(p, k)
if !p2.ProbablyPrime(15) {
return false
}
for i := 0; i ... | require 'openssl'
quad_pow_primes = (1..).lazy.select{|n| (1..4).all?{|exp| OpenSSL::BN.new(n**exp + n + 1).prime?} }
n = 50
puts "The first
quad_pow_primes.take(n).each_slice(10){|s| puts "%8s"*s.size % s}
|
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
var p, p2 *big.Int
func isQuadPowerPrimeSeed(n uint64) bool {
nn := new(big.Int).SetUint64(n)
p.Set(nn)
k := new(big.Int).SetUint64(n + 1)
p2.Add(p, k)
if !p2.ProbablyPrime(15) {
return false
}
for i := 0; i ... | require 'openssl'
quad_pow_primes = (1..).lazy.select{|n| (1..4).all?{|exp| OpenSSL::BN.new(n**exp + n + 1).prime?} }
n = 50
puts "The first
quad_pow_primes.take(n).each_slice(10){|s| puts "%8s"*s.size % s}
|
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"math"
"rcu"
"time"
)
func sos(n int) []int {
if n < 3 {
return []int{}
}
var primes []int
k := (n-3)/2 + 1
marked := make([]bool, k)
limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
for i := 0; i < limit; i++ {
p := 2*i + 3
... | def sieve_of_sundaram(upto)
n = (2.4 * upto * Math.log(upto)) / 2
k = (n - 3) / 2 + 1
bools = [true] * k
(0..(Integer.sqrt(n) - 3) / 2 + 1).each do |i|
p = 2*i + 3
s = (p*p - 3) / 2
(s..k).step(p){|j| bools[j] = false}
end
bools.filter_map.each_with_index {|b, i| (i + 1) * 2 + 1 if b }
end
p si... |
Port the provided Go code into Ruby while preserving the original functionality. | package main
import (
"fmt"
"rcu"
)
const LIMIT = 999999
var primes = rcu.Primes(LIMIT)
func longestSeq(dir string) {
pd := 0
longSeqs := [][]int{{2}}
currSeq := []int{2}
for i := 1; i < len(primes); i++ {
d := primes[i] - primes[i-1]
if (dir == "ascending" && d <= pd) || (di... | require "prime"
limit = 1_000_000
puts "First found longest run of ascending prime gaps up to
p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 < j2-i2 }.max_by(&:size).flatten.uniq
puts "\nFirst found longest run of descending prime gaps up to
p Prime.each(limit).each_cons(2).chunk_while{|(i1... |
Please provide an equivalent version of this Go code in Ruby. | package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
const LIMIT = 11000
primes := rcu.Primes(LIMIT)
facts := make([]*big.Int, LIMIT)
facts[0] = big.NewInt(1)
for i := int64(1); i < LIMIT; i++ {
facts[i] = new(big.Int)
facts[i].Mul(facts[i-1], big.NewInt(i))
... | require "prime"
module Modulo
refine Integer do
def factorial_mod(m) = (1..self).inject(1){|prod, n| (prod *= n) % m }
end
end
using Modulo
primes = Prime.each(11000).to_a
(1..11).each do |n|
res = primes.select do |pr|
prpr = pr*pr
((n-1).factorial_mod(prpr) * (pr-n).factorial_mod(prpr) - (-1)*... |
Write a version of this Go function in Ruby with identical behavior. | package main
import "fmt"
func padovanN(n, t int) []int {
if n < 2 || t < 3 {
ones := make([]int, t)
for i := 0; i < t; i++ {
ones[i] = 1
}
return ones
}
p := padovanN(n-1, t)
for i := n + 1; i < t; i++ {
p[i] = 0
for j := i - 2; j >= i-n-1; ... | func padovan(N) {
Enumerator({|callback|
var n = 2
var pn = [1, 1, 1]
loop {
pn << sum(pn[n-N .. (n++-1) -> grep { _ >= 0 }])
callback(pn[-4])
}
})
}
for n in (2..8) {
say "n =
}
|
Change the programming language of this snippet from Go to Ruby without modifying what it does. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
const limit = 1000000
limit2 := int(math.Cbrt(limit))
primes := rcu.Primes(limit / 6)
pc := len(primes)
var sphenic []int
fmt.Println("Sphenic numbers less than 1,000:")
for i := 0; i < pc-2; i++ {
if ... | require 'prime'
class Integer
def sphenic? = prime_division.map(&:last) == [1, 1, 1]
end
sphenics = (1..).lazy.select(&:sphenic?)
n = 1000
puts "Sphenic numbers less than
p sphenics.take_while{|s| s < n}.to_a
n = 10_000
puts "\nSphenic triplets less than
sps = sphenics.take_while{|s| s < n}.to_a
sps.each_cons(3... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"fmt"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/xsd"
"io/ioutil"
"log"
"os"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
xsdfile := "shiporder.xsd"
f, err := os.Open(xsdfile)
check(err)
... | require('XML::LibXML')
func is_valid_xml(str, schema) {
var parser = %O<XML::LibXML>.new
var xmlschema = %O<XML::LibXML::Schema>.new(string => schema)
try {
xmlschema.validate(parser.parse_string(str))
true
} catch {
false
}
}
var good_xml = '<a>5</a>'
var bad_xml = '... |
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
fmt.Println("Own digits power sums for N = 3 to 9 inclusive:")
for n := 3; n < 10; n++ {
for d := 2; d < 10; d++ {
powers[d] *= d
}
i := int(math.P... | DIGITS = (0..9).to_a
range = (3..18)
res = range.map do |s|
powers = {}
DIGITS.each{|n| powers[n] = n**s}
DIGITS.repeated_combination(s).filter_map do |combi|
sum = powers.values_at(*combi).sum
sum if sum.digits.sort == combi.sort
end.sort
end
puts "Own digits power sums for N =
|
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var ... | require('bigdecimal')
require('bigdecimal/util')
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1 ; yielder.yield(xn2)
xn1 = 1 ; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) }
end
end
def metallic_ratio(b, precision)
xn2 = xn1 = prev = this = 0
lucas(b).eac... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var ... | require('bigdecimal')
require('bigdecimal/util')
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1 ; yielder.yield(xn2)
xn1 = 1 ; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) }
end
end
def metallic_ratio(b, precision)
xn2 = xn1 = prev = this = 0
lucas(b).eac... |
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
... | require 'prime'
require 'gmp'
(2..16).each do |base|
res = Prime.each(1000).select {|n| GMP::Z(("1" * n).to_i(base)).probab_prime? > 0}
puts "Base
end
|
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"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
... | require 'prime'
require 'gmp'
(2..16).each do |base|
res = Prime.each(1000).select {|n| GMP::Z(("1" * n).to_i(base)).probab_prime? > 0}
puts "Base
end
|
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math"
"rcu"
)
var maxDepth = 6
var maxBase = 36
var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true)
var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var maxStrings [][][]int
var mostBases = -1
func maxSlice(a []int) in... | func max_prime_bases(ndig, maxbase=36) {
var maxprimebases = [[]]
var nwithbases = [0]
var maxprime = (10**ndig - 1)
for p in (idiv(maxprime + 1, 10) .. maxprime) {
var dig = p.digits
var bases = (2..maxbase -> grep {|b| dig.all { _ < b } && dig.digits2num(b).is_prime })
if (ba... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"math"
"rcu"
)
var limit = int(math.Log(1e6) * 1e6 * 1.2)
var primes = rcu.Primes(limit)
var prevCats = make(map[int]int)
func cat(p int) int {
if v, ok := prevCats[p]; ok {
return v
}
pf := rcu.PrimeFactors(p + 1)
all := true
for _, f := range pf... | func Erdös_Selfridge_class(n, s=1) is cached {
var f = factor_exp(n+s)
f.last.head > 3 || return 1
f.map {|p| __FUNC__(p.head, s) }.max + 1
}
say "First two hundred primes; Erdös-Selfridge categorized:"
200.pn_primes.group_by(Erdös_Selfridge_class).sort_by{.to_i}.each_2d {|k,v|
say "
}
say "\nSummary ... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"fmt"
"log"
"rcu"
"sort"
)
func ord(n int) string {
if n < 0 {
log.Fatal("Argument must be a non-negative integer.")
}
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%sth", rcu.Commatize(n))
}
m %= 10
suffix := "th"
if m ==... | func f(n) {
var (
p = 2, sp = p,
c = 4, sc = c,
)
var res = []
while (res.len < n) {
if (sc == sp) {
res << [sp, c.composite_count, p.prime_count]
sc += c.next_composite!
}
while (sp < sc) {
sp += p.next_prime!
}
... |
Convert this Go block to Ruby, preserving its control flow and logic. | package main
import (
"fmt"
"rcu"
)
func main() {
limit := int(1e9)
gapStarts := make(map[int]int)
primes := rcu.Primes(limit * 5)
for i := 1; i < len(primes); i++ {
gap := primes[i] - primes[i-1]
if _, ok := gapStarts[gap]; !ok {
gapStarts[gap] = primes[i-1]
... | func prime_gap_records(upto) {
var gaps = []
var p = 3
each_prime(p.next_prime, upto, {|q|
gaps[q-p] := p
p = q
})
gaps.grep { defined(_) }
}
var gaps = prime_gap_records(1e8)
for m in (1 .. gaps.max.len) {
gaps.each_cons(2, {|p,q|
if (abs(q-p) > 10**m) {
... |
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import (
"fmt"
"math"
)
type mwriter struct {
value float64
log string
}
func (m mwriter) bind(f func(v float64) mwriter) mwriter {
n := f(m.value)
n.log = m.log + n.log
return n
}
func unit(v float64, s string) mwriter {
return mwriter{v, fmt.Sprintf(" %-17s: %g\n", ... |
class Writer
attr_reader :value, :log
def initialize(value, log = "New")
@value = value
if value.is_a? Proc
@log = log
else
@log = log + ": " + @value.to_s
end
end
def self.unit(value, log)
Writer.new(value, log)
end
def bind(mwriter)
new_value = mwriter.value.call(@... |
Generate an equivalent Ruby version of this Go code. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func contains(a []string, s string) bool {
for _, e := range a {
if e == s {
return true
}
}
return false
}
func oneAway(a, b string) bool {
sum := 0
for i := 0; i < len(a); i++ {
... | require "set"
Words = File.open("unixdict.txt").read.split("\n").
group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }.
to_h
def word_ladder(from, to)
raise "Length mismatch" unless from.length == to.length
sized_words = Words[from.length]
work_queue = [[from]]
used = Set.new [from]
while work_queue... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"strings"
)
func isDigit(b byte) bool {
return '0' <= b && b <= '9'
}
func separateHouseNumber(address string) (street string, house string) {
length := len(address)
fields := strings.Fields(address)
size := len(fields)
last := fields[size-1]
penult := fiel... | var re = %r[
( .*? )
(?:
\s+
(
| \d+ (?: \- | \/ ) \d+
| (?! 1940 | 1945) \d+ [ a-z I . / \x20 ]* \d*
)
)?
$]x
ARGF.each { |line|
line.chomp!
if (var m = line.match(re)) {
printf("%-25s split as (
}
else {
warn "Can't parse: «
}
}
|
Please provide an equivalent version of this Go code in Ruby. | package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
func main() {
var res []int64
for n := 0; n <= 50; n++ {
ns := strconv.Itoa(n)
k := int64(1)
for {
bk := big.NewInt(k)
s := bk.Exp(bk, bk, nil).String()
if strings.Contains(... | memo = Hash.new{|h, k| h[k] = (k**k).to_s }
res = (0..50).map{|n| (1..).detect{|m| memo[m].include? n.to_s} }
res.each_slice(10){|slice| puts "%4d"*slice.size % slice }
|
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"fmt"
"strings"
)
func derivative(p []int) []int {
if len(p) == 1 {
return []int{0}
}
d := make([]int, len(p)-1)
copy(d, p[1:])
for i := 0; i < len(d); i++ {
d[i] = p[i+1] * (i + 1)
}
return d
}
var ss = []string{"", "", "\u00b2", "\u00b3", "\... | func derivative(f) {
Poly(f.coeffs.map_2d{|e,k| [e-1, k*e] }.flat...)
}
var coeffs = [
[5],
[4,-3],
[-1,6,5],
[-4,3,-2,1],
[-1, 6, 5],
[1,1,0,-1,-1],
]
for c in (coeffs) {
var poly = Poly(c.flip)
var derv = derivative(poly)
var d = { derv.coeff(_) }.map(0..derv.degree)
sa... |
Convert this Go block to Ruby, preserving its control flow and logic. | package main
import "fmt"
type vector = []float64
type matrix []vector
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vecto... | require 'matrix'
m = Matrix[[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3]]
pp m.inv.row_vectors
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version. | package main
import "fmt"
type vector = []float64
type matrix []vector
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vecto... | require 'matrix'
m = Matrix[[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3]]
pp m.inv.row_vectors
|
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float... | func adaptive_Simpson_quadrature(f, left, right, ε = 1e-9) {
func quadrature_mid(l, lf, r, rf) {
var mid = (l+r)/2
var midf = f(mid)
(mid, midf, abs(r-l)/6 * (lf + 4*midf + rf))
}
func recursive_asr(a, fa, b, fb, ε, whole, m, fm) {
var (lm, flm, left) = quadrature_mid(a, f... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float... | func adaptive_Simpson_quadrature(f, left, right, ε = 1e-9) {
func quadrature_mid(l, lf, r, rf) {
var mid = (l+r)/2
var midf = f(mid)
(mid, midf, abs(r-l)/6 * (lf + 4*midf + rf))
}
func recursive_asr(a, fa, b, fb, ε, whole, m, fm) {
var (lm, flm, left) = quadrature_mid(a, f... |
Convert this Go block to Ruby, preserving its control flow and logic. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := m... | def colorful?(ar)
products = []
(1..ar.size).all? do |chunk_size|
ar.each_cons(chunk_size) do |chunk|
product = chunk.inject(&:*)
return false if products.include?(product)
products << product
end
end
end
below100 = (0..100).select{|n| colorful?(n.digits)}
puts "The colorful numbers les... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := m... | def colorful?(ar)
products = []
(1..ar.size).all? do |chunk_size|
ar.each_cons(chunk_size) do |chunk|
product = chunk.inject(&:*)
return false if products.include?(product)
products << product
end
end
end
below100 = (0..100).select{|n| colorful?(n.digits)}
puts "The colorful numbers les... |
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var grid [8][8]byte
func abs(i int) int {
if i >= 0 {
return i
} else {
return -i
}
}
func createFen() string {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
... | def hasNK(board, a, b)
(-1..1).each do |g|
(-1..1).each do |f|
aa = a + f; bb = b + g
if (0..7).includes?(aa) && (0..7).includes?(bb)
p = board[aa + 8 * bb]
return true if p == "K" || p == "k"
end
end
end
return false
end
... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"fmt"
"rcu"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func permutations(input []int) [][]int {
perms := [][]int{input}
a := make([]int, len(input))
copy(a, input)
var n = len(input) - 1
for c... | require "prime"
def find_pan(ar) = ar.permutation(ar.size).find{|perm| perm.join.to_i.prime? }.join.to_i
digits = [7,6,5,4,3,2,1]
puts find_pan(digits)
digits << 0
puts find_pan(digits)
|
Change the programming language of this snippet from Go to Ruby without modifying what it does. | package main
import (
"fmt"
"rcu"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func permutations(input []int) [][]int {
perms := [][]int{input}
a := make([]int, len(input))
copy(a, input)
var n = len(input) - 1
for c... | require "prime"
def find_pan(ar) = ar.permutation(ar.size).find{|perm| perm.join.to_i.prime? }.join.to_i
digits = [7,6,5,4,3,2,1]
puts find_pan(digits)
digits << 0
puts find_pan(digits)
|
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"github.com/fogleman/gg"
"github.com/trubitsyn/go-lindenmayer"
"log"
"math"
)
const twoPi = 2 * math.Pi
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h, theta float64
func main() {
dc.SetRGB(0, 0, 1)
dc.C... | var rules = Hash(
x => 'xF-F+F-xF+F+xF-F+F-x',
)
var lsys = LSystem(
width: 510,
height: 510,
xoff: -505,
yoff: -254,
len: 4,
angle: 90,
color: 'dark green',
)
lsys.execute('F+xF+F+xF', 5, "sierpiński_square_curve.png", rules)
|
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"rcu"
"strconv"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
func main() {
for b := 2; b <= 36; b++ {
if rcu.IsPrime(b) {
continue
}
count... | func is_rhonda_number(n, base = 10) {
base.is_composite || return false
n > 0 || return false
n.digits(base).prod == base*n.factor.sum
}
for b in (2..16 -> grep { .is_composite }) {
say ("First 10 Rhonda numbers to base
10.by { is_rhonda_number(_, b) })
}
|
Transform the following Go implementation into Ruby, maintaining the same output and logic. | package main
import (
"fmt"
"rcu"
)
func prune(a []int) []int {
prev := a[0]
b := []int{prev}
for i := 1; i < len(a); i++ {
if a[i] != prev {
b = append(b, a[i])
prev = a[i]
}
}
return b
}
func main() {
var resF, resD, resT, factors1 []int
f... | say "First 30 Ruth-Aaron numbers (factors):"
say 30.by {|n| (sopfr(n) == sopfr(n+1)) && (n > 0) }.join(' ')
say "\nFirst 30 Ruth-Aaron numbers (divisors):"
say 30.by {|n| ( sopf(n) == sopf(n+1)) && (n > 0) }.join(' ')
|
Keep all operations the same but rewrite the snippet in Ruby. | package main
import "fmt"
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
... | require 'set'
def permutations_with_identical_elements(reps, elements=nil)
elements ||= (1..reps.size)
all = elements.zip(reps).flat_map{|el, r| [el]*r}
all.permutation.inject(Set.new){|s, perm| s << perm.join}
end
permutations_with_identical_elements([2,3,1]).each_slice(10) {|slice| puts slice.join(" ")}
p p... |
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func gcd(a, b uint) uint {
if b == 0 {
return a
}
return gcd(b, a%b)
}
func lcm(a, b uint) uint {
return a / gcd(a, b) * b
}
func ipow(x, p uint) uint {
prod := uint(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
... | func pisano_period_pp(p,k) is cached {
assert(k.is_pos, "k =
assert(p.is_prime, "p =
var (a, b, n) = (0, 1, p**k)
1..Inf -> first_by {
(a, b) = (b, (a+b) % n)
(a == 0) && (b == 1)
}
}
func pisano_period(n) {
n.factor_map {|p,k| pisano_period_pp(p, k) }.lcm
}
say "Pisano ... |
Generate an equivalent Ruby version of this Go code. | package main
import (
"fmt"
"math/big"
"rcu"
"sort"
)
var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)
var three = big.NewInt(3)
var four = big.NewInt(4)
var five = big.NewInt(5)
var six = big.NewInt(6)
func primeFactorsWheel(m *big.Int) []*big.Int {
n := new(big.Int).Set(... | for n in (2..20, 65) {
var steps = []
var orig = n
for (var f = n.factor; true; f = n.factor) {
steps << f
n = Num(f.join)
break if n.is_prime
}
say ("HP(
}
|
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"sort"
"strings"
)
func substrings(s string) []string {
var ss []string
n := len(s)
for i := 0; i < n; i++ {
for j := 1; j <= n-i; j++ {
ss = append(ss, s[i:i+j])
}
}
return ss
}
func reversed(s string) string {
var sb string... | func palindromes(arr) {
gather {
for a in (0..arr.end), b in (a .. arr.end) {
var sublist = arr.ft(a, b)
take(sublist) if (sublist == sublist.flip)
}
}.uniq
}
for n in (100..125) {
say "
}
[9, 169, 12769, 1238769, 123498769, 12346098769, 1234572098769,
123456832098... |
Change the following Go code into Ruby without altering its purpose. | package main
import (
"fmt"
"math"
)
var (
d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,
23.1, 19.6, 19.0, 21.7, 21.4}
d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,
21.9, 22.1, 22.9, 20.5, 24.4}
d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21... | def calculate_p_value(array1, array2)
return 1.0 if array1.size <= 1
return 1.0 if array2.size <= 1
mean1 = array1.sum / array1.size
mean2 = array2.sum / array2.size
return 1.0 if mean1 == mean2
variance1 = 0.0
variance2 = 0.0
array1.each do |x|
variance1 += (mean1 - x)**2
end
array2.each do |x|... |
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"fmt"
"math"
)
var (
d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,
23.1, 19.6, 19.0, 21.7, 21.4}
d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,
21.9, 22.1, 22.9, 20.5, 24.4}
d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21... | def calculate_p_value(array1, array2)
return 1.0 if array1.size <= 1
return 1.0 if array2.size <= 1
mean1 = array1.sum / array1.size
mean2 = array2.sum / array2.size
return 1.0 if mean1 == mean2
variance1 = 0.0
variance2 = 0.0
array1.each do |x|
variance1 += (mean1 - x)**2
end
array2.each do |x|... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
type vector = []*big.Int
type matrix []vector
var (
zero = new(big.Int)
one = big.NewInt(1)
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != ro... | func fibonacci(n) {
([[1,1],[1,0]]**n)[0][1]
}
say 15.of(fibonacci)
|
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"
"time"
)
type vector = []*big.Int
type matrix []vector
var (
zero = new(big.Int)
one = big.NewInt(1)
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != ro... | func fibonacci(n) {
([[1,1],[1,0]]**n)[0][1]
}
say 15.of(fibonacci)
|
Convert this Go snippet to Ruby and keep its semantics consistent. | package main
import (
"fmt"
"log"
"math"
"sort"
"strings"
)
const (
algo = 2
maxAllFactors = 100000
)
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
type term struct{ coef, exp int }
func (t term) mul(t2 term) term {
return term{t.coef * t2.coe... | say "First 30 cyclotomic polynomials:"
for k in (1..30) {
say ("Φ(
}
say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:"
for n in (1..10) {
var k = (1..Inf -> first {|k|
cyclotomic(k).coeffs.any { .tail.abs == n }
})
say "Φ(
}
|
Translate the given Go code snippet into Ruby without altering its behavior. | package main
import (
"fmt"
"log"
"math"
"sort"
"strings"
)
const (
algo = 2
maxAllFactors = 100000
)
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
type term struct{ coef, exp int }
func (t term) mul(t2 term) term {
return term{t.coef * t2.coe... | say "First 30 cyclotomic polynomials:"
for k in (1..30) {
say ("Φ(
}
say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:"
for n in (1..10) {
var k = (1..Inf -> first {|k|
cyclotomic(k).coeffs.any { .tail.abs == n }
})
say "Φ(
}
|
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically? | package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).... | require "bigdecimal/math"
include BigMath
e, pi = E(200), PI(200)
[19, 43, 67, 163].each do |x|
puts "
end
|
Keep all operations the same but rewrite the snippet in Ruby. | package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).... | require "bigdecimal/math"
include BigMath
e, pi = E(200), PI(200)
[19, 43, 67, 163].each do |x|
puts "
end
|
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import (
"fmt"
"sort"
)
type cf struct {
c rune
f int
}
func reverseStr(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func indexOfCf(cfs []cf, r rune) i... | func _MostFreqKHashing(string, k) {
var seen = Hash()
var chars = string.chars
var freq = chars.freq
var schars = freq.keys.sort_by {|c| -freq{c} }
var mfkh = []
for i in ^k {
chars.each { |c|
seen{c} && next
if (freq{c} == freq{schars[i]}) {
see... |
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
var (
dists = calcDists()
dirs = [8]int{1, -1, 10, -10, 9, 11, -11, -9}
)
func calcDists() []float64 {
dists := make([]float64, 10000)
for i := 0; i < 10000; i++ {
ab, cd := math.Floor(float64(i)/100), float64(i%100)
... | module TravelingSalesman {
func Eₛ(distances, path) {
var total = 0
[path, path.slice(1)].zip {|ci,cj|
total += distances[ci-1][cj-1]
}
total
}
func T(k, kmax, kT) { kT * (1 - k/kmax) }
func P(ΔE, k, kmax, kT) { exp(-ΔE / T(k, kmax, kT))... |
Rewrite the snippet below in Ruby so it works the same as the original Go code. | package main
import (
"github.com/fogleman/gg"
"math"
)
func main() {
dc := gg.NewContext(400, 400)
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetRGB(0, 0, 1)
c := (math.Sqrt(5) + 1) / 2
numberOfSeeds := 3000
for i := 0; i <= numberOfSeeds; i++ {
fi := float64(i)
fn := float6... | require('Imager')
func draw_sunflower(seeds=3000) {
var img = %O<Imager>.new(
xsize => 400,
ysize => 400,
)
var c = (sqrt(1.25) + 0.5)
{ |i|
var r = (i**c / seeds)
var θ = (2 * Num.pi * c * i)
var x = (r * sin(θ) + 200)
var y = (r * cos(θ) + 200)
... |
Write the same code in Ruby as shown below in Go. | package main
import (
"fmt"
"rcu"
)
func powerset(set []int) [][]int {
if len(set) == 0 {
return [][]int{{}}
}
head := set[0]
tail := set[1:]
p1 := powerset(tail)
var p2 [][]int
for _, s := range powerset(tail) {
h := []int{head}
h = append(h, s...)
... | say is_practical(2**128 + 1)
say is_practical(2**128 + 4)
|
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"github.com/fogleman/gg"
"math"
)
type tiletype int
const (
kite tiletype = iota
dart
)
type tile struct {
tt tiletype
x, y float64
angle, size float64
}
var gr = (1 + math.Sqrt(5)) / 2
const theta = math.Pi / 5
func setupPrototiles(w, h int) []... | var rules = Hash(
a => 'cE++dE----bE[-cE----aE]++',
b => '+cE--dE[---aE--bE]+',
c => '-aE++bE[+++cE++dE]-',
d => '--cE++++aE[+dE++++bE]--bE',
E => '',
)
var lsys = LSystem(
width: 1000,
height: 1000,
scale: 1,
xoff: -500,
yoff: -500,
len: 40,
angle: 36,
color: '... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"math/big"
)
func repeatedAdd(bf *big.Float, times int) *big.Float {
if times < 2 {
return bf
}
var sum big.Float
for i := 0; i < times; i++ {
sum.Add(&sum, bf)
}
return &sum
}
func main() {
s := "12345679"
t := "123456790"
e := ... | p 12345679e63 * 81 + 1e63
p 12345679012345679e54 * 81 + 1e54
p 12345679012345679012345679e45 * 81 + 1e45
p 12345679012345679012345679012345679e36 * 81 + 1e36
|
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import (
"fmt"
"math/big"
)
func repeatedAdd(bf *big.Float, times int) *big.Float {
if times < 2 {
return bf
}
var sum big.Float
for i := 0; i < times; i++ {
sum.Add(&sum, bf)
}
return &sum
}
func main() {
s := "12345679"
t := "123456790"
e := ... | p 12345679e63 * 81 + 1e63
p 12345679012345679e54 * 81 + 1e54
p 12345679012345679012345679e45 * 81 + 1e45
p 12345679012345679012345679012345679e36 * 81 + 1e36
|
Port the provided Go code into Ruby while preserving the original functionality. | package main
import (
"crypto/tls"
"io/ioutil"
"log"
"net/http"
)
func main() {
cert, err := tls.LoadX509KeyPair(
"./client.local.tld/client.local.tld.crt",
"./client.local.tld/client.local.tld.key",
)
if err != nil {
log.Fatal("Error while loading x509 key pair", err)
}
tlsConfig := &tls.Config... | require 'uri'
require 'net/http'
uri = URI.parse('https://www.example.com')
pem = File.read("/path/to/my.pem")
cert = OpenSSL::X509::Certificate.new(pem)
key = OpenSSL::PKey::RSA.new(pem)
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true,
cert: cert, key: key) do |http|
request ... |
Convert the following code from Go to Ruby, ensuring the logic remains intact. | package main
import (
"bytes"
"crypto/md5"
"crypto/rand"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func connectDB() (*sql.DB, error) {
return sql.Open("mysql", "rosetta:code@/rc")
}
func createUser(db *sql.DB, user, pwd string) error {
salt := make([]byte, 16)
ran... | require 'mysql2'
require 'securerandom'
require 'digest'
def connect_db(host, port = nil, username, password, db)
Mysql2::Client.new(
host: host,
port: port,
username: username,
password: password,
database: db
)
end
def create_user(client, username, password)
salt = SecureRandom.random_byte... |
Write a version of this Go function in Ruby with identical behavior. | package main
import (
"fmt"
"math/rand"
"os/exec"
"raster"
)
func main() {
b := raster.NewBitmap(400, 300)
b.FillRgb(0xc08040)
for i := 0; i < 2000; i++ {
b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)
}
for x := 0; x < 400; x++ {
for y := 240; y < 24... | class Pixmap
PIXMAP_FORMATS = ["P3", "P6"]
PIXMAP_BINARY_FORMATS = ["P6"]
def write_ppm(ios, format="P6")
if not PIXMAP_FORMATS.include?(format)
raise NotImplementedError, "pixmap format
end
ios.puts format, "
ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)
@height.times do ... |
Change the following Go code into Ruby without altering its purpose. | package main
import (
"fmt"
"math/big"
)
var g = [][]int{
0: {1},
2: {0},
5: {2, 6},
6: {5},
1: {2},
3: {1, 2, 4},
4: {5, 3},
7: {4, 7, 6},
}
func main() {
tarjan(g, func(c []int) { fmt.Println(c) })
}
func tarjan(g [][]int, emit func([]int)) {
var indexed, stacked... | func tarjan (k) {
var(:onstack, :index, :lowlink, *stack, *connected)
func strong_connect (vertex, i=0) {
index{vertex} = i
lowlink{vertex} = i+1
onstack{vertex} = true
stack << vertex
for connection in (k{vertex}) {
if (index{connection} == nil) {... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"math"
"sort"
)
const adj = 0.0001
var primes = []uint64{
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,
}
func gcd(x, y uint64) uint64 {
for y != 0 {
x, y = y, x%y
}
return x
}
func isSquareFree(x ui... | func powerful(n, k=2) {
var list = []
func (m,r) {
if (r < k) {
list << m
return nil
}
for a in (1 .. iroot(idiv(n,m), r)) {
if (r > k) {
a.is_coprime(m) || next
a.is_squarefree || next
}
__FUNC... |
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"fmt"
"math"
"sort"
)
const adj = 0.0001
var primes = []uint64{
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,
}
func gcd(x, y uint64) uint64 {
for y != 0 {
x, y = y, x%y
}
return x
}
func isSquareFree(x ui... | func powerful(n, k=2) {
var list = []
func (m,r) {
if (r < k) {
list << m
return nil
}
for a in (1 .. iroot(idiv(n,m), r)) {
if (r > k) {
a.is_coprime(m) || next
a.is_squarefree || next
}
__FUNC... |
Ensure the translated Ruby code behaves exactly like the original Go snippet. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
func main() {
fact := big.NewInt(1)
sum := 0.0
first := int64(0)
firstRatio := 0.0
fmt.Println("The mean proportion of zero digits in factorials up to the following are:")
for n := int64(1); n <= 50000; n++ {
... | [100, 1000, 10_000].each do |n|
v = 1
total_proportion = (1..n).sum do |k|
v *= k
digits = v.digits
Rational(digits.count(0), digits.size)
end
puts "The mean proportion of 0 in factorials from 1 to
end
|
Translate this program into Ruby but keep the logic exactly as in Go. | package main
import (
"bufio"
"fmt"
"golang.org/x/crypto/ssh/terminal"
"log"
"os"
"regexp"
"strconv"
)
type Color struct{ r, g, b int }
type ColorEx struct {
color Color
code string
}
var colors = []ColorEx{
{Color{15, 0, 0}, "31"},
{Color{0, 15, 0}, "32"},
{Color{15... | var ansi = frequire("Term::ANSIColor")
func colorhash(hash) {
hash.split(2).map{|s| ansi.colored(s, "ansi" + s.hex) }.join
}
ARGF.each {|line|
if (STDOUT.is_on_tty && (line =~ /^([[:xdigit:]]+)(.*)/)) {|m|
say (colorhash(m[0]), m[1])
}
else {
say line
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Ruby. | package main
import (
"fmt"
"time"
)
func contains(a []int, v int) bool {
for i := 0; i < len(a); i++ {
if a[i] == v {
return true
}
}
return false
}
func main() {
start := time.Now()
var sends [][4]int
var ors [][2]int
m := 1
digits := []int{0, 2, ... | str = "SEND + 1ORE == 1ONEY"
digits = [0,2,3,4,5,6,7,8,9]
uniq_chars = str.delete("^A-Z").chars.uniq.join
res = digits.permutation(uniq_chars.size).detect do |perm|
num_str = str.tr(uniq_chars, perm.join)
next if num_str.match?(/\b0/)
eval num_str
end
puts str.tr(uniq_chars, res.join)
|
Convert the following code from Go to Ruby, ensuring the logic remains intact. | package main
import (
"fmt"
"math"
)
func endsWithOne(n int) bool {
sum := 0
for {
for n > 0 {
digit := n % 10
sum += digit * digit
n /= 10
}
if sum == 1 {
return true
}
if sum == 89 {
return false
... |
K = 17
F = Array.new(K+1){|n| n==0?1:(1..n).inject(:*)}
g = -> n, gn=[n,0], res=0 { while gn[0]>0
gn = gn[0].divmod(10)
res += gn[1]**2
end
return res==89?0:res
}
N = (G... |
Produce a functionally identical Ruby code for the snippet given in Go. | package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
bs := []byte("Hello world!")
fmt.Println(string(bs))
g := "globe"
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
for i := 0; i < 5; i++ {
data := (*byte)(unsafe.Pointer(hdr.Data + uintptr(i) + 6))
*data ... | require 'cgi'
$SAFE = 4
cgi = CGI::new("html4")
eval(cgi["arbitrary_input"].to_s)
|
Port the following code from Go to Ruby with equivalent syntax and logic. | package main
import (
"fmt"
"github.com/sevlyar/go-daemon"
"log"
"os"
"time"
)
func work() {
f, err := os.Create("daemon_output.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {... | var block = {
for n in (1..100) {
STDOUT.say(n)
Sys.sleep(0.5)
}
}
if (ARGV[0] == 'daemon') {
STDERR.say("Daemon mode")
STDOUT{:fh} = %f'foo.txt'.open_w(){:fh}
STDOUT.autoflush(true)
block.fork
STDERR.say("Exiting")
Sys.exit(0)
}
STDERR.say("Normal mode")
block.run
|
Produce a language-to-language conversion: from Go to Ruby, same semantics. | package main
import (
"fmt"
"github.com/sevlyar/go-daemon"
"log"
"os"
"time"
)
func work() {
f, err := os.Create("daemon_output.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {... | var block = {
for n in (1..100) {
STDOUT.say(n)
Sys.sleep(0.5)
}
}
if (ARGV[0] == 'daemon') {
STDERR.say("Daemon mode")
STDOUT{:fh} = %f'foo.txt'.open_w(){:fh}
STDOUT.autoflush(true)
block.fork
STDERR.say("Exiting")
Sys.exit(0)
}
STDERR.say("Normal mode")
block.run
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.