Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in Ruby while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "io" "log" "os" "sync/atomic" "syscall" ) const ( inputFifo = "/tmp/in.fifo" outputFifo = "/tmp/out.fifo" readsize = 64 << 10 ) func openFifo(path string, oflag int) (f *os.File, err error) { err = syscall....
require 'socket' system '/bin/sh', '-c', <<EOF or abort test -p in || mkfifo in || exit test -p out || mkfifo out || exit EOF def open_sesame(path, mode) reader, writer = UNIXSocket.pair pid = fork do begin reader.close file = File.open(path, mode) writer.send_io file ensure exi...
Convert the following code from Go to Ruby, ensuring the logic remains intact.
package main import ( "fmt" "strings" ) type object = interface{} type sequence = []object var ( src []rune ch rune sdx int token object isSeq bool err = false idents []string ididx []int productions []sequence e...
require 'strscan' Line = Struct.new :where, :str Token = Struct.new :cat, :str, :line, :pos def next_token loop do if @scanner.eos? if s = @in.gets @line = Line.new(" @scanner.string = s else return nil end end ...
Port the following code from Go to Ruby with equivalent syntax and logic.
package main import ( "fmt" "strings" ) type object = interface{} type sequence = []object var ( src []rune ch rune sdx int token object isSeq bool err = false idents []string ididx []int productions []sequence e...
require 'strscan' Line = Struct.new :where, :str Token = Struct.new :cat, :str, :line, :pos def next_token loop do if @scanner.eos? if s = @in.gets @line = Line.new(" @scanner.string = s else return nil end end ...
Write the same code in Ruby as shown below in VB.
Dim TheAddress as long Dim SecVar as byte Dim MyVar as byte MyVar = 10 TheAddress = varptr(MyVar) MEMSET(TheAddress, 102, SizeOf(byte)) showmessage "MyVar = " + str$(MyVar) MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte)) showmessage "SecVar = " + str$(SecVar)
>foo = Object.new >id = foo.object_id >"%x" % (id << 1)
Can you help me rewrite this code in Ruby instead of VB, keeping it the same logically?
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d= createobject("Scripting.Dictionary") for each aa in a x=trim(aa) l=len(x) if l>5 then d.removeall for i=1 to 3 m=mid(x,i,1) if not d.exists(m) then d.add ...
puts File.readlines("unixdict.txt", chomp: true).select{|w| w.end_with?(w[0,3]) && w.size > 5}
Write the same code in Ruby as shown below in VB.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) dim b(25) dim c(128) with new regexp .pattern="([^aeiou])" .global=true for each i in a if len(trim(i))>10 then set matches= .execute(i) rep=false for each m in ...
filtered = File.open("unixdict.txt").each( chomp: true).select do |word| next unless word.size > 10 cons = word.delete('aeiou') cons.chars.uniq.join == cons end grouped = filtered.group_by{|word| word.count('^aeiou')} grouped.sort_by{|k,v| -k}.each do |chunk| puts"\n puts chunk.last.first(10) puts "..." i...
Keep all operations the same but rewrite the snippet in Ruby.
Function Multiply(a As Integer, b As Integer) As Integer Return a * b End Function
def multiply(a, b) a * b end
Port the provided VB code into Ruby while preserving the original functionality.
Public n As New Long[2] Public Sub Main() Dim i0 As Integer = 0, i1 As Integer = 1 Dim j As Integer, c As Integer, P As Integer = 1, Q As Integer = -2 Print "First 30 Jacobsthal numbers:" c = 0 n[i0] = 0 n[i1] = 1 For j = 0 To 29 c += 1 Print Format$(n[i0], " #########"); If (c ...
require 'prime' def jacobsthal(n) = (2**n + n[0])/3 def jacobsthal_lucas(n) = 2**n + (-1)**n def jacobsthal_oblong(n) = jacobsthal(n) * jacobsthal(n+1) puts "First 30 Jacobsthal numbers:" puts (0..29).map{|n| jacobsthal(n) }.join(" ") puts "\nFirst 30 Jacobsthal-Lucas numbers: " puts (0..29).map{|n| jacobsthal_lucas...
Write the same code in Ruby as shown below in VB.
Public n As New Long[2] Public Sub Main() Dim i0 As Integer = 0, i1 As Integer = 1 Dim j As Integer, c As Integer, P As Integer = 1, Q As Integer = -2 Print "First 30 Jacobsthal numbers:" c = 0 n[i0] = 0 n[i1] = 1 For j = 0 To 29 c += 1 Print Format$(n[i0], " #########"); If (c ...
require 'prime' def jacobsthal(n) = (2**n + n[0])/3 def jacobsthal_lucas(n) = 2**n + (-1)**n def jacobsthal_oblong(n) = jacobsthal(n) * jacobsthal(n+1) puts "First 30 Jacobsthal numbers:" puts (0..29).map{|n| jacobsthal(n) }.join(" ") puts "\nFirst 30 Jacobsthal-Lucas numbers: " puts (0..29).map{|n| jacobsthal_lucas...
Port the following code from VB to Ruby with equivalent syntax and logic.
Imports System.Text Module Module1 Function Sieve(limit As Integer) As Integer() Dim primes As New List(Of Integer) From {2} Dim c(limit + 1) As Boolean REM composite = true REM no need to process even numbers > 2 Dim p = 3 While True Dim p2 = p * p ...
require 'prime' PRIMES = Prime.each(1_000_000).to_a difs = [[2], [1], [2,2], [2,4], [4,2], [6,4,2]] difs.each do |ar| res = PRIMES.each_cons(ar.size+1).select do |slice| slice.each_cons(2).zip(ar).all? {|(a,b), c| a+c == b} end puts " end
Generate a Ruby translation of this VB snippet without changing its computational steps.
Module Module1 Sub Main() Dim bufferHeight = Console.BufferHeight Dim bufferWidth = Console.BufferWidth Dim windowHeight = Console.WindowHeight Dim windowWidth = Console.WindowWidth Console.Write("Buffer Height: ") Console.WriteLine(bufferHeight) Console.Wri...
def winsize require 'io/console' IO.console.winsize rescue LoadError [Integer(`tput li`), Integer(`tput co`)] end rows, cols = winsize printf "%d rows by %d columns\n", rows, cols
Convert the following code from VB to Ruby, ensuring the logic remains intact.
s=7*8*9 m=9876432 for i=(m\s)*s to 1 step -s if instr(i,"5")=0 and instr(i,"0")=0 then b=false: j=1 while j<=len(i)-1 and not b if instr(j+1,i,mid(i,j,1))<>0 then b=true j=j+1 wend if not b then j=1 while j<=len(i) and not b if (i mod mid(i,j,1))<>0 then b=true j=...
magic_number = 9*8*7 div = (9876432 // magic_number) * magic_number candidates = div.step(to: 0, by: -magic_number) res = candidates.find do |c| digits = c.to_s.chars.map(&.to_i) (digits & [0,5]).empty? && digits == digits.uniq end puts "Largest decimal number is
Ensure the translated Ruby code behaves exactly like the original VB snippet.
s=7*8*9 m=9876432 for i=(m\s)*s to 1 step -s if instr(i,"5")=0 and instr(i,"0")=0 then b=false: j=1 while j<=len(i)-1 and not b if instr(j+1,i,mid(i,j,1))<>0 then b=true j=j+1 wend if not b then j=1 while j<=len(i) and not b if (i mod mid(i,j,1))<>0 then b=true j=...
magic_number = 9*8*7 div = (9876432 // magic_number) * magic_number candidates = div.step(to: 0, by: -magic_number) res = candidates.find do |c| digits = c.to_s.chars.map(&.to_i) (digits & [0,5]).empty? && digits == digits.uniq end puts "Largest decimal number is
Change the programming language of this snippet from VB to Ruby without modifying what it does.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - ...
require 'matrix' class Matrix def permanent r = (0...row_count).to_a r.permutation.inject(0) do |sum, sigma| sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } end end end m1 = Matrix[[1,2],[3,4]] m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 1...
Convert this VB block to Ruby, preserving its control flow and logic.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - ...
require 'matrix' class Matrix def permanent r = (0...row_count).to_a r.permutation.inject(0) do |sum, sigma| sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } end end end m1 = Matrix[[1,2],[3,4]] m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 1...
Please provide an equivalent version of this VB code in Ruby.
Private Sub Sattolo(Optional ByRef a As Variant) Dim t As Variant, i As Integer If Not IsMissing(a) Then For i = UBound(a) To lbound(a)+1 Step -1 j = Int((UBound(a) - 1 - LBound(a) + 1) * Rnd + LBound(a)) t = a(i) a(i) = a(j) a(j) = t Next i En...
> class Array > def sattolo_cycle! > (length - 1).downto(1) do |i| * j = rand(i) > self[i], self[j] = self[j], self[i] > end > self > end > end => :sattolo_cycle! > > 10.times do * p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sattolo_cycle! > end [10, 6, 9, 7, 8, 1, 3, 2, 5, 4] [3, 7, 5, 10, 4, 8, ...
Ensure the translated Ruby code behaves exactly like the original VB snippet.
Private Sub Sattolo(Optional ByRef a As Variant) Dim t As Variant, i As Integer If Not IsMissing(a) Then For i = UBound(a) To lbound(a)+1 Step -1 j = Int((UBound(a) - 1 - LBound(a) + 1) * Rnd + LBound(a)) t = a(i) a(i) = a(j) a(j) = t Next i En...
> class Array > def sattolo_cycle! > (length - 1).downto(1) do |i| * j = rand(i) > self[i], self[j] = self[j], self[i] > end > self > end > end => :sattolo_cycle! > > 10.times do * p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sattolo_cycle! > end [10, 6, 9, 7, 8, 1, 3, 2, 5, 4] [3, 7, 5, 10, 4, 8, ...
Can you help me rewrite this code in Ruby instead of VB, keeping it the same logically?
Option Explicit Dim objFSO, DBSource Set objFSO = CreateObject("Scripting.FileSystemObject") DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb" With CreateObject("ADODB.Connection") .Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource .Execute "CREATE TABLE ADDRE...
require 'pstore' require 'set' Address = Struct.new :id, :street, :city, :state, :zip db = PStore.new("addresses.pstore") db.transaction do db[:next] ||= 0 db[:ids] ||= Set[] end
Port the provided VB code into Ruby while preserving the original functionality.
Function IsPrime(x As Long) As Boolean Dim i As Long If x Mod 2 = 0 Then Exit Function Else For i = 3 To Int(Sqr(x)) Step 2 If x Mod i = 0 Then Exit Function Next i End If IsPrime = True End Function Function TwinPrimePairs(max As Long) As Long Dim p1 As Bool...
require 'prime' (1..8).each do |n| count = Prime.each(10**n).each_cons(2).count{|p1, p2| p2-p1 == 2} puts "Twin primes below 10** end
Rewrite the snippet below in Ruby so it works the same as the original VB code.
Module Module1 Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean Dim f As Integer = n Mod b : n \= b : While n > 0 If n Mod b <> f Then Return False Else n \= b End While : Return True End Function Function isBrazilian(ByVal n As Integer) As Boolean ...
def sameDigits(n,b) f = n % b while (n /= b) > 0 do if n % b != f then return false end end return true end def isBrazilian(n) if n < 7 then return false end if n % 2 == 0 then return true end for b in 2 .. n - 2 do if sameDigits(n...
Generate a Ruby translation of this VB snippet without changing its computational steps.
Module Module1 Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean Dim f As Integer = n Mod b : n \= b : While n > 0 If n Mod b <> f Then Return False Else n \= b End While : Return True End Function Function isBrazilian(ByVal n As Integer) As Boolean ...
def sameDigits(n,b) f = n % b while (n /= b) > 0 do if n % b != f then return false end end return true end def isBrazilian(n) if n < 7 then return false end if n % 2 == 0 then return true end for b in 2 .. n - 2 do if sameDigits(n...
Produce a functionally identical Ruby code for the snippet given in VB.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&"....
require 'set' a = [0] used = Set[0] used1000 = Set[0] foundDup = false n = 1 while n <= 15 or not foundDup or used1000.size < 1001 nxt = a[n - 1] - n if nxt < 1 or used === nxt then nxt = nxt + 2 * n end alreadyUsed = used === nxt a << nxt if not alreadyUsed then used << nxt ...
Generate a Ruby translation of this VB snippet without changing its computational steps.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&"....
require 'set' a = [0] used = Set[0] used1000 = Set[0] foundDup = false n = 1 while n <= 15 or not foundDup or used1000.size < 1001 nxt = a[n - 1] - n if nxt < 1 or used === nxt then nxt = nxt + 2 * n end alreadyUsed = used === nxt a << nxt if not alreadyUsed then used << nxt ...
Translate the given VB code snippet into Ruby without altering its behavior.
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 ...
y = lambda do |f| lambda {|g| g[g]}[lambda do |g| f[lambda {|*args| g[g][*args]}] end] end fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}} p Array.new(10) {|i| y[fac][i]} fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}} p Array.new(10) {|i| y[fib][i]}
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version.
Public c As Variant Public pi As Double Dim arclists() As Variant Public Enum circles_ xc = 0 yc rc End Enum Public Enum arclists_ rho x_ y_ i_ End Enum Public Enum shoelace_axis u = 0 v End Enum Private Sub give_a_list_of_circles() c = Array(Array(1.6417233788, 1.6121789534, 0.0...
circles = [ [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832854473, 1.0845181219], [ 1.7813504266, 1.6178237031, 0.8162655711], [-0.1985249206, -0...
Write the same algorithm in Ruby as shown in this VB implementation.
Public c As Variant Public pi As Double Dim arclists() As Variant Public Enum circles_ xc = 0 yc rc End Enum Public Enum arclists_ rho x_ y_ i_ End Enum Public Enum shoelace_axis u = 0 v End Enum Private Sub give_a_list_of_circles() c = Array(Array(1.6417233788, 1.6121789534, 0.0...
circles = [ [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832854473, 1.0845181219], [ 1.7813504266, 1.6178237031, 0.8162655711], [-0.1985249206, -0...
Keep all operations the same but rewrite the snippet in Ruby.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factori...
def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n end (9..12).each do |base| puts "Base end
Write the same algorithm in Ruby as shown in this VB implementation.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factori...
def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n end (9..12).each do |base| puts "Base end
Convert this VB snippet to Ruby and keep its semantics consistent.
Option Base 1 Private Function sq_add(arr As Variant, x As Double) As Variant Dim res() As Variant ReDim res(UBound(arr)) For i = 1 To UBound(arr) res(i) = arr(i) + x Next i sq_add = res End Function Private Function beadsort(ByVal a As Variant) As Variant Dim poles() As Variant Re...
class Array def beadsort map {|e| [1] * e}.columns.columns.map(&:length) end def columns y = length x = map(&:length).max Array.new(x) do |row| Array.new(y) { |column| self[column][row] }.compact end end end p [5,3,1,7,4,1,1].beadsort
Write the same code in Ruby as shown below in VB.
Module Module1 Sub Print(ls As List(Of Integer)) Dim iter = ls.GetEnumerator Console.Write("[") If iter.MoveNext Then Console.Write(iter.Current) End If While iter.MoveNext Console.Write(", ") Console.Write(iter.Current) End While ...
N = 2 base = 10 c1 = 0 c2 = 0 for k in 1 .. (base ** N) - 1 c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 print "%d " % [k] end end puts print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
Write the same code in Ruby as shown below in VB.
Module Module1 Sub Print(ls As List(Of Integer)) Dim iter = ls.GetEnumerator Console.Write("[") If iter.MoveNext Then Console.Write(iter.Current) End If While iter.MoveNext Console.Write(", ") Console.Write(iter.Current) End While ...
N = 2 base = 10 c1 = 0 c2 = 0 for k in 1 .. (base ** N) - 1 c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 print "%d " % [k] end end puts print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
Produce a language-to-language conversion: from VB to Ruby, same semantics.
Public Sub Main() Print "The tau functions for the first 100 positive integers are:\n" For i As Integer = 1 To 100 Print Format$(numdiv(i), "####"); If i Mod 10 = 0 Then Print Next End Public Function numdiv(n As Integer) As Integer Dim c As Integer = 1 For i As Integer = 1 To (n + 1...
require 'prime' def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1} (1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
Rewrite the snippet below in Ruby so it works the same as the original VB code.
Public Sub Main() Print "The tau functions for the first 100 positive integers are:\n" For i As Integer = 1 To 100 Print Format$(numdiv(i), "####"); If i Mod 10 = 0 Then Print Next End Public Function numdiv(n As Integer) As Integer Dim c As Integer = 1 For i As Integer = 1 To (n + 1...
require 'prime' def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1} (1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
Convert this VB snippet to Ruby and keep its semantics consistent.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 ...
define tape_length = 50_000; define eof_val = -1; define unbalanced_exit_code = 1; var cmd = 0; var cell = 0; var code = []; var loops = []; var tape = tape_length.of(0); func get_input { static input_buffer = []; input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord}));...
Keep all operations the same but rewrite the snippet in Ruby.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 ...
define tape_length = 50_000; define eof_val = -1; define unbalanced_exit_code = 1; var cmd = 0; var cell = 0; var code = []; var loops = []; var tape = tape_length.of(0); func get_input { static input_buffer = []; input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord}));...
Write the same algorithm in Ruby as shown in this VB implementation.
suite$ = "CDHS" #Club, Diamond, Heart, Spade card$ = "A23456789TJQK" #Cards Ace to King card = 0 dim n(55) #make ordered deck for i = 1 to 52 # of 52 cards n[i] = i next i for i = 1 to 52 * 3 #shuffle deck 3 times i1 = int(rand * 5...
class Card SUITS = %i[ Clubs Hearts Spades Diamonds ] PIPS = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ] @@suit_value = Hash[ SUITS.each_with_index.to_a ] @@pip_value = Hash[ PIPS.each_with_index.to_a ] attr_reader :pip, :suit def initialize(pip,suit) @pip = pip @suit = suit end ...
Write the same code in Ruby as shown below in VB.
Function F(i,n) Dim c: c=CCur(i): If n>Len(c) Then F=Space(n-Len(c))&c Else F=c End Function Function Fact(ByVal n) Dim res If n=0 Then Fact = 1 Else res = 1 While n>0 res = res*n n = n-1 Wend...
def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*) def lah(n, k) case k when 1 then fact(n) when n then 1 when (..1),(n..) then 0 else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k) end end r = (0..12) puts "Unsigned Lah numbers: L(n, k):" puts "n/k r.each do |row| print...
Can you help me rewrite this code in Ruby instead of VB, keeping it the same logically?
Function F(i,n) Dim c: c=CCur(i): If n>Len(c) Then F=Space(n-Len(c))&c Else F=c End Function Function Fact(ByVal n) Dim res If n=0 Then Fact = 1 Else res = 1 While n>0 res = res*n n = n-1 Wend...
def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*) def lah(n, k) case k when 1 then fact(n) when n then 1 when (..1),(n..) then 0 else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k) end end r = (0..12) puts "Unsigned Lah numbers: L(n, k):" puts "n/k r.each do |row| print...
Port the following code from VB to Ruby with equivalent syntax and logic.
Option Explicit Function two_sum(a As Variant, t As Integer) As Variant Dim i, j As Integer i = 0 j = UBound(a) Do While (i < j) If (a(i) + a(j) = t) Then two_sum = Array(i, j) Exit Function ElseIf (a(i) + a(j) < t) Then i = i + 1 ElseIf (a(i) + a(j) > t) ...
def two_sum(numbers, sum) numbers.each_with_index do |x,i| if j = numbers.index(sum - x) then return [i,j] end end [] end numbers = [0, 2, 11, 19, 90] p two_sum(numbers, 21) p two_sum(numbers, 25)
Generate a Ruby translation of this VB snippet without changing its computational steps.
Option Explicit Function two_sum(a As Variant, t As Integer) As Variant Dim i, j As Integer i = 0 j = UBound(a) Do While (i < j) If (a(i) + a(j) = t) Then two_sum = Array(i, j) Exit Function ElseIf (a(i) + a(j) < t) Then i = i + 1 ElseIf (a(i) + a(j) > t) ...
def two_sum(numbers, sum) numbers.each_with_index do |x,i| if j = numbers.index(sum - x) then return [i,j] end end [] end numbers = [0, 2, 11, 19, 90] p two_sum(numbers, 21) p two_sum(numbers, 25)
Convert this VB block to Ruby, preserving its control flow and logic.
print "The first 100 tau numbers are:" n = 0 num = 0 limit = 100 while num < limit n = n +1 tau = 0 for m = 1 to n if n mod m = 0 then tau = tau +1 next m if n mod tau = 0 then num = num +1 if num mod 10 = 1 then print print using("######", n); end if wend end
require 'prime' taus = Enumerator.new do |y| (1..).each do |n| num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 } y << n if n % num_divisors == 0 end end p taus.take(100)
Keep all operations the same but rewrite the snippet in Ruby.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ...
def primeDigitsSum13(n) sum = 0 while n > 0 r = n % 10 if r != 2 and r != 3 and r != 5 and r != 7 then return false end n = (n / 10).floor sum = sum + r end return sum == 13 end c = 0 for i in 1 .. 1000000 if primeDigitsSum13(i) then print...
Port the provided VB code into Ruby while preserving the original functionality.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ...
def primeDigitsSum13(n) sum = 0 while n > 0 r = n % 10 if r != 2 and r != 3 and r != 5 and r != 7 then return false end n = (n / 10).floor sum = sum + r end return sum == 13 end c = 0 for i in 1 .. 1000000 if primeDigitsSum13(i) then print...
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version.
Imports System Imports System.Numerics Imports Microsoft.VisualBasic.Strings Public Module Module1 Public Function IntSqRoot(v As BigInteger) As BigInteger Dim digs As Integer = Math.Max(0, v.ToString().Length / 2 - 1) IntSqRoot = BigInteger.Parse("3" & StrDup(digs, "0")) Dim term As BigIn...
def root(a,b) return b if b<2 a1, c = a-1, 1 f = -> x {(a1*x+b/(x**a1))/a} d = f[c] e = f[d] c, d, e = d, e, f[e] until [d,e].include?(c) [d,e].min end puts "First 2,001 digits of the square root of two:" puts root(2, 2*100**2000)
Write the same code in Ruby as shown below in VB.
Imports System Imports System.Numerics Imports Microsoft.VisualBasic.Strings Public Module Module1 Public Function IntSqRoot(v As BigInteger) As BigInteger Dim digs As Integer = Math.Max(0, v.ToString().Length / 2 - 1) IntSqRoot = BigInteger.Parse("3" & StrDup(digs, "0")) Dim term As BigIn...
def root(a,b) return b if b<2 a1, c = a-1, 1 f = -> x {(a1*x+b/(x**a1))/a} d = f[c] e = f[d] c, d, e = d, e, f[e] until [d,e].include?(c) [d,e].min end puts "First 2,001 digits of the square root of two:" puts root(2, 2*100**2000)
Write the same code in Ruby as shown below in VB.
Module Module1 Function Turn(base As Integer, n As Integer) As Integer Dim sum = 0 While n <> 0 Dim re = n Mod base n \= base sum += re End While Return sum Mod base End Function Sub Fairshare(base As Integer, count As Integer) Co...
def turn(base, n) sum = 0 while n != 0 do rem = n % base n = n / base sum = sum + rem end return sum % base end def fairshare(base, count) print "Base %2d: " % [base] for i in 0 .. count - 1 do t = turn(base, i) print " %2d" % [t] end print "\n" e...
Convert this VB block to Ruby, preserving its control flow and logic.
Module Module1 Dim r As New Random Function getThree(n As Integer) As List(Of Integer) getThree = New List(Of Integer) For i As Integer = 1 To 4 : getThree.Add(r.Next(n) + 1) : Next getThree.Sort() : getThree.RemoveAt(0) End Function Function getSix() As List(Of Integer) ...
def roll_stat dices = Array(Int32).new(4) { rand(1..6) } dices.sum - dices.min end def roll_character loop do stats = Array(Int32).new(6) { roll_stat } return stats if stats.sum >= 75 && stats.count(&.>=(15)) >= 2 end end 10.times do stats = roll_character puts "stats: end
Rewrite the snippet below in Ruby so it works the same as the original VB code.
Imports System.Runtime.CompilerServices Imports System.Text Module Module1 Class Crutch Public ReadOnly len As Integer Public s() As Integer Public i As Integer Public Sub New(len As Integer) Me.len = len s = New Integer(len - 1) {} i = 0 ...
def create_generator(ar) Enumerator.new do |y| cycle = ar.cycle s = [] loop do t = cycle.next s.push(t) v = s.shift y << v (v-1).times{s.push(t)} end end end def rle(ar) ar.slice_when{|a,b| a != b}.map(&:size) end [[20, [1,2]], [20, [2,1]], [30, [1,3,1,2]], [30...
Can you help me rewrite this code in Ruby instead of VB, keeping it the same logically?
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h258...
bar = ('▁'..'█').to_a loop {print 'Numbers please separated by space/commas: ' numbers = gets.split(/[\s,]+/).map(&:to_f) min, max = numbers.minmax puts "min: %5f; max: %5f"% [min, max] div = (max - min) / (bar.size - 1) puts min == max ? bar.last*numbers.size : numbers.map{|num| bar[((num - min) / div).to_i...
Translate the given VB code snippet into Ruby without altering its behavior.
Sub Lis(arr() As Integer) Dim As Integer lb = Lbound(arr), ub = Ubound(arr) Dim As Integer i, lo, hi, mitad, newl, l = 0 Dim As Integer p(ub), m(ub) For i = lb To ub lo = 1 hi = l Do While lo <= hi mitad = Int((lo+hi)/2) If arr(m(mitad)) < arr(i) Then lo = mitad + 1 Else h...
Node = Struct.new(:val, :back) def lis(n) pileTops = [] for x in n low, high = 0, pileTops.size-1 while low <= high mid = low + (high - low) / 2 if pileTops[mid].val >= x high = mid - 1 else low = mid + 1 end end i = low node = Node.new(x) nod...
Convert the following code from VB to Ruby, ensuring the logic remains intact.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d=createobject("scripting.dictionary") redim b(ubound(a)) i=0 for each x in a s=trim(x) if len(s)>=9 then if len(s)= 9 then d.add s,"" b(i)=s i=i+1 end if nex...
new_word_size = 9 well_sized = File.readlines("unixdict.txt", chomp: true).reject{|word| word.size < new_word_size} list = well_sized.each_cons(new_word_size).filter_map do |slice| candidate = (0...new_word_size).inject(""){|res, idx| res << slice[idx][idx] } candidate if well_sized.include?(candidate) end puts li...
Keep all operations the same but rewrite the snippet in Ruby.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim fl...
require 'prime' base = 10 upto = 1000 res = Prime.each(upto).select do |pr| pr.digits(base).each_cons(2).all?{|p1, p2| p1 >= p2} end puts "There are puts res.join(", ")
Write a version of this VB function in Ruby with identical behavior.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim fl...
require 'prime' base = 10 upto = 1000 res = Prime.each(upto).select do |pr| pr.digits(base).each_cons(2).all?{|p1, p2| p1 >= p2} end puts "There are puts res.join(", ")
Translate this program into Ruby but keep the logic exactly as in VB.
Public Sub Main() Dim h As Float = 0 Dim n As Integer, i As Integer Print "The first twenty harmonic numbers are:" For n = 1 To 20 h += 1 / n Print n, h Next Print h = 1 n = 2 For i = 2 To 10 While h < i h += 1 / n n += 1 Wend Print "The first harm...
harmonics = Enumerator.new do |y| res = 0 (1..).each {|n| y << res += Rational(1, n) } end n = 20 The first harmonics.take(n).each_slice(5){|slice| puts "%20s"*slice.size % slice } puts milestones = (1..10).to_a harmonics.each.with_index(1) do |h,i| if h > milestones.first then puts "The first harmonic num...
Change the programming language of this snippet from VB to Ruby without modifying what it does.
#macro assign(sym, expr) __fb_unquote__(__fb_eval__("#undef " + sym)) __fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr)))) #endmacro #define a, b, x assign("a", 8) assign("b", 7) assign("x", Sqr(a) + (Sin(b*3)/2)) Print x assign("x", "goodbye") Print x Sleep
a, b = 5, -7 ans = eval "(a * b).abs"
Change the programming language of this snippet from VB to Ruby without modifying what it does.
#macro assign(sym, expr) __fb_unquote__(__fb_eval__("#undef " + sym)) __fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr)))) #endmacro #define a, b, x assign("a", 8) assign("b", 7) assign("x", Sqr(a) + (Sin(b*3)/2)) Print x assign("x", "goodbye") Print x Sleep
a, b = 5, -7 ans = eval "(a * b).abs"
Can you help me rewrite this code in Ruby instead of VB, keeping it the same logically?
Dim As Uinteger n, num Print "First 20 Cullen numbers:" For n = 1 To 20 num = n * (2^n)+1 Print num; " "; Next Print !"\n\nFirst 20 Woodall numbers:" For n = 1 To 20 num = n * (2^n)-1 Print num; " "; Next n Sleep
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 VB.
Imports System.Math Module Module1 Const MAXPRIME = 99 Const MAXPARENT = 99 Const NBRCHILDREN = 547100 Public Primes As New Collection() Public PrimesR As New Collection() Public Ancest...
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...
Change the programming language of this snippet from VB to Ruby without modifying what it does.
Const wheel="ndeokgelw" Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub Dim oDic Set oDic = WScript.CreateObject("scripting.dictionary") Dim cnt(127) Dim fso Set fso = WScript.CreateObject("Sc...
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
Port the following code from VB to Ruby with equivalent syntax and logic.
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If...
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...
Produce a language-to-language conversion: from VB to Ruby, same semantics.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Iterator Function Loopy(Of T)(seq As IEnumerable(Of T)) As IEnumerable(Of T) While True For Each element In seq Yield element Next End While End Function Iterator Function Turn...
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...
Generate a Ruby translation of this VB snippet without changing its computational steps.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Iterator Function Loopy(Of T)(seq As IEnumerable(Of T)) As IEnumerable(Of T) While True For Each element In seq Yield element Next End While End Function Iterator Function Turn...
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...
Convert this VB snippet to Ruby and keep its semantics consistent.
Private Function GetPixelColor(ByVal Location As Point) As Color Dim b As New Bitmap(1, 1) Dim g As Graphics = Graphics.FromImage(b) g.CopyFromScreen(Location, Point.Empty, New Size(1, 1)) Return b.GetPixel(0, 0) End Function
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
Produce a functionally identical Ruby code for the snippet given in VB.
Public Sub circles() tests = [{0.1234, 0.9876, 0.8765, 0.2345, 2.0; 0.0000, 2.0000, 0.0000, 0.0000, 1.0; 0.1234, 0.9876, 0.1234, 0.9876, 2.0; 0.1234, 0.9876, 0.8765, 0.2345, 0.5; 0.1234, 0.9876, 0.1234, 0.9876, 0.0}] For i = 1 To UBound(tests) x1 = tests(i, 1) y1 = tests(i, 2) x2 = tests...
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) ...
Transform the following VB implementation into Ruby, maintaining the same output and logic.
Public Sub circles() tests = [{0.1234, 0.9876, 0.8765, 0.2345, 2.0; 0.0000, 2.0000, 0.0000, 0.0000, 1.0; 0.1234, 0.9876, 0.1234, 0.9876, 2.0; 0.1234, 0.9876, 0.8765, 0.2345, 0.5; 0.1234, 0.9876, 0.1234, 0.9876, 0.0}] For i = 1 To UBound(tests) x1 = tests(i, 1) y1 = tests(i, 2) x2 = tests...
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) ...
Convert the following code from VB to Ruby, ensuring the logic remains intact.
Declare Function libPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" _ (ByVal filename As String, ByVal Flags As Long) As Long Sub PlaySound(sWav As String) Call libPlaySound(sWav, 1) End Sub
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...
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version.
option explicit class playingcard dim suit dim pips public sub print dim s,p select case suit case "S":s=chrW(&h2660) case "D":s=chrW(&h2666) case "C":s=chrW(&h2663) case "H":s=chrW(&h2665) end select select case pips case 1:p="A" case 11:p="J" case 12:p="Q" case 13:p="K" case else:...
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...
Maintain the same structure and functionality when rewriting this code in Ruby.
option explicit class playingcard dim suit dim pips public sub print dim s,p select case suit case "S":s=chrW(&h2660) case "D":s=chrW(&h2666) case "C":s=chrW(&h2663) case "H":s=chrW(&h2665) end select select case pips case 1:p="A" case 11:p="J" case 12:p="Q" case 13:p="K" case else:...
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...
Translate this program into Ruby but keep the logic exactly as in VB.
Option Explicit Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const HT As String = "H T" Public Sub PenneysGame() Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean Do S = WhoWillBeFirst(Choice("Who will be first")) If S = "ABORT" Then Exit Do ...
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...
Write the same algorithm in Ruby as shown in this VB implementation.
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public pr...
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...
Change the programming language of this snippet from VB to Ruby without modifying what it does.
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public pr...
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...
Change the following VB code into Ruby without altering its purpose.
Module Module1 Structure Interval Dim start As Integer Dim last As Integer Dim print As Boolean Sub New(s As Integer, l As Integer, p As Boolean) start = s last = l print = p End Sub End Structure Sub Main() Dim intervals...
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)...
Write a version of this VB function in Ruby with identical behavior.
Module Module1 Structure Interval Dim start As Integer Dim last As Integer Dim print As Boolean Sub New(s As Integer, l As Integer, p As Boolean) start = s last = l print = p End Sub End Structure Sub Main() Dim intervals...
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)...
Change the programming language of this snippet from VB to Ruby without modifying what it does.
Option Explicit Public Sub coconuts() Dim sailors As Integer Dim share As Long Dim finalshare As Integer Dim minimum As Long, pile As Long Dim i As Long, j As Integer Debug.Print "Sailors", "Pile", "Final share" For sailors = 2 To 6 i = 1 Do While True pile = i ...
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...
Ensure the translated Ruby code behaves exactly like the original VB snippet.
Option Explicit Public Sub coconuts() Dim sailors As Integer Dim share As Long Dim finalshare As Integer Dim minimum As Long, pile As Long Dim i As Long, j As Integer Debug.Print "Sailors", "Pile", "Final share" For sailors = 2 To 6 i = 1 Do While True pile = i ...
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...
Port the provided VB code into Ruby while preserving the original functionality.
Set objXMLDoc = CreateObject("msxml2.domdocument") objXMLDoc.load("In.xml") Set item_nodes = objXMLDoc.selectNodes("//item") i = 1 For Each item In item_nodes If i = 1 Then WScript.StdOut.Write item.xml WScript.StdOut.WriteBlankLines(2) Exit For End If Next Set price_nodes = objXMLDoc.selectNodes("//price") ...
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,...
Transform the following VB implementation into Ruby, maintaining the same output and logic.
Sub Main() Dim HttpReq As WinHttp.WinHttpRequest Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 As Long = &H80& Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 As Long = &H200& Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 As Long = &H800& Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2 #Const USE_PROXY = 1 Set Http...
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
Produce a functionally identical Ruby code for the snippet given in VB.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = obj...
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...
Keep all operations the same but rewrite the snippet in Ruby.
Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2) Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." Dim i, j, curChar, escChar, outText Dim cipher Set cipher = CreateObject("Scripting.Dictionary") alphabet = UCase(alphabet) : j = 0 For i = 1 To 28 curChar = Mid(alphabet...
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...
Write the same algorithm in Ruby as shown in this VB implementation.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1,False,0) cei = 0 : cie = 0 : ei = 0 : ie = 0 Do Until srcFile.AtEndOfStream word = srcFile.ReadLine If InStr(word,"cei") Then cei = cei + 1 ElseIf In...
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...
Translate the given VB code snippet into Ruby without altering its behavior.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1,False,0) cei = 0 : cie = 0 : ei = 0 : ie = 0 Do Until srcFile.AtEndOfStream word = srcFile.ReadLine If InStr(word,"cei") Then cei = cei + 1 ElseIf In...
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...
Ensure the translated Ruby code behaves exactly like the original VB snippet.
Private Sub sierpinski(Order_ As Integer, Side As Double) Dim Circumradius As Double, Inradius As Double Dim Height As Double, Diagonal As Double, HeightDiagonal As Double Dim Pi As Double, p(5) As String, Shp As Shape Circumradius = Sqr(50 + 10 * Sqr(5)) / 10 Inradius = Sqr(25 + 10 * Sqr(5)) / 10 ...
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) ...
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version.
Public n As Variant Private Sub init() n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}] End Sub Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant Dim wtb As Integer Dim bn As Integer Dim prev As String: prev = "#" Dim next_ As String Dim p2468 As Str...
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...
Translate the given VB code snippet into Ruby without altering its behavior.
Option Explicit Const m_limit ="# #" Const m_middle=" # # " Dim a,bnum,i,check,odic a=array(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",_ " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # ...
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 ...
Translate this program into Ruby but keep the logic exactly as in VB.
Sub write_event(event_type,msg) Set objShell = CreateObject("WScript.Shell") Select Case event_type Case "SUCCESS" n = 0 Case "ERROR" n = 1 Case "WARNING" n = 2 Case "INFORMATION" n = 4 Case "AUDIT_SUCCESS" n = 8 Case "AUDIT_FAILURE" n = 16 End Select objShell.LogEvent n, msg Set objS...
require 'win32/eventlog' logger = Win32::EventLog.new logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry")
Produce a functionally identical Ruby code for the snippet given in VB.
Private Function ordinal(s As String) As String Dim irregs As New Collection irregs.Add "first", "one" irregs.Add "second", "two" irregs.Add "third", "three" irregs.Add "fifth", "five" irregs.Add "eighth", "eight" irregs.Add "ninth", "nine" irregs.Add "twelfth", "twelve" Dim i As Int...
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)) }
Rewrite the snippet below in Ruby so it works the same as the original VB code.
Function parse_ip(addr) Set ipv4_pattern = New RegExp ipv4_pattern.Global = True ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}" Set ipv6_pattern = New RegExp ipv6_pattern.Global = True ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}" If ipv4_pattern.Test(addr) T...
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(------ ------- ---- --...
Rewrite the snippet below in Ruby so it works the same as the original VB code.
Module Module1 Structure Point Implements IComparable(Of Point) Public Sub New(mx As Double, my As Double) X = mx Y = my End Sub Public ReadOnly Property X As Double Public ReadOnly Property Y As Double Public Function CompareTo(other As Po...
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) ...
Please provide an equivalent version of this VB code in Ruby.
function isPrime(n) if n < 2 then isPrime = 0 : goto [exit] if n = 2 then isPrime = 1 : goto [exit] if n mod 2 = 0 then isPrime = 0 : goto [exit] isPrime = 1 for i = 3 to int(n^.5) step 2 if n mod i = 0 then isPrime = 0 : goto [exit] next i [exit] end function n = 600851475143 j = 3 while isPrime(n) <> 1...
require 'prime' p 600851475143.prime_division.last.first
Rewrite the snippet below in Ruby so it works the same as the original VB code.
Module Module1 Dim atomicMass As New Dictionary(Of String, Double) From { {"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},...
$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 the given VB code snippet into Ruby without altering its behavior.
Public Sub test() Dim t(2) As Variant t(0) = [{1,2}] t(1) = [{3,4,1}] t(2) = 5 p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}] Dim q(6) As Boolean For i = LBound(t) To UBound(t) If IsArray(t(i)) Then For j = LBound(t(i)) To UBou...
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...
Generate an equivalent Ruby version of this VB code.
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") ...
def backup_and_open(filename) filename = File.realpath(filename) bkup = filename + ".backup" backup_files = Dir.glob(bkup + "*").sort_by do |f| f.match(/\d+$/) $&.nil? ? 0 : $&.to_i end backup_files.reverse.each do |fname| if m = fname.match(/\.backup\.(\d+)$/) File.rename(fname, "%s.%d" % [...
Write the same algorithm in Ruby as shown in this VB implementation.
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") ...
def backup_and_open(filename) filename = File.realpath(filename) bkup = filename + ".backup" backup_files = Dir.glob(bkup + "*").sort_by do |f| f.match(/\d+$/) $&.nil? ? 0 : $&.to_i end backup_files.reverse.each do |fname| if m = fname.match(/\.backup\.(\d+)$/) File.rename(fname, "%s.%d" % [...
Write the same algorithm in Ruby as shown in this VB implementation.
Module Module1 ReadOnly SNL As New Dictionary(Of Integer, Integer) From { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51, 67}, {54, 34}, {62, 19}, {63, 81}, {64, 60}, {71, 91}, {87, 24}, {9...
NONE = 0; LADDER = 1; SNAKE = 2; STAY = 1; MOVE = 2; WIN = 3 class Cell @type; @to; attr_reader :type, :to def initialize; @type = NONE; @to = 0; end def set( t, o ); @type = t; @to = o; end end class Player @pos; @name; attr_accessor :pos; attr_reader :name def initialize( n ); @pos = 0; @name = n...
Port the provided VB code into Ruby while preserving the original functionality.
Module Module1 ReadOnly SNL As New Dictionary(Of Integer, Integer) From { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51, 67}, {54, 34}, {62, 19}, {63, 81}, {64, 60}, {71, 91}, {87, 24}, {9...
NONE = 0; LADDER = 1; SNAKE = 2; STAY = 1; MOVE = 2; WIN = 3 class Cell @type; @to; attr_reader :type, :to def initialize; @type = NONE; @to = 0; end def set( t, o ); @type = t; @to = o; end end class Player @pos; @name; attr_accessor :pos; attr_reader :name def initialize( n ); @pos = 0; @name = n...
Change the following VB code into Ruby without altering its purpose.
Dim dblDistance as Double
test_variable = [1, 9, 8, 3] test_variable.sort test_variable test_variable.sort! test_variable
Ensure the translated Ruby code behaves exactly like the original VB snippet.
Function farey(n As Long, descending As Long) As Long Dim a, b, c, d, k As Long Dim aa, bb, cc, dd, count As Long b = 1 c = 1 d = n count = 0 If descending = True Then a = 1 c = n - 1 End If count += 1 If n < 12 Then Print Str(a); "/"; Str(b); " "; While ((c <= n) And...
require "big" def farey(n) a, b, c, d = 0, 1, 1, n fracs = [] of BigRational fracs << BigRational.new(0,1) while c <= n k = (n + b) // d a, b, c, d = c, d, k * c - a, k * d - b fracs << BigRational.new(a,b) end fracs.uniq.sort end puts "Farey sequence for order 1 throug...
Please provide an equivalent version of this VB code in Ruby.
Function farey(n As Long, descending As Long) As Long Dim a, b, c, d, k As Long Dim aa, bb, cc, dd, count As Long b = 1 c = 1 d = n count = 0 If descending = True Then a = 1 c = n - 1 End If count += 1 If n < 12 Then Print Str(a); "/"; Str(b); " "; While ((c <= n) And...
require "big" def farey(n) a, b, c, d = 0, 1, 1, n fracs = [] of BigRational fracs << BigRational.new(0,1) while c <= n k = (n + b) // d a, b, c, d = c, d, k * c - a, k * d - b fracs << BigRational.new(a,b) end fracs.uniq.sort end puts "Farey sequence for order 1 throug...
Write a version of this VB function in Ruby with identical behavior.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Seque...
def aliquot(n, maxlen=16, maxterm=2**47) return "terminating", [0] if n == 0 s = [] while (s << n).size <= maxlen and n < maxterm n = n.proper_divisors.inject(0, :+) if s.include?(n) case n when s[0] case s.size when 1 then return "perfect", s when 2 then return...
Generate an equivalent Ruby version of this VB code.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Seque...
def aliquot(n, maxlen=16, maxterm=2**47) return "terminating", [0] if n == 0 s = [] while (s << n).size <= maxlen and n < maxterm n = n.proper_divisors.inject(0, :+) if s.include?(n) case n when s[0] case s.size when 1 then return "perfect", s when 2 then return...