Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in Ruby as shown below in VB. | Imports System, System.Console
Module Module1
Dim np As Boolean()
Sub ms(ByVal lmt As Long)
np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True
Dim n As Integer = 2, j As Integer = 1 : While n < lmt
If Not np(n) Then
Dim k As Long = CLng(n) * n
... | require "prime"
magnanimouses = Enumerator.new do |y|
(0..).each {|n| y << n if (1..n.digits.size-1).all? {|k| n.divmod(10**k).sum.prime?} }
end
puts "First 45 magnanimous numbers:"
puts magnanimouses.first(45).join(' ')
puts "\n241st through 250th magnanimous numbers:"
puts magnanimouses.first(250).last(10).join... |
Convert this VB block to Ruby, preserving its control flow and logic. | Imports System.Numerics
Module Module1
Function Sqrt(x As BigInteger) As BigInteger
If x < 0 Then
Throw New ArgumentException("Negative argument.")
End If
If x < 2 Then
Return x
End If
Dim y = x / 2
While y > (x / y)
y = ((x / y) ... | require 'openssl'
(0..).each{|n| puts "2**
|
Convert this VB block to Ruby, preserving its control flow and logic. | Imports System.Numerics
Module Module1
Function Sqrt(x As BigInteger) As BigInteger
If x < 0 Then
Throw New ArgumentException("Negative argument.")
End If
If x < 2 Then
Return x
End If
Dim y = x / 2
While y > (x / y)
y = ((x / y) ... | require 'openssl'
(0..).each{|n| puts "2**
|
Please provide an equivalent version of this VB code in Ruby. | Option Strict On
Option Explicit On
Imports System.IO
Module KlarnerRado
Private Const bitsWidth As Integer = 31
Private bitMask() As Integer = _
New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _
, 2048, 4096, 8192, 16384, 32768, 65536, 131072 _
,... | using Formatting
function KlamerRado(N)
kr = falses(100 * N)
kr[1] = true
for i in 1:30N
if kr[i]
kr[2i + 1] = true
kr[3i + 1] = true
end
end
return [i for i in eachindex(kr) if kr[i]]
end
kr1m = KlamerRado(1000000)
println("First 100 Klarner-Rado numbers:"... |
Port the following code from VB to Ruby with equivalent syntax and logic. | Option Strict On
Option Explicit On
Imports System.IO
Module KlarnerRado
Private Const bitsWidth As Integer = 31
Private bitMask() As Integer = _
New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _
, 2048, 4096, 8192, 16384, 32768, 65536, 131072 _
,... | using Formatting
function KlamerRado(N)
kr = falses(100 * N)
kr[1] = true
for i in 1:30N
if kr[i]
kr[2i + 1] = true
kr[3i + 1] = true
end
end
return [i for i in eachindex(kr) if kr[i]]
end
kr1m = KlamerRado(1000000)
println("First 100 Klarner-Rado numbers:"... |
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version. | Public Type tuple
i As Variant
j As Variant
sum As Variant
End Type
Public Type tuple3
i1 As Variant
j1 As Variant
i2 As Variant
j2 As Variant
i3 As Variant
j3 As Variant
sum As Variant
End Type
Sub taxicab_numbers()
Dim i As Variant, j As Variant
Dim k As Long
Const ... | def taxicab_number(nmax=1200)
[*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort
end
t = [0] + taxicab_number
[*1..25, *2000...2007].each do |i|
puts "%4d: %10d" % [i, t[i][0]] + t[i][1].map{|a| " = %4d**3 + %4d**3" % a}.join
end
|
Convert this VB snippet to Ruby and keep its semantics consistent. | Imports DT = System.DateTime
Module Module1
Iterator Function Primes(lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean
Dim j = 2
Dim d = 3
Dim sq = 4
While sq <= lim
If Not flags(j) Then
Yield j
For k = sq To ... | require 'prime'
Prime.each(30).to_a.combination(3).select{|trio| trio.sum.prime? }.each do |a,b,c|
puts "
end
m = 1000
count = Prime.each(m).to_a.combination(3).count{|trio| trio.sum.prime? }
puts "Count of strange unique prime triplets <
|
Port the following code from VB to Ruby with equivalent syntax and logic. | Imports DT = System.DateTime
Module Module1
Iterator Function Primes(lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean
Dim j = 2
Dim d = 3
Dim sq = 4
While sq <= lim
If Not flags(j) Then
Yield j
For k = sq To ... | require 'prime'
Prime.each(30).to_a.combination(3).select{|trio| trio.sum.prime? }.each do |a,b,c|
puts "
end
m = 1000
count = Prime.each(m).to_a.combination(3).count{|trio| trio.sum.prime? }
puts "Count of strange unique prime triplets <
|
Translate this program into Ruby but keep the logic exactly as in VB. |
n=8
pattern="1001011001101001"
size=n*n: w=len(size)
mult=n\4
wscript.echo "Magic square : " & n & " x " & n
i=0
For r=0 To n-1
l=""
For c=0 To n-1
bit=Mid(pattern, c\mult+(r\mult)*4+1, 1)
If bit="1" Then t=i+1 Else t=size-i
l=l & Right(Space(w) & t, w) & " "
i=i+1
Next
wscript.echo l
Next
wscript.ec... | def double_even_magic_square(n)
raise ArgumentError, "Need multiple of four" if n%4 > 0
block_size, max = n/4, n*n
pre_pat = [true, false, false, true,
false, true, true, false]
pre_pat += pre_pat.reverse
pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size
flat_ar = pattern.each_with_... |
Convert the following code from VB to Ruby, ensuring the logic remains intact. | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To ... | require "prime"
class Integer
def square_free?
prime_division.none?{|pr, exp| exp > 1}
end
end
puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(" ")}
puts
m = 10**12
puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(" ")}
puts
markers = [100, 1000, 10_000, 100_000, 1_000_... |
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version. | Public Sub Main()
Dim units As String[] = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer"]
Dim convs As Single[] = [0.254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000]
Dim i, unit As Integ... | module Distances
RATIOS =
{arshin: 0.7112, centimeter: 0.01, diuym: 0.0254,
fut: 0.3048, kilometer: 1000.0, liniya: 0.00254,
meter: 1.0, milia: 7467.6, piad: 0.1778,
sazhen: 2.1336, tochka: 0.000254, vershok: 0.04445,
versta: 1066.8}
def self.method_missing(meth, arg)... |
Convert this VB block to Ruby, preserving its control flow and logic. | Const n = 2200
Public Sub pq()
Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3
Dim l(n) As Boolean, l_add(9680000) As Boolean
For x = 1 To n
x2 = x * x
For y = x To n
l_add(x2 + y * y) = True
Next y
Next x
For x = 1 To n
s1 ... | n = 2200
l_add, l = Hash(Int32, Bool).new(false), Hash(Int32, Bool).new(false)
(1..n).each do |x|
x2 = x * x
(x..n).each { |y| l_add[x2 + y * y] = true }
end
s = 3
(1..n).each do |x|
s1 = s
s += 2
s2 = s
((x+1)..n).each do |y|
l[y] = true if l_add[s1]
s1 += s2
s2 += 2
end
end
puts (1..n).r... |
Preserve the algorithm and functionality while converting the code from VB to Ruby. | #define isInteger(x) iif(Int(val(x)) = val(x), 1, 0)
Dim As String test(1 To 8) = {"25.000000", "24.999999", "25.000100", "-2.1e120", "-5e-2", "NaN", "Inf", "-0.05"}
For i As Integer = 1 To Ubound(test)
Dim As String s = test(i)
Print s,
If isInteger(s) then Print "is integer" Else Print "is not int... | class Numeric
def to_i?
self == self.to_i rescue false
end
end
ar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2,
Float::NAN, Float::INFINITY,
2r, 2.5r,
2+0i, 2+0.0i, 5-5i]
ar.each{|nu... |
Maintain the same structure and functionality when rewriting this code in Ruby. |
#macro typeDetector(arg)
#if TypeOf(foo) = TypeOf(Byte)
Print arg; " -> It
#elseif TypeOf(foo) = TypeOf(Short)
Print arg; " -> It
#elseif TypeOf(foo) = TypeOf(Integer)
Print arg; " -> It
#elseif TypeOf(foo) = TypeOf(LongInt)
Print arg; " -> It
#elseif TypeOf(foo) = TypeO... | def print_type(x)
puts "Compile-time type of
puts " Actual runtime type is
end
print_type 123
print_type 123.45
print_type rand < 0.5 ? "1" : 0
print_type rand < 1.5
print_type nil
print_type 'c'
print_type "str"
print_type [1,2]
print_type({ 2, "two" })
print_type({a: 1, b: 2})
print_type ->(x : Int32){ x+... |
Preserve the algorithm and functionality while converting the code from VB to Ruby. | Public Sub Main()
For i As Integer = 1 To 10000
If is_steady_square(i) Then Print Format$(i, "####"); "^2 = "; Format$(i ^ 2, "########")
Next
End
Function numdig(n As Integer) As Integer
Dim d As Integer = 0
While n
d += 1
n \= 10
Wend
Return d
End Function
Function is_stea... | p (0..10_000).select{|n| (n*n).to_s.end_with? n.to_s }
|
Convert this VB block to Ruby, preserving its control flow and logic. | Imports System.Console
Namespace safety
Module SafePrimes
Dim pri_HS As HashSet(Of Integer) = Primes(10_000_000).ToHashSet()
Sub Main()
For Each UnSafe In {False, True} : Dim n As Integer = If(UnSafe, 40, 35)
WriteLine($"The first {n} {If(UnSafe, "un", "")}safe primes a... | require "prime"
class Integer
def safe_prime?
((self-1)/2).prime?
end
end
def format_parts(n)
partitions = Prime.each(n).partition(&:safe_prime?).map(&:count)
"There are %d safes and %d unsafes below
end
puts "First 35 safe-primes:"
p Prime.each.lazy.select(&:safe_prime?).take(35).to_a
puts format_parts... |
Write the same code in Ruby as shown below in VB. | Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"
Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1... | def hashJoin(table1, index1, table2, index2)
h = table1.group_by {|s| s[index1]}
h.default = []
table2.collect {|r|
h[r[index2]].collect {|s| [s, r]}
}.flatten(1)
end
table1 = [[27, "Jonah"],
[18, "Alan"],
[28, "Glory"],
[18, "Popeye"],
[28, "Alan"]]
table2 = [... |
Generate an equivalent Ruby version of this VB code. | Imports System.Numerics
Module Module1
Class Solution
ReadOnly root1 As BigInteger
ReadOnly root2 As BigInteger
ReadOnly exists As Boolean
Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean)
root1 = r1
root2 = r2
exists = e
End Sub... | func tonelli(n, p) {
legendre(n, p) == 1 || die "not a square (mod p)"
var q = p-1
var s = valuation(q, 2)
s == 1 ? return(powmod(n, (p + 1) >> 2, p)) : (q >>= s)
var c = powmod(2 ..^ p -> first {|z| legendre(z, p) == -1}, q, p)
var r = powmod(n, (q + 1) >> 1, p)
var t = powmod(n, q, p)
... |
Convert the following code from VB to Ruby, ensuring the logic remains intact. | Imports System.Numerics
Module Module1
Class Solution
ReadOnly root1 As BigInteger
ReadOnly root2 As BigInteger
ReadOnly exists As Boolean
Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean)
root1 = r1
root2 = r2
exists = e
End Sub... | func tonelli(n, p) {
legendre(n, p) == 1 || die "not a square (mod p)"
var q = p-1
var s = valuation(q, 2)
s == 1 ? return(powmod(n, (p + 1) >> 2, p)) : (q >>= s)
var c = powmod(2 ..^ p -> first {|z| legendre(z, p) == -1}, q, p)
var r = powmod(n, (q + 1) >> 1, p)
var t = powmod(n, q, p)
... |
Port the following code from VB to Ruby with equivalent syntax and logic. | Imports System.Text
Module Module1
Structure Operator_
Public ReadOnly Symbol As Char
Public ReadOnly Precedence As Integer
Public ReadOnly Arity As Integer
Public ReadOnly Fun As Func(Of Boolean, Boolean, Boolean)
Public Sub New(symbol As Char, precedence As Integer, f As ... | loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
break if expr.empty?
vars = expr.scan(/\p{Alpha}+/)
if vars.empty?
puts "no variables detected in your boolean expression"
next
end
vars.each {|v| print "
puts "|
prefix = []
suffix = []
vars.each... |
Maintain the same structure and functionality when rewriting this code in Ruby. | Imports System.Text
Module Module1
Structure Operator_
Public ReadOnly Symbol As Char
Public ReadOnly Precedence As Integer
Public ReadOnly Arity As Integer
Public ReadOnly Fun As Func(Of Boolean, Boolean, Boolean)
Public Sub New(symbol As Char, precedence As Integer, f As ... | loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
break if expr.empty?
vars = expr.scan(/\p{Alpha}+/)
if vars.empty?
puts "no variables detected in your boolean expression"
next
end
vars.each {|v| print "
puts "|
prefix = []
suffix = []
vars.each... |
Change the following VB code into Ruby without altering its purpose. | Imports System.Numerics
Module Module1
Sub Main()
Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
Dim one As BigInteger = 1
Dim nine As BigInteger = 9
For ii = 2 To 9
Console.WriteLine("First 10 super-{0} numbers:", ii)
... | (2..8).each do |d|
rep = d.to_s * d
print "
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ")
end
|
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version. | Imports System.Numerics
Module Module1
Sub Main()
Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
Dim one As BigInteger = 1
Dim nine As BigInteger = 9
For ii = 2 To 9
Console.WriteLine("First 10 super-{0} numbers:", ii)
... | (2..8).each do |d|
rep = d.to_s * d
print "
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ")
end
|
Write the same algorithm in Ruby as shown in this VB implementation. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1)
Set objKeyMap = CreateObject("Scripting.Dictionary")
With objKeyMap
.Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5"
.Add "MNO",... | CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
NUMS = "22233344455566677778889999" * 2
dict = "unixdict.txt"
textonyms = File.open(dict){|f| f.map(&:chomp).group_by {|word| word.tr(CHARS, NUMS) } }
puts "There are
They require
puts "\n25287876746242:
|
Write a version of this VB function in Ruby with identical behavior. |
dim i,j
Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12"
for i=1 to 12
for j=1 to i
Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " "
next
Wscript.StdOut.WriteLine ""
next
Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60"
for i=10 to 60 step 10
f... | require "big"
include Math
struct Int
def permutation(k)
(self-k+1..self).product(1.to_big_i)
end
def combination(k)
self.permutation(k) // (1..k).product(1.to_big_i)
end
def big_permutation(k)
exp(lgamma_plus(self) - lgamma_plus(self-k))
end
def big_combination(k)
exp( lgamma_p... |
Generate a Ruby translation of this VB snippet without changing its computational steps. | Dim As Short digits = 500
Dim As Double an = 1
Dim As Double bn = Sqr(0.5)
Dim As Double tn = 0.5^2
Dim As Double pn = 1
Dim As Double prevAn
While pn <= digits
prevAn = an
an = (bn + an) / 2
bn = Sqr(bn * prevAn)
prevAn -= an
tn -= (pn * prevAn^2)
pn *= 2
Wend
Dim As Double pi = ((an + bn)^2) ... |
require 'flt'
Flt::BinNum.Context.precision = 8192
a = n = 1
g = 1 / Flt::BinNum(2).sqrt
z = 0.25
(0..17).each{
x = [(a + g) * 0.5, (a * g).sqrt]
var = x[0] - a
z -= var * var * n
n += n
a = x[0]
g = x[1]
}
puts a * a / z
|
Write the same algorithm in Ruby as shown in this VB implementation. | Dim As Short digits = 500
Dim As Double an = 1
Dim As Double bn = Sqr(0.5)
Dim As Double tn = 0.5^2
Dim As Double pn = 1
Dim As Double prevAn
While pn <= digits
prevAn = an
an = (bn + an) / 2
bn = Sqr(bn * prevAn)
prevAn -= an
tn -= (pn * prevAn^2)
pn *= 2
Wend
Dim As Double pi = ((an + bn)^2) ... |
require 'flt'
Flt::BinNum.Context.precision = 8192
a = n = 1
g = 1 / Flt::BinNum(2).sqrt
z = 0.25
(0..17).each{
x = [(a + g) * 0.5, (a * g).sqrt]
var = x[0] - a
z -= var * var * n
n += n
a = x[0]
g = x[1]
}
puts a * a / z
|
Transform the following VB implementation into Ruby, maintaining the same output and logic. | Imports System, System.Collections.Generic, System.Linq, System.Console
Module LongPrimes
Function Period(ByVal n As Integer) As Integer
Dim m As Integer, r As Integer = 1
For i As Integer = 0 To n : r = 10 * r Mod n : Next
m = r : Period = 1 : While True
r = (10 * r) Mod n : I... | require "big"
def prime?(n)
return n | 1 == 3 if n < 5
return false if n.gcd(6) != 1
pc = typeof(n).new(5)
until pc*pc > n
return false if n % pc == 0 || n % (pc + 2) == 0
pc += 6
end
true
end
def long_prime?(p)
return false unl... |
Preserve the algorithm and functionality while converting the code from VB to Ruby. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = Da... | require 'date'
CYCLES = {physical: 23, emotional: 28, mental: 33}
def biorhythms(date_of_birth, target_date = Date.today.to_s)
days_alive = Date.parse(target_date) - Date.parse(date_of_birth)
CYCLES.each do |name, num_days|
cycle_day = days_alive % num_days
state = case cycle_day
when 0, num_days/2 ... |
Preserve the algorithm and functionality while converting the code from VB to Ruby. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = Da... | require 'date'
CYCLES = {physical: 23, emotional: 28, mental: 33}
def biorhythms(date_of_birth, target_date = Date.today.to_s)
days_alive = Date.parse(target_date) - Date.parse(date_of_birth)
CYCLES.each do |name, num_days|
cycle_day = days_alive % num_days
state = case cycle_day
when 0, num_days/2 ... |
Port the following code from VB to Ruby with equivalent syntax and logic. | Imports System.Numerics
Imports System.Text
Module Module1
Function Gcd(a As BigInteger, b As BigInteger) As BigInteger
If b = 0 Then
If a < 0 Then
Return -a
Else
Return a
End If
Else
Return Gcd(b, a Mod b)
End... | def ef(fr)
ans = []
if fr >= 1
return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1
intfr = fr.to_i
ans, fr = [intfr], fr - intfr
end
x, y = fr.numerator, fr.denominator
while x != 1
ans << Rational(1, (1/fr).ceil)
fr = Rational(-y % x, y * (1/fr).ceil)
x, y = fr.numerator, fr.de... |
Produce a functionally identical Ruby code for the snippet given in VB. | Imports System.Numerics
Imports System.Text
Module Module1
Function Gcd(a As BigInteger, b As BigInteger) As BigInteger
If b = 0 Then
If a < 0 Then
Return -a
Else
Return a
End If
Else
Return Gcd(b, a Mod b)
End... | def ef(fr)
ans = []
if fr >= 1
return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1
intfr = fr.to_i
ans, fr = [intfr], fr - intfr
end
x, y = fr.numerator, fr.denominator
while x != 1
ans << Rational(1, (1/fr).ceil)
fr = Rational(-y % x, y * (1/fr).ceil)
x, y = fr.numerator, fr.de... |
Convert this VB block to Ruby, preserving its control flow and logic. | function isprime(v)
if v mod 2 = 0 then return v = 2
for d = 3 To Int(Sqr(v))+1 Step 2
if v mod d = 0 then return false
next d3
return True
end function
function diff_cubes(n)
return 3*n*(n+1) + 1
end function
function padto(n, s)
outstr = ""
k = length(string(n))
for i = 1 to s-k
outstr = " " + outstr
n... | require "openssl"
RE = /(\d)(?=(\d\d\d)+(?!\d))/
cuban_primes = Enumerator.new do |y|
(1..).each do |n|
cand = 3*n*(n+1) + 1
y << cand if OpenSSL::BN.new(cand).prime?
end
end
def commatize(num)
num.to_s.gsub(RE, "\\1,")
end
cbs = cuban_primes.take(200)
formatted = cbs.map{|cb| commatize(cb).rjust(1... |
Maintain the same structure and functionality when rewriting this code in Ruby. | Imports System.Text
Module Module1
Dim games As New List(Of String) From {"12", "13", "14", "23", "24", "34"}
Dim results = "000000"
Function FromBase3(num As String) As Integer
Dim out = 0
For Each c In num
Dim d = Asc(c) - Asc("0"c)
out = 3 * out + d
Next... | teams = [:a, :b, :c, :d]
matches = teams.combination(2).to_a
outcomes = [:win, :draw, :loss]
gains = {win:[3,0], draw:[1,1], loss:[0,3]}
places_histogram = Array.new(4) {Array.new(10,0)}
outcomes.repeated_permutation(6).each do |outcome|
results = Hash.new(0)
outcome.zip(matches).each do |decision, (team1,... |
Change the following VB code into Ruby without altering its purpose. | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.prece... | rpn = RPNExpression.from_infix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")
|
Write a version of this VB function in Ruby with identical behavior. | Imports System, BI = System.Numerics.BigInteger, System.Console
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End ... | func almkvist_giullera(n) {
(32 * (14*n * (38*n + 9) + 9) * (6*n)!) / (3 * n!**6)
}
func almkvist_giullera_pi(prec = 70) {
local Num!PREC = (4*(prec+1)).numify
var sum = 0
var target = -1
for n in (0..Inf) {
sum += (almkvist_giullera(n) / (10**(6*n + 3)))
var curr = (sum**-.5).as... |
Write the same code in Ruby as shown below in VB. | Imports System, BI = System.Numerics.BigInteger, System.Console
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End ... | func almkvist_giullera(n) {
(32 * (14*n * (38*n + 9) + 9) * (6*n)!) / (3 * n!**6)
}
func almkvist_giullera_pi(prec = 70) {
local Num!PREC = (4*(prec+1)).numify
var sum = 0
var target = -1
for n in (0..Inf) {
sum += (almkvist_giullera(n) / (10**(6*n + 3)))
var curr = (sum**-.5).as... |
Write a version of this VB function in Ruby with identical behavior. | Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
... | var equationtext = <<'EOT'
pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/9... |
Write the same code in Ruby as shown below in VB. | Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
... | var equationtext = <<'EOT'
pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/9... |
Generate an equivalent Ruby version of this VB code. | Public Sub Main()
Print p(12, 1)
Print p(12, 2)
Print p(123, 45)
Print p(123, 12345)
Print p(123, 678910)
End
Function p(L As Integer, n As Integer) As Integer
Dim FAC As Float = 0.30102999566398119521373889472449302677
Dim count As Integer, j As Integer = 0
Dim x As Float, y As Float
D... | def p(l, n)
test = 0
logv = Math.log(2.0) / Math.log(10.0)
factor = 1
loopv = l
while loopv > 10 do
factor = factor * 10
loopv = loopv / 10
end
while n > 0 do
test = test + 1
val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor
if val == l then... |
Ensure the translated Ruby code behaves exactly like the original VB snippet. | Public Sub Main()
Print p(12, 1)
Print p(12, 2)
Print p(123, 45)
Print p(123, 12345)
Print p(123, 678910)
End
Function p(L As Integer, n As Integer) As Integer
Dim FAC As Float = 0.30102999566398119521373889472449302677
Dim count As Integer, j As Integer = 0
Dim x As Float, y As Float
D... | def p(l, n)
test = 0
logv = Math.log(2.0) / Math.log(10.0)
factor = 1
loopv = l
while loopv > 10 do
factor = factor * 10
loopv = loopv / 10
end
while n > 0 do
test = test + 1
val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor
if val == l then... |
Translate the given VB code snippet into Ruby without altering its behavior. | Imports System.Numerics
Module Module1
Class Sterling
Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)
Private Shared Function CacheKey(n As Integer, k As Integer) As String
Return String.Format("{0}:{1}", n, k)
End Function
Private Shared Fun... | @memo = {}
def sterling2(n, k)
key = [n,k]
return @memo[key] if @memo.key?(key)
return 1 if n.zero? and k.zero?
return 0 if n.zero? or k.zero?
return 1 if n == k
return 0 if k > n
res = k * sterling2(n-1, k) + sterling2(n - 1, k-1)
@memo[key] = res
end
r = (0..12)
puts "Sterling2 numbers:"
puts "n/k ... |
Preserve the algorithm and functionality while converting the code from VB to Ruby. | Imports System.Numerics
Module Module1
Class Sterling
Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)
Private Shared Function CacheKey(n As Integer, k As Integer) As String
Return String.Format("{0}:{1}", n, k)
End Function
Private Shared Fun... | @memo = {}
def sterling2(n, k)
key = [n,k]
return @memo[key] if @memo.key?(key)
return 1 if n.zero? and k.zero?
return 0 if n.zero? or k.zero?
return 1 if n == k
return 0 if k > n
res = k * sterling2(n-1, k) + sterling2(n - 1, k-1)
@memo[key] = res
end
r = (0..12)
puts "Sterling2 numbers:"
puts "n/k ... |
Produce a functionally identical Ruby code for the snippet given in VB. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As Bi... | func cipolla(n, p) {
legendre(n, p) == 1 || return nil
var (a = 0, ω2 = 0)
loop {
ω2 = ((a*a - n) % p)
if (legendre(ω2, p) == -1) {
break
}
++a
}
struct point { x, y }
func mul(a, b) {
point((a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) %... |
Can you help me rewrite this code in Ruby instead of VB, keeping it the same logically? | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As Bi... | func cipolla(n, p) {
legendre(n, p) == 1 || return nil
var (a = 0, ω2 = 0)
loop {
ω2 = ((a*a - n) % p)
if (legendre(ω2, p) == -1) {
break
}
++a
}
struct point { x, y }
func mul(a, b) {
point((a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) %... |
Generate a Ruby translation of this VB snippet without changing its computational steps. |
dim p(),a(32),b(32),v,g: redim p(64)
what="99809 1 18 2 19 3 20 4 2017 24 22699 1-4 40355 3"
t1=split(what," ")
for j=0 to ubound(t1)
t2=split(t1(j)): x=t2(0): n=t2(1)
t3=split(x,"-"): x=clng(t3(0))
if ubound(t3)=1 then y=clng(t3(1)) else y=x
t3=split(n,"-"): n=cl... | require "prime"
def prime_partition(x, n)
Prime.each(x).to_a.combination(n).detect{|primes| primes.sum == x}
end
TESTCASES = [[99809, 1], [18, 2], [19, 3], [20, 4], [2017, 24],
[22699, 1], [22699, 2], [22699, 3], [22699, 4], [40355, 3]]
TESTCASES.each do |prime, num|
res = prime_partition(prime, nu... |
Port the provided VB code into Ruby while preserving the original functionality. | Imports System.Drawing
Module Module1
Function Lerp(s As Single, e As Single, t As Single) As Single
Return s + (e - s) * t
End Function
Function Blerp(c00 As Single, c10 As Single, c01 As Single, c11 As Single, tx As Single, ty As Single) As Single
Return Lerp(Lerp(c00, c10, tx), Lerp(c0... | require('Imager')
func scale(img, scaleX, scaleY) {
var (width, height) = (img.getwidth, img.getheight)
var (newWidth, newHeight) = (int(width*scaleX), int(height*scaleY))
var out = %O<Imager>.new(xsize => newWidth, ysize => newHeight)
var lerp = { |s, e, t|
s + t*(e-s)
}
var blerp =... |
Generate a Ruby translation of this VB snippet without changing its computational steps. | Imports System.Drawing
Module Module1
Function Lerp(s As Single, e As Single, t As Single) As Single
Return s + (e - s) * t
End Function
Function Blerp(c00 As Single, c10 As Single, c01 As Single, c11 As Single, tx As Single, ty As Single) As Single
Return Lerp(Lerp(c00, c10, tx), Lerp(c0... | require('Imager')
func scale(img, scaleX, scaleY) {
var (width, height) = (img.getwidth, img.getheight)
var (newWidth, newHeight) = (int(width*scaleX), int(height*scaleY))
var out = %O<Imager>.new(xsize => newWidth, ysize => newHeight)
var lerp = { |s, e, t|
s + t*(e-s)
}
var blerp =... |
Write the same code in Ruby as shown below in VB. | Type vector
x As Double
y As Double
End Type
Type vector2
phi As Double
r As Double
End Type
Private Function vector_addition(u As vector, v As vector) As vector
vector_addition.x = u.x + v.x
vector_addition.y = u.y + v.y
End Function
Private Function vector_subtraction(u As vector, v As vector)... | class Vector
def self.polar(r, angle=0)
new(r*Math.cos(angle), r*Math.sin(angle))
end
attr_reader :x, :y
def initialize(x, y)
raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric)
@x, @y = x, y
end
def +(other)
raise TypeError if self.class != other.class
self.class.new(@... |
Please provide an equivalent version of this VB code in Ruby. |
Dim coef(10),cheby(10)
pi=4*Atn(1)
a=0: b=1: n=10
For i=0 To n-1
coef(i)=Cos(Cos(pi/n*(i+1/2))*(b-a)/2+(b+a)/2)
Next
For i=0 To n-1
w=0
For j=0 To n-1
w=w+coef(j)*Cos(pi/n*i*(j+1/2))
Next
cheby(i)=w*2/n
If cheby(i)<=0 Then t="" Else t=" "
WScript.StdOut.WriteLine i&" : "&t... | def mapp(x, min_x, max_x, min_to, max_to)
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
end
def chebyshevCoef(func, min, max, coef)
n = coef.length
for i in 0 .. n-1 do
m = mapp(Math.cos(Math::PI * (i + 0.5) / n), -1, 1, min, max)
f = func.call(m) * 2 / n
for j... |
Translate this program into Ruby but keep the logic exactly as in VB. |
Dim coef(10),cheby(10)
pi=4*Atn(1)
a=0: b=1: n=10
For i=0 To n-1
coef(i)=Cos(Cos(pi/n*(i+1/2))*(b-a)/2+(b+a)/2)
Next
For i=0 To n-1
w=0
For j=0 To n-1
w=w+coef(j)*Cos(pi/n*i*(j+1/2))
Next
cheby(i)=w*2/n
If cheby(i)<=0 Then t="" Else t=" "
WScript.StdOut.WriteLine i&" : "&t... | def mapp(x, min_x, max_x, min_to, max_to)
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
end
def chebyshevCoef(func, min, max, coef)
n = coef.length
for i in 0 .. n-1 do
m = mapp(Math.cos(Math::PI * (i + 0.5) / n), -1, 1, min, max)
f = func.call(m) * 2 / n
for j... |
Translate this program into Ruby but keep the logic exactly as in VB. | Module Module1
ReadOnly STX As Char = Chr(&H2)
ReadOnly ETX As Char = Chr(&H3)
Sub Rotate(Of T)(a As T())
Dim o = a.Last
For i = a.Length - 1 To 1 Step -1
a(i) = a(i - 1)
Next
a(0) = o
End Sub
Private Function Compare(s1 As String, s2 As String) As Inte... | STX = "\u0002"
ETX = "\u0003"
def bwt(s)
for c in s.split('')
if c == STX or c == ETX then
raise ArgumentError.new("Input can't contain STX or ETX")
end
end
ss = ("%s%s%s" % [STX, s, ETX]).split('')
table = []
for i in 0 .. ss.length - 1
table.append(ss.join)
... |
Change the programming language of this snippet from VB to Ruby without modifying what it does. | Module Module1
ReadOnly STX As Char = Chr(&H2)
ReadOnly ETX As Char = Chr(&H3)
Sub Rotate(Of T)(a As T())
Dim o = a.Last
For i = a.Length - 1 To 1 Step -1
a(i) = a(i - 1)
Next
a(0) = o
End Sub
Private Function Compare(s1 As String, s2 As String) As Inte... | STX = "\u0002"
ETX = "\u0003"
def bwt(s)
for c in s.split('')
if c == STX or c == ETX then
raise ArgumentError.new("Input can't contain STX or ETX")
end
end
ss = ("%s%s%s" % [STX, s, ETX]).split('')
table = []
for i in 0 .. ss.length - 1
table.append(ss.join)
... |
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version. | Imports System.Runtime.CompilerServices
Imports System.Text
Module Module1
<Extension()>
Function AsString(Of T)(c As ICollection(Of T)) As String
Dim sb = New StringBuilder("[")
sb.Append(String.Join(", ", c))
Return sb.Append("]").ToString()
End Function
Private rand As New ... | def riffle deck
left, right = deck.partition{rand(10).odd?}
new_deck = []
until ((left_card=left.pop).to_i + (right_card=right.shift).to_i).zero? do
new_deck << left_card if left_card
new_deck << right_card if right_card
end
new_deck
end
def overhand deck
deck, new_deck = deck.dup, []
s ... |
Translate the given VB code snippet into Ruby without altering its behavior. | Imports System.Runtime.CompilerServices
Imports System.Text
Module Module1
<Extension()>
Function AsString(Of T)(c As ICollection(Of T)) As String
Dim sb = New StringBuilder("[")
sb.Append(String.Join(", ", c))
Return sb.Append("]").ToString()
End Function
Private rand As New ... | def riffle deck
left, right = deck.partition{rand(10).odd?}
new_deck = []
until ((left_card=left.pop).to_i + (right_card=right.shift).to_i).zero? do
new_deck << left_card if left_card
new_deck << right_card if right_card
end
new_deck
end
def overhand deck
deck, new_deck = deck.dup, []
s ... |
Generate an equivalent Ruby version of this VB code. | Module Module1
Class Frac
Private ReadOnly num As Long
Private ReadOnly denom As Long
Public Shared ReadOnly ZERO = New Frac(0, 1)
Public Shared ReadOnly ONE = New Frac(1, 1)
Public Sub New(n As Long, d As Long)
If d = 0 Then
Throw New ArgumentE... | class Frac
attr_accessor:num
attr_accessor:denom
def initialize(n,d)
if d == 0 then
raise ArgumentError.new('d cannot be zero')
end
nn = n
dd = d
if nn == 0 then
dd = 1
elsif dd < 0 then
nn = -nn
dd = -dd
... |
Write the same algorithm in Ruby as shown in this VB implementation. | Module Module1
Function Gcd(a As Long, b As Long)
If b = 0 Then
Return a
End If
Return Gcd(b, a Mod b)
End Function
Class Frac
ReadOnly num As Long
ReadOnly denom As Long
Public Shared ReadOnly ZERO As New Frac(0, 1)
Public Shared ReadOnl... | def binomial(n,k)
if n < 0 or k < 0 or n < k then
return -1
end
if n == 0 or k == 0 then
return 1
end
num = 1
for i in k+1 .. n do
num = num * i
end
denom = 1
for i in 2 .. n-k do
denom = denom * i
end
return num / denom
end
def bernoulli(n... |
Convert the following code from VB to Ruby, ensuring the logic remains intact. | Option Explicit
Sub Main()
Dim Dict As Object, L() As Long
Dim t As Single
Init Dict
L = ListPrimes(100000000)
t = Timer
PrimeConspiracy L, Dict, 1000000
Debug.Print "----------------------------"
Debug.Print "Execution time : " & Format(Timer - t, "0.000s.")
Debug.Print ""
Init Dict
t = Timer
PrimeCon... | require "prime"
def prime_conspiracy(m)
conspiracy = Hash.new(0)
Prime.take(m).map{|n| n%10}.each_cons(2){|a,b| conspiracy[[a,b]] += 1}
puts "
conspiracy.sort.each do |(a,b),v|
puts "%d → %d count:%10d frequency:%7.4f %" % [a, b, v, 100.0*v/m]
end
end
prime_conspiracy(1_000_000)
|
Port the following code from VB to Ruby with equivalent syntax and logic. | Imports System.Text
Module Module1
Class Complex : Implements IFormattable
Private ReadOnly real As Double
Private ReadOnly imag As Double
Public Sub New(r As Double, i As Double)
real = r
imag = i
End Sub
Public Sub New(r As Integer, i As Integer)... |
def base2i_decode(qi)
return 0 if qi == '0'
md = qi.match(/^(?<int>[0-3]+)(?:\.(?<frc>[0-3]+))?$/)
raise 'ill-formed quarter-imaginary base value' if !md
ls_pow = md[:frc] ? -(md[:frc].length) : 0
value = 0
(md[:int] + (md[:frc] ? md[:frc] : '')).reverse.each_char.with_index do |dig, inx|
value += dig... |
Maintain the same structure and functionality when rewriting this code in Ruby. | Public Sub standard_normal()
Dim s() As Variant, bins(71) As Single
ReDim s(20000)
For i = 1 To 20000
s(i) = WorksheetFunction.Norm_S_Inv(Rnd())
Next i
For i = -35 To 35
bins(i + 36) = i / 10
Next i
Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; ... |
class NormalFromUniform
def initialize()
@next = nil
end
def rand()
if @next
retval, @next = @next, nil
return retval
else
u = v = s = nil
loop do
u = Random.rand(-1.0..1.0)
v = Random.rand(-1.0..1.0)
s = u**2 + v**2
break if (s > 0.0) &... |
Change the following VB code into Ruby without altering its purpose. | Imports System, System.Linq, System.Collections.Generic, System.Console
Module Module1
Dim fmt As String = "{0,4} * {1,31:n0} = {2,-28}" & vbLf
Sub B10(ByVal n As Integer)
If n <= 1 Then Return
Dim pow As Integer() = New Integer(n) {},
val As Integer() = New Integer(n) {},
... | def mod(m, n)
result = m % n
if result < 0 then
result = result + n
end
return result
end
def getA004290(n)
if n == 1 then
return 1
end
arr = Array.new(n) { Array.new(n, 0) }
arr[0][0] = 1
arr[0][1] = 1
m = 0
while true
m = m + 1
if arr[m - 1]... |
Change the following VB code into Ruby without altering its purpose. | Module Module1
Dim resu As New List(Of Integer)
Function TestAbundant(n As Integer, ByRef divs As List(Of Integer)) As Boolean
divs = New List(Of Integer)
Dim sum As Integer = -n : For i As Integer = Math.Sqrt(n) To 1 Step -1
If n Mod i = 0 Then divs.Add(i) : Dim j As Integer = n /... | def divisors(n : Int32) : Array(Int32)
divs = [1]
divs2 = [] of Int32
i = 2
while i * i < n
if n % i == 0
j = n // i
divs << i
divs2 << j if i != j
end
i += 1
end
i = divs.size - 1
while i >= 0
divs2 << divs[i]
i -= 1
end
divs2
end
def abundant(n : Int32,... |
Write a version of this VB function in Ruby with identical behavior. | Module Module1
Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)
Dim result As New List(Of Integer) From {
n
}
result.AddRange(seq)
Return result
End Function
Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_... | def check_seq(pos, seq, n, min_len)
if pos > min_len or seq[0] > n then
return min_len, 0
elsif seq[0] == n then
return pos, 1
elsif pos < min_len then
return try_perm(0, pos, seq, n, min_len)
else
return min_len, 0
end
end
def try_perm(i, pos, seq, n, min_len)
i... |
Port the provided VB code into Ruby while preserving the original functionality. | Imports System.Numerics
Imports System.Runtime.CompilerServices
Module Module1
<Extension()>
Function BitLength(v As BigInteger) As Integer
If v < 0 Then
v *= -1
End If
Dim result = 0
While v > 0
v >>= 1
result += 1
End While
... | func montgomeryReduce(m, a) {
{
a += m if a.is_odd
a >>= 1
} * m.as_bin.len
a % m
}
var m = 750791094644726559640638407699
var t1 = 323165824550862327179367294465482435542970161392400401329100
var r1 = 440160025148131680164261562101
var r2 = 435362628198191204145287283255
var x1 = 54001... |
Translate the given VB code snippet into Ruby without altering its behavior. | Module Module1
Function GetDivisors(n As Integer) As List(Of Integer)
Dim divs As New List(Of Integer) From {
1, n
}
Dim i = 2
While i * i <= n
If n Mod i = 0 Then
Dim j = n \ i
divs.Add(i)
If i <> j Then
... | class Integer
def divisors
res = [1, self]
(2..Integer.sqrt(self)).each do |n|
div, mod = divmod(n)
res << n << div if mod.zero?
end
res.uniq.sort
end
def zumkeller?
divs = divisors
sum = divs.sum
return false unless sum.even? && sum >= self*2
half = sum / 2
... |
Generate an equivalent Ruby version of this VB code. | Imports System.Console
Imports DT = System.DateTime
Imports Lsb = System.Collections.Generic.List(Of SByte)
Imports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte))
Imports UI = System.UInt64
Module Module1
Const MxD As SByte = 15
Public Structure term
Public coeff A... | Term = Struct.new(:coeff, :ix1, :ix2) do
end
MAX_DIGITS = 16
def toLong(digits, reverse)
sum = 0
if reverse then
i = digits.length - 1
while i >=0
sum = sum *10 + digits[i]
i = i - 1
end
else
i = 0
while i < digits.length
sum = s... |
Convert this VB block to Ruby, preserving its control flow and logic. | Imports System.Reflection
Module Module1
Class TestClass
Private privateField = 7
Public ReadOnly Property PublicNumber = 4
Private ReadOnly Property PrivateNumber = 2
End Class
Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return From p ... | class Foo
@@xyz = nil
def initialize(name, age)
@name, @age = name, age
end
def add_sex(sex)
@sex = sex
end
end
p foo = Foo.new("Angel", 18)
p foo.instance_variables
p foo.instance_variable_defined?(:@age)
p foo.instance_variable_get(:@age)
p foo.instance_variable_s... |
Translate the given VB code snippet into Ruby without altering its behavior. | Module Module1
Class Node
Public Sub New(Len As Integer)
Length = Len
Edges = New Dictionary(Of Char, Integer)
End Sub
Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)
Length = len
Edges = If(IsNothing(edg),... | class Node
def initialize(length, edges = {}, suffix = 0)
@length = length
@edges = edges
@suffix = suffix
end
attr_reader :length
attr_reader :edges
attr_accessor :suffix
end
EVEN_ROOT = 0
ODD_ROOT = 1
def eertree(s)
tree = [
Node.new(0, {}, ODD_ROOT),
... |
Generate an equivalent Ruby version of this VB code. | Module Module1
Class Node
Public Sub New(Len As Integer)
Length = Len
Edges = New Dictionary(Of Char, Integer)
End Sub
Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)
Length = len
Edges = If(IsNothing(edg),... | class Node
def initialize(length, edges = {}, suffix = 0)
@length = length
@edges = edges
@suffix = suffix
end
attr_reader :length
attr_reader :edges
attr_accessor :suffix
end
EVEN_ROOT = 0
ODD_ROOT = 1
def eertree(s)
tree = [
Node.new(0, {}, ODD_ROOT),
... |
Change the programming language of this snippet from VB to Ruby without modifying what it does. | Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Leng... | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
nums = [25420294593250030202636073700053352635053786165627414518,
0x61,
0x626262,
0x636363,
0x73696d706c792061206c6f6e6720737472696e67,
0x516b6fcd0f,
0xbf4f89001e670274dd,
0x572e4794,
... |
Keep all operations the same but rewrite the snippet in Ruby. | Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Leng... | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
nums = [25420294593250030202636073700053352635053786165627414518,
0x61,
0x626262,
0x636363,
0x73696d706c792061206c6f6e6720737472696e67,
0x516b6fcd0f,
0xbf4f89001e670274dd,
0x572e4794,
... |
Convert this VB block to Ruby, preserving its control flow and logic. | Option Strict On
Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim u = a
a = b
b = u
End Sub
Sub PrintSquare(latin As Matrix)
For Each row In latin
Dim... | def printSquare(a)
for row in a
print row, "\n"
end
print "\n"
end
def dList(n, start)
start = start - 1
a = Array.new(n) {|i| i}
a[0], a[start] = a[start], a[0]
a[1..] = a[1..].sort
first = a[1]
r = []
recurse = lambda {|last|
if last == first then
... |
Port the provided VB code into Ruby while preserving the original functionality. | Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Intege... | func korasaju(Array g) {
var vis = g.len.of(false)
var L = []
var x = g.end
var t = g.len.of { [] }
func visit(u) {
if (!vis[u]) {
vis[u] = true
g[u].each {|v|
visit(v)
t[v] << u
}
L[x--] = u
... |
Preserve the algorithm and functionality while converting the code from VB to Ruby. | Imports System.Numerics
Imports System.Text
Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long)
Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))
Module Module1
Function CumulativeFreq(freq As Freq) As Freq
Dim total... | def cumulative_freq(freq)
cf = {}
total = 0
freq.keys.sort.each do |b|
cf[b] = total
total += freq[b]
end
return cf
end
def arithmethic_coding(bytes, radix)
freq = Hash.new(0)
bytes.each { |b| freq[b] += 1 }
cf = cumulative_freq(freq)
base = bytes.size
lower = 0
pf = 1... |
Maintain the same structure and functionality when rewriting this code in Ruby. | Option Explicit
Private Type Adress
Row As Integer
Column As Integer
End Type
Private myTable() As String
Sub Main()
Dim keyw As String, boolQ As Boolean, text As String, test As Long
Dim res As String
keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example")
If keyw = "" Then GoTo ErrorHan... | class Playfair
Size = 5
def initialize(key, missing)
@missing = missing.upcase
alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''
extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet
grid = extended.uniq[0...Size*Size].each_slice(Size).to_a
coords = {}
grid.each_with_ind... |
Generate an equivalent Ruby version of this VB code. | Option Explicit
Private Type Adress
Row As Integer
Column As Integer
End Type
Private myTable() As String
Sub Main()
Dim keyw As String, boolQ As Boolean, text As String, test As Long
Dim res As String
keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example")
If keyw = "" Then GoTo ErrorHan... | class Playfair
Size = 5
def initialize(key, missing)
@missing = missing.upcase
alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''
extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet
grid = extended.uniq[0...Size*Size].each_slice(Size).to_a
coords = {}
grid.each_with_ind... |
Can you help me rewrite this code in Ruby instead of VB, keeping it the same logically? | Module Module1
Structure Node
Private ReadOnly m_val As String
Private ReadOnly m_parsed As List(Of String)
Sub New(initial As String)
m_val = initial
m_parsed = New List(Of String)
End Sub
Sub New(s As String, p As List(Of String))
m_va... | def split_text_with_dict(text, dict, splited=[])
solutions = []
dict.each do |word|
if text.start_with? word
new_text = text.delete_prefix word
new_splited = splited.dup<< word
if new_text.empty?
solutions << new_splited
else
sols = split_text_with_dict(new_text, dict, ne... |
Write a version of this VB function in Ruby with identical behavior. | Imports System, Microsoft.VisualBasic.DateAndTime
Public Module Module1
Const n As Integer = 5
Dim Board As String
Dim Starting As Integer = 1
Dim Target As Integer = 13
Dim Moves As Integer()
Dim bi() As Integer
Dim ib() As Integer
Dim nl As Char = Convert.ToChar(10)
... |
G = [[0,1,3],[0,2,5],[1,3,6],[1,4,8],[2,4,7],[2,5,9],[3,4,5],[3,6,10],[3,7,12],[4,7,11],[4,8,13],[5,8,12],[5,9,14],[6,7,8],[7,8,9],[10,11,12],[11,12,13],[12,13,14],
[3,1,0],[5,2,0],[6,3,1],[8,4,1],[7,4,2],[9,5,2],[5,4,3],[10,6,3],[12,7,3],[11,7,4],[13,8,4],[12,8,5],[14,9,5],[8,7,6],[9,8,7],[12,11,10],[13,12,11],[... |
Produce a language-to-language conversion: from VB to Ruby, same semantics. | #include "isPrime.kbs"
num = 3
while num < 992
if isPrime(num) then
if isPrime(num+2) then
if isPrime(num+6) then
if isPrime(num+8) then print num; " "; num+2; " "; num+6; " "; num+8
end if
end if
end if
num += 2
end while
end
| require 'prime'
res = Prime.each(1000).each_cons(4).select do |p1, p2, p3, p4|
p1+2 == p2 && p2+4 == p3 && p3+2 == p4
end
res.each{|slice| puts slice.join(", ")}
|
Change the programming language of this snippet from VB to Ruby without modifying what it does. | Option explicit
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray()
private filename
private Palette,szpal
public property get xmin():xmin=xmini:end property
public property get ymin():ymin=ymini:end property
public property ge... | def settings
size(300, 300)
end
def setup
sketch_title 'Color Wheel'
background(0)
radius = width / 2.0
center = width / 2
grid(width, height) do |x, y|
rx = x - center
ry = y - center
sat = Math.hypot(rx, ry) / radius
if sat <= 1.0
hue = ((Math.atan2(ry, rx) / PI) + 1) / 2.0
co... |
Write a version of this VB function in Ruby with identical behavior. | #include "isprime.bas"
#include "factorial.bas"
Print "First 10 factorial primes:"
Dim As Integer found = 0, i = 1
While found < 10
Dim As Integer fct = factorial (i)
If isprime(fct-1) Then
found += 1
Print Using "##: ##_! - 1 = &"; found; i; fct-1
End If
If isprime(fct+1) Then
... | require 'openssl'
factorial_primes = Enumerator.new do |y|
fact = 1
(1..).each do |i|
fact *= i
y << [i, "- 1", fact - 1] if OpenSSL::BN.new(fact - 1).prime?
y << [i, "+ 1", fact + 1] if OpenSSL::BN.new(fact + 1).prime?
end
end
factorial_primes.first(30).each do |a|
s = a.last.to_s
if s.size > 4... |
Port the following code from VB to Ruby with equivalent syntax and logic. | Option Strict On
Option Explicit On
Module WilsonPrimes
Function isPrime(p As Integer) As Boolean
If p < 2 Then Return False
If p Mod 2 = 0 Then Return p = 2
IF p Mod 3 = 0 Then Return p = 3
Dim d As Integer = 5
Do While d * d <= p
If p Mod d = 0 Then
... | require "prime"
module Modulo
refine Integer do
def factorial_mod(m) = (1..self).inject(1){|prod, n| (prod *= n) % m }
end
end
using Modulo
primes = Prime.each(11000).to_a
(1..11).each do |n|
res = primes.select do |pr|
prpr = pr*pr
((n-1).factorial_mod(prpr) * (pr-n).factorial_mod(prpr) - (-1)*... |
Rewrite this program in Ruby while keeping its functionality equivalent to the VB version. | Option explicit
Function fileexists(fn)
fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn)
End Function
Function xmlvalid(strfilename)
Dim xmldoc,xmldoc2,objSchemas
Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
If fileexists(Replace(strfilename,".xml",".dtd")) Then
xmlDoc.set... | require('XML::LibXML')
func is_valid_xml(str, schema) {
var parser = %O<XML::LibXML>.new
var xmlschema = %O<XML::LibXML::Schema>.new(string => schema)
try {
xmlschema.validate(parser.parse_string(str))
true
} catch {
false
}
}
var good_xml = '<a>5</a>'
var bad_xml = '... |
Port the provided VB code into Ruby while preserving the original functionality. | Option Strict On
Option Explicit On
Imports System.IO
Module OwnDigitsPowerSum
Public Sub Main
Dim used(9) As Integer
Dim check(9) As Integer
Dim power(9, 9) As Long
For i As Integer = 0 To 9
check(i) = 0
Next i
For i As Integer = 1 To 9
... | DIGITS = (0..9).to_a
range = (3..18)
res = range.map do |s|
powers = {}
DIGITS.each{|n| powers[n] = n**s}
DIGITS.repeated_combination(s).filter_map do |combi|
sum = powers.values_at(*combi).sum
sum if sum.digits.sort == combi.sort
end.sort
end
puts "Own digits power sums for N =
|
Please provide an equivalent version of this VB code in Ruby. | Imports BI = System.Numerics.BigInteger
Module Module1
Function IntSqRoot(v As BI, res As BI) As BI
REM res is the initial guess
Dim term As BI = 0
Dim d As BI = 0
Dim dl As BI = 1
While dl <> d
term = v / res
res = (res + term) >> 1
dl =... | require('bigdecimal')
require('bigdecimal/util')
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1 ; yielder.yield(xn2)
xn1 = 1 ; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) }
end
end
def metallic_ratio(b, precision)
xn2 = xn1 = prev = this = 0
lucas(b).eac... |
Convert this VB block to Ruby, preserving its control flow and logic. | Imports BI = System.Numerics.BigInteger
Module Module1
Function IntSqRoot(v As BI, res As BI) As BI
REM res is the initial guess
Dim term As BI = 0
Dim d As BI = 0
Dim dl As BI = 1
While dl <> d
term = v / res
res = (res + term) >> 1
dl =... | require('bigdecimal')
require('bigdecimal/util')
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1 ; yielder.yield(xn2)
xn1 = 1 ; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) }
end
end
def metallic_ratio(b, precision)
xn2 = xn1 = prev = this = 0
lucas(b).eac... |
Write the same code in Ruby as shown below in VB. | Private Function inverse(mat As Variant) As Variant
Dim len_ As Integer: len_ = UBound(mat)
Dim tmp() As Variant
ReDim tmp(2 * len_ + 1)
Dim aug As Variant
ReDim aug(len_)
For i = 0 To len_
If UBound(mat(i)) <> len_ Then Debug.Print 9 / 0
aug(i) = tmp
For j = 0 To len_
... | require 'matrix'
m = Matrix[[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3]]
pp m.inv.row_vectors
|
Convert this VB snippet to Ruby and keep its semantics consistent. | Private Function inverse(mat As Variant) As Variant
Dim len_ As Integer: len_ = UBound(mat)
Dim tmp() As Variant
ReDim tmp(2 * len_ + 1)
Dim aug As Variant
ReDim aug(len_)
For i = 0 To len_
If UBound(mat(i)) <> len_ Then Debug.Print 9 / 0
aug(i) = tmp
For j = 0 To len_
... | require 'matrix'
m = Matrix[[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3]]
pp m.inv.row_vectors
|
Maintain the same structure and functionality when rewriting this code in Ruby. | 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... | var rules = Hash(
x => 'xF-F+F-xF+F+xF-F+F-x',
)
var lsys = LSystem(
width: 510,
height: 510,
xoff: -505,
yoff: -254,
len: 4,
angle: 90,
color: 'dark green',
)
lsys.execute('F+xF+F+xF', 5, "sierpiński_square_curve.png", rules)
|
Write the same code in Ruby as shown below in VB. | Imports System.Collections.Generic, System.Linq, System.Console
Module Module1
Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean
If n <= 0 Then Return False Else If f.Contains(n) Then Return True
Select Case n.CompareTo(f.Sum())
Case 1 : Return False : Cas... | say is_practical(2**128 + 1)
say is_practical(2**128 + 4)
|
Please provide an equivalent version of this C code in R. | #include <stdio.h>
#define SWAP(r,s) do{ t=r; r=s; s=t; } while(0)
void StoogeSort(int a[], int i, int j)
{
int t;
if (a[j] < a[i]) SWAP(a[i], a[j]);
if (j - i > 1)
{
t = (j - i + 1) / 3;
StoogeSort(a, i, j - t);
StoogeSort(a, i + t, j);
StoogeSort(a, i, j - t);
}
}
... | stoogesort = function(vect) {
i = 1
j = length(vect)
if(vect[j] < vect[i]) vect[c(j, i)] = vect[c(i, j)]
if(j - i > 1) {
t = (j - i + 1) %/% 3
vect[i:(j - t)] = stoogesort(vect[i:(j - t)])
vect[(i + t):j] = stoogesort(vect[(i + t):j])
vect[i:(j - t)] = stoogesort(vect[i:(j - t)])
}
vect
}
v = sample(21,... |
Produce a functionally identical R code for the snippet given in C. | #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, ... | truncate_file <- function(filename, n_bytes) {
stopifnot(
"file does not exist"= file.exists(filename),
"not enough bytes in file"= file.size(filename) >= n_bytes
)
input.con <- file(filename, "rb")
bindata <- readBin(input.con, integer(), n=n_bytes/4)
close(input.con)
tmp.filename... |
Transform the following C implementation into R, maintaining the same output and logic. | #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, ... | truncate_file <- function(filename, n_bytes) {
stopifnot(
"file does not exist"= file.exists(filename),
"not enough bytes in file"= file.size(filename) >= n_bytes
)
input.con <- file(filename, "rb")
bindata <- readBin(input.con, integer(), n=n_bytes/4)
close(input.con)
tmp.filename... |
Port the following code from C to R with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx ... | conv <- function(a, b) {
p <- length(a)
q <- length(b)
n <- p + q - 1
r <- nextn(n, f=2)
y <- fft(fft(c(a, rep(0, r-p))) * fft(c(b, rep(0, r-q))), inverse=TRUE)/r
y[1:n]
}
deconv <- function(a, b) {
p <- length(a)
q <- length(b)
n <- p - q + 1
r <- nextn(max(p, q), f=2)
y <- fft(fft(c(a, rep(0, r-p))) / fft... |
Change the following C code into R without altering its purpose. | #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1)... | > seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 0 items
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 1 item
|
Write the same algorithm in R as shown in this C implementation. | #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1)... | > seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 0 items
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 1 item
|
Translate this program into R but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
... | do.if <- function(expr, cond) if(cond) expr
|
Ensure the translated R code behaves exactly like the original C snippet. | #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
... | do.if <- function(expr, cond) if(cond) expr
|
Port the following code from C to R with equivalent syntax and logic. | #include <stdio.h>
#include <ctype.h>
char rfc3986[256] = {0};
char html5[256] = {0};
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, "%c", tb[*s]);
else sprintf(enc, "%%%02X", *s);
while (*++enc);
}
}
int main()
{
const char url[] = "http:
char enc[(s... | URLencode("http://foo bar/")
|
Please provide an equivalent version of this C code in R. | #include <stdio.h>
#include <ctype.h>
char rfc3986[256] = {0};
char html5[256] = {0};
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, "%c", tb[*s]);
else sprintf(enc, "%%%02X", *s);
while (*++enc);
}
}
int main()
{
const char url[] = "http:
char enc[(s... | URLencode("http://foo bar/")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.