Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
require 'prime' RE = /123/ puts Prime.each(100_000).select {|prime| RE.match? prime.to_s}.join(" "), "" puts "
Please provide an equivalent version of this Go code in Ruby.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
say "Values of p such that (p, p+2, p+6) are all prime:" 5500.primes.grep{|p| all_prime(p+2, p+6) }.say
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
say "Values of p such that (p, p+2, p+6) are all prime:" 5500.primes.grep{|p| all_prime(p+2, p+6) }.say
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) ...
require 'prime' p Prime.each(500).each_cons(2).select{|p, q| (p*q+2).prime? }
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) ...
require 'prime' p Prime.each(500).each_cons(2).select{|p, q| (p*q+2).prime? }
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } ...
class Integer def square? isqrt = Integer.sqrt(self) isqrt*isqrt == self end end list = [3,4,34,25,9,12,36,56,36].chain( [2,8,81,169,34,55,76,49,7], [75,121,75,144,35,16,46,35]) p list.select(&:square?).sort
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } ...
class Integer def square? isqrt = Integer.sqrt(self) isqrt*isqrt == self end end list = [3,4,34,25,9,12,36,56,36].chain( [2,8,81,169,34,55,76,49,7], [75,121,75,144,35,16,46,35]) p list.select(&:square?).sort
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 main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > ...
require 'prime' generator2357 = Enumerator.new do |y| gen23 = Prime::Generator23.new gen23.each {|n| y << n unless (n%5 == 0 || n%7 == 0) } end res = generator2357.lazy.select do |n| primes, exp = n.prime_division.transpose next if exp.sum < 2 s = n.to_s primes.all?{|pr| s.match?(-pr.to_s) } end res.tak...
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > ...
require 'prime' generator2357 = Enumerator.new do |y| gen23 = Prime::Generator23.new gen23.each {|n| y << n unless (n%5 == 0 || n%7 == 0) } end res = generator2357.lazy.select do |n| primes, exp = n.prime_division.transpose next if exp.sum < 2 s = n.to_s primes.all?{|pr| s.match?(-pr.to_s) } end res.tak...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import ( "fmt" "math" "rcu" ) func magicConstant(n int) int { return (n*n + 1) * n / 2 } var ss = []string{ "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", } func superscript(n int) string { if n < 10 { return ss[n]...
func f(n) { (n+2) * ((n+2)**2 + 1) / 2 } func order(n) { iroot(2*n, 3) + 1 } say ("First 20 terms: ", f.map(1..20).join(' ')) say ("1000th term: ", f(1000), " with order ", order(f(1000))) for n in (1 .. 20) { printf("order(10^%-2s) = %s\n", n, order(10**n)) }
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" big "github.com/ncw/gmp" ) func cullen(n uint) *big.Int { one := big.NewInt(1) bn := big.NewInt(int64(n)) res := new(big.Int).Lsh(one, n) res.Mul(res, bn) return res.Add(res, one) } func woodall(n uint) *big.Int { res := cullen(n) return res.Sub(res, bi...
require 'openssl' cullen = Enumerator.new{|y| (1..).each{|n| y << (n*(1<<n) + 1)} } woodall = Enumerator.new{|y| (1..).each{|n| y << (n*(1<<n) - 1)} } cullen_primes = Enumerator.new{|y| (1..).each {|i|y << i if OpenSSL::BN.new(cullen.next).prime?}} woodall_primes = Enumerator.new{|y| (1..).each{|i|y << i if OpenSSL:...
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "regexp" "strings" ) var elements = ` hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon ...
require "time" last_revision = Time.utc year: 2021, month: 2, day: 25 element_list : Array(String) = %w( hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine arg...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" "rcu" "strconv" "strings" ) func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { fmt.Println("Primes < 500 which a...
res = Prime.each(500).filter_map do |pr| str = pr.to_s(16) str if str == str.reverse end puts res.join(", ")
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 reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { fmt.Println("Primes < 500 which a...
res = Prime.each(500).filter_map do |pr| str = pr.to_s(16) str if str == str.reverse end puts res.join(", ")
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "rcu" ) func main() { var squares []int limit := int(math.Sqrt(1000)) i := 1 for i <= limit { n := i * i if rcu.IsPrime(n + 1) { squares = append(squares, n) } if i == 1 { i = 2 } else { ...
require 'prime' p (1..Integer.sqrt(1000)).filter_map{|n| sqr = n*n; sqr if (sqr+1).prime? }
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "rcu" ) func main() { var squares []int limit := int(math.Sqrt(1000)) i := 1 for i <= limit { n := i * i if rcu.IsPrime(n + 1) { squares = append(squares, n) } if i == 1 { i = 2 } else { ...
require 'prime' p (1..Integer.sqrt(1000)).filter_map{|n| sqr = n*n; sqr if (sqr+1).prime? }
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import ( "bufio" "fmt" "io" "os" ) func Runer(r io.RuneReader) func() (rune, error) { return func() (r rune, err error) { r, _, err = r.ReadRune() return } } func main() { runes := Runer(bufio.NewReader(os.Stdin)) for r, err := runes(); err != nil; r,err =...
File.open("input.txt") do |file| file.each_char { |c| p c } end
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) ...
$rows_of_pins = 12 $width = $rows_of_pins * 10 + ($rows_of_pins+1)*14 Shoes.app( :width => $width + 14, :title => "Galton Box" ) do @bins = Array.new($rows_of_pins+1, 0) @x_coords = Array.new($rows_of_pins) {Array.new} @y_coords = Array.new($rows_of_pins) stack(:width => $width) do stroke gray ...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "sort" ) func getPrimes(max int) []int { if max < 2 { return []int{} } lprimes := []int{2} outer: for x := 3; x <= max; x += 2 { for _, p := range lprimes { if x%p == 0 { continue outer } } lpri...
var maxsum = 99 var primes = maxsum.primes var descendants = (maxsum+1).of { [] } var ancestors = (maxsum+1).of { [] } for p in (primes) { descendants[p] << p for s in (1 .. descendants.end-p) { descendants[s + p] << descendants[s].map {|q| p*q }... } } for p in (primes + [4]) { descendants...
Write the same algorithm in Ruby as shown in this Go implementation.
package main import ( "fmt" "math" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { var squares []int outer: for i := 1; i < 50; i++ { if isSquare(i) { squares = append(squares, i) } else { n := i ...
def f(n) if n < 1 then return end i = 1 while true do sq = i * i while sq > n do sq = (sq / 10).floor end if sq == n then print "%3d %9d %4d\n" % [n, i * i, i] return end i = i + 1 end end print("Prefix ...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "math" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { var squares []int outer: for i := 1; i < 50; i++ { if isSquare(i) { squares = append(squares, i) } else { n := i ...
def f(n) if n < 1 then return end i = 1 while true do sq = i * i while sq > n do sq = (sq / 10).floor end if sq == n then print "%3d %9d %4d\n" % [n, i * i, i] return end i = i + 1 end end print("Prefix ...
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } ...
class Array def circle_sort! while _circle_sort!(0, size-1) > 0 end self end private def _circle_sort!(lo, hi, swaps=0) return swaps if lo == hi low, high = lo, hi mid = (lo + hi) / 2 while lo < hi if self[lo] > self[hi] self[lo], self[hi] = self[hi], self[lo] ...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } letters := "deegklnow" wordsAll := bytes.Split(b, []byte{'\n'}) var words [][]...
wheel = "ndeokgelw" middle, wheel_size = wheel[4], wheel.size res = File.open("unixdict.txt").each_line.select do |word| w = word.chomp next unless w.size.between?(3, wheel_size) next unless w.match?(middle) wheel.each_char{|c| w.sub!(c, "") } w.empty? end puts res
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } ...
def getitem(s, depth=0) out = [""] until s.empty? c = s[0] break if depth>0 and (c == ',' or c == '}') if c == '{' and x = getgroup(s[1..-1], depth+1) out = out.product(x[0]).map{|a,b| a+b} s = x[1] else s, c = s[1..-1], c + s[1] if c == '\\' and s.size > 1 out, s = out.map...
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "sort" "strconv" ) type wheel struct { next int values []string } type wheelMap = map[string]wheel func generate(wheels wheelMap, start string, maxCount int) { count := 0 w := wheels[start] for { s := w.values[w.next] v, err := strconv.At...
groups = [{A: [1, 2, 3]}, {A: [1, :B, 2], B: [3, 4]}, {A: [1, :D, :D], D: [6, 7, 8]}, {A: [1, :B, :C], B: [3, 4], C: [5, :B]} ] groups.each do |group| p group wheels = group.transform_values(&:cycle) res = 20.times.map do el = wheels[:A].next el = wheels[el].next until el.i...
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "fmt" "sort" "strconv" ) type wheel struct { next int values []string } type wheelMap = map[string]wheel func generate(wheels wheelMap, start string, maxCount int) { count := 0 w := wheels[start] for { s := w.values[w.next] v, err := strconv.At...
groups = [{A: [1, 2, 3]}, {A: [1, :B, 2], B: [3, 4]}, {A: [1, :D, :D], D: [6, 7, 8]}, {A: [1, :B, :C], B: [3, 4], C: [5, :B]} ] groups.each do |group| p group wheels = group.transform_values(&:cycle) res = 20.times.map do el = wheels[:A].next el = wheels[el].next until el.i...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "github.com/go-vgo/robotgo" ) func main() { x, y := robotgo.GetMousePos() color := robotgo.GetPixelColor(x, y) fmt.Printf("Color of pixel at (%d, %d) is 0x%s\n", x, y, color) }
module Screen IMPORT_COMMAND = '/usr/bin/import' def self.pixel(x, y) if m = ` m[1..3].map(&:to_i) else false end end end
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" "golang.org/x/net/html" "io/ioutil" "net/http" "regexp" "strings" ) var ( expr = `<h3 class="title"><a class=.*?href="(.*?)".*?>(.*?)</a></h3>` + `.*?<div class="compText aAbs" ><p class=.*?>(.*?)</p></div>` rx = regexp.MustCompile(expr) ) type Yaho...
require 'open-uri' require 'hpricot' SearchResult = Struct.new(:url, :title, :content) class SearchYahoo @@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil] def initialize(term) @term = term @page = 1 @results = nil @url = URI::HTTP.build(@@urlinfo) end def next_result if n...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe on...
Pt = Struct.new(:x, :y) Circle = Struct.new(:x, :y, :r) def circles_from(pt1, pt2, r) raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0 return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0 dx, dy = pt2.x - pt1.x, pt2.y - pt1.y q = Math.hypot(dx, dy) ...
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe on...
Pt = Struct.new(:x, :y) Circle = Struct.new(:x, :y, :r) def circles_from(pt1, pt2, r) raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0 return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0 dx, dy = pt2.x - pt1.x, pt2.y - pt1.y q = Math.hypot(dx, dy) ...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "math" ) func max(a, b uint64) uint64 { if a > b { return a } return b } func min(a, b uint64) uint64 { if a < b { return a } return b } func ndigits(x uint64) (n int) { for ; x > 0; x /= 10 { n++ } return } fu...
def factor_pairs n first = n / (10 ** (n.to_s.size / 2) - 1) (first .. n ** 0.5).map { |i| [i, n / i] if n % i == 0 }.compact end def vampire_factors n return [] if n.to_s.size.odd? half = n.to_s.size / 2 factor_pairs(n).select do |a, b| a.to_s.size == half && b.to_s.size == half && [a, b].count {|x|...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "log" "os" "os/exec" ) func main() { args := []string{ "-m", "-v", "0.75", "a.wav", "-v", "0.25", "b.wav", "-d", "trim", "4", "6", "repeat", "5", } cmd := exec.Command("sox", args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr ...
require 'win32/sound' include Win32 sound1 = ENV['WINDIR'] + '\Media\Windows XP Startup.wav' sound2 = ENV['WINDIR'] + '\Media\Windows XP Shutdown.wav' puts "play the sounds sequentially" [sound1, sound2].each do |s| t1 = Time.now Sound.play(s) puts "' end puts "attempt to play the sounds simultaneously" [so...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) ...
deck = ([:black, :red] * 26 ).shuffle black_pile, red_pile, discard = [] of Symbol, [] of Symbol, [] of Symbol until deck.empty? discard << deck.pop discard.last == :black ? black_pile << deck.pop : red_pile << deck.pop end x = rand( [black_pile.size, red_pile.size].min ) red_bunch = (0...x).map { red_pile.de...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) ...
deck = ([:black, :red] * 26 ).shuffle black_pile, red_pile, discard = [] of Symbol, [] of Symbol, [] of Symbol until deck.empty? discard << deck.pop discard.last == :black ? black_pile << deck.pop : red_pile << deck.pop end x = rand( [black_pile.size, red_pile.size].min ) red_bunch = (0...x).map { red_pile.de...
Convert this Go snippet to Ruby and keep its semantics consistent.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
def initN n = Array.new(15){Array.new(11, ' ')} for i in 1..15 n[i - 1][5] = 'x' end return n end def horiz(n, c1, c2, r) for c in c1..c2 n[r][c] = 'x' end end def verti(n, r1, r2, c) for r in r1..r2 n[r][c] = 'x' end end def diagd(n, c1, c2, r) for c in c1...
Write the same code in Ruby as shown below in Go.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
def initN n = Array.new(15){Array.new(11, ' ')} for i in 1..15 n[i - 1][5] = 'x' end return n end def horiz(n, c1, c2, r) for c in c1..c2 n[r][c] = 'x' end end def verti(n, r1, r2, c) for r in r1..r2 n[r][c] = 'x' end end def diagd(n, c1, c2, r) for c in c1...
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted...
class Card include Comparable attr_accessor :ordinal attr_reader :suit, :face SUITS = %i(♥ ♦ ♣ ♠) FACES = %i(2 3 4 5 6 7 8 9 10 j q k a) def initialize(str) @face, @suit = parse(str) @ordinal = FACES.index(@face) end def <=> (other) self.ordinal <=> other.ordinal end def to...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted...
class Card include Comparable attr_accessor :ordinal attr_reader :suit, :face SUITS = %i(♥ ♦ ♣ ♠) FACES = %i(2 3 4 5 6 7 8 9 10 j q k a) def initialize(str) @face, @suit = parse(str) @ordinal = FACES.index(@face) end def <=> (other) self.ordinal <=> other.ordinal end def to...
Change the following Go code into Ruby without altering its purpose.
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >=...
def fibonacci_word(n) words = ["1", "0"] (n-1).times{ words << words[-1] + words[-2] } words[n] end def print_fractal(word) area = Hash.new(" ") x = y = 0 dx, dy = 0, -1 area[[x,y]] = "S" word.each_char.with_index(1) do |c,n| area[[x+dx, y+dy]] = dx.zero? ? "|" : "-" x, y = x+2*dx, y+2*dy a...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import "fmt" import "math/rand" func main(){ var a1,a2,a3,y,match,j,k int var inp string y=1 for y==1{ fmt.Println("Enter your sequence:") fmt.Scanln(&inp) var Ai [3] int var user [3] int for j=0;j<3;j++{ if(inp[j]==104){ user[j]=1 }else{ user[j]=0 } } for k=0;k<3;k++{ Ai[k]=rand.Intn(2) } for user[0]==Ai[...
Toss = [:Heads, :Tails] def yourChoice puts "Enter your choice (H/T)" choice = [] 3.times do until (c = $stdin.getc.upcase) == "H" or c == "T" end choice << (c=="H" ? Toss[0] : Toss[1]) end puts "You chose choice end loop do puts "\n%s I start, %s you start ..... %s" % [*Toss, coin = Toss.s...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
Shoes.app(:height=>540,:width=>540, :title=>"Sierpinski Triangle") do def triangle(slot, tri, color) x, y, len = tri slot.append do fill color shape do move_to(x,y) dx = len * Math::cos(Math::PI/3) dy = len * Math::sin(Math::PI/3) line_to(x-dx, y+dy) line_to...
Write the same code in Ruby as shown below in Go.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
Shoes.app(:height=>540,:width=>540, :title=>"Sierpinski Triangle") do def triangle(slot, tri, color) x, y, len = tri slot.append do fill color shape do move_to(x,y) dx = len * Math::cos(Math::PI/3) dy = len * Math::sin(Math::PI/3) line_to(x-dx, y+dy) line_to...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strings" ) func printBlock(data string, le int) { a := []byte(data) sumBytes := 0 for _, b := range a { sumBytes += int(b - 48) } fmt.Printf("\nblocks %c, cells %d\n", a, le) if le-sumBytes <= 0 { fmt.Println("No solution") return ...
def nonoblocks(cell, blocks) raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1 nblock(cell, blocks, '', []) end def nblock(cell, blocks, position, result) if cell <= 0 result << position[0..cell-1] elsif blocks.empty? or blocks[0].zero? result << position ...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "strings" ) func printBlock(data string, le int) { a := []byte(data) sumBytes := 0 for _, b := range a { sumBytes += int(b - 48) } fmt.Printf("\nblocks %c, cells %d\n", a, le) if le-sumBytes <= 0 { fmt.Println("No solution") return ...
def nonoblocks(cell, blocks) raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1 nblock(cell, blocks, '', []) end def nblock(cell, blocks, position, result) if cell <= 0 result << position[0..cell-1] elsif blocks.empty? or blocks[0].zero? result << position ...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import "fmt" type Range struct { start, end uint64 print bool } func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9...
def main intervals = [ [2, 1000, true], [1000, 4000, true], [2, 10000, false], [2, 100000, false], [2, 1000000, false], [2, 10000000, false], [2, 100000000, false], [2, 1000000000, false] ] for intv in intervals (start, ending, display)...
Generate an equivalent Ruby version of this Go code.
package main import "fmt" type Range struct { start, end uint64 print bool } func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9...
def main intervals = [ [2, 1000, true], [1000, 4000, true], [2, 10000, false], [2, 100000, false], [2, 1000000, false], [2, 10000000, false], [2, 100000000, false], [2, 1000000000, false] ] for intv in intervals (start, ending, display)...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "strconv" ) const ( ul = "╔" uc = "╦" ur = "╗" ll = "╚" lc = "╩" lr = "╝" hb = "═" vb = "║" ) var mayan = [5]string{ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", } const ( m0 = " Θ " m5 = "────" ) func dec2vig(n uint64) []u...
numbers = ARGV.map(&:to_i) if numbers.length == 0 puts puts("usage: exit end def maya_print(number) digits5s1s = number.to_s(20).chars.map { |ch| ch.to_i(20) }.map { |dig| dig.divmod(5) } puts(('+----' * digits5s1s.length) + '+') 3.downto(0) do |row| digits5s1s.each do |d5s1s| if row < d5s1s[0] ...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import "fmt" func main() { coconuts := 11 outer: for ns := 2; ns < 10; ns++ { hidden := make([]int, ns) coconuts = (coconuts/ns)*ns + 1 for { nc := coconuts for s := 1; s <= ns; s++ { if nc%ns == 1 { hidden[s-1] =...
def valid?(sailor, nuts) sailor.times do return false if (nuts % sailor) != 1 nuts -= 1 + nuts / sailor end nuts > 0 and nuts % sailor == 0 end [5,6].each do |sailor| n = sailor n += 1 until valid?(sailor, n) puts "\n (sailor+1).times do div, mod = n.divmod(sailor) puts " n -= 1 + d...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import "fmt" func main() { coconuts := 11 outer: for ns := 2; ns < 10; ns++ { hidden := make([]int, ns) coconuts = (coconuts/ns)*ns + 1 for { nc := coconuts for s := 1; s <= ns; s++ { if nc%ns == 1 { hidden[s-1] =...
def valid?(sailor, nuts) sailor.times do return false if (nuts % sailor) != 1 nuts -= 1 + nuts / sailor end nuts > 0 and nuts % sailor == 0 end [5,6].each do |sailor| n = sailor n += 1 until valid?(sailor, n) puts "\n (sailor+1).times do div, mod = n.divmod(sailor) puts " n -= 1 + d...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := ...
require_relative 'raster_graphics' class Pixmap def self.read_ppm(ios) format = ios.gets.chomp width, height = ios.gets.chomp.split.map(&:to_i) max_colour = ios.gets.chomp if !PIXMAP_FORMATS.include?(format) || (width < 1) || (height < 1) || (max_colour != '255') ios.close ...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m...
watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ] watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ] words = ["One","Two","Three","Four","Five","Six","Seven","Eight"] sound = "ding!" loop do time = Time.now if time.sec == 0 an...
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m...
watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ] watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ] words = ["One","Two","Three","Four","Five","Six","Seven","Eight"] sound = "ding!" loop do time = Time.now if time.sec == 0 an...
Convert this Go block to Ruby, preserving its control flow and logic.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math/rand" "os" "time" ) const ( imageWidth = 300 imageHeight = 200 nSites = 10 ) func main() { writePngFile(generateVoronoi(randomSites())) } func generateVoronoi(sx, sy []int) image.Im...
require_relative 'raster_graphics' class ColourPixel < Pixel def initialize(x, y, colour) @colour = colour super x, y end attr_accessor :colour def distance_to(px, py) Math.hypot(px - x, py - y) end end width = 300 height = 200 npoints = 20 pixmap = Pixmap.new(width, height) @bases = npoints...
Please provide an equivalent version of this Go code in Ruby.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math/rand" "os" "time" ) const ( imageWidth = 300 imageHeight = 200 nSites = 10 ) func main() { writePngFile(generateVoronoi(randomSites())) } func generateVoronoi(sx, sy []int) image.Im...
require_relative 'raster_graphics' class ColourPixel < Pixel def initialize(x, y, colour) @colour = colour super x, y end attr_accessor :colour def distance_to(px, py) Math.hypot(px - x, py - y) end end width = 300 height = 200 npoints = 20 pixmap = Pixmap.new(width, height) @bases = npoints...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=examp...
require 'rubygems' require 'net/ldap' ldap = Net::LDAP.new(:host => 'ldap.example.com', :base => 'o=companyname') ldap.authenticate('bind_dn', 'bind_pass')
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import "fmt" type Item struct { name string weight, value, qty int } var items = []Item{ {"map", 9, 150, 1}, {"compass", 13, 35, 1}, {"water", 153, 200, 2}, {"sandwich", 50, 60, 2}, {"glucose", 15, 60, 2}, {"tin", 68, 45, 3}, {"banana", 27, 60, 3}, {"apple", 39, 40, 3},...
record Item, name : String, weight : Int32, value : Int32, count : Int32 record Selection, mask : Array(Int32), cur_index : Int32, total_value : Int32 class Knapsack @threshold_value = 0 @threshold_choice : Selection? getter checked_nodes = 0 def knapsack_step(taken, items, remaining_weight) if taken.tot...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" "github.com/tiaguinho/gosoap" "log" ) type CheckVatResponse struct { CountryCode string `xml:"countryCode"` VatNumber string `xml:"vatNumber"` RequestDate string `xml:"requestDate"` Valid string `xml:"valid"` Name string `xml:"name"` Addre...
require 'soap/wsdlDriver' wsdl = SOAP::WSDLDriverFactory.new("http://example.com/soap/wsdl") soap = wsdl.create_rpc_driver response1 = soap.soapFunc(:elementName => "value") puts response1.soapFuncReturn response2 = soap.anotherSoapFunc(:aNumber => 42) puts response2.anotherSoapFuncReturn
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
require "getoptlong" require "rdoc/usage" def phone(name, message) puts "Calling puts message end def test phone("Barry", "Hi!") phone("Cindy", "Hello!") end def main mode = :usage name = "" message = "" opts=GetoptLong.new( ["--help", "-h", GetoptLong::NO_ARGUMENT], ["--eddy", "...
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
require "getoptlong" require "rdoc/usage" def phone(name, message) puts "Calling puts message end def test phone("Barry", "Hi!") phone("Cindy", "Hello!") end def main mode = :usage name = "" message = "" opts=GetoptLong.new( ["--help", "-h", GetoptLong::NO_ARGUMENT], ["--eddy", "...
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "sort" "strconv" "strings" ) var board [][]int var start, given []int func setup(input []string) { puzzle := make([][]string, len(input)) for i := 0; i < len(input); i++ { puzzle[i] = strings.Fields(input[i]) } nCols := len(puzzle[0]) nRows...
class Hidato Cell = Struct.new(:value, :used, :adj) ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] def initialize(board, pout=true) @board = [] board.each_line do |line| @board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil] end @board ...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "sort" "strconv" "strings" ) var board [][]int var start, given []int func setup(input []string) { puzzle := make([][]string, len(input)) for i := 0; i < len(input); i++ { puzzle[i] = strings.Fields(input[i]) } nCols := len(puzzle[0]) nRows...
class Hidato Cell = Struct.new(:value, :used, :adj) ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] def initialize(board, pout=true) @board = [] board.each_line do |line| @board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil] end @board ...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import "fmt" type link struct { int next *link } func linkInts(s []int) *link { if len(s) == 0 { return nil } return &link{s[0], linkInts(s[1:])} } func (l *link) String() string { if l == nil { return "nil" } r := fmt.Sprintf("[%d", l.int) for l = l....
class Array def strandsort a = dup result = [] until a.empty? v = a.first sublist, a = a.partition{|val| v=val if v<=val} result.each_index do |idx| break if sublist.empty? result.insert(idx, sublist.shift) if sublist.first < result[idx] end result +...
Keep all operations the same but rewrite the snippet in Ruby.
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d...
module Angles BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 } def self.method_missing(meth, angle) from, to = BASES.values_at(*meth.to_s.split("2")) raise NoMethodError, meth if (from.nil? or to.nil?) mod = (angle.to_f * to / from) % to angle < 0 ? mod - to : mod end...
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "encoding/xml" "fmt" "log" "os" ) type Inventory struct { XMLName xml.Name `xml:"inventory"` Title string `xml:"title,attr"` Sections []struct { XMLName xml.Name `xml:"section"` Name string `xml:"name,attr"` Items []struct { XMLName xml.Name `xml:"item"` Name ...
require "rexml/document" include REXML doc = Document.new( %q@<inventory title="OmniCorp Store ... </inventory> @ ) invisibility = XPath.first( doc, "//item" ) XPath.each( doc, "//price") { |element| puts element.text } names = XPath.match( doc,...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "encoding/base64" "io" "log" "net/http" "strings" ) const userPass = "rosetta:code" const unauth = http.StatusUnauthorized func hw(w http.ResponseWriter, req *http.Request) { auth := req.Header.Get("Authorization") if !strings.HasPrefix(auth, "Basic ") { log....
require 'uri' require 'net/http' uri = URI.parse('https://www.example.com') response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| request = Net::HTTP::Get.new uri request.basic_auth('username', 'password') http.request request end
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "fmt" "sort" ) type rankable interface { Len() int RankEqual(int, int) bool } func StandardRank(d rankable) []float64 { r := make([]float64, d.Len()) var k int for i := range r { if i == 0 || !d.RankEqual(i, i-1) { k = i + 1 } r[i] = float64(k) } return r } func ModifiedRank(...
ar = "44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen".lines.map{|line| line.split} grouped = ar.group_by{|pair| pair.shift.to_i} s_rnk = 1 m_rnk = o_rnk = 0 puts "stand.\tmod.\tdense\tord.\tfract." grouped.each.with_index(1) do |(score, names), d_rnk| m_rnk += names.flatten!.size f_rnk = (s_r...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "log" "os/exec" "strings" "time" ) func main() { s := "Actions speak louder than words." prev := "" prevLen := 0 bs := "" for _, word := range strings.Fields(s) { cmd := exec.Command("espeak", word) if err := cmd.Run(); err != nil { ...
load 'speechsynthesis.rb' if ARGV.length == 1 $text = "This is default text for the highlight and speak program" else $text = ARGV[1..-1].join(" ") end $words = $text.split Shoes.app do @idx = 0 stack do @sentence = para(strong($words[0] + " "), $words[1..-1].map {|word| span(word + " ")}) button "Sa...
Translate the given Go code snippet into Ruby without altering its behavior.
package main import ( "fmt" "log" "os/exec" "strings" "time" ) func main() { s := "Actions speak louder than words." prev := "" prevLen := 0 bs := "" for _, word := range strings.Fields(s) { cmd := exec.Command("espeak", word) if err := cmd.Run(); err != nil { ...
load 'speechsynthesis.rb' if ARGV.length == 1 $text = "This is default text for the highlight and speak program" else $text = ARGV[1..-1].join(" ") end $words = $text.split Shoes.app do @idx = 0 stack do @sentence = para(strong($words[0] + " "), $words[1..-1].map {|word| span(word + " ")}) button "Sa...
Change the following Go code into Ruby without altering its purpose.
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { cas...
require 'stringio' class ConfigFile def self.file(filename) fh = File.open(filename) obj = self.new(fh) obj.filename = filename fh.close obj end def self.data(string) fh = StringIO.new(string) obj = self.new(fh) fh.close obj end def initialize(filehandle) @lin...
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "strings" ) func main() { key := ` 8752390146 ET AON RIS 5BC/FGHJKLM 0PQD.VWXYZU` p := "you have put on 7.5 pounds since I saw you." fmt.Println(p) c := enc(key, p) fmt.Println(c) fmt.Println(dec(key, c)) } func enc(bd, pt string) (ct string) { enc :=...
class StraddlingCheckerboard EncodableChars = "A-Z0-9." SortedChars = " ./" + [*"A".."Z"].join def initialize(board = nil) if board.nil? rest = "BCDFGHJKLMPQUVWXYZ/.".chars.shuffle @board = [" ESTONIAR".chars.shuffle, rest[0..9], rest[10..19]] elsif board.chars.sort.join == SortedC...
Translate the given Go code snippet into Ruby without altering its behavior.
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei ...
require 'open-uri' plausibility_ratio = 2 counter = Hash.new(0) path = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' rules = [['I before E when not preceded by C:', 'ie', 'ei'], ['E before I when preceded by C:', 'cei', 'cie']] open(path){|f| f.each{|line| line.scan(/ie|ei|cie|cei/){|match| counter[m...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei ...
require 'open-uri' plausibility_ratio = 2 counter = Hash.new(0) path = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' rules = [['I before E when not preceded by C:', 'ie', 'ei'], ['E before I when preceded by C:', 'cei', 'cie']] open(path){|f| f.each{|line| line.scan(/ie|ei|cie|cei/){|match| counter[m...
Please provide an equivalent version of this Go code in Ruby.
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) } func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { ...
def ipart(n); n.truncate; end def fpart(n); n - ipart(n); end def rfpart(n); 1.0 - fpart(n); end class Pixmap def draw_line_antialised(p1, p2, colour) x1, y1 = p1.x, p1.y x2, y2 = p2.x, p2.y steep = (y2 - y1).abs > (x2 - x1).abs if steep x1, y1 = y1, x1 x2, y2 = y2, x2 end if x1...
Produce a language-to-language conversion: from Go to Ruby, same semantics.
package main import ( "fmt" "sort" ) func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := n...
func next_from_digits(n, b = 10) { var a = n.digits(b).flip while (a.next_permutation) { with (a.flip.digits2num(b)) { |t| return t if (t > n) } } return 0 } say 'Next largest integer able to be made from these digits, or zero if no larger exists:' for n in ( 0, 9, 1...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "sort" ) func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := n...
func next_from_digits(n, b = 10) { var a = n.digits(b).flip while (a.next_permutation) { with (a.flip.digits2num(b)) { |t| return t if (t > n) } } return 0 } say 'Next largest integer able to be made from these digits, or zero if no larger exists:' for n in ( 0, 9, 1...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "math" "strings" ) func main() { for _, n := range [...]int64{ 0, 4, 6, 11, 13, 75, 100, 337, -164, math.MaxInt64, } { fmt.Println(fourIsMagic(n)) } } func fourIsMagic(n int64) string { s := say(n) s = strings.ToUpper(s[:1]) + s[1:] t := s for n != 4 { n = int64(len(s)) ...
module NumberToWord NUMBERS = { 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16...
Keep all operations the same but rewrite the snippet in Ruby.
package main import ( "fmt" "math/rand" "strings" "time" ) var cylinder = [6]bool{} func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t } func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } fun...
class Revolver attr_accessor :strategy attr_reader :notches, :shot_count def initialize(strategy = [:load, :spin, :shoot], num_chambers = 6) @chambers = Array.new(num_chambers) @strategy = strategy @notches, @shot_count, @loaded_count = 0, 0, 0 end def load raise "gun completely loaded " i...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "github.com/fogleman/gg" "image/color" "math" ) var ( red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = color.RGBA{0, 255, 255, 255} ) var ( w, h ...
THETA = Math::PI * 2 / 5 SCALE_FACTOR = (3 - Math.sqrt(5)) / 2 MARGIN = 20 attr_reader :pentagons, :renderer def settings size(400, 400) end def setup sketch_title 'Pentaflake' radius = width / 2 - 2 * MARGIN center = Vec2D.new(radius - 2 * MARGIN, 3 * MARGIN) pentaflake = Pentaflake.new(center, radius, 5) ...
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "bytes" "fmt" "strings" ) var in = ` 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 0111001111001110...
class ZhangSuen NEIGHBOUR8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] CIRCULARS = NEIGHBOUR8 + [NEIGHBOUR8.first] def initialize(str, black=" s1 = str.each_line.map{|line| line.chomp.each_char.map{|c| c==black ? 1 : 0}} s2 = s1.map{|line| line.map{0}} xrange = 1...
Port the provided Go code into Ruby while preserving the original functionality.
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr...
pieces = %i(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) regexes = [/♗(..)*♗/, /♖.*♔.*♖/] row = pieces.shuffle.join until regexes.all?{|re| re.match(row)} puts row
Generate an equivalent Ruby version of this Go code.
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[st...
DIGIT_F = { " " " " " " " " " " } DIGIT_R = { " " " " " " " " " " } END_SENTINEL = " MID_SENTINEL = " def decode_upc(s) def decode_upc_impl(input) upc = input.strip if upc.length != 95 then ...
Preserve the algorithm and functionality while converting the code from Go to Ruby.
package main import ( "fmt" "os/exec" ) func main() { command := "EventCreate" args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION", "/SO", "Go", "/D", "\"Rosetta Code Example\""} cmd := exec.Command(command, args...) err := cmd.Run() if err != nil { fmt....
require 'win32/eventlog' logger = Win32::EventLog.new logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry")
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
import ( "fmt" "strings" ) func main() { for _, n := range []int64{ 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, } { fmt.Println(sayOrdinal(n)) } } var irregularOrdinals = map[string]string{ "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth"...
var lingua_en = frequire('Lingua::EN::Numbers') var tests = [1,2,3,4,5,11,65,100,101,272,23456,8007006005004003] tests.each {|n| printf("%16s : %s\n", n, lingua_en.num2en_ordinal(n)) }
Port the provided Go code into Ruby while preserving the original functionality.
package main import ( "encoding/hex" "fmt" "io" "net" "os" "strconv" "strings" "text/tabwriter" ) func parseIPPort(address string) (net.IP, *uint64, error) { ip := net.ParseIP(address) if ip != nil { return ip, nil, nil } host, portStr, err := net.SplitHostPort(address) if err != nil { return nil,...
require 'ipaddr' TESTCASES = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80"] output = [%w(String Address Port Family Hex), %w(------ ------- ---- --...
Change the programming language of this snippet from Go to Ruby without modifying what it does.
package main import ( "fmt" "math" ) const eps = 1e-14 type point struct{ x, y float64 } func (p point) String() string { if p.x == 0 { p.x = 0 } if p.y == 0 { p.y = 0 } return fmt.Sprintf("(%g, %g)", p.x, p.y) } func sq(x float64) float64 { return x * x } ...
EPS = 1e-14 def sq(x) return x * x end def intersects(p1, p2, cp, r, segment) res = [] (x0, y0) = cp (x1, y1) = p1 (x2, y2) = p2 aa = y2 - y1 bb = x1 - x2 cc = x2 * y1 - x1 * y2 a = sq(aa) + sq(bb) if bb.abs >= EPS then b = 2 * (aa * cc + aa * bb * y0 - sq(bb) * x0) ...
Generate an equivalent Ruby version of this Go code.
package main import "fmt" func largestPrimeFactor(n uint64) uint64 { if n < 2 { return 1 } inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6} max := uint64(1) for n%2 == 0 { max = 2 n /= 2 } for n%3 == 0 { max = 3 n /= 3 } for n%5 == 0 { max = ...
require 'prime' p 600851475143.prime_division.last.first
Port the provided Go code into Ruby while preserving the original functionality.
package main import ( "fmt" "log" "math" "strings" ) var error = "Argument must be a numeric literal or a decimal numeric string." func getNumDecimals(n interface{}) int { switch v := n.(type) { case int: return 0 case float64: if v == math.Trunc(v) { return 0 ...
func number_of_decimals(n, limit = 1e5) { var prec = Num(Num!PREC)>>2 var prev = '' n = Number(n) if !n.kind_of(Number) loop { var str = n.as_dec(prec) if (prev == str) { return (str.contains('.') ? str.substr(str.index('.')+1).len : 0) } prev = str ...
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import "fmt" func printMinCells(n int) { fmt.Printf("Minimum number of cells after, before, above and below %d x %d square:\n", n, n) p := 1 if n > 20 { p = 2 } for r := 0; r < n; r++ { cells := make([]int, n) for c := 0; c < n; c++ { nums := []int{...
def dist2edge(n) width = (n/2).to_s.size+1 m = n-1 (0..m).map do |x| (0..m).map{|y| [x, y, m-x, m-y].min.to_s.center(width) }.join end end puts dist2edge(10)
Ensure the translated Ruby code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" ) func main() { list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3} maxDiff := -1.0 var maxPairs [][2]float64 for i := 1; i < len(list); i++ { diff := math.Abs(list[i-1] - list[i]) if diff > maxDiff { maxDi...
list = [1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3] max_dif, pairs = list.each_cons(2).group_by{|a,b| (a-b).abs}.max puts "Maximum difference is pairs.each{|pair| p pair}
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c,...
require 'HLPsolver' ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]] board1 = <<EOS . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . EOS t0 = Time.now HLPsolver.new(board1).solve puts "
Convert this Go block to Ruby, preserving its control flow and logic.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c,...
require 'HLPsolver' ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]] board1 = <<EOS . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . EOS t0 = Time.now HLPsolver.new(board1).solve puts "
Transform the following Go implementation into Ruby, maintaining the same output and logic.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00...
require 'HLPsolver' ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]] board1 = <<EOS 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 ...
Rewrite the snippet below in Ruby so it works the same as the original Go code.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00...
require 'HLPsolver' ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]] board1 = <<EOS 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 ...
Maintain the same structure and functionality when rewriting this code in Ruby.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", ...
class Example def foo puts "this is foo" end def bar puts "this is bar" end def method_missing(name, *args, &block) puts "tried to handle unknown method %s" % name unless args.empty? puts "it had arguments: %p" % [args] end end end example = ...
Change the following Go code into Ruby without altering its purpose.
package main import ( "fmt" "strconv" "strings" ) var atomicMass = map[string]float64{ "H": 1.008, "He": 4.002602, "Li": 6.94, "Be": 9.0121831, "B": 10.81, "C": 12.011, "N": 14.007, "O": 15.999, "F": 18.998403163, "Ne": 20.1797, "Na": 22.9897692...
$atomicMass = { "H" => 1.008, "He" => 4.002602, "Li" => 6.94, "Be" => 9.0121831, "B" => 10.81, "C" => 12.011, "N" => 14.007, "O" => 15.999, "F" => 18.998403163, "Ne" => 20.1797, "Na" => 22.98976928, "Mg" => 24.305, "Al" => 26.9815385, ...
Translate this program into Ruby but keep the logic exactly as in Go.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
var rules = Hash( x => 'xF+G+xF--F--xF+G+x', ) var lsys = LSystem( width: 550, height: 550, xoff: -9, yoff: -271, len: 5, angle: 45, color: 'dark green', ) lsys.execute('F--xF--F--xF', 5, "sierpiński_curve.png", rules)
Change the following Go code into Ruby without altering its purpose.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
var rules = Hash( x => 'xF+G+xF--F--xF+G+x', ) var lsys = LSystem( width: 550, height: 550, xoff: -9, yoff: -271, len: 5, angle: 45, color: 'dark green', ) lsys.execute('F--xF--F--xF', 5, "sierpiński_curve.png", rules)
Generate a Ruby translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
fn selectively_replace_chars(s string, char_map map[string]string) string { mut bytes := s.bytes() mut counts := { 'a': 0 'b': 0 'r': 0 } for i := s.len - 1; i >= 0; i-- { c := s[i].ascii_str() if c in ['a', 'b', 'r'] { bytes[i] = char_map[c][counts[c]...
Can you help me rewrite this code in Ruby instead of Go, keeping it the same logically?
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
fn selectively_replace_chars(s string, char_map map[string]string) string { mut bytes := s.bytes() mut counts := { 'a': 0 'b': 0 'r': 0 } for i := s.len - 1; i >= 0; i-- { c := s[i].ascii_str() if c in ['a', 'b', 'r'] { bytes[i] = char_map[c][counts[c]...
Write a version of this Go function in Ruby with identical behavior.
package main import ( "fmt" "os" "sort" "strings" "text/template" ) func main() { const t = `[[[{{index .P 1}}, {{index .P 2}}], [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], {{index .P 5}}]] ` type S struct { P map[int]string } var s S s.P = map[int]string{ ...
def with_payload(template, payload, used = nil) template.map do |item| if item.is_a? Enumerable with_payload(item, payload, used) else used << item payload[item] end end end p = {"Payload t = { { {1, 2}, {3, 4, 1}, 5}} used = Set(Int32).new puts with_payload(t, p, used...