Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | >>> y = str( 5**4**3**2 )
>>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
| Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim Implems() As String = {"Built-In", "Recursive", "Iterative"},
powers() As Integer = {5, 4, 3, 2}
Function intPowR(val As BI, exp As BI) As BI
If exp = 0 Then Return 1
Dim ne As BI, vs As BI = val * val
If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)
ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val
End Function
Function intPowI(val As BI, exp As BI) As BI
intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val
val *= val : exp >>= 1 : End While
End Function
Sub DoOne(title As String, p() As Integer)
Dim st As DateTime = DateTime.Now, res As BI, resStr As String
Select Case (Array.IndexOf(Implems, title))
Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))
Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))
Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))
End Select : resStr = res.ToString()
Dim et As TimeSpan = DateTime.Now - st
Debug.Assert(resStr.Length = 183231)
Debug.Assert(resStr.StartsWith("62060698786608744707"))
Debug.Assert(resStr.EndsWith("92256259918212890625"))
WriteLine("n = {0}", String.Join("^", powers))
WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20))
WriteLine("n digits = {0}", resStr.Length)
WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds)
End Sub
Sub Main()
For Each itm As String in Implems : DoOne(itm, powers) : Next
If Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module
|
Change the following Python code into VB without altering its purpose. | import math
shades = ('.',':','!','*','o','e','&','
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)
| shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
|
Transform the following Python implementation into VB, maintaining the same output and logic. | import math
shades = ('.',':','!','*','o','e','&','
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)
| shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
|
Convert this Python block to VB, preserving its control flow and logic. | >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
| Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
|
Write the same code in VB as shown below in Python. | >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
| Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
|
Generate an equivalent VB version of this Python code. | >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
| Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
|
Produce a language-to-language conversion: from Python to VB, same semantics. | from random import randrange
while True:
a = randrange(20)
print(a)
if a == 10:
break
b = randrange(20)
print(b)
| Public Sub LoopsBreak()
Dim value As Integer
Randomize
Do While True
value = Int(20 * Rnd)
Debug.Print value
If value = 10 Then Exit Do
Debug.Print Int(20 * Rnd)
Loop
End Sub
|
Keep all operations the same but rewrite the snippet in VB. | def water_collected(tower):
N = len(tower)
highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
for n in range(N)]
print("highest_left: ", highest_left)
print("highest_right: ", highest_right)
print("water_level: ", water_level)
print("tower_level: ", tower)
print("total_water: ", sum(water_level))
print("")
return sum(water_level)
towers = [[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
[water_collected(tower) for tower in towers]
|
Module Module1
Sub Main(Args() As String)
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1
Dim wta As Integer()() = {
New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
Dim blk As String,
lf As String = vbLf,
tb = "██", wr = "≈≈", mt = " "
For i As Integer = 0 To wta.Length - 1
Dim bpf As Integer
blk = ""
Do
bpf = 0 : Dim floor As String = ""
For j As Integer = 0 To wta(i).Length - 1
If wta(i)(j) > 0 Then
floor &= tb : wta(i)(j) -= 1 : bpf += 1
Else
floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)
End If
Next
If bpf > 0 Then blk = floor & lf & blk
Loop Until bpf = 0
While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While
While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While
If shoTow Then Console.Write("{0}{1}", lf, blk)
Console.Write("Block {0} retains {1,2} water units.{2}", i + 1,
(blk.Length - blk.Replace(wr, "").Length) \ 2, lf)
Next
End Sub
End Module
|
Produce a language-to-language conversion: from Python to VB, same semantics. | import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".format(i), end="" )
count += 1
print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))
ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
| 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 limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module
|
Write the same code in VB as shown below in Python. | import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".format(i), end="" )
count += 1
print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))
ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
| 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 limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module
|
Can you help me rewrite this code in VB instead of Python, keeping it the same logically? |
from __future__ import division
def jaro(s, t):
s_len = len(s)
t_len = len(t)
if s_len == 0 and t_len == 0:
return 1
match_distance = (max(s_len, t_len) // 2) - 1
s_matches = [False] * s_len
t_matches = [False] * t_len
matches = 0
transpositions = 0
for i in range(s_len):
start = max(0, i - match_distance)
end = min(i + match_distance + 1, t_len)
for j in range(start, end):
if t_matches[j]:
continue
if s[i] != t[j]:
continue
s_matches[i] = True
t_matches[j] = True
matches += 1
break
if matches == 0:
return 0
k = 0
for i in range(s_len):
if not s_matches[i]:
continue
while not t_matches[k]:
k += 1
if s[i] != t[k]:
transpositions += 1
k += 1
return ((matches / s_len) +
(matches / t_len) +
((matches - transpositions / 2) / matches)) / 3
def main():
for s, t in [('MARTHA', 'MARHTA'),
('DIXON', 'DICKSONX'),
('JELLYFISH', 'SMELLYFISH')]:
print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t)))
if __name__ == '__main__':
main()
| Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = Len(text1)
s2 = Len(text2)
limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)
match1 = String(s1, dummyChar)
match2 = String(s2, dummyChar)
For l = 1 To WorksheetFunction.Min(4, s1, s2)
If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For
Next l
l = l - 1
For i = 1 To s1
f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)
t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)
j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)
If j > 0 Then
m = m + 1
text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)
match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)
match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)
End If
Next i
match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare)
match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare)
t = 0
For i = 1 To m
If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1
Next i
JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3
JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)
End Function
|
Maintain the same structure and functionality when rewriting this code in VB. | from itertools import count, islice
def _basechange_int(num, b):
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __name__ == '__main__':
for b in (2, 3, 5, 11):
print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
| 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)
Console.Write("Base {0,2}:", base)
For i = 1 To count
Dim t = Turn(base, i - 1)
Console.Write(" {0,2}", t)
Next
Console.WriteLine()
End Sub
Sub TurnCount(base As Integer, count As Integer)
Dim cnt(base) As Integer
For i = 1 To base
cnt(i - 1) = 0
Next
For i = 1 To count
Dim t = Turn(base, i - 1)
cnt(t) += 1
Next
Dim minTurn = Integer.MaxValue
Dim maxTurn = Integer.MinValue
Dim portion = 0
For i = 1 To base
Dim num = cnt(i - 1)
If num > 0 Then
portion += 1
End If
If num < minTurn Then
minTurn = num
End If
If num > maxTurn Then
maxTurn = num
End If
Next
Console.Write(" With {0} people: ", base)
If 0 = minTurn Then
Console.WriteLine("Only {0} have a turn", portion)
ElseIf minTurn = maxTurn Then
Console.WriteLine(minTurn)
Else
Console.WriteLine("{0} or {1}", minTurn, maxTurn)
End If
End Sub
Sub Main()
Fairshare(2, 25)
Fairshare(3, 25)
Fairshare(5, 25)
Fairshare(11, 25)
Console.WriteLine("How many times does each get a turn in 50000 iterations?")
TurnCount(191, 50000)
TurnCount(1377, 50000)
TurnCount(49999, 50000)
TurnCount(50000, 50000)
TurnCount(50001, 50000)
End Sub
End Module
|
Write a version of this Python function in VB with identical behavior. | from itertools import count, islice
def _basechange_int(num, b):
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __name__ == '__main__':
for b in (2, 3, 5, 11):
print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
| 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)
Console.Write("Base {0,2}:", base)
For i = 1 To count
Dim t = Turn(base, i - 1)
Console.Write(" {0,2}", t)
Next
Console.WriteLine()
End Sub
Sub TurnCount(base As Integer, count As Integer)
Dim cnt(base) As Integer
For i = 1 To base
cnt(i - 1) = 0
Next
For i = 1 To count
Dim t = Turn(base, i - 1)
cnt(t) += 1
Next
Dim minTurn = Integer.MaxValue
Dim maxTurn = Integer.MinValue
Dim portion = 0
For i = 1 To base
Dim num = cnt(i - 1)
If num > 0 Then
portion += 1
End If
If num < minTurn Then
minTurn = num
End If
If num > maxTurn Then
maxTurn = num
End If
Next
Console.Write(" With {0} people: ", base)
If 0 = minTurn Then
Console.WriteLine("Only {0} have a turn", portion)
ElseIf minTurn = maxTurn Then
Console.WriteLine(minTurn)
Else
Console.WriteLine("{0} or {1}", minTurn, maxTurn)
End If
End Sub
Sub Main()
Fairshare(2, 25)
Fairshare(3, 25)
Fairshare(5, 25)
Fairshare(11, 25)
Console.WriteLine("How many times does each get a turn in 50000 iterations?")
TurnCount(191, 50000)
TurnCount(1377, 50000)
TurnCount(49999, 50000)
TurnCount(50000, 50000)
TurnCount(50001, 50000)
End Sub
End Module
|
Change the programming language of this snippet from Python to VB without modifying what it does. | from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(prec=9, assoc=L),
')': OpInfo(prec=0, assoc=L),
}
NUM, LPAREN, RPAREN = 'NUMBER ( )'.split()
def get_input(inp = None):
'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'
if inp is None:
inp = input('expression: ')
tokens = inp.strip().split()
tokenvals = []
for token in tokens:
if token in ops:
tokenvals.append((token, ops[token]))
else:
tokenvals.append((NUM, token))
return tokenvals
def shunting(tokenvals):
outq, stack = [], []
table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]
for token, val in tokenvals:
note = action = ''
if token is NUM:
action = 'Add number to output'
outq.append(val)
table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
elif token in ops:
t1, (p1, a1) = token, val
v = t1
note = 'Pop ops from stack to output'
while stack:
t2, (p2, a2) = stack[-1]
if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):
if t1 != RPAREN:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
break
else:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
stack.pop()
action = '(Pop & discard "(")'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
break
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
else:
note = ''
break
note = ''
note = ''
if t1 != RPAREN:
stack.append((token, val))
action = 'Push op token to stack'
else:
action = 'Discard ")"'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
note = 'Drain stack to output'
while stack:
v = ''
t2, (p2, a2) = stack[-1]
action = '(Pop op)'
stack.pop()
outq.append(t2)
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
return table
if __name__ == '__main__':
infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
print( 'For infix expression: %r\n' % infix )
rp = shunting(get_input(infix))
maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]
row = rp[0]
print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
for row in rp[1:]:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
print('\n The final output RPN is: %r' % rp[-1][2])
| 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.precedence = precedence
Me.rightAssociative = rightAssociative
End Sub
End Class
ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From
{
{"^", New SymbolType("^", 4, True)},
{"*", New SymbolType("*", 3, False)},
{"/", New SymbolType("/", 3, False)},
{"+", New SymbolType("+", 2, False)},
{"-", New SymbolType("-", 2, False)}
}
Function ToPostfix(infix As String) As String
Dim tokens = infix.Split(" ")
Dim stack As New Stack(Of String)
Dim output As New List(Of String)
Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]")
For Each token In tokens
Dim iv As Integer
Dim op1 As SymbolType
Dim op2 As SymbolType
If Integer.TryParse(token, iv) Then
output.Add(token)
Print(token)
ElseIf Operators.TryGetValue(token, op1) Then
While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)
Dim c = op1.precedence.CompareTo(op2.precedence)
If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then
output.Add(stack.Pop())
Else
Exit While
End If
End While
stack.Push(token)
Print(token)
ElseIf token = "(" Then
stack.Push(token)
Print(token)
ElseIf token = ")" Then
Dim top = ""
While stack.Count > 0
top = stack.Pop()
If top <> "(" Then
output.Add(top)
Else
Exit While
End If
End While
If top <> "(" Then
Throw New ArgumentException("No matching left parenthesis.")
End If
Print(token)
End If
Next
While stack.Count > 0
Dim top = stack.Pop()
If Not Operators.ContainsKey(top) Then
Throw New ArgumentException("No matching right parenthesis.")
End If
output.Add(top)
End While
Print("pop")
Return String.Join(" ", output)
End Function
Sub Main()
Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
Console.WriteLine(ToPostfix(infix))
End Sub
End Module
|
Convert this Python block to VB, preserving its control flow and logic. | Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))
11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>>
| Function tpk(s)
arr = Split(s," ")
For i = UBound(arr) To 0 Step -1
n = fx(CDbl(arr(i)))
If n > 400 Then
WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
Else
WScript.StdOut.WriteLine arr(i) & " = " & n
End If
Next
End Function
Function fx(x)
fx = Sqr(Abs(x))+5*x^3
End Function
WScript.StdOut.Write "Please enter a series of numbers:"
list = WScript.StdIn.ReadLine
tpk(list)
|
Translate the given Python code snippet into VB without altering its behavior. | >>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits"
mid = length // 2
return s[mid-1:mid+2]
>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
>>> failing = [1, 2, -1, -10, 2002, -2002, 0]
>>> for x in passing + failing:
try:
answer = middle_three_digits(x)
except AssertionError as error:
answer = error
print("middle_three_digits(%s) returned: %r" % (x, answer))
middle_three_digits(123) returned: '123'
middle_three_digits(12345) returned: '234'
middle_three_digits(1234567) returned: '345'
middle_three_digits(987654321) returned: '654'
middle_three_digits(10001) returned: '000'
middle_three_digits(-10001) returned: '000'
middle_three_digits(-123) returned: '123'
middle_three_digits(-100) returned: '100'
middle_three_digits(100) returned: '100'
middle_three_digits(-12345) returned: '234'
middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>>
| Option Explicit
Sub Main_Middle_three_digits()
Dim Numbers, i&
Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _
100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
For i = 0 To 16
Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i)))
Next
End Sub
Function Middle3digits(strNb As String) As String
If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1)
If Len(strNb) < 3 Then
Middle3digits = "Error ! Number of digits must be >= 3"
ElseIf Len(strNb) Mod 2 = 0 Then
Middle3digits = "Error ! Number of digits must be odd"
Else
Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)
End If
End Function
|
Translate the given Python code snippet into VB without altering its behavior. | from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e
| Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & ReverseWord(W, count, l)
End If
Loop While count < Len(W)
OddWordFirst = temp
End Function
Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
Do
d = d + 1
Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
FindNextPunct = d
End Function
Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
ExtractWord = Mid(W, c, i)
c = c + Len(ExtractWord)
End Function
Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
sep = Right(Mid(W, c, i), 1)
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function
|
Port the following code from Python to VB with equivalent syntax and logic. | from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e
| Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & ReverseWord(W, count, l)
End If
Loop While count < Len(W)
OddWordFirst = temp
End Function
Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
Do
d = d + 1
Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
FindNextPunct = d
End Function
Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
ExtractWord = Mid(W, c, i)
c = c + Len(ExtractWord)
End Function
Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
sep = Right(Mid(W, c, i), 1)
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function
|
Convert the following code from Python to VB, ensuring the logic remains intact. |
from datetime import date, timedelta
from math import floor, sin, pi
def biorhythms(birthdate,targetdate):
print("Born: "+birthdate+" Target: "+targetdate)
birthdate = date.fromisoformat(birthdate)
targetdate = date.fromisoformat(targetdate)
days = (targetdate - birthdate).days
print("Day: "+str(days))
cycle_labels = ["Physical", "Emotional", "Mental"]
cycle_lengths = [23, 28, 33]
quadrants = [("up and rising", "peak"), ("up but falling", "transition"),
("down and falling", "valley"), ("down but rising", "transition")]
for i in range(3):
label = cycle_labels[i]
length = cycle_lengths[i]
position = days % length
quadrant = int(floor((4 * position) / length))
percentage = int(round(100 * sin(2 * pi * position / length),0))
transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)
trend, next = quadrants[quadrant]
if percentage > 95:
description = "peak"
elif percentage < -95:
description = "valley"
elif abs(percentage) < 5:
description = "critical transition"
else:
description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")"
print(label+" day "+str(position)+": "+description)
biorhythms("1943-03-09","1972-07-11")
| 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 = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. |
from datetime import date, timedelta
from math import floor, sin, pi
def biorhythms(birthdate,targetdate):
print("Born: "+birthdate+" Target: "+targetdate)
birthdate = date.fromisoformat(birthdate)
targetdate = date.fromisoformat(targetdate)
days = (targetdate - birthdate).days
print("Day: "+str(days))
cycle_labels = ["Physical", "Emotional", "Mental"]
cycle_lengths = [23, 28, 33]
quadrants = [("up and rising", "peak"), ("up but falling", "transition"),
("down and falling", "valley"), ("down but rising", "transition")]
for i in range(3):
label = cycle_labels[i]
length = cycle_lengths[i]
position = days % length
quadrant = int(floor((4 * position) / length))
percentage = int(round(100 * sin(2 * pi * position / length),0))
transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)
trend, next = quadrants[quadrant]
if percentage > 95:
description = "peak"
elif percentage < -95:
description = "valley"
elif abs(percentage) < 5:
description = "critical transition"
else:
description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")"
print(label+" day "+str(position)+": "+description)
biorhythms("1943-03-09","1972-07-11")
| 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 = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
|
Translate this program into VB but keep the logic exactly as in Python. | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute()
<sqlite3.Cursor object at 0x013265C0>
>>>
| 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 ADDRESS (STREET VARCHAR(30) NOT NULL," &_
"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
.Close
End With
|
Produce a functionally identical VB code for the snippet given in Python. | def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
| Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Dim l As List(Of Integer) = {1, 1}.ToList()
Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer
Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)
End Function
Sub Main(ByVal args As String())
Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,
selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}
Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1
Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take)
Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take)))
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:")
For Each ii As Integer In selection
Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1
Console.WriteLine("{0,3}: {1:n0}", ii, j)
Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max
If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For
Next
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" &
" series up to the {0}th item is {1}always one.", max, If(good, "", "not "))
End Sub
End Module
|
Transform the following Python implementation into VB, maintaining the same output and logic. | from itertools import groupby
def soundex(word):
codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r")
soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)
cmap2 = lambda kar: soundDict.get(kar, '9')
sdx = ''.join(cmap2(kar) for kar in word.lower())
sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')
sdx3 = sdx2[0:4].ljust(4,'0')
return sdx3
|
tt=array( _
"Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _
"Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example")
tv=array( _
"A261","A261","G200","G200","H416","H416","L000","L300", _
"M220","P236","R163","R163","R150","T522","S532","E251")
For i=lbound(tt) To ubound(tt)
ts=soundex(tt(i))
If ts<>tv(i) Then ok=" KO "& tv(i) Else ok=""
Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok
Next
Function getCode(c)
Select Case c
Case "B", "F", "P", "V"
getCode = "1"
Case "C", "G", "J", "K", "Q", "S", "X", "Z"
getCode = "2"
Case "D", "T"
getCode = "3"
Case "L"
getCode = "4"
Case "M", "N"
getCode = "5"
Case "R"
getCode = "6"
Case "W","H"
getCode = "-"
End Select
End Function
Function soundex(s)
Dim code, previous, i
code = UCase(Mid(s, 1, 1))
previous = getCode(UCase(Mid(s, 1, 1)))
For i = 2 To Len(s)
current = getCode(UCase(Mid(s, i, 1)))
If current <> "" And current <> "-" And current <> previous Then code = code & current
If current <> "-" Then previous = current
Next
soundex = Mid(code & "000", 1, 4)
End Function
|
Preserve the algorithm and functionality while converting the code from Python to VB. |
import socket
import thread
import time
HOST = ""
PORT = 4004
def accept(conn):
def threaded():
while True:
conn.send("Please enter your name: ")
try:
name = conn.recv(1024).strip()
except socket.error:
continue
if name in users:
conn.send("Name entered is already in use.\n")
elif name:
conn.setblocking(False)
users[name] = conn
broadcast(name, "+++ %s arrived +++" % name)
break
thread.start_new_thread(threaded, ())
def broadcast(name, message):
print message
for to_name, conn in users.items():
if to_name != name:
try:
conn.send(message + "\n")
except socket.error:
pass
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((HOST, PORT))
server.listen(1)
print "Listening on %s" % ("%s:%s" % server.getsockname())
users = {}
while True:
try:
while True:
try:
conn, addr = server.accept()
except socket.error:
break
accept(conn)
for name, conn in users.items():
try:
message = conn.recv(1024)
except socket.error:
continue
if not message:
del users[name]
broadcast(name, "--- %s leaves ---" % name)
else:
broadcast(name, "%s> %s" % (name, message.strip()))
time.sleep(.1)
except (SystemExit, KeyboardInterrupt):
break
| Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Module Module1
Class State
Private ReadOnly client As TcpClient
Private ReadOnly sb As New StringBuilder
Public Sub New(name As String, client As TcpClient)
Me.Name = name
Me.client = client
End Sub
Public ReadOnly Property Name As String
Public Sub Send(text As String)
Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text))
client.GetStream().Write(bytes, 0, bytes.Length)
End Sub
End Class
ReadOnly connections As New Dictionary(Of Integer, State)
Dim listen As TcpListener
Dim serverThread As Thread
Sub Main()
listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004)
serverThread = New Thread(New ThreadStart(AddressOf DoListen))
serverThread.Start()
End Sub
Private Sub DoListen()
listen.Start()
Console.WriteLine("Server: Started server")
Do
Console.Write("Server: Waiting...")
Dim client = listen.AcceptTcpClient()
Console.WriteLine(" Connected")
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))
clientThread.Start(client)
Loop
End Sub
Private Sub DoClient(client As TcpClient)
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId)
Dim bytes = Encoding.ASCII.GetBytes("Enter name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
Dim done As Boolean
Dim name As String
Do
If Not client.Connected Then
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End If
name = Receive(client)
done = True
For Each cl In connections
Dim state = cl.Value
If state.Name = name Then
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
done = False
End If
Next
Loop While Not done
connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Broadcast(String.Format("+++ {0} arrived +++", name))
Do
Dim text = Receive(client)
If text = "/quit" Then
Broadcast(String.Format("Connection from {0} closed.", name))
connections.Remove(Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Exit Do
End If
If Not client.Connected Then
Exit Do
End If
Broadcast(String.Format("{0}> {1}", name, text))
Loop
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End Sub
Private Function Receive(client As TcpClient) As String
Dim sb As New StringBuilder
Do
If client.Available > 0 Then
While client.Available > 0
Dim ch = Chr(client.GetStream.ReadByte())
If ch = vbCr Then
Continue While
End If
If ch = vbLf Then
Return sb.ToString()
End If
sb.Append(ch)
End While
Thread.Sleep(100)
End If
Loop
End Function
Private Sub Broadcast(text As String)
Console.WriteLine(text)
For Each client In connections
If client.Key <> Thread.CurrentThread.ManagedThreadId Then
Dim state = client.Value
state.Send(text)
End If
Next
End Sub
End Module
|
Port the provided Python code into VB while preserving the original functionality. | def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
| Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
|
Generate an equivalent VB version of this Python code. | def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
| Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
|
Produce a functionally identical VB code for the snippet given in Python. | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
| Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
|
Keep all operations the same but rewrite the snippet in VB. | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
| Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
|
Generate a VB translation of this Python snippet without changing its computational steps. | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
| Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
| 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.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from Python to VB. | import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
| 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.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
|
Translate the given Python code snippet into VB without altering its behavior. |
states = { 'ready':{
'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
'responses' : ['d','q']},
'waiting':{
'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
'responses' : ['s','r']},
'dispense' : {
'prompt' : 'Machine dispensing: please (r)emove product',
'responses' : ['r']},
'refunding' : {
'prompt' : 'Refunding money',
'responses' : []},
'exit' :{}
}
transitions = { 'ready': {
'd': 'waiting',
'q': 'exit'},
'waiting' : {
's' : 'dispense',
'r' : 'refunding'},
'dispense' : {
'r' : 'ready'},
'refunding' : {
'' : 'ready'}}
def Acceptor(prompt, valids):
if not valids:
print(prompt)
return ''
else:
while True:
resp = input(prompt)[0].lower()
if resp in valids:
return resp
def finite_state_machine(initial_state, exit_state):
response = True
next_state = initial_state
current_state = states[next_state]
while response != exit_state:
response = Acceptor(current_state['prompt'], current_state['responses'])
next_state = transitions[next_state][response]
current_state = states[next_state]
if __name__ == "__main__":
finite_state_machine('ready','q')
| Enum states
READY
WAITING
DISPENSE
REFUND
QU1T
End Enum
Public Sub finite_state_machine()
Dim state As Integer: state = READY: ch = " "
Do While True
Debug.Print ch
Select Case state
Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :"
Do While True
If ch = "D" Then
state = WAITING
Exit Do
End If
If ch = "Q" Then
state = QU1T
Exit Do
End If
ch = InputBox("Machine is READY. (D)eposit or (Q)uit :")
Loop
Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :"
Do While True
If ch = "S" Then
state = DISPENSE
Exit Do
End If
If ch = "R" Then
state = REFUND
Exit Do
End If
ch = InputBox("(S)elect product or choose to (R)efund :")
Loop
Case DISPENSE: Debug.Print "Dispensing product..."
Do While True
If ch = "C" Then
state = READY
Exit Do
End If
ch = InputBox("Please (C)ollect product. :")
Loop
Case REFUND: Debug.Print "Please collect refund."
state = READY
ch = " "
Case QU1T: Debug.Print "Thank you, shutting down now."
Exit Sub
End Select
Loop
End Sub
|
Convert this Python snippet to VB and keep its semantics consistent. |
states = { 'ready':{
'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
'responses' : ['d','q']},
'waiting':{
'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
'responses' : ['s','r']},
'dispense' : {
'prompt' : 'Machine dispensing: please (r)emove product',
'responses' : ['r']},
'refunding' : {
'prompt' : 'Refunding money',
'responses' : []},
'exit' :{}
}
transitions = { 'ready': {
'd': 'waiting',
'q': 'exit'},
'waiting' : {
's' : 'dispense',
'r' : 'refunding'},
'dispense' : {
'r' : 'ready'},
'refunding' : {
'' : 'ready'}}
def Acceptor(prompt, valids):
if not valids:
print(prompt)
return ''
else:
while True:
resp = input(prompt)[0].lower()
if resp in valids:
return resp
def finite_state_machine(initial_state, exit_state):
response = True
next_state = initial_state
current_state = states[next_state]
while response != exit_state:
response = Acceptor(current_state['prompt'], current_state['responses'])
next_state = transitions[next_state][response]
current_state = states[next_state]
if __name__ == "__main__":
finite_state_machine('ready','q')
| Enum states
READY
WAITING
DISPENSE
REFUND
QU1T
End Enum
Public Sub finite_state_machine()
Dim state As Integer: state = READY: ch = " "
Do While True
Debug.Print ch
Select Case state
Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :"
Do While True
If ch = "D" Then
state = WAITING
Exit Do
End If
If ch = "Q" Then
state = QU1T
Exit Do
End If
ch = InputBox("Machine is READY. (D)eposit or (Q)uit :")
Loop
Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :"
Do While True
If ch = "S" Then
state = DISPENSE
Exit Do
End If
If ch = "R" Then
state = REFUND
Exit Do
End If
ch = InputBox("(S)elect product or choose to (R)efund :")
Loop
Case DISPENSE: Debug.Print "Dispensing product..."
Do While True
If ch = "C" Then
state = READY
Exit Do
End If
ch = InputBox("Please (C)ollect product. :")
Loop
Case REFUND: Debug.Print "Please collect refund."
state = READY
ch = " "
Case QU1T: Debug.Print "Thank you, shutting down now."
Exit Sub
End Select
Loop
End Sub
|
Keep all operations the same but rewrite the snippet in VB. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
| 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 BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
|
Please provide an equivalent version of this Python code in VB. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
| 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 BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
|
Generate a VB translation of this Python snippet without changing its computational steps. | from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i in range(5):
t.forward(s)
t.right(72)
t.end_fill()
def sierpinski(i, t, s):
t.setheading(0)
new_size = s * side_ratio
if i > 1:
i -= 1
for j in range(4):
t.right(36)
short = s * side_ratio / part_ratio
dist = [short, s, s, short][j]
spawn = Turtle()
if hide_turtles:spawn.hideturtle()
spawn.penup()
spawn.setposition(t.position())
spawn.setheading(t.heading())
spawn.forward(dist)
sierpinski(i, spawn, new_size)
sierpinski(i, t, new_size)
else:
pentagon(t, s)
del t
def main():
t = Turtle()
t.hideturtle()
t.penup()
screen = t.getscreen()
y = screen.window_height()
t.goto(0, y/2-20)
i = 5
size = 300
size *= part_ratio
sierpinski(i, t, size)
main()
| 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
Height = Circumradius + Inradius
Diagonal = (1 + Sqr(5)) / 2
HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4
Pi = WorksheetFunction.Pi
Ratio = Height / (2 * Height + HeightDiagonal)
Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _
2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)
p(0) = Shp.Name
Shp.Rotation = 180
Shp.Line.Weight = 0
For j = 1 To Order_
For i = 0 To 4
Set Shp = Shp.Duplicate
p(i + 1) = Shp.Name
If i = 0 Then Shp.Rotation = 0
Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)
Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)
Shp.Visible = msoTrue
Next i
Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group
p(0) = Shp.Name
If j < Order_ Then
Shp.ScaleHeight Ratio, False
Shp.ScaleWidth Ratio, False
Shp.Rotation = 180
Shp.Left = 2 * Side
Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side
End If
Next j
End Sub
Public Sub main()
sierpinski Order_:=5, Side:=200
End Sub
|
Write the same code in VB as shown below in Python. | def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr =
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of %i i.e. %s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
| Function rep_string(s)
max_len = Int(Len(s)/2)
tmp = ""
If max_len = 0 Then
rep_string = "No Repeating String"
Exit Function
End If
For i = 1 To max_len
If InStr(i+1,s,tmp & Mid(s,i,1))Then
tmp = tmp & Mid(s,i,1)
Else
Exit For
End If
Next
Do While Len(tmp) > 0
If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
rep_string = tmp
Exit Do
Else
tmp = Mid(tmp,1,Len(tmp)-1)
End If
Loop
If Len(tmp) > 0 Then
rep_string = tmp
Else
rep_string = "No Repeating String"
End If
End Function
arr = Array("1001110011","1110111011","0010010010","1010101010",_
"1111111111","0100101101","0100100","101","11","00","1")
For n = 0 To UBound(arr)
WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
WScript.StdOut.WriteLine
Next
|
Translate this program into VB but keep the logic exactly as in Python. | 'c' == "c"
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
| Debug.Print "Tom said, ""The fox ran away."""
Debug.Print "Tom said,
|
Produce a language-to-language conversion: from Python to VB, same semantics. |
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack()
root.mainloop()
| TYPE syswindowstru
screenheight AS INTEGER
screenwidth AS INTEGER
maxheight AS INTEGER
maxwidth AS INTEGER
END TYPE
DIM syswindow AS syswindowstru
syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
|
Write the same code in VB as shown below in Python. | >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>>
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
|
Enum fruits
apple
banana
cherry
End Enum
Enum fruits2
pear = 5
mango = 10
kiwi = 20
pineapple = 20
End Enum
Sub test()
Dim f As fruits
f = apple
Debug.Print "apple equals "; f
Debug.Print "kiwi equals "; kiwi
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
End Sub
|
Write the same algorithm in VB as shown in this Python implementation. | import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
| Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
|
Port the provided Python code into VB while preserving the original functionality. | import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
| Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
|
Produce a language-to-language conversion: from Python to VB, same semantics. | from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port ))
| 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) Then
port = Split(addr,":")
octet = Split(port(0),".")
ipv4_hex = ""
For i = 0 To UBound(octet)
If octet(i) <= 255 And octet(i) >= 0 Then
ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2)
Else
ipv4_hex = "Erroneous Address"
Exit For
End If
Next
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: " & ipv4_hex & vbCrLf
If UBound(port) = 1 Then
If port(1) <= 65535 And port(1) >= 0 Then
parse_ip = parse_ip & "Port: " & port(1) & vbCrLf
Else
parse_ip = parse_ip & "Port: Invalid" & vbCrLf
End If
End If
End If
If ipv6_pattern.Test(addr) Then
parse_ip = "Test Case: " & addr & vbCrLf
port_v6 = "Port: "
ipv6_hex = ""
If InStr(1,addr,"[") Then
port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1)))
addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1))
End If
word = Split(addr,":")
word_count = 0
For i = 0 To UBound(word)
If word(i) = "" Then
If i < UBound(word) Then
If Int((7-(i+1))/2) = 1 Then
k = 1
ElseIf UBound(word) < 6 Then
k = Int((7-(i+1))/2)
ElseIf UBound(word) >= 6 Then
k = Int((7-(i+1))/2)-1
End If
For j = 0 To k
ipv6_hex = ipv6_hex & "0000"
word_count = word_count + 1
Next
Else
For j = 0 To (7-word_count)
ipv6_hex = ipv6_hex & "0000"
Next
End If
Else
ipv6_hex = ipv6_hex & Right("0000" & word(i),4)
word_count = word_count + 1
End If
Next
parse_ip = parse_ip & "Address: " & ipv6_hex &_
vbCrLf & port_v6 & vbCrLf
End If
If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: Invalid Address" & vbCrLf
End If
End Function
ip_arr = Array("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","RosettaCode")
For n = 0 To UBound(ip_arr)
WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf
Next
|
Write the same code in VB as shown below in Python. | from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower().split()
def mapnum2words(words):
number2words = defaultdict(list)
reject = 0
for word in words:
try:
number2words[''.join(CH2NUM[ch] for ch in word)].append(word)
except KeyError:
reject += 1
return dict(number2words), reject
def interactiveconversions():
global inp, ch, num
while True:
inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower()
if inp:
if all(ch in '23456789' for ch in inp):
if inp in num2words:
print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join(
num2words[inp])))
else:
print(" Number {0} has no textonyms in the dictionary.".format(inp))
elif all(ch in CH2NUM for ch in inp):
num = ''.join(CH2NUM[ch] for ch in inp)
print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format(
inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num])))
else:
print(" I don't understand %r" % inp)
else:
print("Thank you")
break
if __name__ == '__main__':
words = getwords(URL)
print("Read %i words from %r" % (len(words), URL))
wordset = set(words)
num2words, reject = mapnum2words(words)
morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)
maxwordpernum = max(len(values) for values in num2words.values())
print(.format(len(words) - reject, URL, len(num2words), morethan1word))
print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum)
maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)
for num, wrds in maxwpn:
print(" %s maps to: %s" % (num, ', '.join(wrds)))
interactiveconversions()
| 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", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9"
End With
TotalWords = 0
UniqueCombinations = 0
Set objUniqueWords = CreateObject("Scripting.Dictionary")
Set objMoreThanOneWord = CreateObject("Scripting.Dictionary")
Do Until objInFile.AtEndOfStream
Word = objInFile.ReadLine
c = 0
Num = ""
If Word <> "" Then
For i = 1 To Len(Word)
For Each Key In objKeyMap.Keys
If InStr(1,Key,Mid(Word,i,1),1) > 0 Then
Num = Num & objKeyMap.Item(Key)
c = c + 1
End If
Next
Next
If c = Len(Word) Then
TotalWords = TotalWords + 1
If objUniqueWords.Exists(Num) = False Then
objUniqueWords.Add Num, ""
UniqueCombinations = UniqueCombinations + 1
Else
If objMoreThanOneWord.Exists(Num) = False Then
objMoreThanOneWord.Add Num, ""
End If
End If
End If
End If
Loop
WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_
"They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_
objMoreThanOneWord.Count & " digit combinations represent Textonyms."
objInFile.Close
|
Generate a VB translation of this Python snippet without changing its computational steps. | def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst))
| Public Function RangeExtraction(AList) As String
Const RangeDelim = "-"
Dim result As String
Dim InRange As Boolean
Dim Posn, ub, lb, rangestart, rangelen As Integer
result = ""
ub = UBound(AList)
lb = LBound(AList)
Posn = lb
While Posn < ub
rangestart = Posn
rangelen = 0
InRange = True
While InRange
rangelen = rangelen + 1
If Posn = ub Then
InRange = False
Else
InRange = (AList(Posn + 1) = AList(Posn) + 1)
Posn = Posn + 1
End If
Wend
If rangelen > 2 Then
result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))
Else
For i = rangestart To rangestart + rangelen - 1
result = result & "," & Format$(AList(i))
Next
End If
Posn = rangestart + rangelen
Wend
RangeExtraction = Mid$(result, 2)
End Function
Public Sub RangeTest()
Dim MyList As Variant
MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)
Debug.Print "a) "; RangeExtraction(MyList)
Dim MyOtherList(1 To 20) As Integer
MyOtherList(1) = -6
MyOtherList(2) = -3
MyOtherList(3) = -2
MyOtherList(4) = -1
MyOtherList(5) = 0
MyOtherList(6) = 1
MyOtherList(7) = 3
MyOtherList(8) = 4
MyOtherList(9) = 5
MyOtherList(10) = 7
MyOtherList(11) = 8
MyOtherList(12) = 9
MyOtherList(13) = 10
MyOtherList(14) = 11
MyOtherList(15) = 14
MyOtherList(16) = 15
MyOtherList(17) = 17
MyOtherList(18) = 18
MyOtherList(19) = 19
MyOtherList(20) = 20
Debug.Print "b) "; RangeExtraction(MyOtherList)
End Sub
|
Change the following Python code into VB without altering its purpose. | fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
|
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
"\triangle.txt",1,False)
row = Split(objinfile.ReadAll,vbCrLf)
For i = UBound(row) To 0 Step -1
row(i) = Split(row(i)," ")
If i < UBound(row) Then
For j = 0 To UBound(row(i))
If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))
Else
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))
End If
Next
End If
Next
WScript.Echo row(0)(0)
objinfile.Close
Set objfso = Nothing
|
Ensure the translated VB code behaves exactly like the original Python snippet. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after))
| 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 String
For i = 1 To UBound(n)
next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)
wtb = wtb - (prev = "." And next_ <= "#")
bn = bn - (i > 1 And next_ <= "#")
If (i And 1) = 0 Then p2468 = p2468 & prev
prev = next_
Next i
If step = 2 Then
p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)
End If
Dim ret(2) As Variant
ret(0) = wtb
ret(1) = bn
ret(2) = p2468
AB = ret
End Function
Private Sub Zhang_Suen(text As Variant)
Dim wtb As Integer
Dim bn As Integer
Dim changed As Boolean, changes As Boolean
Dim p2468 As String
Dim x As Integer, y As Integer, step As Integer
Do While True
changed = False
For step = 1 To 2
changes = False
For y = 1 To UBound(text) - 1
For x = 2 To Len(text(y)) - 1
If Mid(text(y), x, 1) = "#" Then
ret = AB(text, y, x, step)
wtb = ret(0)
bn = ret(1)
p2468 = ret(2)
If wtb = 1 _
And bn >= 2 And bn <= 6 _
And InStr(1, Mid(p2468, 1, 3), ".") _
And InStr(1, Mid(p2468, 2, 3), ".") Then
changes = True
text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x)
End If
End If
Next x
Next y
If changes Then
For y = 1 To UBound(text) - 1
text(y) = Replace(text(y), "!", ".")
Next y
changed = True
End If
Next step
If Not changed Then Exit Do
Loop
Debug.Print Join(text, vbCrLf)
End Sub
Public Sub main()
init
Dim Small_rc(9) As String
Small_rc(0) = "................................"
Small_rc(1) = ".#########.......########......."
Small_rc(2) = ".###...####.....####..####......"
Small_rc(3) = ".###....###.....###....###......"
Small_rc(4) = ".###...####.....###............."
Small_rc(5) = ".#########......###............."
Small_rc(6) = ".###.####.......###....###......"
Small_rc(7) = ".###..####..###.####..####.###.."
Small_rc(8) = ".###...####.###..########..###.."
Small_rc(9) = "................................"
Zhang_Suen (Small_rc)
End Sub
|
Transform the following Python implementation into VB, maintaining the same output and logic. | s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
| Option Strict On
Option Explicit On
Imports System.IO
Module vMain
Public Sub Main
Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}
For i As Integer = 0 To Ubound(s)
Dim curr As Integer = s(i)
Dim prev As Integer
If i > 1 AndAlso curr = prev Then
Console.Out.WriteLine(i)
End If
prev = curr
Next i
End Sub
End Module
|
Write the same algorithm in VB as shown in this Python implementation. | l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0
if s < 5:
pushMatrix()
translate(x1, 0)
line(0, 0, s, 0)
line(2 * s, 0, 3 * s, 0)
translate(s, 0)
rotate(radians(60))
line(0, 0, s, 0)
translate(s, 0)
rotate(radians(-120))
line(0, 0, s, 0)
popMatrix()
return
pushMatrix()
translate(x1, 0)
kcurve(0, s)
kcurve(2 * s, 3 * s)
translate(s, 0)
rotate(radians(60))
kcurve(0, s)
translate(s, 0)
rotate(radians(-120))
kcurve(0, s)
popMatrix()
| 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 property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
if ori>(pi*2) then ori=ori-pi*2
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
sub koch (n,le)
if n=0 then x.fw le :exit sub
koch n-1, le/3
x.lt 1
koch n-1, le/3
x.rt 2
koch n-1, le/3
x.lt 1
koch n-1, le/3
end sub
dim x,i
set x=new turtle
x.iangle=60
x.orient=0
x.incr=3
x.x=100:x.y=300
for i=0 to 3
koch 7,100
x.rt 2
next
set x=nothing
|
Write the same algorithm in VB as shown in this Python implementation. | from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
| Sub draw()
Dim sh As Shape, sl As Shape
Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)
Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)
sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)
End Sub
|
Change the programming language of this snippet from Python to VB without modifying what it does. |
import urllib.request
from collections import Counter
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
dictionary = open("unixdict.txt","r")
wordList = dictionary.read().split('\n')
dictionary.close()
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]
for word in filteredWords[:-9]:
position = filteredWords.index(word)
newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
if newWord in filteredWords:
print(newWord)
| 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
next
redim preserve b(i-1)
wscript.echo i
j=1
for i=0 to ubound(b)-9
s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_
mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)
if d.exists(s9) then
wscript.echo j,s9
d.remove(s9)
j=j+1
end if
next
|
Change the following Python code into VB without altering its purpose. |
from unicodedata import name
def unicode_code(ch):
return 'U+{:04x}'.format(ord(ch))
def utf8hex(ch):
return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()
if __name__ == "__main__":
print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))
chars = ['A', 'ö', 'Ж', '€', '𝄞']
for char in chars:
print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
| Private Function unicode_2_utf8(x As Long) As Byte()
Dim y() As Byte
Dim r As Long
Select Case x
Case 0 To &H7F
ReDim y(0)
y(0) = x
Case &H80 To &H7FF
ReDim y(1)
y(0) = 192 + x \ 64
y(1) = 128 + x Mod 64
Case &H800 To &H7FFF
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case 32768 To 65535
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case &H10000 To &H10FFFF
ReDim y(3)
y(3) = 128 + x Mod 64
r = x \ 64
y(2) = 128 + r Mod 64
r = r \ 64
y(1) = 128 + r Mod 64
y(0) = 240 + r \ 64
Case Else
MsgBox "what else?" & x & " " & Hex(x)
End Select
unicode_2_utf8 = y
End Function
Private Function utf8_2_unicode(x() As Byte) As Long
Dim first As Long, second As Long, third As Long, fourth As Long
Dim total As Long
Select Case UBound(x) - LBound(x)
Case 0
If x(0) < 128 Then
total = x(0)
Else
MsgBox "highest bit set error"
End If
Case 1
If x(0) \ 32 = 6 Then
first = x(0) Mod 32
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
Else
MsgBox "mask error"
End If
Else
MsgBox "leading byte error"
End If
total = 64 * first + second
Case 2
If x(0) \ 16 = 14 Then
first = x(0) Mod 16
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error middle byte"
End If
Else
MsgBox "leading byte error"
End If
total = 4096 * first + 64 * second + third
Case 3
If x(0) \ 8 = 30 Then
first = x(0) Mod 8
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
If x(3) \ 64 = 2 Then
fourth = x(3) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error third byte"
End If
Else
MsgBox "mask error second byte"
End If
Else
MsgBox "mask error leading byte"
End If
total = CLng(262144 * first + 4096 * second + 64 * third + fourth)
Case Else
MsgBox "more bytes than expected"
End Select
utf8_2_unicode = total
End Function
Public Sub program()
Dim cp As Variant
Dim r() As Byte, s As String
cp = [{65, 246, 1046, 8364, 119070}]
Debug.Print "ch unicode UTF-8 encoded decoded"
For Each cpi In cp
r = unicode_2_utf8(CLng(cpi))
On Error Resume Next
s = CStr(Hex(cpi))
Debug.Print ChrW(cpi); String$(10 - Len(s), " "); s,
If Err.Number = 5 Then Debug.Print "?"; String$(10 - Len(s), " "); s,
s = ""
For Each yz In r
s = s & CStr(Hex(yz)) & " "
Next yz
Debug.Print String$(13 - Len(s), " "); s;
s = CStr(Hex(utf8_2_unicode(r)))
Debug.Print String$(8 - Len(s), " "); s
Next cpi
End Sub
|
Ensure the translated VB code behaves exactly like the original Python snippet. | def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
print "\nMagic constant = %d"%sum(s[0])
printsq(MagicSquareDoublyEven(8))
|
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.echo "Magic constant=" & (n*n+1)*n/2
|
Maintain the same structure and functionality when rewriting this code in VB. | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
| Function mtf_encode(s)
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122
symbol_table.Add Chr(j)
Next
output = ""
For i = 1 To Len(s)
char = Mid(s,i,1)
If i = Len(s) Then
output = output & symbol_table.IndexOf(char,0)
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
Else
output = output & symbol_table.IndexOf(char,0) & " "
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_encode = output
End Function
Function mtf_decode(s)
code = Split(s," ")
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122
symbol_table.Add Chr(j)
Next
output = ""
For i = 0 To UBound(code)
char = symbol_table(code(i))
output = output & char
If code(i) <> 0 Then
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_decode = output
End Function
wordlist = Array("broood","bananaaa","hiphophiphop")
For Each word In wordlist
WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_
mtf_decode(mtf_encode(word)) & "."
WScript.StdOut.WriteBlankLines(1)
Next
|
Change the following Python code into VB without altering its purpose. | import os
exit_code = os.system('ls')
output = os.popen('ls').read()
| Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
|
Transform the following Python implementation into VB, maintaining the same output and logic. |
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ("Finished validating good xml")
except lxml.etree.XMLSyntaxError as err:
print (err)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
except lxml.etree.XMLSyntaxError as err:
print (err)
| 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.setProperty "ProhibitDTD", False
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then
xmlDoc.setProperty "ProhibitDTD", True
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0")
xmlDoc2.validateOnParse = True
xmlDoc2.async = False
xmlDoc2.load(Replace (strfilename,".xml",".xsd"))
Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0")
objSchemas.Add "", xmlDoc2
Else
Set xmlvalid= Nothing:Exit Function
End If
Set xmlvalid=xmldoc.parseError
End Function
Sub displayerror (parserr)
Dim strresult
If parserr is Nothing Then
strresult= "could not find dtd or xsd for " & strFileName
Else
With parserr
Select Case .errorcode
Case 0
strResult = "Valid: " & strFileName & vbCr
Case Else
strResult = vbCrLf & "ERROR! Failed to validate " & _
strFileName & vbCrLf &.reason & vbCr & _
"Error code: " & .errorCode & ", Line: " & _
.line & ", Character: " & _
.linepos & ", Source: """ & _
.srcText & """ - " & vbCrLf
End Select
End With
End If
WScript.Echo strresult
End Sub
Dim strfilename
strfilename="shiporder.xml"
displayerror xmlvalid (strfilename)
|
Convert this Python snippet to VB and keep its semantics consistent. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
| Function LIS(arr)
n = UBound(arr)
Dim p()
ReDim p(n)
Dim m()
ReDim m(n)
l = 0
For i = 0 To n
lo = 1
hi = l
Do While lo <= hi
middle = Int((lo+hi)/2)
If arr(m(middle)) < arr(i) Then
lo = middle + 1
Else
hi = middle - 1
End If
Loop
newl = lo
p(i) = m(newl-1)
m(newl) = i
If newL > l Then
l = newl
End If
Next
Dim s()
ReDim s(l)
k = m(l)
For i = l-1 To 0 Step - 1
s(i) = arr(k)
k = p(k)
Next
LIS = Join(s,",")
End Function
WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))
WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
|
Generate a VB translation of this Python snippet without changing its computational steps. | import sys, math, collections
Sphere = collections.namedtuple("Sphere", "cx cy cz r")
V3 = collections.namedtuple("V3", "x y z")
def normalize((x, y, z)):
len = math.sqrt(x**2 + y**2 + z**2)
return V3(x / len, y / len, z / len)
def dot(v1, v2):
d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z
return -d if d < 0 else 0.0
def hit_sphere(sph, x0, y0):
x = x0 - sph.cx
y = y0 - sph.cy
zsq = sph.r ** 2 - (x ** 2 + y ** 2)
if zsq < 0:
return (False, 0, 0)
szsq = math.sqrt(zsq)
return (True, sph.cz - szsq, sph.cz + szsq)
def draw_sphere(k, ambient, light):
shades = ".:!*oe&
pos = Sphere(20.0, 20.0, 0.0, 20.0)
neg = Sphere(1.0, 1.0, -6.0, 20.0)
for i in xrange(int(math.floor(pos.cy - pos.r)),
int(math.ceil(pos.cy + pos.r) + 1)):
y = i + 0.5
for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),
int(math.ceil(pos.cx + 2 * pos.r) + 1)):
x = (j - pos.cx) / 2.0 + 0.5 + pos.cx
(h, zb1, zb2) = hit_sphere(pos, x, y)
if not h:
hit_result = 0
else:
(h, zs1, zs2) = hit_sphere(neg, x, y)
if not h:
hit_result = 1
elif zs1 > zb1:
hit_result = 1
elif zs2 > zb2:
hit_result = 0
elif zs2 > zb1:
hit_result = 2
else:
hit_result = 1
if hit_result == 0:
sys.stdout.write(' ')
continue
elif hit_result == 1:
vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)
elif hit_result == 2:
vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)
vec = normalize(vec)
b = dot(light, vec) ** k + ambient
intensity = int((1 - b) * len(shades))
intensity = min(len(shades), max(0, intensity))
sys.stdout.write(shades[intensity])
print
light = normalize(V3(-50, 30, 50))
draw_sphere(2, 0.5, light)
|
option explicit
const x_=0
const y_=1
const z_=2
const r_=3
function clamp(x,b,t)
if x<b then
clamp=b
elseif x>t then
clamp =t
else
clamp=x
end if
end function
function dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function
function normal (byval v)
dim ilen:ilen=1/sqr(dot(v,v)):
v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:
normal=v:
end function
function hittest(s,x,y)
dim z
z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2
if z>=0 then
z=sqr(z)
hittest=array(s(z_)-z,s(z_)+z)
else
hittest=0
end if
end function
sub deathstar(pos, neg, sun, k, amb)
dim x,y,shades,result,shade,hp,hn,xx,b
shades=array(" ",".",":","!","*","o","e","&","#","%","@")
for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5
for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5
hp=hittest (pos, x, y)
hn=hittest(neg,x,y)
if not isarray(hp) then
result=0
elseif not isarray(hn) then
result=1
elseif hn(0)>hp(0) then
result=1
elseif hn(1)>hp(1) then
result=0
elseif hn(1)>hp(0) then
result=2
else
result=1
end if
shade=-1
select case result
case 0
shade=0
case 1
xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))
case 2
xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))
end select
if shade <>0 then
b=dot(sun,xx)^k+amb
shade=clamp((1-b) *ubound(shades),1,ubound(shades))
end if
wscript.stdout.write string(2,shades(shade))
next
wscript.stdout.write vbcrlf
next
end sub
deathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1
|
Convert this Python block to VB, preserving its control flow and logic. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-0.2495892950, -0.3832854473, 1.0845181219),
Circle( 1.7813504266, 1.6178237031, 0.8162655711),
Circle(-0.1985249206, -0.8343333301, 0.0538864941),
Circle(-1.7011985145, -0.1263820964, 0.4776976918),
Circle(-0.4319462812, 1.4104420482, 0.7886291537),
Circle( 0.2178372997, -0.9499557344, 0.0357871187),
Circle(-0.6294854565, -1.3078893852, 0.7653357688),
Circle( 1.7952608455, 0.6281269104, 0.2727652452),
Circle( 1.4168575317, 1.0683357171, 1.1016025378),
Circle( 1.4637371396, 0.9463877418, 1.1846214562),
Circle(-0.5263668798, 1.7315156631, 1.4428514068),
Circle(-1.2197352481, 0.9144146579, 1.0727263474),
Circle(-0.1389358881, 0.1092805780, 0.7350208828),
Circle( 1.5293954595, 0.0030278255, 1.2472867347),
Circle(-0.5258728625, 1.3782633069, 1.3495508831),
Circle(-0.1403562064, 0.2437382535, 1.3804956588),
Circle( 0.8055826339, -0.0482092025, 0.3327165165),
Circle(-0.6311979224, 0.7184578971, 0.2491045282),
Circle( 1.4685857879, -0.8347049536, 1.3670667538),
Circle(-0.6855727502, 1.6465021616, 1.0593087096),
Circle( 0.0152957411, 0.0638919221, 0.9771215985)]
def main():
x_min = min(c.x - c.r for c in circles)
x_max = max(c.x + c.r for c in circles)
y_min = min(c.y - c.r for c in circles)
y_max = max(c.y + c.r for c in circles)
box_side = 500
dx = (x_max - x_min) / box_side
dy = (y_max - y_min) / box_side
count = 0
for r in xrange(box_side):
y = y_min + r * dy
for c in xrange(box_side):
x = x_min + c * dx
if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)
for circle in circles):
count += 1
print "Approximated area:", count * dx * dy
main()
| 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.0848270516), _
Array(-1.4944608174, 1.2077959613, 1.1039549836), _
Array(0.6110294452, -0.6907087527, 0.9089162485), _
Array(0.3844862411, 0.2923344616, 0.2375743054), _
Array(-0.249589295, -0.3832854473, 1.0845181219), _
Array(1.7813504266, 1.6178237031, 0.8162655711), _
Array(-0.1985249206, -0.8343333301, 0.0538864941), _
Array(-1.7011985145, -0.1263820964, 0.4776976918), _
Array(-0.4319462812, 1.4104420482, 0.7886291537), _
Array(0.2178372997, -0.9499557344, 0.0357871187), _
Array(-0.6294854565, -1.3078893852, 0.7653357688), _
Array(1.7952608455, 0.6281269104, 0.2727652452), _
Array(1.4168575317, 1.0683357171, 1.1016025378), _
Array(1.4637371396, 0.9463877418, 1.1846214562), _
Array(-0.5263668798, 1.7315156631, 1.4428514068), _
Array(-1.2197352481, 0.9144146579, 1.0727263474), _
Array(-0.1389358881, 0.109280578, 0.7350208828), _
Array(1.5293954595, 0.0030278255, 1.2472867347), _
Array(-0.5258728625, 1.3782633069, 1.3495508831), _
Array(-0.1403562064, 0.2437382535, 1.3804956588), _
Array(0.8055826339, -0.0482092025, 0.3327165165), _
Array(-0.6311979224, 0.7184578971, 0.2491045282), _
Array(1.4685857879, -0.8347049536, 1.3670667538), _
Array(-0.6855727502, 1.6465021616, 1.0593087096), _
Array(0.0152957411, 0.0638919221, 0.9771215985))
pi = WorksheetFunction.pi()
End Sub
Private Function shoelace(s As Collection) As Double
Dim t As Double
If s.Count > 2 Then
s.Add s(1)
For i = 1 To s.Count - 1
t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v)
Next i
End If
shoelace = t / 2
End Function
Private Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _
f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer)
If acol.Count = 0 Then Exit Sub
Debug.Assert acol.Count Mod 2 = 0
Debug.Assert f0 <> f1
If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1
If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0
If f0 < f1 Then
If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub
i = acol.Count + 1
start = 1
Do
i = i - 1
Loop Until f1 > acol(i)(rho)
If i Mod 2 = start Then
acol.Add Array(f1, u1, v1, j), after:=i
End If
i = 0
Do
i = i + 1
Loop Until f0 < acol(i)(rho)
If i Mod 2 = 1 - start Then
acol.Add Array(f0, u0, v0, j), before:=i
i = i + 1
End If
Do While acol(i)(rho) < f1
acol.Remove i
If i > acol.Count Then Exit Do
Loop
Else
start = 1
If f0 > acol(1)(rho) Then
i = acol.Count + 1
Do
i = i - 1
Loop While f0 < acol(i)(0)
If f0 = pi Then
acol.Add Array(f0, u0, v0, j), before:=i
Else
If i Mod 2 = start Then
acol.Add Array(f0, u0, v0, j), after:=i
End If
End If
End If
If f1 <= acol(acol.Count)(rho) Then
i = 0
Do
i = i + 1
Loop While f1 > acol(i)(rho)
If f1 + pi < 5E-16 Then
acol.Add Array(f1, u1, v1, j), after:=i
Else
If i Mod 2 = 1 - start Then
acol.Add Array(f1, u1, v1, j), before:=i
End If
End If
End If
Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1
acol.Remove acol.Count
If acol.Count = 0 Then Exit Do
Loop
If acol.Count > 0 Then
Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this)
acol.Remove 1
If acol.Count = 0 Then Exit Do
Loop
End If
End If
End Sub
Private Sub circle_cross()
ReDim arclists(LBound(c) To UBound(c))
Dim alpha As Double, beta As Double
Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double
Dim i As Integer, j As Integer
For i = LBound(c) To UBound(c)
Dim arccol As New Collection
arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i)
arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1)
For j = LBound(c) To UBound(c)
If i <> j Then
x0 = c(i)(xc)
y0 = c(i)(yc)
r0 = c(i)(rc)
x1 = c(j)(xc)
y1 = c(j)(yc)
r1 = c(j)(rc)
d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2)
If d >= r0 + r1 Or d <= Abs(r0 - r1) Then
Else
a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d)
h = Sqr(r0 ^ 2 - a ^ 2)
x2 = x0 + a * (x1 - x0) / d
y2 = y0 + a * (y1 - y0) / d
x3 = x2 + h * (y1 - y0) / d
y3 = y2 - h * (x1 - x0) / d
alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0)
x4 = x2 - h * (y1 - y0) / d
y4 = y2 + h * (x1 - x0) / d
beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0)
arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j
End If
End If
Next j
Set arclists(i) = arccol
Set arccol = Nothing
Next i
End Sub
Private Sub make_path()
Dim pathcol As New Collection, arcsum As Double
i0 = UBound(arclists)
finished = False
Do While True
arcsum = 0
Do While arclists(i0).Count = 0
i0 = i0 - 1
Loop
j0 = arclists(i0).Count
next_i = i0
next_j = j0
Do While True
x = arclists(next_i)(next_j)(x_)
y = arclists(next_i)(next_j)(y_)
pathcol.Add Array(x, y)
prev_i = next_i
prev_j = next_j
If arclists(next_i)(next_j - 1)(i_) = next_i Then
next_j = arclists(next_i).Count - 1
If next_j = 1 Then Exit Do
Else
next_j = next_j - 1
End If
r = c(next_i)(rc)
a1 = arclists(next_i)(prev_j)(rho)
a2 = arclists(next_i)(next_j)(rho)
If a1 > a2 Then
alpha = a1 - a2
Else
alpha = 2 * pi - a2 + a1
End If
arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2
next_i = arclists(next_i)(next_j)(i_)
next_j = arclists(next_i).Count
If next_j = 0 Then Exit Do
Do While arclists(next_i)(next_j)(i_) <> prev_i
next_j = next_j - 1
Loop
If next_i = i0 And next_j = j0 Then
finished = True
Exit Do
End If
Loop
If finished Then Exit Do
i0 = i0 - 1
Set pathcol = Nothing
Loop
Debug.Print shoelace(pathcol) + arcsum
End Sub
Public Sub total_circles()
give_a_list_of_circles
circle_cross
make_path
End Sub
|
Convert this Python snippet to VB and keep its semantics consistent. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-0.2495892950, -0.3832854473, 1.0845181219),
Circle( 1.7813504266, 1.6178237031, 0.8162655711),
Circle(-0.1985249206, -0.8343333301, 0.0538864941),
Circle(-1.7011985145, -0.1263820964, 0.4776976918),
Circle(-0.4319462812, 1.4104420482, 0.7886291537),
Circle( 0.2178372997, -0.9499557344, 0.0357871187),
Circle(-0.6294854565, -1.3078893852, 0.7653357688),
Circle( 1.7952608455, 0.6281269104, 0.2727652452),
Circle( 1.4168575317, 1.0683357171, 1.1016025378),
Circle( 1.4637371396, 0.9463877418, 1.1846214562),
Circle(-0.5263668798, 1.7315156631, 1.4428514068),
Circle(-1.2197352481, 0.9144146579, 1.0727263474),
Circle(-0.1389358881, 0.1092805780, 0.7350208828),
Circle( 1.5293954595, 0.0030278255, 1.2472867347),
Circle(-0.5258728625, 1.3782633069, 1.3495508831),
Circle(-0.1403562064, 0.2437382535, 1.3804956588),
Circle( 0.8055826339, -0.0482092025, 0.3327165165),
Circle(-0.6311979224, 0.7184578971, 0.2491045282),
Circle( 1.4685857879, -0.8347049536, 1.3670667538),
Circle(-0.6855727502, 1.6465021616, 1.0593087096),
Circle( 0.0152957411, 0.0638919221, 0.9771215985)]
def main():
x_min = min(c.x - c.r for c in circles)
x_max = max(c.x + c.r for c in circles)
y_min = min(c.y - c.r for c in circles)
y_max = max(c.y + c.r for c in circles)
box_side = 500
dx = (x_max - x_min) / box_side
dy = (y_max - y_min) / box_side
count = 0
for r in xrange(box_side):
y = y_min + r * dy
for c in xrange(box_side):
x = x_min + c * dx
if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)
for circle in circles):
count += 1
print "Approximated area:", count * dx * dy
main()
| 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.0848270516), _
Array(-1.4944608174, 1.2077959613, 1.1039549836), _
Array(0.6110294452, -0.6907087527, 0.9089162485), _
Array(0.3844862411, 0.2923344616, 0.2375743054), _
Array(-0.249589295, -0.3832854473, 1.0845181219), _
Array(1.7813504266, 1.6178237031, 0.8162655711), _
Array(-0.1985249206, -0.8343333301, 0.0538864941), _
Array(-1.7011985145, -0.1263820964, 0.4776976918), _
Array(-0.4319462812, 1.4104420482, 0.7886291537), _
Array(0.2178372997, -0.9499557344, 0.0357871187), _
Array(-0.6294854565, -1.3078893852, 0.7653357688), _
Array(1.7952608455, 0.6281269104, 0.2727652452), _
Array(1.4168575317, 1.0683357171, 1.1016025378), _
Array(1.4637371396, 0.9463877418, 1.1846214562), _
Array(-0.5263668798, 1.7315156631, 1.4428514068), _
Array(-1.2197352481, 0.9144146579, 1.0727263474), _
Array(-0.1389358881, 0.109280578, 0.7350208828), _
Array(1.5293954595, 0.0030278255, 1.2472867347), _
Array(-0.5258728625, 1.3782633069, 1.3495508831), _
Array(-0.1403562064, 0.2437382535, 1.3804956588), _
Array(0.8055826339, -0.0482092025, 0.3327165165), _
Array(-0.6311979224, 0.7184578971, 0.2491045282), _
Array(1.4685857879, -0.8347049536, 1.3670667538), _
Array(-0.6855727502, 1.6465021616, 1.0593087096), _
Array(0.0152957411, 0.0638919221, 0.9771215985))
pi = WorksheetFunction.pi()
End Sub
Private Function shoelace(s As Collection) As Double
Dim t As Double
If s.Count > 2 Then
s.Add s(1)
For i = 1 To s.Count - 1
t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v)
Next i
End If
shoelace = t / 2
End Function
Private Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _
f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer)
If acol.Count = 0 Then Exit Sub
Debug.Assert acol.Count Mod 2 = 0
Debug.Assert f0 <> f1
If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1
If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0
If f0 < f1 Then
If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub
i = acol.Count + 1
start = 1
Do
i = i - 1
Loop Until f1 > acol(i)(rho)
If i Mod 2 = start Then
acol.Add Array(f1, u1, v1, j), after:=i
End If
i = 0
Do
i = i + 1
Loop Until f0 < acol(i)(rho)
If i Mod 2 = 1 - start Then
acol.Add Array(f0, u0, v0, j), before:=i
i = i + 1
End If
Do While acol(i)(rho) < f1
acol.Remove i
If i > acol.Count Then Exit Do
Loop
Else
start = 1
If f0 > acol(1)(rho) Then
i = acol.Count + 1
Do
i = i - 1
Loop While f0 < acol(i)(0)
If f0 = pi Then
acol.Add Array(f0, u0, v0, j), before:=i
Else
If i Mod 2 = start Then
acol.Add Array(f0, u0, v0, j), after:=i
End If
End If
End If
If f1 <= acol(acol.Count)(rho) Then
i = 0
Do
i = i + 1
Loop While f1 > acol(i)(rho)
If f1 + pi < 5E-16 Then
acol.Add Array(f1, u1, v1, j), after:=i
Else
If i Mod 2 = 1 - start Then
acol.Add Array(f1, u1, v1, j), before:=i
End If
End If
End If
Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1
acol.Remove acol.Count
If acol.Count = 0 Then Exit Do
Loop
If acol.Count > 0 Then
Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this)
acol.Remove 1
If acol.Count = 0 Then Exit Do
Loop
End If
End If
End Sub
Private Sub circle_cross()
ReDim arclists(LBound(c) To UBound(c))
Dim alpha As Double, beta As Double
Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double
Dim i As Integer, j As Integer
For i = LBound(c) To UBound(c)
Dim arccol As New Collection
arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i)
arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1)
For j = LBound(c) To UBound(c)
If i <> j Then
x0 = c(i)(xc)
y0 = c(i)(yc)
r0 = c(i)(rc)
x1 = c(j)(xc)
y1 = c(j)(yc)
r1 = c(j)(rc)
d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2)
If d >= r0 + r1 Or d <= Abs(r0 - r1) Then
Else
a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d)
h = Sqr(r0 ^ 2 - a ^ 2)
x2 = x0 + a * (x1 - x0) / d
y2 = y0 + a * (y1 - y0) / d
x3 = x2 + h * (y1 - y0) / d
y3 = y2 - h * (x1 - x0) / d
alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0)
x4 = x2 - h * (y1 - y0) / d
y4 = y2 + h * (x1 - x0) / d
beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0)
arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j
End If
End If
Next j
Set arclists(i) = arccol
Set arccol = Nothing
Next i
End Sub
Private Sub make_path()
Dim pathcol As New Collection, arcsum As Double
i0 = UBound(arclists)
finished = False
Do While True
arcsum = 0
Do While arclists(i0).Count = 0
i0 = i0 - 1
Loop
j0 = arclists(i0).Count
next_i = i0
next_j = j0
Do While True
x = arclists(next_i)(next_j)(x_)
y = arclists(next_i)(next_j)(y_)
pathcol.Add Array(x, y)
prev_i = next_i
prev_j = next_j
If arclists(next_i)(next_j - 1)(i_) = next_i Then
next_j = arclists(next_i).Count - 1
If next_j = 1 Then Exit Do
Else
next_j = next_j - 1
End If
r = c(next_i)(rc)
a1 = arclists(next_i)(prev_j)(rho)
a2 = arclists(next_i)(next_j)(rho)
If a1 > a2 Then
alpha = a1 - a2
Else
alpha = 2 * pi - a2 + a1
End If
arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2
next_i = arclists(next_i)(next_j)(i_)
next_j = arclists(next_i).Count
If next_j = 0 Then Exit Do
Do While arclists(next_i)(next_j)(i_) <> prev_i
next_j = next_j - 1
Loop
If next_i = i0 And next_j = j0 Then
finished = True
Exit Do
End If
Loop
If finished Then Exit Do
i0 = i0 - 1
Set pathcol = Nothing
Loop
Debug.Print shoelace(pathcol) + arcsum
End Sub
Public Sub total_circles()
give_a_list_of_circles
circle_cross
make_path
End Sub
|
Please provide an equivalent version of this Python code in VB. | import math
import random
def GammaInc_Q( a, x):
a1 = a-1
a2 = a-2
def f0( t ):
return t**a1*math.exp(-t)
def df0(t):
return (a1-t)*t**a2*math.exp(-t)
y = a1
while f0(y)*(x-y) >2.0e-8 and y < x: y += .3
if y > x: y = x
h = 3.0e-4
n = int(y/h)
h = y/n
hh = 0.5*h
gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))
return gamax/gamma_spounge(a)
c = None
def gamma_spounge( z):
global c
a = 12
if c is None:
k1_factrl = 1.0
c = []
c.append(math.sqrt(2.0*math.pi))
for k in range(1,a):
c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )
k1_factrl *= -k
accm = c[0]
for k in range(1,a):
accm += c[k] / (z+k)
accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)
return accm/z;
def chi2UniformDistance( dataSet ):
expected = sum(dataSet)*1.0/len(dataSet)
cntrd = (d-expected for d in dataSet)
return sum(x*x for x in cntrd)/expected
def chi2Probability(dof, distance):
return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)
def chi2IsUniform(dataSet, significance):
dof = len(dataSet)-1
dist = chi2UniformDistance(dataSet)
return chi2Probability( dof, dist ) > significance
dset1 = [ 199809, 200665, 199607, 200270, 199649 ]
dset2 = [ 522573, 244456, 139979, 71531, 21461 ]
for ds in (dset1, dset2):
print "Data set:", ds
dof = len(ds)-1
distance =chi2UniformDistance(ds)
print "dof: %d distance: %.4f" % (dof, distance),
prob = chi2Probability( dof, distance)
print "probability: %.4f"%prob,
print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
| Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
Debug.Print "[1] ""Data set:"" ";
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
Total = Total + ObservationFrequencies(i)
Debug.Print ObservationFrequencies(i); " ";
Next i
DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
Ei = Total / (DegreesOfFreedom + 1)
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
Next i
p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
Debug.Print
Debug.Print " Chi-squared test for given frequencies"
Debug.Print "X-squared ="; ChiSquared; ", ";
Debug.Print "df ="; DegreesOfFreedom; ", ";
Debug.Print "p-value = "; Format(p_value, "0.0000")
Test4DiscreteUniformDistribution = p_value > Significance
End Function
Public Sub test()
Dim O() As Variant
O = [{199809,200665,199607,200270,199649}]
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """"
O = [{522573,244456,139979,71531,21461}]
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """"
End Sub
|
Rewrite the snippet below in VB so it works the same as the original Python code. | def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in .split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n"
| 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 String.IsNullOrEmpty(s) Then
Exit While
End If
out.AddRange(g)
If s(0) = "}" Then
If comma Then
Return Tuple.Create(out, s.Substring(1))
End If
Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1))
End If
If s(0) = "," Then
comma = True
s = s.Substring(1)
End If
End While
Return Nothing
End Function
Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)
Dim out As New List(Of String) From {""}
While Not String.IsNullOrEmpty(s)
Dim c = s(0)
If depth > 0 AndAlso (c = "," OrElse c = "}") Then
Return Tuple.Create(out, s)
End If
If c = "{" Then
Dim x = GetGroup(s.Substring(1), depth + 1)
If Not IsNothing(x) Then
Dim tout As New List(Of String)
For Each a In out
For Each b In x.Item1
tout.Add(a + b)
Next
Next
out = tout
s = x.Item2
Continue While
End If
End If
If c = "\" AndAlso s.Length > 1 Then
c += s(1)
s = s.Substring(1)
End If
out = out.Select(Function(a) a + c).ToList()
s = s.Substring(1)
End While
Return Tuple.Create(out, s)
End Function
Sub Main()
For Each s In {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\, again\, }}more }cowbell!",
"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
}
Dim fmt = "{0}" + vbNewLine + vbTab + "{1}"
Dim parts = GetItem(s)
Dim res = String.Join(vbNewLine + vbTab, parts.Item1)
Console.WriteLine(fmt, s, res)
Next
End Sub
End Module
|
Please provide an equivalent version of this Python code in VB. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
var_args(1, (2,3))
var_args()
fixed_args(y=2, x=1)
if 1:
no_args()
assert no_args() is None
def return_something():
return 1
x = return_something()
def is_builtin(x):
print(x.__name__ in dir(__builtins__))
is_builtin(pow)
is_builtin(is_builtin)
def takes_anything(*args, **kwargs):
for each in args:
print(each)
for key, value in sorted(kwargs.items()):
print("%s:%s" % (key, value))
wrapped_fn(*args, **kwargs)
|
Function no_arguments() As String
no_arguments = "ok"
End Function
Function fixed_number(argument1 As Integer, argument2 As Integer)
fixed_number = argument1 + argument2
End Function
Function optional_parameter(Optional argument1 = 1) As Integer
optional_parameter = argument1
End Function
Function variable_number(arguments As Variant) As Integer
variable_number = UBound(arguments)
End Function
Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
named_arguments = argument1 + argument2
End Function
Function statement() As String
Debug.Print "function called as statement"
statement = "ok"
End Function
Function return_value() As String
return_value = "ok"
End Function
Sub foo()
Debug.Print "subroutine",
End Sub
Function bar() As String
bar = "function"
End Function
Function passed_by_value(ByVal s As String) As String
s = "written over"
passed_by_value = "passed by value"
End Function
Function passed_by_reference(ByRef s As String) As String
s = "written over"
passed_by_reference = "passed by reference"
End Function
Sub no_parentheses(myargument As String)
Debug.Print myargument,
End Sub
Public Sub calling_a_function()
Debug.Print "no arguments", , no_arguments
Debug.Print "no arguments", , no_arguments()
Debug.Print "fixed_number", , fixed_number(1, 1)
Debug.Print "optional parameter", optional_parameter
Debug.Print "optional parameter", optional_parameter(2)
Debug.Print "variable number", variable_number([{"hello", "there"}])
Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
statement
s = "no_arguments"
Debug.Print "first-class context", Application.Run(s)
returnvalue = return_value
Debug.Print "obtained return value", returnvalue
foo
Debug.Print , bar
Dim t As String
t = "unaltered"
Debug.Print passed_by_value(t), t
Debug.Print passed_by_reference(t), t
no_parentheses "calling a subroutine"
Debug.Print "does not require parentheses"
Call no_parentheses("deprecated use")
Debug.Print "of parentheses"
End Sub
|
Port the provided Python code into VB while preserving the original functionality. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
var_args(1, (2,3))
var_args()
fixed_args(y=2, x=1)
if 1:
no_args()
assert no_args() is None
def return_something():
return 1
x = return_something()
def is_builtin(x):
print(x.__name__ in dir(__builtins__))
is_builtin(pow)
is_builtin(is_builtin)
def takes_anything(*args, **kwargs):
for each in args:
print(each)
for key, value in sorted(kwargs.items()):
print("%s:%s" % (key, value))
wrapped_fn(*args, **kwargs)
|
Function no_arguments() As String
no_arguments = "ok"
End Function
Function fixed_number(argument1 As Integer, argument2 As Integer)
fixed_number = argument1 + argument2
End Function
Function optional_parameter(Optional argument1 = 1) As Integer
optional_parameter = argument1
End Function
Function variable_number(arguments As Variant) As Integer
variable_number = UBound(arguments)
End Function
Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
named_arguments = argument1 + argument2
End Function
Function statement() As String
Debug.Print "function called as statement"
statement = "ok"
End Function
Function return_value() As String
return_value = "ok"
End Function
Sub foo()
Debug.Print "subroutine",
End Sub
Function bar() As String
bar = "function"
End Function
Function passed_by_value(ByVal s As String) As String
s = "written over"
passed_by_value = "passed by value"
End Function
Function passed_by_reference(ByRef s As String) As String
s = "written over"
passed_by_reference = "passed by reference"
End Function
Sub no_parentheses(myargument As String)
Debug.Print myargument,
End Sub
Public Sub calling_a_function()
Debug.Print "no arguments", , no_arguments
Debug.Print "no arguments", , no_arguments()
Debug.Print "fixed_number", , fixed_number(1, 1)
Debug.Print "optional parameter", optional_parameter
Debug.Print "optional parameter", optional_parameter(2)
Debug.Print "variable number", variable_number([{"hello", "there"}])
Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
statement
s = "no_arguments"
Debug.Print "first-class context", Application.Run(s)
returnvalue = return_value
Debug.Print "obtained return value", returnvalue
foo
Debug.Print , bar
Dim t As String
t = "unaltered"
Debug.Print passed_by_value(t), t
Debug.Print passed_by_reference(t), t
no_parentheses "calling a subroutine"
Debug.Print "does not require parentheses"
Call no_parentheses("deprecated use")
Debug.Print "of parentheses"
End Sub
|
Change the programming language of this snippet from Python to VB without modifying what it does. | import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input !')
return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
| VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 2265
ClientLeft = 60
ClientTop = 600
ClientWidth = 2175
LinkTopic = "Form1"
ScaleHeight = 2265
ScaleWidth = 2175
StartUpPosition = 3
Begin VB.CommandButton cmdRnd
Caption = "Random"
Height = 495
Left = 120
TabIndex = 2
Top = 1680
Width = 1215
End
Begin VB.CommandButton cmdInc
Caption = "Increment"
Height = 495
Left = 120
TabIndex = 1
Top = 1080
Width = 1215
End
Begin VB.TextBox txtValue
Height = 495
Left = 120
TabIndex = 0
Text = "0"
Top = 240
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub Form_Load()
Randomize Timer
End Sub
Private Sub cmdRnd_Click()
If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11)
End Sub
Private Sub cmdInc_Click()
If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub
Private Sub txtValue_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 8, 43, 45, 48 To 57
Case Else
KeyAscii = 0
End Select
End Sub
|
Translate the given Python code snippet into VB without altering its behavior. | from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines):
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in range(trials):
bins[one_of_n(range(n))] += 1
return bins
print(one_of_n_test())
| Dim chosen(10)
For j = 1 To 1000000
c = one_of_n(10)
chosen(c) = chosen(c) + 1
Next
For k = 1 To 10
WScript.StdOut.WriteLine k & ". " & chosen(k)
Next
Function one_of_n(n)
Randomize
For i = 1 To n
If Rnd(1) < 1/i Then
one_of_n = i
End If
Next
End Function
|
Preserve the algorithm and functionality while converting the code from Python to VB. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
delim = " "
if len(num[-1]) > len(hyphen[-1]):
num = hyphen
delim = "-"
if num[-1] in irregularOrdinals:
num[-1] = delim + irregularOrdinals[num[-1]]
elif num[-1].endswith("y"):
num[-1] = delim + num[-1][:-1] + "ieth"
else:
num[-1] = delim + num[-1] + "th"
return "".join(num)
if __name__ == "__main__":
tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split()
for num in tests:
print("{} => {}".format(num, num2ordinal(num)))
TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
for h in ("m", "b", "tr", "quadr", "quint", "sext",
"sept", "oct", "non", "dec")]
def nonzero(c, n, connect=''):
return "" if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) + " thousand"
else:
return spell_integer(n) + " " + HUGE[e]
def base1000_rev(n):
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return "minus " + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero("-", b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
else:
num = ", ".join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num)
| 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 Integer
For i = Len(s) To 1 Step -1
ch = Mid(s, i, 1)
If ch = " " Or ch = "-" Then Exit For
Next i
On Error GoTo 1
ord = irregs(Right(s, Len(s) - i))
ordinal = Left(s, i) & ord
Exit Function
1:
If Right(s, 1) = "y" Then
s = Left(s, Len(s) - 1) & "ieth"
Else
s = s & "th"
End If
ordinal = s
End Function
Public Sub ordinals()
tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]
init
For i = 1 To UBound(tests)
Debug.Print ordinal(spell(tests(i)))
Next i
End Sub
|
Preserve the algorithm and functionality while converting the code from Python to VB. | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
| Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(j)) Then
If digit.Item(CStr(j)) = CInt(l) Then
c = c + 1
End If
ElseIf l = 0 Then
c = c + 1
Else
Exit For
End If
Next
If c = Len(n) Then
IsSelfDescribing = True
End If
End Function
start_time = Now
s = ""
For m = 1 To 100000000
If IsSelfDescribing(m) Then
WScript.StdOut.WriteLine m
End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
|
Write the same algorithm in VB as shown in this Python implementation. | def prepend(n, seq):
return [n] + seq
def check_seq(pos, seq, n, min_len):
if pos > min_len or seq[0] > n:
return min_len, 0
if seq[0] == n:
return pos, 1
if pos < min_len:
return try_perm(0, pos, seq, n, min_len)
return min_len, 0
def try_perm(i, pos, seq, n, min_len):
if i > pos:
return min_len, 0
res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)
res2 = try_perm(i + 1, pos, seq, n, res1[0])
if res2[0] < res1[0]:
return res2
if res2[0] == res1[0]:
return res2[0], res1[1] + res2[1]
raise Exception("try_perm exception")
def init_try_perm(x):
return try_perm(0, 0, [1], x, 12)
def find_brauer(num):
res = init_try_perm(num)
print
print "N = ", num
print "Minimum length of chains: L(n) = ", res[0]
print "Number of minimum length Brauer chains: ", res[1]
nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums:
find_brauer(i)
| 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_len As Integer) As Tuple(Of Integer, Integer)
If pos > min_len OrElse seq(0) > n Then
Return Tuple.Create(min_len, 0)
End If
If seq(0) = n Then
Return Tuple.Create(pos, 1)
End If
If pos < min_len Then
Return TryPerm(0, pos, seq, n, min_len)
End If
Return Tuple.Create(min_len, 0)
End Function
Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)
If i > pos Then
Return Tuple.Create(min_len, 0)
End If
Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)
Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)
If res2.Item1 < res1.Item1 Then
Return res2
End If
If res2.Item1 = res1.Item1 Then
Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)
End If
Throw New Exception("TryPerm exception")
End Function
Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)
Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)
End Function
Sub FindBrauer(num As Integer)
Dim res = InitTryPerm(num)
Console.WriteLine("N = {0}", num)
Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1)
Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2)
Console.WriteLine()
End Sub
Sub Main()
Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
Array.ForEach(nums, Sub(n) FindBrauer(n))
End Sub
End Module
|
Please provide an equivalent version of this Python code in VB. |
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3);
| Private Sub Repeat(rid As String, n As Integer)
For i = 1 To n
Application.Run rid
Next i
End Sub
Private Sub Hello()
Debug.Print "Hello"
End Sub
Public Sub main()
Repeat "Hello", 5
End Sub
|
Translate the given Python code snippet into VB without altering its behavior. |
bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __name__ == '__main__':
import re
for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'):
print("\nNumbers:", line)
numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())]
mn, mx, sp = sparkline(numbers)
print(' min: %5f; max: %5f' % (mn, mx))
print(" " + sp)
|
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(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_
chrw(&h2586)&chrw(&h2587)&chrw(&h2588)
nn=8
end sub
public function bg (s)
a=split(replace(replace(s,","," ")," "," ")," ")
mn=999999:mx=-999999:cnt=ubound(a)+1
for i=0 to ubound(a)
a(i)=cdbl(trim(a(i)))
if a(i)>mx then mx=a(i)
if a(i)<mn then mn=a(i)
next
ss="Data: "
for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next
ss=ss+vbcrlf + "sparkline: "
for i=0 to ubound(a)
x=scale(a(i))
ss=ss & string(6,mid(bar,x,1))
next
bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _
" cnt: "& ubound(a)+1 &vbcrlf
end function
private function scale(x)
if x=<mn then
scale=1
elseif x>=mx then
scale=nn
else
scale=int(nn* (x-mn)/(mx-mn)+1)
end if
end function
end class
ensure_cscript
set b=new bargraph
wscript.stdout.writeblanklines 2
wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1")
wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5")
wscript.echo b.bg("0, 1, 19, 20")
wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999")
set b=nothing
wscript.echo "If bars don
"font to DejaVu Sans Mono or any other that has the bargrph characters" & _
vbcrlf
wscript.stdout.write "Press any key.." : wscript.stdin.read 1
|
Rewrite the snippet below in VB so it works the same as the original Python code. | >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
>>> modinv(42, 2017)
1969
>>>
| Private Function mul_inv(a As Long, n As Long) As Variant
If n < 0 Then n = -n
If a < 0 Then a = n - ((-a) Mod n)
Dim t As Long: t = 0
Dim nt As Long: nt = 1
Dim r As Long: r = n
Dim nr As Long: nr = a
Dim q As Long
Do While nr <> 0
q = r \ nr
tmp = t
t = nt
nt = tmp - q * nt
tmp = r
r = nr
nr = tmp - q * nr
Loop
If r > 1 Then
mul_inv = "a is not invertible"
Else
If t < 0 Then t = t + n
mul_inv = t
End If
End Function
Public Sub mi()
Debug.Print mul_inv(42, 2017)
Debug.Print mul_inv(40, 1)
Debug.Print mul_inv(52, -217)
Debug.Print mul_inv(-486, 217)
Debug.Print mul_inv(40, 2018)
End Sub
|
Maintain the same structure and functionality when rewriting this code in VB. | from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b"<h1>Goodbye, World!</h1>"
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
| Class HTTPSock
Inherits TCPSocket
Event Sub DataAvailable()
Dim headers As New InternetHeaders
headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!")))
headers.AppendHeader("Content-Type", "text/plain")
headers.AppendHeader("Content-Encoding", "identity")
headers.AppendHeader("Connection", "close")
Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!"
Me.Write(data)
Me.Close
End Sub
End Class
Class HTTPServ
Inherits ServerSocket
Event Sub AddSocket() As TCPSocket
Return New HTTPSock
End Sub
End Class
Class App
Inherits Application
Event Sub Run(Args() As String)
Dim sock As New HTTPServ
sock.Port = 8080
sock.Listen()
While True
App.DoEvents
Wend
End Sub
End Class
|
Transform the following Python implementation into VB, maintaining the same output and logic. |
def isowndigitspowersum(integer):
digits = [int(c) for c in str(integer)]
exponent = len(digits)
return sum(x ** exponent for x in digits) == integer
print("Own digits power sums for N = 3 to 9 inclusive:")
for i in range(100, 1000000000):
if isowndigitspowersum(i):
print(i)
| 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
power(1, i) = i
Next i
For j As Integer = 2 To 9
For i As Integer = 1 To 9
power(j, i) = power(j - 1, i) * i
Next i
Next j
Dim lowestDigit(9) As Integer
lowestDigit(1) = -1
lowestDigit(2) = -1
Dim p10 As Long = 100
For i As Integer = 3 To 9
For p As Integer = 2 To 9
Dim np As Long = power(i, p) * i
If Not ( np < p10) Then Exit For
lowestDigit(i) = p
Next p
p10 *= 10
Next i
Dim maxZeros(9, 9) As Integer
For i As Integer = 1 To 9
For j As Integer = 1 To 9
maxZeros(i, j) = 0
Next j
Next i
p10 = 1000
For w As Integer = 3 To 9
For d As Integer = lowestDigit(w) To 9
Dim nz As Integer = 9
Do
If nz < 0 Then
Exit Do
Else
Dim np As Long = power(w, d) * nz
IF Not ( np > p10) Then Exit Do
End If
nz -= 1
Loop
maxZeros(w, d) = If(nz > w, 0, w - nz)
Next d
p10 *= 10
Next w
Dim numbers(100) As Long
Dim nCount As Integer = 0
Dim tryCount As Integer = 0
Dim digits(9) As Integer
For d As Integer = 1 To 9
digits(d) = 9
Next d
For d As Integer = 0 To 8
used(d) = 0
Next d
used(9) = 9
Dim width As Integer = 9
Dim last As Integer = width
p10 = 100000000
Do While width > 2
tryCount += 1
Dim dps As Long = 0
check(0) = used(0)
For i As Integer = 1 To 9
check(i) = used(i)
If used(i) <> 0 Then
dps += used(i) * power(width, i)
End If
Next i
Dim n As Long = dps
Do
check(CInt(n Mod 10)) -= 1
n \= 10
Loop Until n <= 0
Dim reduceWidth As Boolean = dps <= p10
If Not reduceWidth Then
Dim zCount As Integer = 0
For i As Integer = 0 To 9
If check(i) <> 0 Then Exit For
zCount+= 1
Next i
If zCount = 10 Then
nCount += 1
numbers(nCount) = dps
End If
used(digits(last)) -= 1
digits(last) -= 1
If digits(last) = 0 Then
If used(0) >= maxZeros(width, digits(1)) Then
digits(last) = -1
End If
End If
If digits(last) >= 0 Then
used(digits(last)) += 1
Else
Dim prev As Integer = last
Do
prev -= 1
If prev < 1 Then
Exit Do
Else
used(digits(prev)) -= 1
digits(prev) -= 1
IF digits(prev) >= 0 Then Exit Do
End If
Loop
If prev > 0 Then
If prev = 1 Then
If digits(1) <= lowestDigit(width) Then
prev = 0
End If
End If
If prev <> 0 Then
used(digits(prev)) += 1
For i As Integer = prev + 1 To width
digits(i) = digits(prev)
used(digits(prev)) += 1
Next i
End If
End If
If prev <= 0 Then
reduceWidth = True
End If
End If
End If
If reduceWidth Then
last -= 1
width = last
If last > 0 Then
For d As Integer = 1 To last
digits(d) = 9
Next d
For d As Integer = last + 1 To 9
digits(d) = -1
Next d
For d As Integer = 0 To 8
used(d) = 0
Next d
used(9) = last
p10 \= 10
End If
End If
Loop
Console.Out.WriteLine("Own digits power sums for N = 3 to 9 inclusive:")
For i As Integer = nCount To 1 Step -1
Console.Out.WriteLine(numbers(i))
Next i
Console.Out.WriteLine("Considered " & tryCount & " digit combinations")
End Sub
End Module
|
Translate the given Python code snippet into VB without altering its behavior. | def KlarnerRado(N):
K = [1]
for i in range(N):
j = K[i]
firstadd, secondadd = 2 * j + 1, 3 * j + 1
if firstadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < firstadd < K[pos + 1]:
K.insert(pos + 1, firstadd)
break
elif firstadd > K[-1]:
K.append(firstadd)
if secondadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < secondadd < K[pos + 1]:
K.insert(pos + 1, secondadd)
break
elif secondadd > K[-1]:
K.append(secondadd)
return K
kr1m = KlarnerRado(100_000)
print('First 100 Klarner-Rado sequence numbers:')
for idx, v in enumerate(kr1m[:100]):
print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '')
for n in [1000, 10_000, 100_000]:
print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
| 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 _
, 262144, 524288, 1048576, 2097152, 4194304, 8388608 _
, 16777216, 33554432, 67108864, 134217728, 268435456 _
, 536870912, 1073741824 _
}
Private Const maxElement As Integer = 1100000000
Private Function BitSet(bit As Integer, v As Integer) As Boolean
Return (v And bitMask(bit - 1)) <> 0
End Function
Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer
Return b Or bitMask(bit - 1)
End Function
Public Sub Main
Dim kr(maxElement \ bitsWidth) As Integer
For i As Integer = 0 To kr.Count() - 1
kr(i) = 0
Next i
Dim krCount As Integer = 0
Dim n21 As Integer = 3
Dim n31 As Integer = 4
Dim p10 As Integer = 1000
Dim iBit As Integer = 0
Dim iOverBw As Integer = 0
Dim p2Bit As Integer = 1
Dim p2OverBw As Integer = 0
Dim p3Bit As Integer = 1
Dim p3OverBw As Integer = 0
kr(0) = SetBit(1, kr(0))
Dim kri As Boolean = True
Dim lastI As Integer = 0
For i As Integer = 1 To maxElement
iBit += 1
If iBit > bitsWidth Then
iBit = 1
iOverBw += 1
End If
If i = n21 Then
If BitSet(p2Bit, kr(p2OverBw)) Then
kri = True
End If
p2Bit += 1
If p2Bit > bitsWidth Then
p2Bit = 1
p2OverBw += 1
End If
n21 += 2
End If
If i = n31 Then
If BitSet(p3Bit, kr(p3OverBw)) Then
kri = True
End If
p3Bit += 1
If p3Bit > bitsWidth Then
p3Bit = 1
p3OverBw += 1
End If
n31 += 3
End If
If kri Then
lastI = i
kr(iOverBw) = SetBit(iBit, kr(iOverBw))
krCount += 1
If krCount <= 100 Then
Console.Out.Write(" " & i.ToString().PadLeft(3))
If krCount Mod 20 = 0 Then
Console.Out.WriteLine()
End If
ElseIf krCount = p10 Then
Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10))
p10 *= 10
End If
kri = False
End If
Next i
Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10))
End Sub
End Module
|
Generate a VB translation of this Python snippet without changing its computational steps. | def KlarnerRado(N):
K = [1]
for i in range(N):
j = K[i]
firstadd, secondadd = 2 * j + 1, 3 * j + 1
if firstadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < firstadd < K[pos + 1]:
K.insert(pos + 1, firstadd)
break
elif firstadd > K[-1]:
K.append(firstadd)
if secondadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < secondadd < K[pos + 1]:
K.insert(pos + 1, secondadd)
break
elif secondadd > K[-1]:
K.append(secondadd)
return K
kr1m = KlarnerRado(100_000)
print('First 100 Klarner-Rado sequence numbers:')
for idx, v in enumerate(kr1m[:100]):
print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '')
for n in [1000, 10_000, 100_000]:
print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
| 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 _
, 262144, 524288, 1048576, 2097152, 4194304, 8388608 _
, 16777216, 33554432, 67108864, 134217728, 268435456 _
, 536870912, 1073741824 _
}
Private Const maxElement As Integer = 1100000000
Private Function BitSet(bit As Integer, v As Integer) As Boolean
Return (v And bitMask(bit - 1)) <> 0
End Function
Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer
Return b Or bitMask(bit - 1)
End Function
Public Sub Main
Dim kr(maxElement \ bitsWidth) As Integer
For i As Integer = 0 To kr.Count() - 1
kr(i) = 0
Next i
Dim krCount As Integer = 0
Dim n21 As Integer = 3
Dim n31 As Integer = 4
Dim p10 As Integer = 1000
Dim iBit As Integer = 0
Dim iOverBw As Integer = 0
Dim p2Bit As Integer = 1
Dim p2OverBw As Integer = 0
Dim p3Bit As Integer = 1
Dim p3OverBw As Integer = 0
kr(0) = SetBit(1, kr(0))
Dim kri As Boolean = True
Dim lastI As Integer = 0
For i As Integer = 1 To maxElement
iBit += 1
If iBit > bitsWidth Then
iBit = 1
iOverBw += 1
End If
If i = n21 Then
If BitSet(p2Bit, kr(p2OverBw)) Then
kri = True
End If
p2Bit += 1
If p2Bit > bitsWidth Then
p2Bit = 1
p2OverBw += 1
End If
n21 += 2
End If
If i = n31 Then
If BitSet(p3Bit, kr(p3OverBw)) Then
kri = True
End If
p3Bit += 1
If p3Bit > bitsWidth Then
p3Bit = 1
p3OverBw += 1
End If
n31 += 3
End If
If kri Then
lastI = i
kr(iOverBw) = SetBit(iBit, kr(iOverBw))
krCount += 1
If krCount <= 100 Then
Console.Out.Write(" " & i.ToString().PadLeft(3))
If krCount Mod 20 = 0 Then
Console.Out.WriteLine()
End If
ElseIf krCount = p10 Then
Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10))
p10 *= 10
End If
kri = False
End If
Next i
Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10))
End Sub
End Module
|
Write the same algorithm in VB as shown in this Python implementation. | tutor = False
def pancakesort(data):
if len(data) <= 1:
return data
if tutor: print()
for size in range(len(data), 1, -1):
maxindex = max(range(size), key=data.__getitem__)
if maxindex+1 != size:
if maxindex != 0:
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), maxindex+1 ))
data[:maxindex+1] = reversed(data[:maxindex+1])
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), size ))
data[:size] = reversed(data[:size])
if tutor: print()
|
Public Sub printarray(A)
For i = LBound(A) To UBound(A)
Debug.Print A(i),
Next
Debug.Print
End Sub
Public Sub Flip(ByRef A, p1, p2, trace)
If trace Then Debug.Print "we
Cut = Int((p2 - p1 + 1) / 2)
For i = 0 To Cut - 1
temp = A(i)
A(i) = A(p2 - i)
A(p2 - i) = temp
Next
End Sub
Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False)
lb = LBound(A)
ub = UBound(A)
Length = ub - lb + 1
If Length <= 1 Then
Exit Sub
End If
For i = ub To lb + 1 Step -1
P = lb
Maximum = A(P)
For j = lb + 1 To i
If A(j) > Maximum Then
P = j
Maximum = A(j)
End If
Next j
If P < i Then
If P > 1 Then
Flip A, lb, P, trace
If trace Then printarray A
End If
Flip A, lb, i, trace
If trace Then printarray A
End If
Next i
End Sub
Public Sub TestPancake(Optional trace As Boolean = False)
Dim A()
A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)
Debug.Print "Initial array:"
printarray A
pancakesort A, trace
Debug.Print "Final array:"
printarray A
End Sub
|
Preserve the algorithm and functionality while converting the code from Python to VB. | assert 1.008 == molar_mass('H')
assert 2.016 == molar_mass('H2')
assert 18.015 == molar_mass('H2O')
assert 34.014 == molar_mass('H2O2')
assert 34.014 == molar_mass('(HO)2')
assert 142.036 == molar_mass('Na2SO4')
assert 84.162 == molar_mass('C6H12')
assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')
assert 176.124 == molar_mass('C6H4O2(OH)4')
assert 386.664 == molar_mass('C27H46O')
assert 315 == molar_mass('Uue')
| 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},
{"Na", 22.98976928},
{"Mg", 24.305},
{"Al", 26.9815385},
{"Si", 28.085},
{"P", 30.973761998},
{"S", 32.06},
{"Cl", 35.45},
{"Ar", 39.948},
{"K", 39.0983},
{"Ca", 40.078},
{"Sc", 44.955908},
{"Ti", 47.867},
{"V", 50.9415},
{"Cr", 51.9961},
{"Mn", 54.938044},
{"Fe", 55.845},
{"Co", 58.933194},
{"Ni", 58.6934},
{"Cu", 63.546},
{"Zn", 65.38},
{"Ga", 69.723},
{"Ge", 72.63},
{"As", 74.921595},
{"Se", 78.971},
{"Br", 79.904},
{"Kr", 83.798},
{"Rb", 85.4678},
{"Sr", 87.62},
{"Y", 88.90584},
{"Zr", 91.224},
{"Nb", 92.90637},
{"Mo", 95.95},
{"Ru", 101.07},
{"Rh", 102.9055},
{"Pd", 106.42},
{"Ag", 107.8682},
{"Cd", 112.414},
{"In", 114.818},
{"Sn", 118.71},
{"Sb", 121.76},
{"Te", 127.6},
{"I", 126.90447},
{"Xe", 131.293},
{"Cs", 132.90545196},
{"Ba", 137.327},
{"La", 138.90547},
{"Ce", 140.116},
{"Pr", 140.90766},
{"Nd", 144.242},
{"Pm", 145},
{"Sm", 150.36},
{"Eu", 151.964},
{"Gd", 157.25},
{"Tb", 158.92535},
{"Dy", 162.5},
{"Ho", 164.93033},
{"Er", 167.259},
{"Tm", 168.93422},
{"Yb", 173.054},
{"Lu", 174.9668},
{"Hf", 178.49},
{"Ta", 180.94788},
{"W", 183.84},
{"Re", 186.207},
{"Os", 190.23},
{"Ir", 192.217},
{"Pt", 195.084},
{"Au", 196.966569},
{"Hg", 200.592},
{"Tl", 204.38},
{"Pb", 207.2},
{"Bi", 208.9804},
{"Po", 209},
{"At", 210},
{"Rn", 222},
{"Fr", 223},
{"Ra", 226},
{"Ac", 227},
{"Th", 232.0377},
{"Pa", 231.03588},
{"U", 238.02891},
{"Np", 237},
{"Pu", 244},
{"Am", 243},
{"Cm", 247},
{"Bk", 247},
{"Cf", 251},
{"Es", 252},
{"Fm", 257},
{"Uue", 315},
{"Ubn", 299}
}
Function Evaluate(s As String) As Double
s += "["
Dim sum = 0.0
Dim symbol = ""
Dim number = ""
For i = 1 To s.Length
Dim c = s(i - 1)
If "@" <= c AndAlso c <= "[" Then
Dim n = 1
If number <> "" Then
n = Integer.Parse(number)
End If
If symbol <> "" Then
sum += atomicMass(symbol) * n
End If
If c = "[" Then
Exit For
End If
symbol = c.ToString
number = ""
ElseIf "a" <= c AndAlso c <= "z" Then
symbol += c
ElseIf "0" <= c AndAlso c <= "9" Then
number += c
Else
Throw New Exception(String.Format("Unexpected symbol {0} in molecule", c))
End If
Next
Return sum
End Function
Function ReplaceFirst(text As String, search As String, replace As String) As String
Dim pos = text.IndexOf(search)
If pos < 0 Then
Return text
Else
Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
End If
End Function
Function ReplaceParens(s As String) As String
Dim letter = "s"c
While True
Dim start = s.IndexOf("(")
If start = -1 Then
Exit While
End If
For i = start + 1 To s.Length - 1
If s(i) = ")" Then
Dim expr = s.Substring(start + 1, i - start - 1)
Dim symbol = String.Format("@{0}", letter)
s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)
atomicMass(symbol) = Evaluate(expr)
letter = Chr(Asc(letter) + 1)
Exit For
End If
If s(i) = "(" Then
start = i
Continue For
End If
Next
End While
Return s
End Function
Sub Main()
Dim molecules() As String = {
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
}
For Each molecule In molecules
Dim mass = Evaluate(ReplaceParens(molecule))
Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass)
Next
End Sub
End Module
|
Write the same code in VB as shown below in Python. | def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
r[d] = True
s1 += s2
s2 += 2
return [i for i, val in enumerate(r) if not val and i]
if __name__ == '__main__':
n = 2200
print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
| 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 = s
s = s + 2
s2 = s
For y = x + 1 To n
If l_add(s1) Then l(y) = True
s1 = s1 + s2
s2 = s2 + 2
Next
Next
For x = 1 To n
If Not l(x) Then Debug.Print x;
Next
Debug.Print
End Sub
|
Translate the given Python code snippet into VB without altering its behavior. |
from numpy import mean
from random import sample
def gen_long_stairs(start_step, start_length, climber_steps, add_steps):
secs, behind, total = 0, start_step, start_length
while True:
behind += climber_steps
behind += sum([behind > n for n in sample(range(total), add_steps)])
total += add_steps
secs += 1
yield (secs, behind, total)
ls = gen_long_stairs(1, 100, 1, 5)
print("Seconds Behind Ahead\n----------------------")
while True:
secs, pos, len = next(ls)
if 600 <= secs < 610:
print(secs, " ", pos, " ", len - pos)
elif secs == 610:
break
print("\nTen thousand trials to top:")
times, heights = [], []
for trial in range(10_000):
trialstairs = gen_long_stairs(1, 100, 1, 5)
while True:
sec, step, height = next(trialstairs)
if step >= height:
times.append(sec)
heights.append(height)
break
print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
| Option Explicit
Randomize Timer
Function pad(s,n)
If n<0 Then pad= right(space(-n) & s ,-n) Else pad= left(s& space(n),n) End If
End Function
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
Function Rounds(maxsecs,wiz,a)
Dim mystep,maxstep,toend,j,i,x,d
If IsArray(a) Then d=True: print "seconds behind pending"
maxstep=100
For j=1 To maxsecs
For i=1 To wiz
If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1
maxstep=maxstep+1
Next
mystep=mystep+1
If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function
If d Then
If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)
End If
Next
Rounds=Array(maxsecs,maxstep)
End Function
Dim n,r,a,sumt,sums,ntests,t,maxsecs
ntests=10000
maxsecs=7000
t=timer
a=Array(600,609)
For n=1 To ntests
r=Rounds(maxsecs,5,a)
If r(0)<>maxsecs Then
sumt=sumt+r(0)
sums=sums+r(1)
End if
a=""
Next
print vbcrlf & "Done " & ntests & " tests in " & Timer-t & " seconds"
print "escaped in " & sumt/ntests & " seconds with " & sums/ntests & " stairs"
|
Port the provided Python code into VB while preserving the original functionality. | seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
| Option Explicit
Dim seed As Long
Sub Main()
Dim i As Integer
seed = 675248
For i = 1 To 5
Debug.Print Rand
Next i
End Sub
Function Rand() As Variant
Dim s As String
s = CStr(seed ^ 2)
Do While Len(s) <> 12
s = "0" + s
Loop
seed = Val(Mid(s, 4, 6))
Rand = seed
End Function
|
Please provide an equivalent version of this Python code in VB. | seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
| Option Explicit
Dim seed As Long
Sub Main()
Dim i As Integer
seed = 675248
For i = 1 To 5
Debug.Print Rand
Next i
End Sub
Function Rand() As Variant
Dim s As String
s = CStr(seed ^ 2)
Do While Len(s) <> 12
s = "0" + s
Loop
seed = Val(Mid(s, 4, 6))
Rand = seed
End Function
|
Translate this program into VB but keep the logic exactly as in Python. |
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.disabled_prefix = disabled_prefix
def __str__(self):
disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]
value = (' %s' % self.value, '')[self.value is None]
return ''.join((disabled, self.name, value))
def get(self):
enabled = not bool(self.disabled)
if self.value is None:
value = enabled
else:
value = enabled and self.value
return value
class Config(object):
reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'
def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):
self.disabled_prefix = disabled_prefix
self.contents = []
self.options = {}
self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)
if fname:
self.parse_file(fname)
def __str__(self):
return '\n'.join(map(str, self.contents))
def parse_file(self, fname):
with open(fname) as f:
self.parse_lines(f)
return self
def parse_lines(self, lines):
for line in lines:
self.parse_line(line)
return self
def parse_line(self, line):
s = ''.join(c for c in line.strip() if c in string.printable)
moOPTION = self.creOPTION.match(s)
if moOPTION:
name = moOPTION.group('name').upper()
if not name in self.options:
self.add_option(name, moOPTION.group('value'),
moOPTION.group('disabled'))
else:
if not s.startswith(self.disabled_prefix):
self.contents.append(line.rstrip())
return self
def add_option(self, name, value=None, disabled=False):
name = name.upper()
opt = Option(name, value, disabled)
self.options[name] = opt
self.contents.append(opt)
return opt
def set_option(self, name, value=None, disabled=False):
name = name.upper()
opt = self.options.get(name)
if opt:
opt.value = value
opt.disabled = disabled
else:
opt = self.add_option(name, value, disabled)
return opt
def enable_option(self, name, value=None):
return self.set_option(name, value, False)
def disable_option(self, name, value=None):
return self.set_option(name, value, True)
def get_option(self, name):
opt = self.options.get(name.upper())
value = opt.get() if opt else None
return value
if __name__ == '__main__':
import sys
cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)
cfg.disable_option('needspeeling')
cfg.enable_option('seedsremoved')
cfg.enable_option('numberofbananas', 1024)
cfg.enable_option('numberofstrawberries', 62000)
print cfg
| 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 = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\IN_config.txt",1)
Output = ""
Isnumberofstrawberries = False
With objInFile
Do Until .AtEndOfStream
line = .ReadLine
If Left(line,1) = "#" Or line = "" Then
Output = Output & line & vbCrLf
ElseIf Left(line,1) = " " And InStr(line,"#") Then
Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf
ElseIf Replace(Replace(line,";","")," ","") <> "" Then
If InStr(1,line,"FAVOURITEFRUIT",1) Then
Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf
ElseIf InStr(1,line,"NEEDSPEELING",1) Then
Output = Output & "; " & "NEEDSPEELING" & vbCrLf
ElseIf InStr(1,line,"SEEDSREMOVED",1) Then
Output = Output & "SEEDSREMOVED" & vbCrLf
ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then
Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf
ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then
Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf
Isnumberofstrawberries = True
End If
End If
Loop
If Isnumberofstrawberries = False Then
Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf
Isnumberofstrawberries = True
End If
.Close
End With
Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\OUT_config.txt",2,True)
With objOutFile
.Write Output
.Close
End With
Set objFSO = Nothing
Set objParamLookup = Nothing
|
Ensure the translated VB code behaves exactly like the original Python snippet. | from logpy import *
from logpy.core import lall
import time
def lefto(q, p, list):
return membero((q,p), zip(list, list[1:]))
def nexto(q, p, list):
return conde([lefto(q, p, list)], [lefto(p, q, list)])
houses = var()
zebraRules = lall(
(eq, (var(), var(), var(), var(), var()), houses),
(membero, ('Englishman', var(), var(), var(), 'red'), houses),
(membero, ('Swede', var(), var(), 'dog', var()), houses),
(membero, ('Dane', var(), 'tea', var(), var()), houses),
(lefto, (var(), var(), var(), var(), 'green'),
(var(), var(), var(), var(), 'white'), houses),
(membero, (var(), var(), 'coffee', var(), 'green'), houses),
(membero, (var(), 'Pall Mall', var(), 'birds', var()), houses),
(membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses),
(eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),
(eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), var(), 'cats', var()), houses),
(nexto, (var(), 'Dunhill', var(), var(), var()),
(var(), var(), var(), 'horse', var()), houses),
(membero, (var(), 'Blue Master', 'beer', var(), var()), houses),
(membero, ('German', 'Prince', var(), var(), var()), houses),
(nexto, ('Norwegian', var(), var(), var(), var()),
(var(), var(), var(), var(), 'blue'), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), 'water', var(), var()), houses),
(membero, (var(), var(), var(), 'zebra', var()), houses)
)
t0 = time.time()
solutions = run(0, houses, zebraRules)
t1 = time.time()
dur = t1-t0
count = len(solutions)
zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]
print "%i solutions in %.2f seconds" % (count, dur)
print "The %s is the owner of the zebra" % zebraOwner
print "Here are all the houses:"
for line in solutions[0]:
print str(line)
| Option Base 1
Public Enum attr
Colour = 1
Nationality
Beverage
Smoke
Pet
End Enum
Public Enum Drinks_
Beer = 1
Coffee
Milk
Tea
Water
End Enum
Public Enum nations
Danish = 1
English
German
Norwegian
Swedish
End Enum
Public Enum colors
Blue = 1
Green
Red
White
Yellow
End Enum
Public Enum tobaccos
Blend = 1
BlueMaster
Dunhill
PallMall
Prince
End Enum
Public Enum animals
Bird = 1
Cat
Dog
Horse
Zebra
End Enum
Public permutation As New Collection
Public perm(5) As Variant
Const factorial5 = 120
Public Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant
Private Sub generate(n As Integer, A As Variant)
If n = 1 Then
permutation.Add A
Else
For i = 1 To n
generate n - 1, A
If n Mod 2 = 0 Then
tmp = A(i)
A(i) = A(n)
A(n) = tmp
Else
tmp = A(1)
A(1) = A(n)
A(n) = tmp
End If
Next i
End If
End Sub
Function house(i As Integer, name As Variant) As Integer
Dim x As Integer
For x = 1 To 5
If perm(i)(x) = name Then
house = x
Exit For
End If
Next x
End Function
Function left_of(h1 As Integer, h2 As Integer) As Boolean
left_of = (h1 - h2) = -1
End Function
Function next_to(h1 As Integer, h2 As Integer) As Boolean
next_to = Abs(h1 - h2) = 1
End Function
Private Sub print_house(i As Integer)
Debug.Print i & ": "; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _
Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))
End Sub
Public Sub Zebra_puzzle()
Colours = [{"blue","green","red","white","yellow"}]
Nationalities = [{"Dane","English","German","Norwegian","Swede"}]
Drinks = [{"beer","coffee","milk","tea","water"}]
Smokes = [{"Blend","Blue Master","Dunhill","Pall Mall","Prince"}]
Pets = [{"birds","cats","dog","horse","zebra"}]
Dim solperms As New Collection
Dim solutions As Integer
Dim b(5) As Integer, i As Integer
For i = 1 To 5: b(i) = i: Next i
generate 5, b
For c = 1 To factorial5
perm(Colour) = permutation(c)
If left_of(house(Colour, Green), house(Colour, White)) Then
For n = 1 To factorial5
perm(Nationality) = permutation(n)
If house(Nationality, Norwegian) = 1 _
And house(Nationality, English) = house(Colour, Red) _
And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then
For d = 1 To factorial5
perm(Beverage) = permutation(d)
If house(Nationality, Danish) = house(Beverage, Tea) _
And house(Beverage, Coffee) = house(Colour, Green) _
And house(Beverage, Milk) = 3 Then
For s = 1 To factorial5
perm(Smoke) = permutation(s)
If house(Colour, Yellow) = house(Smoke, Dunhill) _
And house(Nationality, German) = house(Smoke, Prince) _
And house(Smoke, BlueMaster) = house(Beverage, Beer) _
And next_to(house(Beverage, Water), house(Smoke, Blend)) Then
For p = 1 To factorial5
perm(Pet) = permutation(p)
If house(Nationality, Swedish) = house(Pet, Dog) _
And house(Smoke, PallMall) = house(Pet, Bird) _
And next_to(house(Smoke, Blend), house(Pet, Cat)) _
And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then
For i = 1 To 5
print_house i
Next i
Debug.Print
solutions = solutions + 1
solperms.Add perm
End If
Next p
End If
Next s
End If
Next d
End If
Next n
End If
Next c
Debug.Print Format(solutions, "@"); " solution" & IIf(solutions > 1, "s", "") & " found"
For i = 1 To solperms.Count
For j = 1 To 5
perm(j) = solperms(i)(j)
Next j
Debug.Print "The " & Nationalities(perm(Nationality)(house(Pet, Zebra))) & " owns the Zebra"
Next i
End Sub
|
Transform the following Python implementation into VB, maintaining the same output and logic. |
from operator import attrgetter
from typing import Iterator
import mwclient
URL = 'www.rosettacode.org'
API_PATH = '/mw/'
def unimplemented_tasks(language: str,
*,
url: str,
api_path: str) -> Iterator[str]:
site = mwclient.Site(url, path=api_path)
all_tasks = site.categories['Programming Tasks']
language_tasks = site.categories[language]
name = attrgetter('name')
all_tasks_names = map(name, all_tasks)
language_tasks_names = set(map(name, language_tasks))
for task in all_tasks_names:
if task not in language_tasks_names:
yield task
if __name__ == '__main__':
tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)
print(*tasks, sep='\n')
| Set http= CreateObject("WinHttp.WinHttpRequest.5.1")
Set oDic = WScript.CreateObject("scripting.dictionary")
start="https://rosettacode.org"
Const lang="VBScript"
Dim oHF
gettaskslist "about:/wiki/Category:Programming_Tasks" ,True
print odic.Count
gettaskslist "about:/wiki/Category:Draft_Programming_Tasks",True
print "total tasks " & odic.Count
gettaskslist "about:/wiki/Category:"&lang,False
print "total tasks not in " & lang & " " &odic.Count & vbcrlf
For Each d In odic.keys
print d &vbTab & Replace(odic(d),"about:", start)
next
WScript.Quit(1)
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
Function getpage(name)
Set oHF=Nothing
Set oHF = CreateObject("HTMLFILE")
http.open "GET",name,False
http.send
oHF.write "<html><body></body></html>"
oHF.body.innerHTML = http.responsetext
Set getpage=Nothing
End Function
Sub gettaskslist(b,build)
nextpage=b
While nextpage <>""
nextpage=Replace(nextpage,"about:", start)
WScript.Echo nextpage
getpage(nextpage)
Set xtoc = oHF.getElementbyId("mw-pages")
nextpage=""
For Each ch In xtoc.children
If ch.innertext= "next page" Then
nextpage=ch.attributes("href").value
ElseIf ch.attributes("class").value="mw-content-ltr" Then
Set ytoc=ch.children(0)
Exit For
End If
Next
For Each ch1 In ytoc.children
For Each ch2 In ch1.children(1).children
Set ch=ch2.children(0)
If build Then
odic.Add ch.innertext , ch.attributes("href").value
else
odic.Remove ch.innertext
End if
Next
Next
Wend
End Sub
|
Generate a VB translation of this Python snippet without changing its computational steps. | import mpmath as mp
with mp.workdps(72):
def integer_term(n):
p = 532 * n * n + 126 * n + 9
return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)
def exponent_term(n):
return -(mp.mpf("6.0") * n + 3)
def nthterm(n):
return integer_term(n) * mp.mpf("10.0")**exponent_term(n)
for n in range(10):
print("Term ", n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\nπ to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath π is ', end='')
mp.nprint(mp.pi, 71)
| 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 While : Return r
End Function
Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String
digs += 1
Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb
Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1
For n As BI = 0 To dg - 1
If n > 0 Then t3 = t3 * BI.Pow(n, 6)
te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6
If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)
If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t)
su += te : If te < 10 Then
digs -= 1
If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _
"after the decimal point." & vbLf, n, digs)
Exit For
End If
For j As BI = n * 6 + 1 To n * 6 + 6
t1 = t1 * j : Next
d += 2 : t2 += 126 + 532 * d
Next
Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _
/ su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))
Return s(0) & "." & s.Substring(1, digs)
End Function
Sub Main(ByVal args As String())
WriteLine(dump(70, true))
End Sub
End Module
|
Change the following Python code into VB without altering its purpose. | import mpmath as mp
with mp.workdps(72):
def integer_term(n):
p = 532 * n * n + 126 * n + 9
return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)
def exponent_term(n):
return -(mp.mpf("6.0") * n + 3)
def nthterm(n):
return integer_term(n) * mp.mpf("10.0")**exponent_term(n)
for n in range(10):
print("Term ", n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\nπ to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath π is ', end='')
mp.nprint(mp.pi, 71)
| 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 While : Return r
End Function
Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String
digs += 1
Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb
Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1
For n As BI = 0 To dg - 1
If n > 0 Then t3 = t3 * BI.Pow(n, 6)
te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6
If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)
If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t)
su += te : If te < 10 Then
digs -= 1
If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _
"after the decimal point." & vbLf, n, digs)
Exit For
End If
For j As BI = n * 6 + 1 To n * 6 + 6
t1 = t1 * j : Next
d += 2 : t2 += 126 + 532 * d
Next
Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _
/ su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))
Return s(0) & "." & s.Substring(1, digs)
End Function
Sub Main(ByVal args As String())
WriteLine(dump(70, true))
End Sub
End Module
|
Please provide an equivalent version of this Python code in VB. | from itertools import chain, cycle, accumulate, combinations
from typing import List, Tuple
def factors5(n: int) -> List[int]:
def prime_powers(n):
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d + (p,)
yield(d)
if n > 1: yield((n,))
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r[:-1]
def powerset(s: List[int]) -> List[Tuple[int, ...]]:
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))
def is_practical(x: int) -> bool:
if x == 1:
return True
if x %2:
return False
f = factors5(x)
ps = powerset(f)
found = {y for y in {sum(i) for i in ps}
if 1 <= y < x}
return len(found) == x - 1
if __name__ == '__main__':
n = 333
p = [x for x in range(1, n + 1) if is_practical(x)]
print(f"There are {len(p)} Practical numbers from 1 to {n}:")
print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])
x = 666
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
| 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 : Case 0 : Return True
Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0)
rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)
End Select : Return true
End Function
Function ip(ByVal n As Integer) As Boolean
Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()
Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))
End Function
Sub Main()
Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m
If ip(i) OrElse i = 1 Then c += 1 : Write("{0,3} {1}", i, If(c Mod 10 = 0, vbLf, ""))
i += If(i = 1, 1, 2) : End While
Write(vbLf & "Found {0} practical numbers between 1 and {1} inclusive." & vbLf, c, m)
Do : m = If(m < 500, m << 1, m * 10 + 6)
Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4
End Sub
End Module
|
Produce a functionally identical VB code for the snippet given in Python. | 2.3
.3
.3e4
.3e+34
.3e-34
2.e34
| Sub Main()
Dim d As Double
Dim s As Single
d = -12.3456
d = 1000#
d = 0.00001
d = 67#
d = 8.9
d = 0.33
d = 0#
d = 2# * 10 ^ 3
d = 2E+50
d = 2E-50
s = -12.3456!
s = 1000!
s = 0.00001!
s = 67!
s = 8.9!
s = 0.33!
s = 0!
s = 2! * 10 ^ 3
End Sub
|
Port the provided Python code into VB while preserving the original functionality. | import re
from random import shuffle, randint
dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
class Grid:
def __init__(self):
self.num_attempts = 0
self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]
self.solutions = []
def read_words(filename):
max_len = max(n_rows, n_cols)
words = []
with open(filename, "r") as file:
for line in file:
s = line.strip().lower()
if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:
words.append(s)
return words
def place_message(grid, msg):
msg = re.sub(r'[^A-Z]', "", msg.upper())
message_len = len(msg)
if 0 < message_len < grid_size:
gap_size = grid_size // message_len
for i in range(0, message_len):
pos = i * gap_size + randint(0, gap_size)
grid.cells[pos // n_cols][pos % n_cols] = msg[i]
return message_len
return 0
def try_location(grid, word, direction, pos):
r = pos // n_cols
c = pos % n_cols
length = len(word)
if (dirs[direction][0] == 1 and (length + c) > n_cols) or \
(dirs[direction][0] == -1 and (length - 1) > c) or \
(dirs[direction][1] == 1 and (length + r) > n_rows) or \
(dirs[direction][1] == -1 and (length - 1) > r):
return 0
rr = r
cc = c
i = 0
overlaps = 0
while i < length:
if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:
return 0
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
rr = r
cc = c
i = 0
while i < length:
if grid.cells[rr][cc] == word[i]:
overlaps += 1
else:
grid.cells[rr][cc] = word[i]
if i < length - 1:
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
letters_placed = length - overlaps
if letters_placed > 0:
grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr))
return letters_placed
def try_place_word(grid, word):
rand_dir = randint(0, len(dirs))
rand_pos = randint(0, grid_size)
for direction in range(0, len(dirs)):
direction = (direction + rand_dir) % len(dirs)
for pos in range(0, grid_size):
pos = (pos + rand_pos) % grid_size
letters_placed = try_location(grid, word, direction, pos)
if letters_placed > 0:
return letters_placed
return 0
def create_word_search(words):
grid = None
num_attempts = 0
while num_attempts < 100:
num_attempts += 1
shuffle(words)
grid = Grid()
message_len = place_message(grid, "Rosetta Code")
target = grid_size - message_len
cells_filled = 0
for word in words:
cells_filled += try_place_word(grid, word)
if cells_filled == target:
if len(grid.solutions) >= min_words:
grid.num_attempts = num_attempts
return grid
else:
break
return grid
def print_result(grid):
if grid is None or grid.num_attempts == 0:
print("No grid to display")
return
size = len(grid.solutions)
print("Attempts: {0}".format(grid.num_attempts))
print("Number of words: {0}".format(size))
print("\n 0 1 2 3 4 5 6 7 8 9\n")
for r in range(0, n_rows):
print("{0} ".format(r), end='')
for c in range(0, n_cols):
print(" %c " % grid.cells[r][c], end='')
print()
print()
for i in range(0, size - 1, 2):
print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1]))
if size % 2 == 1:
print(grid.solutions[size - 1])
if __name__ == "__main__":
print_result(create_word_search(read_words("unixdict.txt")))
| Module Module1
ReadOnly Dirs As Integer(,) = {
{1, 0}, {0, 1}, {1, 1},
{1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}
}
Const RowCount = 10
Const ColCount = 10
Const GridSize = RowCount * ColCount
Const MinWords = 25
Class Grid
Public cells(RowCount - 1, ColCount - 1) As Char
Public solutions As New List(Of String)
Public numAttempts As Integer
Sub New()
For i = 0 To RowCount - 1
For j = 0 To ColCount - 1
cells(i, j) = ControlChars.NullChar
Next
Next
End Sub
End Class
Dim Rand As New Random()
Sub Main()
PrintResult(CreateWordSearch(ReadWords("unixdict.txt")))
End Sub
Function ReadWords(filename As String) As List(Of String)
Dim maxlen = Math.Max(RowCount, ColCount)
Dim words As New List(Of String)
Dim objReader As New IO.StreamReader(filename)
Dim line As String
Do While objReader.Peek() <> -1
line = objReader.ReadLine()
If line.Length > 3 And line.Length < maxlen Then
If line.All(Function(c) Char.IsLetter(c)) Then
words.Add(line)
End If
End If
Loop
Return words
End Function
Function CreateWordSearch(words As List(Of String)) As Grid
For numAttempts = 1 To 1000
Shuffle(words)
Dim grid As New Grid()
Dim messageLen = PlaceMessage(grid, "Rosetta Code")
Dim target = GridSize - messageLen
Dim cellsFilled = 0
For Each word In words
cellsFilled = cellsFilled + TryPlaceWord(grid, word)
If cellsFilled = target Then
If grid.solutions.Count >= MinWords Then
grid.numAttempts = numAttempts
Return grid
Else
Exit For
End If
End If
Next
Next
Return Nothing
End Function
Function PlaceMessage(grid As Grid, msg As String) As Integer
msg = msg.ToUpper()
msg = msg.Replace(" ", "")
If msg.Length > 0 And msg.Length < GridSize Then
Dim gapSize As Integer = GridSize / msg.Length
Dim pos = 0
Dim lastPos = -1
For i = 0 To msg.Length - 1
If i = 0 Then
pos = pos + Rand.Next(gapSize - 1)
Else
pos = pos + Rand.Next(2, gapSize - 1)
End If
Dim r As Integer = Math.Floor(pos / ColCount)
Dim c = pos Mod ColCount
grid.cells(r, c) = msg(i)
lastPos = pos
Next
Return msg.Length
End If
Return 0
End Function
Function TryPlaceWord(grid As Grid, word As String) As Integer
Dim randDir = Rand.Next(Dirs.GetLength(0))
Dim randPos = Rand.Next(GridSize)
For d = 0 To Dirs.GetLength(0) - 1
Dim dd = (d + randDir) Mod Dirs.GetLength(0)
For p = 0 To GridSize - 1
Dim pp = (p + randPos) Mod GridSize
Dim lettersPLaced = TryLocation(grid, word, dd, pp)
If lettersPLaced > 0 Then
Return lettersPLaced
End If
Next
Next
Return 0
End Function
Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer
Dim r As Integer = pos / ColCount
Dim c = pos Mod ColCount
Dim len = word.Length
If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then
Return 0
End If
If r = RowCount OrElse c = ColCount Then
Return 0
End If
Dim rr = r
Dim cc = c
For i = 0 To len - 1
If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then
Return 0
End If
cc = cc + Dirs(dir, 0)
rr = rr + Dirs(dir, 1)
Next
Dim overlaps = 0
rr = r
cc = c
For i = 0 To len - 1
If grid.cells(rr, cc) = word(i) Then
overlaps = overlaps + 1
Else
grid.cells(rr, cc) = word(i)
End If
If i < len - 1 Then
cc = cc + Dirs(dir, 0)
rr = rr + Dirs(dir, 1)
End If
Next
Dim lettersPlaced = len - overlaps
If lettersPlaced > 0 Then
grid.solutions.Add(String.Format("{0,-10} ({1},{2})({3},{4})", word, c, r, cc, rr))
End If
Return lettersPlaced
End Function
Sub PrintResult(grid As Grid)
If IsNothing(grid) OrElse grid.numAttempts = 0 Then
Console.WriteLine("No grid to display")
Return
End If
Console.WriteLine("Attempts: {0}", grid.numAttempts)
Console.WriteLine("Number of words: {0}", GridSize)
Console.WriteLine()
Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9")
For r = 0 To RowCount - 1
Console.WriteLine()
Console.Write("{0} ", r)
For c = 0 To ColCount - 1
Console.Write(" {0} ", grid.cells(r, c))
Next
Next
Console.WriteLine()
Console.WriteLine()
For i = 0 To grid.solutions.Count - 1
If i Mod 2 = 0 Then
Console.Write("{0}", grid.solutions(i))
Else
Console.WriteLine(" {0}", grid.solutions(i))
End If
Next
Console.WriteLine()
End Sub
Sub Shuffle(Of T)(list As IList(Of T))
Dim r As Random = New Random()
For i = 0 To list.Count - 1
Dim index As Integer = r.Next(i, list.Count)
If i <> index Then
Dim temp As T = list(i)
list(i) = list(index)
list(index) = temp
End If
Next
End Sub
End Module
|
Can you help me rewrite this code in VB instead of Python, keeping it the same logically? | >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
| Imports System.Reflection
Public Class MyClazz
Private answer As Integer = 42
End Class
Public Class Program
Public Shared Sub Main()
Dim myInstance = New MyClazz()
Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim answer = fieldInfo.GetValue(myInstance)
Console.WriteLine(answer)
End Sub
End Class
|
Write the same algorithm in VB as shown in this Python implementation. | >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
| Imports System.Reflection
Public Class MyClazz
Private answer As Integer = 42
End Class
Public Class Program
Public Shared Sub Main()
Dim myInstance = New MyClazz()
Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim answer = fieldInfo.GetValue(myInstance)
Console.WriteLine(answer)
End Sub
End Class
|
Can you help me rewrite this code in VB instead of Python, keeping it the same logically? |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.rte.len = 0
self.S = [0]
self.maxSufT = self.rte
def get_max_suffix_pal(self, startNode, a):
u = startNode
i = len(self.S)
k = u.len
while id(u) != id(self.rto) and self.S[i - k - 1] != a:
assert id(u) != id(u.link)
u = u.link
k = u.len
return u
def add(self, a):
Q = self.get_max_suffix_pal(self.maxSufT, a)
createANewNode = not a in Q.edges
if createANewNode:
P = Node()
self.nodes.append(P)
P.len = Q.len + 2
if P.len == 1:
P.link = self.rte
else:
P.link = self.get_max_suffix_pal(Q.link, a).edges[a]
Q.edges[a] = P
self.maxSufT = Q.edges[a]
self.S.append(a)
return createANewNode
def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
for lnkName in nd.edges:
nd2 = nd.edges[lnkName]
self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)
if id(nd) != id(self.rto) and id(nd) != id(self.rte):
tmp = "".join(charsToHere)
if id(nodesToHere[0]) == id(self.rte):
assembled = tmp[::-1] + tmp
else:
assembled = tmp[::-1] + tmp[1:]
result.append(assembled)
if __name__=="__main__":
st = "eertree"
print ("Processing string", st)
eertree = Eertree()
for ch in st:
eertree.add(ch)
print ("Number of sub-palindromes:", len(eertree.nodes))
result = []
eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result)
eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result)
print ("Sub-palindromes:", result)
| 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), New Dictionary(Of Char, Integer), edg)
Suffix = suf
End Sub
Property Edges As Dictionary(Of Char, Integer)
Property Length As Integer
Property Suffix As Integer
End Class
ReadOnly EVEN_ROOT As Integer = 0
ReadOnly ODD_ROOT As Integer = 1
Function Eertree(s As String) As List(Of Node)
Dim tree As New List(Of Node) From {
New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),
New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)
}
Dim suffix = ODD_ROOT
Dim n As Integer
Dim k As Integer
For i = 1 To s.Length
Dim c = s(i - 1)
n = suffix
While True
k = tree(n).Length
Dim b = i - k - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
n = tree(n).Suffix
End While
If tree(n).Edges.ContainsKey(c) Then
suffix = tree(n).Edges(c)
Continue For
End If
suffix = tree.Count
tree.Add(New Node(k + 2))
tree(n).Edges(c) = suffix
If tree(suffix).Length = 1 Then
tree(suffix).Suffix = 0
Continue For
End If
While True
n = tree(n).Suffix
Dim b = i - tree(n).Length - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
End While
Dim a = tree(n)
Dim d = a.Edges(c)
Dim e = tree(suffix)
e.Suffix = d
Next
Return tree
End Function
Function SubPalindromes(tree As List(Of Node)) As List(Of String)
Dim s As New List(Of String)
Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)
For Each c In tree(n).Edges.Keys
Dim m = tree(n).Edges(c)
Dim p1 = c + p + c
s.Add(p1)
children(m, p1)
Next
End Sub
children(0, "")
For Each c In tree(1).Edges.Keys
Dim m = tree(1).Edges(c)
Dim ct = c.ToString()
s.Add(ct)
children(m, ct)
Next
Return s
End Function
Sub Main()
Dim tree = Eertree("eertree")
Dim result = SubPalindromes(tree)
Dim listStr = String.Join(", ", result)
Console.WriteLine("[{0}]", listStr)
End Sub
End Module
|
Ensure the translated VB code behaves exactly like the original Python snippet. |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.rte.len = 0
self.S = [0]
self.maxSufT = self.rte
def get_max_suffix_pal(self, startNode, a):
u = startNode
i = len(self.S)
k = u.len
while id(u) != id(self.rto) and self.S[i - k - 1] != a:
assert id(u) != id(u.link)
u = u.link
k = u.len
return u
def add(self, a):
Q = self.get_max_suffix_pal(self.maxSufT, a)
createANewNode = not a in Q.edges
if createANewNode:
P = Node()
self.nodes.append(P)
P.len = Q.len + 2
if P.len == 1:
P.link = self.rte
else:
P.link = self.get_max_suffix_pal(Q.link, a).edges[a]
Q.edges[a] = P
self.maxSufT = Q.edges[a]
self.S.append(a)
return createANewNode
def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
for lnkName in nd.edges:
nd2 = nd.edges[lnkName]
self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)
if id(nd) != id(self.rto) and id(nd) != id(self.rte):
tmp = "".join(charsToHere)
if id(nodesToHere[0]) == id(self.rte):
assembled = tmp[::-1] + tmp
else:
assembled = tmp[::-1] + tmp[1:]
result.append(assembled)
if __name__=="__main__":
st = "eertree"
print ("Processing string", st)
eertree = Eertree()
for ch in st:
eertree.add(ch)
print ("Number of sub-palindromes:", len(eertree.nodes))
result = []
eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result)
eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result)
print ("Sub-palindromes:", result)
| 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), New Dictionary(Of Char, Integer), edg)
Suffix = suf
End Sub
Property Edges As Dictionary(Of Char, Integer)
Property Length As Integer
Property Suffix As Integer
End Class
ReadOnly EVEN_ROOT As Integer = 0
ReadOnly ODD_ROOT As Integer = 1
Function Eertree(s As String) As List(Of Node)
Dim tree As New List(Of Node) From {
New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),
New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)
}
Dim suffix = ODD_ROOT
Dim n As Integer
Dim k As Integer
For i = 1 To s.Length
Dim c = s(i - 1)
n = suffix
While True
k = tree(n).Length
Dim b = i - k - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
n = tree(n).Suffix
End While
If tree(n).Edges.ContainsKey(c) Then
suffix = tree(n).Edges(c)
Continue For
End If
suffix = tree.Count
tree.Add(New Node(k + 2))
tree(n).Edges(c) = suffix
If tree(suffix).Length = 1 Then
tree(suffix).Suffix = 0
Continue For
End If
While True
n = tree(n).Suffix
Dim b = i - tree(n).Length - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
End While
Dim a = tree(n)
Dim d = a.Edges(c)
Dim e = tree(suffix)
e.Suffix = d
Next
Return tree
End Function
Function SubPalindromes(tree As List(Of Node)) As List(Of String)
Dim s As New List(Of String)
Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)
For Each c In tree(n).Edges.Keys
Dim m = tree(n).Edges(c)
Dim p1 = c + p + c
s.Add(p1)
children(m, p1)
Next
End Sub
children(0, "")
For Each c In tree(1).Edges.Keys
Dim m = tree(1).Edges(c)
Dim ct = c.ToString()
s.Add(ct)
children(m, ct)
Next
Return s
End Function
Sub Main()
Dim tree = Eertree("eertree")
Dim result = SubPalindromes(tree)
Dim listStr = String.Join(", ", result)
Console.WriteLine("[{0}]", listStr)
End Sub
End Module
|
Convert the following code from Python to VB, ensuring the logic remains intact. |
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
| DEFINT A-Z
DECLARE FUNCTION p% (Yr AS INTEGER)
DECLARE FUNCTION LongYear% (Yr AS INTEGER)
DIM iYi, iYf, i
CLS
PRINT "This program calculates which are 53-week years in a range."
PRINT
INPUT "Initial year"; iYi
INPUT "Final year (could be the same)"; iYf
IF iYf >= iYi THEN
FOR i = iYi TO iYf
IF LongYear(i) THEN
PRINT i; " ";
END IF
NEXT i
END IF
PRINT
PRINT
PRINT "End of program."
END
FUNCTION LongYear% (Yr AS INTEGER)
LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)
END FUNCTION
FUNCTION p% (Yr AS INTEGER)
p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7
END FUNCTION
|
Generate an equivalent VB version of this Python code. | from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s % 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def printZumkellers(N, oddonly=False):
nprinted = 0
for n in range(1, 10**5):
if (oddonly == False or n % 2) and isZumkeller(n):
print(f'{n:>8}', end='')
nprinted += 1
if nprinted % 10 == 0:
print()
if nprinted >= N:
return
print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)
| 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
divs.Add(j)
End If
End If
i += 1
End While
Return divs
End Function
Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean
If sum = 0 Then
Return True
End If
Dim le = divs.Count
If le = 0 Then
Return False
End If
Dim last = divs(le - 1)
Dim newDivs As New List(Of Integer)
For i = 1 To le - 1
newDivs.Add(divs(i - 1))
Next
If last > sum Then
Return IsPartSum(newDivs, sum)
End If
Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)
End Function
Function IsZumkeller(n As Integer) As Boolean
Dim divs = GetDivisors(n)
Dim sum = divs.Sum()
REM if sum is odd can
If sum Mod 2 = 1 Then
Return False
End If
REM if n is odd use
If n Mod 2 = 1 Then
Dim abundance = sum - 2 * n
Return abundance > 0 AndAlso abundance Mod 2 = 0
End If
REM if n and sum are both even check if there
Return IsPartSum(divs, sum \ 2)
End Function
Sub Main()
Console.WriteLine("The first 220 Zumkeller numbers are:")
Dim i = 2
Dim count = 0
While count < 220
If IsZumkeller(i) Then
Console.Write("{0,3} ", i)
count += 1
If count Mod 20 = 0 Then
Console.WriteLine()
End If
End If
i += 1
End While
Console.WriteLine()
Console.WriteLine("The first 40 odd Zumkeller numbers are:")
i = 3
count = 0
While count < 40
If IsZumkeller(i) Then
Console.Write("{0,5} ", i)
count += 1
If count Mod 10 = 0 Then
Console.WriteLine()
End If
End If
i += 2
End While
Console.WriteLine()
Console.WriteLine("The first 40 odd Zumkeller numbers which don
i = 3
count = 0
While count < 40
If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then
Console.Write("{0,7} ", i)
count += 1
If count Mod 8 = 0 Then
Console.WriteLine()
End If
End If
i += 2
End While
End Sub
End Module
|
Produce a functionally identical VB code for the snippet given in Python. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| Private Type Associative
Key As String
Value As Variant
End Type
Sub Main_Array_Associative()
Dim BaseArray(2) As Associative, UpdateArray(2) As Associative
FillArrays BaseArray, UpdateArray
ReDim Result(UBound(BaseArray)) As Associative
MergeArray Result, BaseArray, UpdateArray
PrintOut Result
End Sub
Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)
Dim i As Long, Respons As Long
Res = Base
For i = LBound(Update) To UBound(Update)
If Exist(Respons, Base, Update(i).Key) Then
Res(Respons).Value = Update(i).Value
Else
ReDim Preserve Res(UBound(Res) + 1)
Res(UBound(Res)).Key = Update(i).Key
Res(UBound(Res)).Value = Update(i).Value
End If
Next
End Sub
Private Function Exist(R As Long, B() As Associative, K As String) As Boolean
Dim i As Long
Do
If B(i).Key = K Then
Exist = True
R = i
End If
i = i + 1
Loop While i <= UBound(B) And Not Exist
End Function
Private Sub FillArrays(B() As Associative, U() As Associative)
B(0).Key = "name"
B(0).Value = "Rocket Skates"
B(1).Key = "price"
B(1).Value = 12.75
B(2).Key = "color"
B(2).Value = "yellow"
U(0).Key = "price"
U(0).Value = 15.25
U(1).Key = "color"
U(1).Value = "red"
U(2).Key = "year"
U(2).Value = 1974
End Sub
Private Sub PrintOut(A() As Associative)
Dim i As Long
Debug.Print "Key", "Value"
For i = LBound(A) To UBound(A)
Debug.Print A(i).Key, A(i).Value
Next i
Debug.Print "-----------------------------"
End Sub
|
Generate a VB translation of this Python snippet without changing its computational steps. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| Private Type Associative
Key As String
Value As Variant
End Type
Sub Main_Array_Associative()
Dim BaseArray(2) As Associative, UpdateArray(2) As Associative
FillArrays BaseArray, UpdateArray
ReDim Result(UBound(BaseArray)) As Associative
MergeArray Result, BaseArray, UpdateArray
PrintOut Result
End Sub
Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)
Dim i As Long, Respons As Long
Res = Base
For i = LBound(Update) To UBound(Update)
If Exist(Respons, Base, Update(i).Key) Then
Res(Respons).Value = Update(i).Value
Else
ReDim Preserve Res(UBound(Res) + 1)
Res(UBound(Res)).Key = Update(i).Key
Res(UBound(Res)).Value = Update(i).Value
End If
Next
End Sub
Private Function Exist(R As Long, B() As Associative, K As String) As Boolean
Dim i As Long
Do
If B(i).Key = K Then
Exist = True
R = i
End If
i = i + 1
Loop While i <= UBound(B) And Not Exist
End Function
Private Sub FillArrays(B() As Associative, U() As Associative)
B(0).Key = "name"
B(0).Value = "Rocket Skates"
B(1).Key = "price"
B(1).Value = 12.75
B(2).Key = "color"
B(2).Value = "yellow"
U(0).Key = "price"
U(0).Value = 15.25
U(1).Key = "color"
U(1).Value = "red"
U(2).Key = "year"
U(2).Value = 1974
End Sub
Private Sub PrintOut(A() As Associative)
Dim i As Long
Debug.Print "Key", "Value"
For i = LBound(A) To UBound(A)
Debug.Print A(i).Key, A(i).Value
Next i
Debug.Print "-----------------------------"
End Sub
|
Convert the following code from Python to VB, ensuring the logic remains intact. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256)
| 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 = d
d = term - res
End While
Return term
End Function
Function DoOne(b As Integer, digs As Integer) As String
REM calculates result via square root, not iterations
Dim s = b * b + 4
digs += 1
Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))
Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g)
bs += b * BI.Parse("1" + New String("0", digs))
bs >>= 1
bs += 4
Dim st = bs.ToString
digs -= 1
Return String.Format("{0}.{1}", st(0), st.Substring(1, digs))
End Function
Function DivIt(a As BI, b As BI, digs As Integer) As String
REM performs division
Dim al = a.ToString.Length
Dim bl = b.ToString.Length
digs += 1
a *= BI.Pow(10, digs << 1)
b *= BI.Pow(10, digs)
Dim s = (a / b + 5).ToString
digs -= 1
Return s(0) + "." + s.Substring(1, digs)
End Function
REM custom formatting
Function Joined(x() As BI) As String
Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
Dim res = ""
For i = 0 To x.Length - 1
res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i))
Next
Return res
End Function
Sub Main()
REM calculates and checks each "metal"
Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc")
Dim t = ""
Dim n As BI
Dim nm1 As BI
Dim k As Integer
Dim j As Integer
For b = 0 To 9
Dim lst(14) As BI
lst(0) = 1
lst(1) = 1
For i = 2 To 14
lst(i) = b * lst(i - 1) + lst(i - 2)
Next
REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15
n = lst(14)
nm1 = lst(13)
k = 0
j = 13
While k = 0
Dim lt = t
t = DivIt(n, nm1, 32)
If lt = t Then
k = If(b = 0, 1, j)
End If
Dim onn = n
n = b * n + nm1
nm1 = onn
j += 1
End While
Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst))
Next
REM now calculate and check big one
n = 1
nm1 = 1
k = 0
j = 1
While k = 0
Dim lt = t
t = DivIt(n, nm1, 256)
If lt = t Then
k = j
End If
Dim onn = n
n += nm1
nm1 = onn
j += 1
End While
Console.WriteLine()
Console.WriteLine("Au to 256 digits:")
Console.WriteLine(t)
Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256))
End Sub
End Module
|
Transform the following Python implementation into VB, maintaining the same output and logic. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256)
| 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 = d
d = term - res
End While
Return term
End Function
Function DoOne(b As Integer, digs As Integer) As String
REM calculates result via square root, not iterations
Dim s = b * b + 4
digs += 1
Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))
Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g)
bs += b * BI.Parse("1" + New String("0", digs))
bs >>= 1
bs += 4
Dim st = bs.ToString
digs -= 1
Return String.Format("{0}.{1}", st(0), st.Substring(1, digs))
End Function
Function DivIt(a As BI, b As BI, digs As Integer) As String
REM performs division
Dim al = a.ToString.Length
Dim bl = b.ToString.Length
digs += 1
a *= BI.Pow(10, digs << 1)
b *= BI.Pow(10, digs)
Dim s = (a / b + 5).ToString
digs -= 1
Return s(0) + "." + s.Substring(1, digs)
End Function
REM custom formatting
Function Joined(x() As BI) As String
Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
Dim res = ""
For i = 0 To x.Length - 1
res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i))
Next
Return res
End Function
Sub Main()
REM calculates and checks each "metal"
Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc")
Dim t = ""
Dim n As BI
Dim nm1 As BI
Dim k As Integer
Dim j As Integer
For b = 0 To 9
Dim lst(14) As BI
lst(0) = 1
lst(1) = 1
For i = 2 To 14
lst(i) = b * lst(i - 1) + lst(i - 2)
Next
REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15
n = lst(14)
nm1 = lst(13)
k = 0
j = 13
While k = 0
Dim lt = t
t = DivIt(n, nm1, 32)
If lt = t Then
k = If(b = 0, 1, j)
End If
Dim onn = n
n = b * n + nm1
nm1 = onn
j += 1
End While
Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst))
Next
REM now calculate and check big one
n = 1
nm1 = 1
k = 0
j = 1
While k = 0
Dim lt = t
t = DivIt(n, nm1, 256)
If lt = t Then
k = j
End If
Dim onn = n
n += nm1
nm1 = onn
j += 1
End While
Console.WriteLine()
Console.WriteLine("Au to 256 digits:")
Console.WriteLine(t)
Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256))
End Sub
End Module
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.