Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this C# function in VB with identical behavior. | using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
Debug.Assert(result.Length == 183231);
Debug.Assert(result.StartsWith("62060698786608744707"));
Debug.Assert(result.EndsWith("92256259918212890625"));
Console.WriteLine("n = 5^4^3^2");
Console.WriteLine("n = {0}...{1}",
result.Substring(0, 20),
result.Substring(result.Length - 20, 20)
);
Console.WriteLine("n digits = {0}", result.Length);
}
}
| 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
|
Convert this C# snippet to VB and keep its semantics consistent. | Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
| 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 algorithm in VB as shown in this C# implementation. | Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
| 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
|
Ensure the translated VB code behaves exactly like the original C# snippet. | class Program
{
static void Main(string[] args)
{
Random random = new Random();
while (true)
{
int a = random.Next(20);
Console.WriteLine(a);
if (a == 10)
break;
int b = random.Next(20)
Console.WriteLine(b);
}
Console.ReadLine();
}
}
| 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
|
Port the provided C# code into VB while preserving the original functionality. | class Program
{
static void Main(string[] args)
{
Random random = new Random();
while (true)
{
int a = random.Next(20);
Console.WriteLine(a);
if (a == 10)
break;
int b = random.Next(20)
Console.WriteLine(b);
}
Console.ReadLine();
}
}
| 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
|
Write the same code in VB as shown below in C#. | class Program
{
static void Main(string[] args)
{
int[][] wta = {
new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },
new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};
string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " ";
for (int i = 0; i < wta.Length; i++)
{
int bpf; blk = ""; do
{
string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
{
if (wta[i][j] > 0)
{ floor += tb; wta[i][j] -= 1; bpf += 1; }
else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
}
if (bpf > 0) blk = floor + lf + blk;
} while (bpf > 0);
while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
if (args.Length > 0) System.Console.Write("\n{0}", blk);
System.Console.WriteLine("Block {0} retains {1,2} water units.",
i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
}
}
}
|
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
|
Keep all operations the same but rewrite the snippet in VB. | class Program
{
static void Main(string[] args)
{
int[][] wta = {
new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },
new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};
string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " ";
for (int i = 0; i < wta.Length; i++)
{
int bpf; blk = ""; do
{
string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
{
if (wta[i][j] > 0)
{ floor += tb; wta[i][j] -= 1; bpf += 1; }
else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
}
if (bpf > 0) blk = floor + lf + blk;
} while (bpf > 0);
while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
if (args.Length > 0) System.Console.Write("\n{0}", blk);
System.Console.WriteLine("Block {0} retains {1,2} water units.",
i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
}
}
}
|
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
|
Rewrite this program in VB while keeping its functionality equivalent to the C# version. | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
Console.WriteLine(infix.ToPostfix());
}
}
public static class ShuntingYard
{
private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators
= new (string symbol, int precedence, bool rightAssociative) [] {
("^", 4, true),
("*", 3, false),
("/", 3, false),
("+", 2, false),
("-", 2, false)
}.ToDictionary(op => op.symbol);
public static string ToPostfix(this string infix) {
string[] tokens = infix.Split(' ');
var stack = new Stack<string>();
var output = new List<string>();
foreach (string token in tokens) {
if (int.TryParse(token, out _)) {
output.Add(token);
Print(token);
} else if (operators.TryGetValue(token, out var op1)) {
while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {
int c = op1.precedence.CompareTo(op2.precedence);
if (c < 0 || !op1.rightAssociative && c <= 0) {
output.Add(stack.Pop());
} else {
break;
}
}
stack.Push(token);
Print(token);
} else if (token == "(") {
stack.Push(token);
Print(token);
} else if (token == ")") {
string top = "";
while (stack.Count > 0 && (top = stack.Pop()) != "(") {
output.Add(top);
}
if (top != "(") throw new ArgumentException("No matching left parenthesis.");
Print(token);
}
}
while (stack.Count > 0) {
var top = stack.Pop();
if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis.");
output.Add(top);
}
Print("pop");
return string.Join(" ", output);
void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}");
void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]");
}
}
| 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
|
Keep all operations the same but rewrite the snippet in VB. | using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}
| 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
|
Keep all operations the same but rewrite the snippet in VB. | using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static List<int> l = new List<int>() { 1, 1 };
static int gcd(int a, int b) {
return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }
static void Main(string[] args) {
int max = 1000; int take = 15; int i = 1;
int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };
do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }
while (l.Count < max || l[l.Count - 2] != selection.Last());
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take);
Console.WriteLine("{0}\n", string.Join(", ", l.Take(take)));
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:");
foreach (int ii in selection) {
int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); }
Console.WriteLine(); bool good = true;
for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }
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, good ? "" : "not ");
}
}
| 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
|
Can you help me rewrite this code in VB instead of C#, keeping it the same logically? | using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ChatServer {
class State {
private TcpClient client;
private StringBuilder sb = new StringBuilder();
public string Name { get; }
public State(string name, TcpClient client) {
Name = name;
this.client = client;
}
public void Add(byte b) {
sb.Append((char)b);
}
public void Send(string text) {
var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text));
client.GetStream().Write(bytes, 0, bytes.Length);
}
}
class Program {
static TcpListener listen;
static Thread serverthread;
static Dictionary<int, State> connections = new Dictionary<int, State>();
static void Main(string[] args) {
listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004);
serverthread = new Thread(new ThreadStart(DoListen));
serverthread.Start();
}
private static void DoListen() {
listen.Start();
Console.WriteLine("Server: Started server");
while (true) {
Console.WriteLine("Server: Waiting...");
TcpClient client = listen.AcceptTcpClient();
Console.WriteLine("Server: Waited");
Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));
clientThread.Start(client);
}
}
private static void DoClient(object client) {
TcpClient tClient = (TcpClient)client;
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId);
byte[] bytes = Encoding.ASCII.GetBytes("Enter name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
string name = string.Empty;
bool done = false;
do {
if (!tClient.Connected) {
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
name = Receive(tClient);
done = true;
if (done) {
foreach (var cl in connections) {
var state = cl.Value;
if (state.Name == name) {
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
done = false;
}
}
}
} while (!done);
connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));
Console.WriteLine("\tTotal connections: {0}", connections.Count);
Broadcast(string.Format("+++ {0} arrived +++", name));
do {
string text = Receive(tClient);
if (text == "/quit") {
Broadcast(string.Format("Connection from {0} closed.", name));
connections.Remove(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("\tTotal connections: {0}", connections.Count);
break;
}
if (!tClient.Connected) {
break;
}
Broadcast(string.Format("{0}> {1}", name, text));
} while (true);
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
private static string Receive(TcpClient client) {
StringBuilder sb = new StringBuilder();
do {
if (client.Available > 0) {
while (client.Available > 0) {
char ch = (char)client.GetStream().ReadByte();
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.ToString();
}
sb.Append(ch);
}
}
Thread.Sleep(100);
} while (true);
}
private static void Broadcast(string text) {
Console.WriteLine(text);
foreach (var oClient in connections) {
if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {
State state = oClient.Value;
state.Send(text);
}
}
}
}
}
| 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
|
Generate a VB translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.Linq;
public class FindPalindromicNumbers
{
static void Main(string[] args)
{
var query =
PalindromicTernaries()
.Where(IsPalindromicBinary)
.Take(6);
foreach (var x in query) {
Console.WriteLine("Decimal: " + x);
Console.WriteLine("Ternary: " + ToTernary(x));
Console.WriteLine("Binary: " + Convert.ToString(x, 2));
Console.WriteLine();
}
}
public static IEnumerable<long> PalindromicTernaries() {
yield return 0;
yield return 1;
yield return 13;
yield return 23;
var f = new List<long> {0};
long fMiddle = 9;
while (true) {
for (long edge = 1; edge < 3; edge++) {
int i;
do {
long result = fMiddle;
long fLeft = fMiddle * 3;
long fRight = fMiddle / 3;
for (int j = f.Count - 1; j >= 0; j--) {
result += (fLeft + fRight) * f[j];
fLeft *= 3;
fRight /= 3;
}
result += (fLeft + fRight) * edge;
yield return result;
for (i = f.Count - 1; i >= 0; i--) {
if (f[i] == 2) {
f[i] = 0;
} else {
f[i]++;
break;
}
}
} while (i >= 0);
}
f.Add(0);
fMiddle *= 3;
}
}
public static bool IsPalindromicBinary(long number) {
long n = number;
long reverse = 0;
while (n != 0) {
reverse <<= 1;
if ((n & 1) == 1) reverse++;
n >>= 1;
}
return reverse == number;
}
public static string ToTernary(long n)
{
if (n == 0) return "0";
string result = "";
while (n > 0) { {
result = (n % 3) + result;
n /= 3;
}
return result;
}
}
| 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 C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.Linq;
public class FindPalindromicNumbers
{
static void Main(string[] args)
{
var query =
PalindromicTernaries()
.Where(IsPalindromicBinary)
.Take(6);
foreach (var x in query) {
Console.WriteLine("Decimal: " + x);
Console.WriteLine("Ternary: " + ToTernary(x));
Console.WriteLine("Binary: " + Convert.ToString(x, 2));
Console.WriteLine();
}
}
public static IEnumerable<long> PalindromicTernaries() {
yield return 0;
yield return 1;
yield return 13;
yield return 23;
var f = new List<long> {0};
long fMiddle = 9;
while (true) {
for (long edge = 1; edge < 3; edge++) {
int i;
do {
long result = fMiddle;
long fLeft = fMiddle * 3;
long fRight = fMiddle / 3;
for (int j = f.Count - 1; j >= 0; j--) {
result += (fLeft + fRight) * f[j];
fLeft *= 3;
fRight /= 3;
}
result += (fLeft + fRight) * edge;
yield return result;
for (i = f.Count - 1; i >= 0; i--) {
if (f[i] == 2) {
f[i] = 0;
} else {
f[i]++;
break;
}
}
} while (i >= 0);
}
f.Add(0);
fMiddle *= 3;
}
}
public static bool IsPalindromicBinary(long number) {
long n = number;
long reverse = 0;
while (n != 0) {
reverse <<= 1;
if ((n & 1) == 1) reverse++;
n >>= 1;
}
return reverse == number;
}
public static string ToTernary(long n)
{
if (n == 0) return "0";
string result = "";
while (n > 0) { {
result = (n % 3) + result;
n /= 3;
}
return result;
}
}
| 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 C# version. | static void Main(string[] args)
{
int bufferHeight = Console.BufferHeight;
int bufferWidth = Console.BufferWidth;
int windowHeight = Console.WindowHeight;
int 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);
Console.ReadLine();
}
| 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
|
Rewrite the snippet below in VB so it works the same as the original C# code. | using System;
using System.Numerics;
namespace CipollaAlgorithm {
class Program {
static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;
private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {
BigInteger n = BigInteger.Parse(ns);
BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;
BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);
if (ls(n) != 1) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
BigInteger a = 0;
BigInteger omega2;
while (true) {
omega2 = (a * a + p - n) % p;
if (ls(omega2) == p - 1) {
break;
}
a += 1;
}
BigInteger finalOmega = omega2;
Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {
return new Tuple<BigInteger, BigInteger>(
(aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,
(aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p
);
}
Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);
Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);
BigInteger nn = ((p + 1) >> 1) % p;
while (nn > 0) {
if ((nn & 1) == 1) {
r = mul(r, s);
}
s = mul(s, s);
nn >>= 1;
}
if (r.Item2 != 0) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
if (r.Item1 * r.Item1 % p != n) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);
}
static void Main(string[] args) {
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", ""));
}
}
}
| 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
|
Write the same algorithm in VB as shown in this C# implementation. | using System;
using System.Numerics;
namespace CipollaAlgorithm {
class Program {
static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;
private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {
BigInteger n = BigInteger.Parse(ns);
BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;
BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);
if (ls(n) != 1) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
BigInteger a = 0;
BigInteger omega2;
while (true) {
omega2 = (a * a + p - n) % p;
if (ls(omega2) == p - 1) {
break;
}
a += 1;
}
BigInteger finalOmega = omega2;
Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {
return new Tuple<BigInteger, BigInteger>(
(aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,
(aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p
);
}
Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);
Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);
BigInteger nn = ((p + 1) >> 1) % p;
while (nn > 0) {
if ((nn & 1) == 1) {
r = mul(r, s);
}
s = mul(s, s);
nn >>= 1;
}
if (r.Item2 != 0) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
if (r.Item1 * r.Item1 % p != n) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);
}
static void Main(string[] args) {
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", ""));
}
}
}
| 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
|
Produce a functionally identical VB code for the snippet given in C#. | string path = @"C:\Windows\System32";
string multiline = @"Line 1.
Line 2.
Line 3.";
| Debug.Print "Tom said, ""The fox ran away."""
Debug.Print "Tom said,
|
Convert the following code from C# to VB, ensuring the logic remains intact. | using System;
using System.Drawing;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Rectangle bounds = Screen.PrimaryScreen.Bounds;
Console.WriteLine($"Primary screen bounds: {bounds.Width}x{bounds.Height}");
Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
Console.WriteLine($"Primary screen working area: {workingArea.Width}x{workingArea.Height}");
}
}
| 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
|
Produce a functionally identical VB code for the snippet given in C#. | enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits : int { apple = 0, banana = 1, cherry = 2 }
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
|
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
|
Convert the following code from C# to VB, ensuring the logic remains intact. |
using System;
class Program
{
static void Main()
{
uint[] r = items1();
Console.WriteLine(r[0] + " v " + r[1] + " a " + r[2] + " b");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 1000; i > 0; i--) items1();
Console.Write(sw.Elapsed); Console.Read();
}
static uint[] items0()
{
uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;
for (a = 0; a <= 10; a++)
for (b = 0; a * 5 + b * 3 <= 50; b++)
for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)
if (v0 < (v = a * 30 + b * 18 + c * 25))
{
v0 = v; a0 = a; b0 = b; c0 = c;
}
return new uint[] { a0, b0, c0 };
}
static uint[] items1()
{
uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;
for (a = 0; a <= 10; a++)
for (b = 0; a * 5 + b * 3 <= 50; b++)
{
c = (250 - a * 25 - b * 15) / 2;
if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;
if (v0 < (v = a * 30 + b * 18 + c * 25))
{ v0 = v; a0 = a; b0 = b; c0 = c; }
}
return new uint[] { a0, b0, c0 };
}
}
| Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function
Sub Main()
Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5
Dim P&, I&, G&, A&, M, Cur(Value To Volume)
Dim S As New Collection: S.Add Array(0)
Const SackW = 25, SackV = 0.25
Dim Panacea: Panacea = Array(3000, 0.3, 0.025)
Dim Ichor: Ichor = Array(1800, 0.2, 0.015)
Dim Gold: Gold = Array(2500, 2, 0.002)
For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))
For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))
For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))
For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next
If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _
S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1
Next G, I, P
Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount"
For Each M In S
If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)
Next
End Sub
|
Generate an equivalent VB version of this C# code. | using System;
using System.Collections.Generic;
using System.Linq;
class RangeExtraction
{
static void Main()
{
const string testString = "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";
var result = String.Join(",", RangesToStrings(GetRanges(testString)));
Console.Out.WriteLine(result);
}
public static IEnumerable<IEnumerable<int>> GetRanges(string testString)
{
var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));
var current = new List<int>();
foreach (var n in numbers)
{
if (current.Count == 0)
{
current.Add(n);
}
else
{
if (current.Max() + 1 == n)
{
current.Add(n);
}
else
{
yield return current;
current = new List<int> { n };
}
}
}
yield return current;
}
public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)
{
foreach (var range in ranges)
{
if (range.Count() == 1)
{
yield return range.Single().ToString();
}
else if (range.Count() == 2)
{
yield return range.Min() + "," + range.Max();
}
else
{
yield return range.Min() + "-" + range.Max();
}
}
}
}
| 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
|
Please provide an equivalent version of this C# code in VB. | using System;
namespace TypeDetection {
class C { }
struct S { }
enum E {
NONE,
}
class Program {
static void ShowType<T>(T t) {
Console.WriteLine("The type of '{0}' is {1}", t, t.GetType());
}
static void Main() {
ShowType(5);
ShowType(7.5);
ShowType('d');
ShowType(true);
ShowType("Rosetta");
ShowType(new C());
ShowType(new S());
ShowType(E.NONE);
ShowType(new int[] { 1, 2, 3 });
}
}
}
| Public Sub main()
Dim c(1) As Currency
Dim d(1) As Double
Dim dt(1) As Date
Dim a(1) As Integer
Dim l(1) As Long
Dim s(1) As Single
Dim e As Variant
Dim o As Object
Set o = New Application
Debug.Print TypeName(o)
Debug.Print TypeName(1 = 1)
Debug.Print TypeName(CByte(1))
Set o = New Collection
Debug.Print TypeName(o)
Debug.Print TypeName(1@)
Debug.Print TypeName(c)
Debug.Print TypeName(CDate(1))
Debug.Print TypeName(dt)
Debug.Print TypeName(CDec(1))
Debug.Print TypeName(1#)
Debug.Print TypeName(d)
Debug.Print TypeName(e)
Debug.Print TypeName(CVErr(1))
Debug.Print TypeName(1)
Debug.Print TypeName(a)
Debug.Print TypeName(1&)
Debug.Print TypeName(l)
Set o = Nothing
Debug.Print TypeName(o)
Debug.Print TypeName([A1])
Debug.Print TypeName(1!)
Debug.Print TypeName(s)
Debug.Print TypeName(CStr(1))
Debug.Print TypeName(Worksheets(1))
End Sub
|
Transform the following C# implementation into VB, maintaining the same output and logic. | using System;
namespace RosetaCode
{
class MainClass
{
public static void Main (string[] args)
{
int[,] list = new int[18,19];
string input = @"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";
var charArray = input.Split ('\n');
for (int i=0; i < charArray.Length; i++) {
var numArr = charArray[i].Trim().Split(' ');
for (int j = 0; j<numArr.Length; j++)
{
int number = Convert.ToInt32 (numArr[j]);
list [i, j] = number;
}
}
for (int i = 16; i >= 0; i--) {
for (int j = 0; j < 18; j++) {
list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);
}
}
Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0]));
}
}
}
|
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
|
Port the following code from C# to VB with equivalent syntax and logic. | using System;
using System.Text;
namespace Rosetta
{
class Program
{
static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));
static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
foreach (int unicodePoint in new int[] { 0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})
{
byte[] asUtf8bytes = MyEncoder(unicodePoint);
string theCharacter = MyDecoder(asUtf8bytes);
Console.WriteLine("{0,8} {1,5} {2,-15}", unicodePoint.ToString("X4"), theCharacter, BitConverter.ToString(asUtf8bytes));
}
}
}
}
| 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
|
Change the following C# code into VB without altering its purpose. | using System;
namespace MagicSquareDoublyEven
{
class Program
{
static void Main(string[] args)
{
int n = 8;
var result = MagicSquareDoublyEven(n);
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write("{0,2} ", result[i, j]);
Console.WriteLine();
}
Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2);
Console.ReadLine();
}
private static int[,] MagicSquareDoublyEven(int n)
{
if (n < 4 || n % 4 != 0)
throw new ArgumentException("base must be a positive "
+ "multiple of 4");
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4;
int[,] result = new int[n, n];
for (int r = 0, i = 0; r < n; r++)
{
for (int c = 0; c < n; c++, i++)
{
int bitPos = c / mult + (r / mult) * 4;
result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
}
|
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
|
Convert this C# snippet to VB and keep its semantics consistent. | using System;
using System.Collections.Generic;
using System.Text;
namespace MoveToFront
{
class Program
{
private static char[] symbolTable;
private static void setSymbolTable()
{
symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
}
private static void moveToFront(int charIndex)
{
char toFront = symbolTable[charIndex];
for (int j = charIndex; j > 0; j--)
{
symbolTable[j] = symbolTable[j - 1];
}
symbolTable[0] = toFront;
}
public static int[] Encode(string input)
{
setSymbolTable();
var output = new List<int>();
foreach (char c in input)
{
for (int i = 0; i < 26; i++)
{
if (symbolTable[i] == c)
{
output.Add(i);
moveToFront(i);
break;
}
}
}
return output.ToArray();
}
public static string Decode(int[] input)
{
setSymbolTable();
var output = new StringBuilder(input.Length);
foreach (int n in input)
{
output.Append(symbolTable[n]);
moveToFront(n);
}
return output.ToString();
}
static void Main(string[] args)
{
string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" };
int[] encoding;
foreach (string s in testInputs)
{
Console.WriteLine($"Encoding for '{s}':");
encoding = Encode(s);
foreach (int i in encoding)
{
Console.Write($"{i} ");
}
Console.WriteLine($"\nDecoding for '{s}':");
Console.WriteLine($"{Decode(encoding)}\n");
}
}
}
}
| 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
|
Write a version of this C# function in VB with identical behavior. | using System.Diagnostics;
namespace Execute
{
class Program
{
static void Main(string[] args)
{
Process.Start("cmd.exe", "/c dir");
}
}
}
| Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
|
Can you help me rewrite this code in VB instead of C#, keeping it the same logically? | using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class Test
{
public static void Main()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, "http:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
XmlReader reader = XmlReader.Create("http:
while (reader.Read());
Console.WriteLine("The XML file is valid for the given xsd file");
}
private static void ValidationCallBack(object sender, ValidationEventArgs e) {
Console.WriteLine("Validation Error: {0}", e.Message);
}
}
| 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 C# snippet to VB and keep its semantics consistent. | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class LIS
{
public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>
values == null ? throw new ArgumentNullException() :
FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();
private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {
if (index == values.Count) return current;
if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)
return FindRecImpl(values, current, index + 1, comparer);
return Max(
FindRecImpl(values, current, index + 1, comparer),
FindRecImpl(values, current + values[index], index + 1, comparer)
);
}
private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;
class Sequence<T> : IEnumerable<T>
{
public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);
public Sequence(T value, Sequence<T> tail)
{
Value = value;
Tail = tail;
Length = tail == null ? 0 : tail.Length + 1;
}
public T Value { get; }
public Sequence<T> Tail { get; }
public int Length { get; }
public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);
public IEnumerator<T> GetEnumerator()
{
for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| 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 an equivalent VB version of this C# code. | using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using static System.Linq.Enumerable;
public static class BraceExpansion
{
enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }
const char L = '{', R = '}', S = ',';
public static void Main() {
string[] input = {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
@"{,{,gotta have{ ,\, again\, }}more }cowbell!",
@"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
};
foreach (string text in input) Expand(text);
}
static void Expand(string input) {
Token token = Tokenize(input);
foreach (string value in token) Console.WriteLine(value);
Console.WriteLine();
}
static Token Tokenize(string input) {
var tokens = new List<Token>();
var buffer = new StringBuilder();
bool escaping = false;
int level = 0;
foreach (char c in input) {
(escaping, level, tokens, buffer) = c switch {
_ when escaping => (false, level, tokens, buffer.Append(c)),
'\\' => (true, level, tokens, buffer.Append(c)),
L => (escaping, level + 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),
S when level > 0 => (escaping, level,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),
R when level > 0 => (escaping, level - 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),
_ => (escaping, level, tokens, buffer.Append(c))
};
}
if (buffer.Length > 0) tokens.Add(buffer.Flush());
for (int i = 0; i < tokens.Count; i++) {
if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {
tokens[i] = tokens[i].Value;
}
}
return new Token(tokens, TokenType.Concat);
}
static List<Token> Merge(this List<Token> list) {
int separators = 0;
int last = list.Count - 1;
for (int i = list.Count - 3; i >= 0; i--) {
if (list[i].Type == TokenType.Separator) {
separators++;
Concat(list, i + 1, last);
list.RemoveAt(i);
last = i;
} else if (list[i].Type == TokenType.OpenBrace) {
Concat(list, i + 1, last);
if (separators > 0) {
list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);
list.RemoveRange(i+1, list.Count - i - 1);
} else {
list[i] = L.ToString();
list[^1] = R.ToString();
Concat(list, i, list.Count);
}
break;
}
}
return list;
}
static void Concat(List<Token> list, int s, int e) {
for (int i = e - 2; i >= s; i--) {
(Token a, Token b) = (list[i], list[i+1]);
switch (a.Type, b.Type) {
case (TokenType.Text, TokenType.Text):
list[i] = a.Value + b.Value;
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Concat):
a.SubTokens.AddRange(b.SubTokens);
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Text) when b.Value == "":
list.RemoveAt(i+1);
break;
case (TokenType.Text, TokenType.Concat) when a.Value == "":
list.RemoveAt(i);
break;
default:
list[i] = new Token(new [] { a, b }, TokenType.Concat);
list.RemoveAt(i+1);
break;
}
}
}
private struct Token : IEnumerable<string>
{
private List<Token>? _subTokens;
public string Value { get; }
public TokenType Type { get; }
public List<Token> SubTokens => _subTokens ??= new List<Token>();
public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);
public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList());
public static implicit operator Token(string value) => new Token(value, TokenType.Text);
public IEnumerator<string> GetEnumerator() => (Type switch
{
TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)),
TokenType.Alternate => from t in SubTokens from s in t select s,
_ => Repeat(Value, 1)
}).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
static List<Token> With(this List<Token> list, Token token) {
list.Add(token);
return list;
}
static IEnumerable<Token> Range(this List<Token> list, Range range) {
int start = range.Start.GetOffset(list.Count);
int end = range.End.GetOffset(list.Count);
for (int i = start; i < end; i++) yield return list[i];
}
static string Flush(this StringBuilder builder) {
string result = builder.ToString();
builder.Clear();
return result;
}
}
| 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
|
Generate a VB translation of this C# snippet without changing its computational steps. | using System;
using System.ComponentModel;
using System.Windows.Forms;
class RosettaInteractionForm : Form
{
class NumberModel: INotifyPropertyChanged
{
Random rnd = new Random();
public event PropertyChangedEventHandler PropertyChanged = delegate {};
int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
public void ResetToRandom(){
Value = rnd.Next(5000);
}
}
NumberModel model = new NumberModel{ Value = 0};
RosettaInteractionForm()
{
var tbNumber = new MaskedTextBox
{
Mask="0000",
ResetOnSpace = false,
Dock = DockStyle.Top
};
tbNumber.DataBindings.Add("Text", model, "Value");
var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
btIncrement.Click += delegate
{
model.Value++;
};
var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
btDecrement.Click += delegate
{
model.Value--;
};
var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom };
btRandom.Click += delegate
{
if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
model.ResetToRandom();
};
Controls.Add(tbNumber);
Controls.Add(btIncrement);
Controls.Add(btDecrement);
Controls.Add(btRandom);
}
static void Main()
{
Application.Run(new RosettaInteractionForm());
}
}
| 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
|
Write the same algorithm in VB as shown in this C# implementation. | class Program
{
private static Random rnd = new Random();
public static int one_of_n(int n)
{
int currentChoice = 1;
for (int i = 2; i <= n; i++)
{
double outerLimit = 1D / (double)i;
if (rnd.NextDouble() < outerLimit)
currentChoice = i;
}
return currentChoice;
}
static void Main(string[] args)
{
Dictionary<int, int> results = new Dictionary<int, int>();
for (int i = 1; i < 11; i++)
results.Add(i, 0);
for (int i = 0; i < 1000000; i++)
{
int result = one_of_n(10);
results[result] = results[result] + 1;
}
for (int i = 1; i < 11; i++)
Console.WriteLine("{0}\t{1}", i, results[i]);
Console.ReadLine();
}
}
| 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
|
Produce a functionally identical VB code for the snippet given in C#. | using System;
namespace AdditionChains {
class Program {
static int[] Prepend(int n, int[] seq) {
int[] result = new int[seq.Length + 1];
Array.Copy(seq, 0, result, 1, seq.Length);
result[0] = n;
return result;
}
static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {
if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);
if (seq[0] == n) return new Tuple<int, int>(pos, 1);
if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);
return new Tuple<int, int>(min_len, 0);
}
static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {
if (i > pos) return new Tuple<int, int>(min_len, 0);
Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);
Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);
if (res2.Item1 < res1.Item1) return res2;
if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);
throw new Exception("TryPerm exception");
}
static Tuple<int, int> InitTryPerm(int x) {
return TryPerm(0, 0, new int[] { 1 }, x, 12);
}
static void FindBrauer(int num) {
Tuple<int, int> res = InitTryPerm(num);
Console.WriteLine();
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);
}
static void Main(string[] args) {
int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };
Array.ForEach(nums, n => FindBrauer(n));
}
}
}
| 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 C# code in VB. | using System;
namespace Repeat {
class Program {
static void Repeat(int count, Action<int> fn) {
if (null == fn) {
throw new ArgumentNullException("fn");
}
for (int i = 0; i < count; i++) {
fn.Invoke(i + 1);
}
}
static void Main(string[] args) {
Repeat(3, x => Console.WriteLine("Example {0}", x));
}
}
}
| 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
|
Rewrite this program in VB while keeping its functionality equivalent to the C# version. | public class Program
{
static void Main()
{
System.Console.WriteLine(42.ModInverse(2017));
}
}
public static class IntExtensions
{
public static int ModInverse(this int a, int m)
{
if (m == 1) return 0;
int m0 = m;
(int x, int y) = (1, 0);
while (a > 1) {
int q = a / m;
(a, m) = (m, a % m);
(x, y) = (y, x - q * y);
}
return x < 0 ? x + m0 : x;
}
}
| 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
|
Convert the following code from C# to VB, ensuring the logic remains intact. | public class Program
{
static void Main()
{
System.Console.WriteLine(42.ModInverse(2017));
}
}
public static class IntExtensions
{
public static int ModInverse(this int a, int m)
{
if (m == 1) return 0;
int m0 = m;
(int x, int y) = (1, 0);
while (a > 1) {
int q = a / m;
(a, m) = (m, a % m);
(x, y) = (y, x - q * y);
}
return x < 0 ? x + m0 : x;
}
}
| 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
|
Translate this program into VB but keep the logic exactly as in C#. | using System.Text;
using System.Net.Sockets;
using System.Net;
namespace WebServer
{
class GoodByeWorld
{
static void Main(string[] args)
{
const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n";
const int port = 8080;
bool serverRunning = true;
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (serverRunning)
{
Socket socketConnection = tcpListener.AcceptSocket();
byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);
socketConnection.Send(bMsg);
socketConnection.Disconnect(true);
}
}
}
}
| 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
|
Ensure the translated VB code behaves exactly like the original C# snippet. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChemicalCalculator {
class Program {
static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {
{"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.630},
{"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.90550},
{"Pd", 106.42},
{"Ag", 107.8682},
{"Cd", 112.414},
{"In", 114.818},
{"Sn", 118.710},
{"Sb", 121.760},
{"Te", 127.60},
{"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.500},
{"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.98040},
{"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},
};
static double Evaluate(string s) {
s += "[";
double sum = 0.0;
string symbol = "";
string number = "";
for (int i = 0; i < s.Length; ++i) {
var c = s[i];
if ('@' <= c && c <= '[') {
int n = 1;
if (number != "") {
n = int.Parse(number);
}
if (symbol != "") {
sum += atomicMass[symbol] * n;
}
if (c == '[') {
break;
}
symbol = c.ToString();
number = "";
} else if ('a' <= c && c <= 'z') {
symbol += c;
} else if ('0' <= c && c <= '9') {
number += c;
} else {
throw new Exception(string.Format("Unexpected symbol {0} in molecule", c));
}
}
return sum;
}
static string ReplaceFirst(string text, string search, string replace) {
int pos = text.IndexOf(search);
if (pos < 0) {
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
static string ReplaceParens(string s) {
char letter = 's';
while (true) {
var start = s.IndexOf('(');
if (start == -1) {
break;
}
for (int i = start + 1; i < s.Length; ++i) {
if (s[i] == ')') {
var expr = s.Substring(start + 1, i - start - 1);
var symbol = string.Format("@{0}", letter);
s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);
atomicMass[symbol] = Evaluate(expr);
letter++;
break;
}
if (s[i] == '(') {
start = i;
continue;
}
}
}
return s;
}
static void Main() {
var molecules = new string[]{
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
};
foreach (var molecule in molecules) {
var mass = Evaluate(ReplaceParens(molecule));
Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass);
}
}
}
}
| 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
|
Translate the given C# code snippet into VB without altering its behavior. | using System;
namespace PythagoreanQuadruples {
class Program {
const int MAX = 2200;
const int MAX2 = MAX * MAX * 2;
static void Main(string[] args) {
bool[] found = new bool[MAX + 1];
bool[] a2b2 = new bool[MAX2 + 1];
int s = 3;
for(int a = 1; a <= MAX; a++) {
int a2 = a * a;
for (int b=a; b<=MAX; b++) {
a2b2[a2 + b * b] = true;
}
}
for (int c = 1; c <= MAX; c++) {
int s1 = s;
s += 2;
int s2 = s;
for (int d = c + 1; d <= MAX; d++) {
if (a2b2[s1]) found[d] = true;
s1 += s2;
s2 += 2;
}
}
Console.WriteLine("The values of d <= {0} which can't be represented:", MAX);
for (int d = 1; d < MAX; d++) {
if (!found[d]) Console.Write("{0} ", d);
}
Console.WriteLine();
}
}
}
| 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
|
Generate a VB translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
public enum Colour { Red, Green, White, Yellow, Blue }
public enum Nationality { Englishman, Swede, Dane, Norwegian,German }
public enum Pet { Dog, Birds, Cats, Horse, Zebra }
public enum Drink { Coffee, Tea, Milk, Beer, Water }
public enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}
public static class ZebraPuzzle
{
private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;
static ZebraPuzzle()
{
var solve = from colours in Permute<Colour>()
where (colours,Colour.White).IsRightOf(colours, Colour.Green)
from nations in Permute<Nationality>()
where nations[0] == Nationality.Norwegian
where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red)
where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue)
from drinks in Permute<Drink>()
where drinks[2] == Drink.Milk
where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green)
where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane)
from pets in Permute<Pet>()
where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede)
from smokes in Permute<Smoke>()
where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds)
where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow)
where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats)
where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse)
where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer)
where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German)
where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend)
select (colours, drinks, smokes, pets, nations);
_solved = solve.First();
}
private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);
private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;
private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);
private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a, U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)
{
if (values.Count() == 1)
return values.ToSingleton();
return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));
}
public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());
private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }
private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();
public static new String ToString()
{
var sb = new StringBuilder();
sb.AppendLine("House Colour Drink Nationality Smokes Pet");
sb.AppendLine("───── ────── ──────── ─────────── ────────── ─────");
var (colours, drinks, smokes, pets, nations) = _solved;
for (var i = 0; i < 5; i++)
sb.AppendLine($"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}");
return sb.ToString();
}
public static void Main(string[] arguments)
{
var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];
WriteLine($"The zebra owner is {owner}");
Write(ToString());
Read();
}
}
| 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
|
Keep all operations the same but rewrite the snippet in VB. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
public enum Colour { Red, Green, White, Yellow, Blue }
public enum Nationality { Englishman, Swede, Dane, Norwegian,German }
public enum Pet { Dog, Birds, Cats, Horse, Zebra }
public enum Drink { Coffee, Tea, Milk, Beer, Water }
public enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}
public static class ZebraPuzzle
{
private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;
static ZebraPuzzle()
{
var solve = from colours in Permute<Colour>()
where (colours,Colour.White).IsRightOf(colours, Colour.Green)
from nations in Permute<Nationality>()
where nations[0] == Nationality.Norwegian
where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red)
where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue)
from drinks in Permute<Drink>()
where drinks[2] == Drink.Milk
where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green)
where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane)
from pets in Permute<Pet>()
where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede)
from smokes in Permute<Smoke>()
where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds)
where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow)
where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats)
where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse)
where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer)
where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German)
where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend)
select (colours, drinks, smokes, pets, nations);
_solved = solve.First();
}
private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);
private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;
private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);
private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a, U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)
{
if (values.Count() == 1)
return values.ToSingleton();
return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));
}
public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());
private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }
private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();
public static new String ToString()
{
var sb = new StringBuilder();
sb.AppendLine("House Colour Drink Nationality Smokes Pet");
sb.AppendLine("───── ────── ──────── ─────────── ────────── ─────");
var (colours, drinks, smokes, pets, nations) = _solved;
for (var i = 0; i < 5; i++)
sb.AppendLine($"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}");
return sb.ToString();
}
public static void Main(string[] arguments)
{
var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];
WriteLine($"The zebra owner is {owner}");
Write(ToString());
Read();
}
}
| 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
|
Generate a VB translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Net;
class Program {
static List<string> GetTitlesFromCategory(string category) {
string searchQueryFormat = "http:
List<string> results = new List<string>();
string cmcontinue = string.Empty;
do {
string cmContinueKeyValue;
if (cmcontinue.Length > 0)
cmContinueKeyValue = String.Format("&cmcontinue={0}", cmcontinue);
else
cmContinueKeyValue = String.Empty;
string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);
string content = new WebClient().DownloadString(query);
results.AddRange(new Regex("\"title\":\"(.+?)\"").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));
cmcontinue = Regex.Match(content, @"{""cmcontinue"":""([^""]+)""}", RegexOptions.IgnoreCase).Groups["1"].Value;
} while (cmcontinue.Length > 0);
return results;
}
static string[] GetUnimplementedTasksFromLanguage(string language) {
List<string> alltasks = GetTitlesFromCategory("Programming_Tasks");
List<string> lang = GetTitlesFromCategory(language);
return alltasks.Where(x => !lang.Contains(x)).ToArray();
}
static void Main(string[] args) {
string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);
foreach (string i in unimpl) Console.WriteLine(i);
}
}
| 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
|
Convert the following code from C# to VB, ensuring the logic remains intact. | using System;
using BI = System.Numerics.BigInteger;
using static System.Console;
class Program {
static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }
static string dump(int digs, bool show = false) {
int gb = 1, dg = ++digs + gb, z;
BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,
t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;
for (BI n = 0; n < dg; n++) {
if (n > 0) t3 *= BI.Pow(n, 6);
te = t1 * t2 / t3;
if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);
else te /= BI.Pow (10, -z);
if (show && n < 10)
WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t);
su += te; if (te < 10) {
if (show) WriteLine("\n{0} iterations required for {1} digits " +
"after the decimal point.\n", n, --digs); break; }
for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;
t2 += 126 + 532 * (d += 2);
}
string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) /
su / 32 * 3 * BI.Pow((BI)10, dg + 5)));
return s[0] + "." + s.Substring(1, digs); }
static void Main(string[] args) {
WriteLine(dump(70, true)); }
}
| 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
|
Maintain the same structure and functionality when rewriting this code in VB. | using System;
using BI = System.Numerics.BigInteger;
using static System.Console;
class Program {
static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }
static string dump(int digs, bool show = false) {
int gb = 1, dg = ++digs + gb, z;
BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,
t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;
for (BI n = 0; n < dg; n++) {
if (n > 0) t3 *= BI.Pow(n, 6);
te = t1 * t2 / t3;
if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);
else te /= BI.Pow (10, -z);
if (show && n < 10)
WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t);
su += te; if (te < 10) {
if (show) WriteLine("\n{0} iterations required for {1} digits " +
"after the decimal point.\n", n, --digs); break; }
for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;
t2 += 126 + 532 * (d += 2);
}
string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) /
su / 32 * 3 * BI.Pow((BI)10, dg + 5)));
return s[0] + "." + s.Substring(1, digs); }
static void Main(string[] args) {
WriteLine(dump(70, true)); }
}
| 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
|
Generate an equivalent VB version of this C# code. | using System.Collections.Generic; using System.Linq; using static System.Console;
class Program {
static bool soas(int n, IEnumerable<int> f) {
if (n <= 0) return false; if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;
case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);
return soas(d, rf) || soas(n, rf); } return true; }
static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();
return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f)); }
static void Main() {
int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)
if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : "");
Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m);
do Write("\n{0,5} is a{1}practical number.",
m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
| 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
|
Preserve the algorithm and functionality while converting the code from C# to VB. | double d = 1;
d = 1d;
d = 1D;
d = 1.2;
d = 1.2d;
d = .2;
d = 12e-12;
d = 12E-12;
d = 1_234e-1_2;
float f = 1;
f = 1f;
f = 1F;
f = 1.2f;
f = .2f;
f = 12e-12f;
f = 12E-12f;
f = 1_234e-1_2f;
decimal m = 1;
m = 1m;
m = 1m;
m = 1.2m;
m = .2m;
m = 12e-12m;
m = 12E-12m;
m = 1_234e-1_2m;
| 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
|
Convert this C# block to VB, preserving its control flow and logic. | double d = 1;
d = 1d;
d = 1D;
d = 1.2;
d = 1.2d;
d = .2;
d = 12e-12;
d = 12E-12;
d = 1_234e-1_2;
float f = 1;
f = 1f;
f = 1F;
f = 1.2f;
f = .2f;
f = 12e-12f;
f = 12E-12f;
f = 1_234e-1_2f;
decimal m = 1;
m = 1m;
m = 1m;
m = 1.2m;
m = .2m;
m = 12e-12m;
m = 12E-12m;
m = 1_234e-1_2m;
| 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
|
Change the programming language of this snippet from C# to VB without modifying what it does. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Wordseach
{
static class Program
{
readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
class Grid
{
public char[,] Cells = new char[nRows, nCols];
public List<string> Solutions = new List<string>();
public int NumAttempts;
}
readonly static int nRows = 10;
readonly static int nCols = 10;
readonly static int gridSize = nRows * nCols;
readonly static int minWords = 25;
readonly static Random rand = new Random();
static void Main(string[] args)
{
PrintResult(CreateWordSearch(ReadWords("unixdict.txt")));
}
private static List<string> ReadWords(string filename)
{
int maxLen = Math.Max(nRows, nCols);
return System.IO.File.ReadAllLines(filename)
.Select(s => s.Trim().ToLower())
.Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$"))
.ToList();
}
private static Grid CreateWordSearch(List<string> words)
{
int numAttempts = 0;
while (++numAttempts < 100)
{
words.Shuffle();
var grid = new Grid();
int messageLen = PlaceMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled = 0;
foreach (var word in words)
{
cellsFilled += TryPlaceWord(grid, word);
if (cellsFilled == target)
{
if (grid.Solutions.Count >= minWords)
{
grid.NumAttempts = numAttempts;
return grid;
}
else break;
}
}
}
return null;
}
private static int TryPlaceWord(Grid grid, string word)
{
int randDir = rand.Next(dirs.GetLength(0));
int randPos = rand.Next(gridSize);
for (int dir = 0; dir < dirs.GetLength(0); dir++)
{
dir = (dir + randDir) % dirs.GetLength(0);
for (int pos = 0; pos < gridSize; pos++)
{
pos = (pos + randPos) % gridSize;
int lettersPlaced = TryLocation(grid, word, dir, pos);
if (lettersPlaced > 0)
return lettersPlaced;
}
}
return 0;
}
private static int TryLocation(Grid grid, string word, int dir, int pos)
{
int r = pos / nCols;
int c = pos % nCols;
int len = word.Length;
if ((dirs[dir, 0] == 1 && (len + c) > nCols)
|| (dirs[dir, 0] == -1 && (len - 1) > c)
|| (dirs[dir, 1] == 1 && (len + r) > nRows)
|| (dirs[dir, 1] == -1 && (len - 1) > r))
return 0;
int rr, cc, i, overlaps = 0;
for (i = 0, rr = r, cc = c; i < len; i++)
{
if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])
{
return 0;
}
cc += dirs[dir, 0];
rr += dirs[dir, 1];
}
for (i = 0, rr = r, cc = c; i < len; i++)
{
if (grid.Cells[rr, cc] == word[i])
overlaps++;
else
grid.Cells[rr, cc] = word[i];
if (i < len - 1)
{
cc += dirs[dir, 0];
rr += dirs[dir, 1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0)
{
grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})");
}
return lettersPlaced;
}
private static int PlaceMessage(Grid grid, string msg)
{
msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", "");
int messageLen = msg.Length;
if (messageLen > 0 && messageLen < gridSize)
{
int gapSize = gridSize / messageLen;
for (int i = 0; i < messageLen; i++)
{
int pos = i * gapSize + rand.Next(gapSize);
grid.Cells[pos / nCols, pos % nCols] = msg[i];
}
return messageLen;
}
return 0;
}
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rand.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
private static void PrintResult(Grid grid)
{
if (grid == null || grid.NumAttempts == 0)
{
Console.WriteLine("No grid to display");
return;
}
int size = grid.Solutions.Count;
Console.WriteLine("Attempts: " + grid.NumAttempts);
Console.WriteLine("Number of words: " + size);
Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9");
for (int r = 0; r < nRows; r++)
{
Console.Write("\n{0} ", r);
for (int c = 0; c < nCols; c++)
Console.Write(" {0} ", grid.Cells[r, c]);
}
Console.WriteLine("\n");
for (int i = 0; i < size - 1; i += 2)
{
Console.WriteLine("{0} {1}", grid.Solutions[i],
grid.Solutions[i + 1]);
}
if (size % 2 == 1)
Console.WriteLine(grid.Solutions[size - 1]);
Console.ReadLine();
}
}
}
| 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
|
Rewrite the snippet below in VB so it works the same as the original C# code. | using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answer = fieldInfo.GetValue(myInstance);
Console.WriteLine(answer);
}
}
| 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 code in VB as shown below in C#. | using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answer = fieldInfo.GetValue(myInstance);
Console.WriteLine(answer);
}
}
| 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
|
Port the provided C# code into VB while preserving the original functionality. | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
this.Length = length;
this.Edges = edges;
this.Suffix = suffix;
}
public int Length { get; set; }
public Dictionary<char, int> Edges { get; set; }
public int Suffix { get; set; }
}
class Program {
const int EVEN_ROOT = 0;
const int ODD_ROOT = 1;
static List<Node> Eertree(string s) {
List<Node> tree = new List<Node> {
new Node(0, new Dictionary<char, int>(), ODD_ROOT),
new Node(-1, new Dictionary<char, int>(), ODD_ROOT)
};
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.Length; i++) {
char c = s[i];
for (n = suffix; ; n = tree[n].Suffix) {
k = tree[n].Length;
int b = i - k - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
if (tree[n].Edges.ContainsKey(c)) {
suffix = tree[n].Edges[c];
continue;
}
suffix = tree.Count;
tree.Add(new Node(k + 2));
tree[n].Edges[c] = suffix;
if (tree[suffix].Length == 1) {
tree[suffix].Suffix = 0;
continue;
}
while (true) {
n = tree[n].Suffix;
int b = i - tree[n].Length - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
tree[suffix].Suffix = tree[n].Edges[c];
}
return tree;
}
static List<string> SubPalindromes(List<Node> tree) {
List<string> s = new List<string>();
SubPalindromes_children(0, "", tree, s);
foreach (var c in tree[1].Edges.Keys) {
int m = tree[1].Edges[c];
string ct = c.ToString();
s.Add(ct);
SubPalindromes_children(m, ct, tree, s);
}
return s;
}
static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {
foreach (var c in tree[n].Edges.Keys) {
int m = tree[n].Edges[c];
string p1 = c + p + c;
s.Add(p1);
SubPalindromes_children(m, p1, tree, s);
}
}
static void Main(string[] args) {
List<Node> tree = Eertree("eertree");
List<string> result = SubPalindromes(tree);
string listStr = string.Join(", ", result);
Console.WriteLine("[{0}]", listStr);
}
}
}
| 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
|
Rewrite this program in VB while keeping its functionality equivalent to the C# version. | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
this.Length = length;
this.Edges = edges;
this.Suffix = suffix;
}
public int Length { get; set; }
public Dictionary<char, int> Edges { get; set; }
public int Suffix { get; set; }
}
class Program {
const int EVEN_ROOT = 0;
const int ODD_ROOT = 1;
static List<Node> Eertree(string s) {
List<Node> tree = new List<Node> {
new Node(0, new Dictionary<char, int>(), ODD_ROOT),
new Node(-1, new Dictionary<char, int>(), ODD_ROOT)
};
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.Length; i++) {
char c = s[i];
for (n = suffix; ; n = tree[n].Suffix) {
k = tree[n].Length;
int b = i - k - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
if (tree[n].Edges.ContainsKey(c)) {
suffix = tree[n].Edges[c];
continue;
}
suffix = tree.Count;
tree.Add(new Node(k + 2));
tree[n].Edges[c] = suffix;
if (tree[suffix].Length == 1) {
tree[suffix].Suffix = 0;
continue;
}
while (true) {
n = tree[n].Suffix;
int b = i - tree[n].Length - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
tree[suffix].Suffix = tree[n].Edges[c];
}
return tree;
}
static List<string> SubPalindromes(List<Node> tree) {
List<string> s = new List<string>();
SubPalindromes_children(0, "", tree, s);
foreach (var c in tree[1].Edges.Keys) {
int m = tree[1].Edges[c];
string ct = c.ToString();
s.Add(ct);
SubPalindromes_children(m, ct, tree, s);
}
return s;
}
static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {
foreach (var c in tree[n].Edges.Keys) {
int m = tree[n].Edges[c];
string p1 = c + p + c;
s.Add(p1);
SubPalindromes_children(m, p1, tree, s);
}
}
static void Main(string[] args) {
List<Node> tree = Eertree("eertree");
List<string> result = SubPalindromes(tree);
string listStr = string.Join(", ", result);
Console.WriteLine("[{0}]", listStr);
}
}
}
| 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
|
Generate a VB translation of this C# snippet without changing its computational steps. | using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program
{
public static void Main()
{
WriteLine("Long years in the 21st century:");
WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
}
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i < end; i++) yield return i;
}
}
| 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
|
Convert this C# block to VB, preserving its control flow and logic. | using System;
using System.Collections.Generic;
using System.Linq;
namespace ZumkellerNumbers {
class Program {
static List<int> GetDivisors(int n) {
List<int> divs = new List<int> {
1, n
};
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int j = n / i;
divs.Add(i);
if (i != j) {
divs.Add(j);
}
}
}
return divs;
}
static bool IsPartSum(List<int> divs, int sum) {
if (sum == 0) {
return true;
}
var le = divs.Count;
if (le == 0) {
return false;
}
var last = divs[le - 1];
List<int> newDivs = new List<int>();
for (int i = 0; i < le - 1; i++) {
newDivs.Add(divs[i]);
}
if (last > sum) {
return IsPartSum(newDivs, sum);
}
return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);
}
static bool IsZumkeller(int n) {
var divs = GetDivisors(n);
var sum = divs.Sum();
if (sum % 2 == 1) {
return false;
}
if (n % 2 == 1) {
var abundance = sum - 2 * n;
return abundance > 0 && abundance % 2 == 0;
}
return IsPartSum(divs, sum / 2);
}
static void Main() {
Console.WriteLine("The first 220 Zumkeller numbers are:");
int i = 2;
for (int count = 0; count < 220; i++) {
if (IsZumkeller(i)) {
Console.Write("{0,3} ", i);
count++;
if (count % 20 == 0) {
Console.WriteLine();
}
}
}
Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:");
i = 3;
for (int count = 0; count < 40; i += 2) {
if (IsZumkeller(i)) {
Console.Write("{0,5} ", i);
count++;
if (count % 10 == 0) {
Console.WriteLine();
}
}
}
Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:");
i = 3;
for (int count = 0; count < 40; i += 2) {
if (i % 10 != 5 && IsZumkeller(i)) {
Console.Write("{0,7} ", i);
count++;
if (count % 8 == 0) {
Console.WriteLine();
}
}
}
}
}
}
| 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
|
Keep all operations the same but rewrite the snippet in VB. | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
| 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
|
Port the provided C# code into VB while preserving the original functionality. | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
| 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
|
Write a version of this C# function in VB with identical behavior. | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static string doOne(int b, int digs) {
int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),
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; string st = bs.ToString();
return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); }
static string divIt(BI a, BI b, int digs) {
int al = a.ToString().Length, bl = b.ToString().Length;
a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);
string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); }
static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
string res = ""; for (int i = 0; i < x.Length; i++) res +=
string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; }
static void Main(string[] args) {
WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc");
int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) {
BI[] lst = new BI[15]; lst[0] = lst[1] = 1;
for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];
n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;
on = n; n = b * n + nm1; nm1 = on; }
WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{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)); }
n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;
on = n; n += nm1; nm1 = on; }
WriteLine("\nAu to 256 digits:"); WriteLine(t);
WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(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
|
Produce a language-to-language conversion: from C# to VB, same semantics. | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static string doOne(int b, int digs) {
int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),
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; string st = bs.ToString();
return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); }
static string divIt(BI a, BI b, int digs) {
int al = a.ToString().Length, bl = b.ToString().Length;
a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);
string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); }
static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
string res = ""; for (int i = 0; i < x.Length; i++) res +=
string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; }
static void Main(string[] args) {
WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc");
int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) {
BI[] lst = new BI[15]; lst[0] = lst[1] = 1;
for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];
n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;
on = n; n = b * n + nm1; nm1 = on; }
WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{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)); }
n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;
on = n; n += nm1; nm1 = on; }
WriteLine("\nAu to 256 digits:"); WriteLine(t);
WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(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
|
Rewrite this program in VB while keeping its functionality equivalent to the C# version. | using static System.Linq.Enumerable;
using static System.String;
using static System.Console;
using System.Collections.Generic;
using System;
using EdgeList = System.Collections.Generic.List<(int node, double weight)>;
public static class Dijkstra
{
public static void Main() {
Graph graph = new Graph(6);
Func<char, int> id = c => c - 'a';
Func<int , char> name = i => (char)(i + 'a');
foreach (var (start, end, cost) in new [] {
('a', 'b', 7),
('a', 'c', 9),
('a', 'f', 14),
('b', 'c', 10),
('b', 'd', 15),
('c', 'd', 11),
('c', 'f', 2),
('d', 'e', 6),
('e', 'f', 9),
}) {
graph.AddEdge(id(start), id(end), cost);
}
var path = graph.FindPath(id('a'));
for (int d = id('b'); d <= id('f'); d++) {
WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse()));
}
IEnumerable<(double distance, int node)> Path(int start, int destination) {
yield return (path[destination].distance, destination);
for (int i = destination; i != start; i = path[i].prev) {
yield return (path[path[i].prev].distance, path[i].prev);
}
}
}
}
sealed class Graph
{
private readonly List<EdgeList> adjacency;
public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();
public int Count => adjacency.Count;
public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);
public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;
public bool AddEdge(int s, int e, double weight) {
if (HasEdge(s, e)) return false;
adjacency[s].Add((e, weight));
return true;
}
public (double distance, int prev)[] FindPath(int start) {
var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();
info[start].distance = 0;
var visited = new System.Collections.BitArray(adjacency.Count);
var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));
heap.Push((start, 0));
while (heap.Count > 0) {
var current = heap.Pop();
if (visited[current.node]) continue;
var edges = adjacency[current.node];
for (int n = 0; n < edges.Count; n++) {
int v = edges[n].node;
if (visited[v]) continue;
double alt = info[current.node].distance + edges[n].weight;
if (alt < info[v].distance) {
info[v] = (alt, current.node);
heap.Push((v, alt));
}
}
visited[current.node] = true;
}
return info;
}
}
sealed class Heap<T>
{
private readonly IComparer<T> comparer;
private readonly List<T> list = new List<T> { default };
public Heap() : this(default(IComparer<T>)) { }
public Heap(IComparer<T> comparer) {
this.comparer = comparer ?? Comparer<T>.Default;
}
public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }
public int Count => list.Count - 1;
public void Push(T element) {
list.Add(element);
SiftUp(list.Count - 1);
}
public T Pop() {
T result = list[1];
list[1] = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
SiftDown(1);
return result;
}
private static int Parent(int i) => i / 2;
private static int Left(int i) => i * 2;
private static int Right(int i) => i * 2 + 1;
private void SiftUp(int i) {
while (i > 1) {
int parent = Parent(i);
if (comparer.Compare(list[i], list[parent]) > 0) return;
(list[parent], list[i]) = (list[i], list[parent]);
i = parent;
}
}
private void SiftDown(int i) {
for (int left = Left(i); left < list.Count; left = Left(i)) {
int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;
int right = Right(i);
if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;
if (smallest == i) return;
(list[i], list[smallest]) = (list[smallest], list[i]);
i = smallest;
}
}
}
| Class Branch
Public from As Node
Public towards As Node
Public length As Integer
Public distance As Integer
Public key As String
Class Node
Public key As String
Public correspondingBranch As Branch
Const INFINITY = 32767
Private Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)
Dim a As New Collection
Dim b As New Collection
Dim c As New Collection
Dim I As New Collection
Dim II As New Collection
Dim III As New Collection
Dim u As Node, R_ As Node, dist As Integer
For Each n In Nodes
c.Add n, n.key
Next n
For Each e In Branches
III.Add e, e.key
Next e
a.Add P, P.key
c.Remove P.key
Set u = P
Do
For Each r In III
If r.from Is u Then
Set R_ = r.towards
If Belongs(R_, c) Then
c.Remove R_.key
b.Add R_, R_.key
Set R_.correspondingBranch = r
If u.correspondingBranch Is Nothing Then
R_.correspondingBranch.distance = r.length
Else
R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length
End If
III.Remove r.key
II.Add r, r.key
Else
If Belongs(R_, b) Then
If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then
II.Remove R_.correspondingBranch.key
II.Add r, r.key
Set R_.correspondingBranch = r
R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length
End If
End If
End If
End If
Next r
dist = INFINITY
Set u = Nothing
For Each n In b
If dist > n.correspondingBranch.distance Then
dist = n.correspondingBranch.distance
Set u = n
End If
Next n
b.Remove u.key
a.Add u, u.key
II.Remove u.correspondingBranch.key
I.Add u.correspondingBranch, u.correspondingBranch.key
Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)
If Not Q Is Nothing Then GetPath Q
End Sub
Private Function Belongs(n As Node, col As Collection) As Boolean
Dim obj As Node
On Error GoTo err
Belongs = True
Set obj = col(n.key)
Exit Function
err:
Belongs = False
End Function
Private Sub GetPath(Target As Node)
Dim path As String
If Target.correspondingBranch Is Nothing Then
path = "no path"
Else
path = Target.key
Set u = Target
Do While Not u.correspondingBranch Is Nothing
path = u.correspondingBranch.from.key & " " & path
Set u = u.correspondingBranch.from
Loop
Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path
End If
End Sub
Public Sub test()
Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node
Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch
Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch
Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = "ab": ab.distance = INFINITY
Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = "ac": ac.distance = INFINITY
Set af.from = a: Set af.towards = f: af.length = 14: af.key = "af": af.distance = INFINITY
Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = "bc": bc.distance = INFINITY
Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = "bd": bd.distance = INFINITY
Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = "cd": cd.distance = INFINITY
Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = "cf": cf.distance = INFINITY
Set de.from = d: Set de.towards = e: de.length = 6: de.key = "de": de.distance = INFINITY
Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = "ef": ef.distance = INFINITY
a.key = "a"
b.key = "b"
c.key = "c"
d.key = "d"
e.key = "e"
f.key = "f"
Dim testNodes As New Collection
Dim testBranches As New Collection
testNodes.Add a, "a"
testNodes.Add b, "b"
testNodes.Add c, "c"
testNodes.Add d, "d"
testNodes.Add e, "e"
testNodes.Add f, "f"
testBranches.Add ab, "ab"
testBranches.Add ac, "ac"
testBranches.Add af, "af"
testBranches.Add bc, "bc"
testBranches.Add bd, "bd"
testBranches.Add cd, "cd"
testBranches.Add cf, "cf"
testBranches.Add de, "de"
testBranches.Add ef, "ef"
Debug.Print "From", "To", "Distance", "Path"
Dijkstra testNodes, testBranches, a, e
Dijkstra testNodes, testBranches, a
GetPath f
End Sub
|
Convert this C# snippet to VB and keep its semantics consistent. | using System;
using System.Text;
namespace GeometricAlgebra {
struct Vector {
private readonly double[] dims;
public Vector(double[] da) {
dims = da;
}
public static Vector operator -(Vector v) {
return v * -1.0;
}
public static Vector operator +(Vector lhs, Vector rhs) {
var result = new double[32];
Array.Copy(lhs.dims, 0, result, 0, lhs.Length);
for (int i = 0; i < result.Length; i++) {
result[i] = lhs[i] + rhs[i];
}
return new Vector(result);
}
public static Vector operator *(Vector lhs, Vector rhs) {
var result = new double[32];
for (int i = 0; i < lhs.Length; i++) {
if (lhs[i] != 0.0) {
for (int j = 0; j < lhs.Length; j++) {
if (rhs[j] != 0.0) {
var s = ReorderingSign(i, j) * lhs[i] * rhs[j];
var k = i ^ j;
result[k] += s;
}
}
}
}
return new Vector(result);
}
public static Vector operator *(Vector v, double scale) {
var result = (double[])v.dims.Clone();
for (int i = 0; i < result.Length; i++) {
result[i] *= scale;
}
return new Vector(result);
}
public double this[int key] {
get {
return dims[key];
}
set {
dims[key] = value;
}
}
public int Length {
get {
return dims.Length;
}
}
public Vector Dot(Vector rhs) {
return (this * rhs + rhs * this) * 0.5;
}
private static int BitCount(int i) {
i -= ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i + (i >> 4)) & 0x0F0F0F0F;
i += (i >> 8);
i += (i >> 16);
return i & 0x0000003F;
}
private static double ReorderingSign(int i, int j) {
int k = i >> 1;
int sum = 0;
while (k != 0) {
sum += BitCount(k & j);
k >>= 1;
}
return ((sum & 1) == 0) ? 1.0 : -1.0;
}
public override string ToString() {
var it = dims.GetEnumerator();
StringBuilder sb = new StringBuilder("[");
if (it.MoveNext()) {
sb.Append(it.Current);
}
while (it.MoveNext()) {
sb.Append(", ");
sb.Append(it.Current);
}
sb.Append(']');
return sb.ToString();
}
}
class Program {
static double[] DoubleArray(uint size) {
double[] result = new double[size];
for (int i = 0; i < size; i++) {
result[i] = 0.0;
}
return result;
}
static Vector E(int n) {
if (n > 4) {
throw new ArgumentException("n must be less than 5");
}
var result = new Vector(DoubleArray(32));
result[1 << n] = 1.0;
return result;
}
static readonly Random r = new Random();
static Vector RandomVector() {
var result = new Vector(DoubleArray(32));
for (int i = 0; i < 5; i++) {
var singleton = new double[] { r.NextDouble() };
result += new Vector(singleton) * E(i);
}
return result;
}
static Vector RandomMultiVector() {
var result = new Vector(DoubleArray(32));
for (int i = 0; i < result.Length; i++) {
result[i] = r.NextDouble();
}
return result;
}
static void Main() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i < j) {
if (E(i).Dot(E(j))[0] != 0.0) {
Console.WriteLine("Unexpected non-null sclar product.");
return;
}
} else if (i == j) {
if ((E(i).Dot(E(j)))[0] == 0.0) {
Console.WriteLine("Unexpected null sclar product.");
}
}
}
}
var a = RandomMultiVector();
var b = RandomMultiVector();
var c = RandomMultiVector();
var x = RandomVector();
Console.WriteLine((a * b) * c);
Console.WriteLine(a * (b * c));
Console.WriteLine();
Console.WriteLine(a * (b + c));
Console.WriteLine(a * b + a * c);
Console.WriteLine();
Console.WriteLine((a + b) * c);
Console.WriteLine(a * c + b * c);
Console.WriteLine();
Console.WriteLine(x * x);
}
}
}
| Option Strict On
Imports System.Text
Module Module1
Structure Vector
Private ReadOnly dims() As Double
Public Sub New(da() As Double)
dims = da
End Sub
Public Shared Operator -(v As Vector) As Vector
Return v * -1.0
End Operator
Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector
Dim result(31) As Double
Array.Copy(lhs.dims, 0, result, 0, lhs.Length)
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) = lhs(i2) + rhs(i2)
Next
Return New Vector(result)
End Operator
Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector
Dim result(31) As Double
For i = 1 To lhs.Length
Dim i2 = i - 1
If lhs(i2) <> 0.0 Then
For j = 1 To lhs.Length
Dim j2 = j - 1
If rhs(j2) <> 0.0 Then
Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)
Dim k = i2 Xor j2
result(k) += s
End If
Next
End If
Next
Return New Vector(result)
End Operator
Public Shared Operator *(v As Vector, scale As Double) As Vector
Dim result = CType(v.dims.Clone, Double())
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) *= scale
Next
Return New Vector(result)
End Operator
Default Public Property Index(key As Integer) As Double
Get
Return dims(key)
End Get
Set(value As Double)
dims(key) = value
End Set
End Property
Public ReadOnly Property Length As Integer
Get
Return dims.Length
End Get
End Property
Public Function Dot(rhs As Vector) As Vector
Return (Me * rhs + rhs * Me) * 0.5
End Function
Private Shared Function BitCount(i As Integer) As Integer
i -= ((i >> 1) And &H55555555)
i = (i And &H33333333) + ((i >> 2) And &H33333333)
i = (i + (i >> 4)) And &HF0F0F0F
i += (i >> 8)
i += (i >> 16)
Return i And &H3F
End Function
Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double
Dim k = i >> 1
Dim sum = 0
While k <> 0
sum += BitCount(k And j)
k >>= 1
End While
Return If((sum And 1) = 0, 1.0, -1.0)
End Function
Public Overrides Function ToString() As String
Dim it = dims.GetEnumerator
Dim sb As New StringBuilder("[")
If it.MoveNext() Then
sb.Append(it.Current)
End If
While it.MoveNext
sb.Append(", ")
sb.Append(it.Current)
End While
sb.Append("]")
Return sb.ToString
End Function
End Structure
Function DoubleArray(size As Integer) As Double()
Dim result(size - 1) As Double
For i = 1 To size
Dim i2 = i - 1
result(i2) = 0.0
Next
Return result
End Function
Function E(n As Integer) As Vector
If n > 4 Then
Throw New ArgumentException("n must be less than 5")
End If
Dim result As New Vector(DoubleArray(32))
result(1 << n) = 1.0
Return result
End Function
ReadOnly r As New Random()
Function RandomVector() As Vector
Dim result As New Vector(DoubleArray(32))
For i = 1 To 5
Dim i2 = i - 1
Dim singleton() As Double = {r.NextDouble()}
result += New Vector(singleton) * E(i2)
Next
Return result
End Function
Function RandomMultiVector() As Vector
Dim result As New Vector(DoubleArray(32))
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) = r.NextDouble()
Next
Return result
End Function
Sub Main()
For i = 1 To 5
Dim i2 = i - 1
For j = 1 To 5
Dim j2 = j - 1
If i2 < j2 Then
If E(i2).Dot(E(j2))(0) <> 0.0 Then
Console.Error.WriteLine("Unexpected non-null scalar product")
Return
End If
ElseIf i2 = j2 Then
If E(i2).Dot(E(j2))(0) = 0.0 Then
Console.Error.WriteLine("Unexpected null scalar product")
Return
End If
End If
Next
Next
Dim a = RandomMultiVector()
Dim b = RandomMultiVector()
Dim c = RandomMultiVector()
Dim x = RandomVector()
Console.WriteLine((a * b) * c)
Console.WriteLine(a * (b * c))
Console.WriteLine()
Console.WriteLine(a * (b + c))
Console.WriteLine(a * b + a * c)
Console.WriteLine()
Console.WriteLine((a + b) * c)
Console.WriteLine(a * c + b * c)
Console.WriteLine()
Console.WriteLine(x * x)
End Sub
End Module
|
Write the same code in VB as shown below in C#. | using System;
using System.Collections.Generic;
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,int> assocArray = new Dictionary<string,int>();
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
assocArray["!"] = 3;
foreach (KeyValuePair<string, int> kvp in assocArray)
{
Console.WriteLine(kvp.Key + " : " + kvp.Value);
}
foreach (string key in assocArray.Keys)
{
Console.WriteLine(key);
}
foreach (int val in assocArray.Values)
{
Console.WriteLine(val.ToString());
}
}
}
}
| Option Explicit
Sub Test()
Dim h As Object, i As Long, u, v, s
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
For Each s In h.Keys
Debug.Print s
Next
For Each s In h.Items
Debug.Print s
Next
u = h.Keys
v = h.Items
For i = 0 To h.Count - 1
Debug.Print u(i), v(i)
Next
End Sub
|
Convert this C# block to VB, preserving its control flow and logic. | using System;
using System.Globalization;
struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 10;
public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);
public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);
static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;
readonly int _value;
public int Value => this._value == 0 ? MIN_VALUE : this._value;
public LimitedInt(int value)
{
if (!IsValidValue(value))
throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}.");
this._value = value;
}
#region IComparable
public int CompareTo(object obj)
{
if (obj is LimitedInt l) return this.Value.CompareTo(l);
throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj));
}
#endregion
#region IComparable<LimitedInt>
public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);
#endregion
#region IConvertible
public TypeCode GetTypeCode() => this.Value.GetTypeCode();
bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);
byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);
char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);
DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);
decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);
double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);
short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);
int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);
long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);
sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);
float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);
string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);
object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);
ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);
uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);
ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);
#endregion
#region IEquatable<LimitedInt>
public bool Equals(LimitedInt other) => this == other;
#endregion
#region IFormattable
public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);
#endregion
#region operators
public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;
public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;
public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;
public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;
public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;
public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;
public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);
public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);
public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);
public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);
public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);
public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);
public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);
public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);
public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);
public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);
public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;
public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);
public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);
public static implicit operator int(LimitedInt value) => value.Value;
public static explicit operator LimitedInt(int value)
{
if (!IsValidValue(value)) throw new OverflowException();
return new LimitedInt(value);
}
#endregion
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
=> this.Value.TryFormat(destination, out charsWritten, format, provider);
public override int GetHashCode() => this.Value.GetHashCode();
public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);
public override string ToString() => this.Value.ToString();
#region static methods
public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);
public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);
public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);
public static int Parse(string s) => int.Parse(s);
public static int Parse(string s, NumberStyles style) => int.Parse(s, style);
public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);
public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);
#endregion
}
| Private mvarValue As Integer
Public Property Let Value(ByVal vData As Integer)
If (vData > 10) Or (vData < 1) Then
Error 380
Else
mvarValue = vData
End If
End Property
Public Property Get Value() As Integer
Value = mvarValue
End Property
Private Sub Class_Initialize()
mvarValue = 1
End Sub
|
Translate the given C# code snippet into VB without altering its behavior. | using System;
using System.Collections.Generic;
using System.Linq;
namespace HashJoin
{
public class AgeName
{
public AgeName(byte age, string name)
{
Age = age;
Name = name;
}
public byte Age { get; private set; }
public string Name { get; private set; }
}
public class NameNemesis
{
public NameNemesis(string name, string nemesis)
{
Name = name;
Nemesis = nemesis;
}
public string Name { get; private set; }
public string Nemesis { get; private set; }
}
public class DataContext
{
public DataContext()
{
AgeName = new List<AgeName>();
NameNemesis = new List<NameNemesis>();
}
public List<AgeName> AgeName { get; set; }
public List<NameNemesis> NameNemesis { get; set; }
}
public class AgeNameNemesis
{
public AgeNameNemesis(byte age, string name, string nemesis)
{
Age = age;
Name = name;
Nemesis = nemesis;
}
public byte Age { get; private set; }
public string Name { get; private set; }
public string Nemesis { get; private set; }
}
class Program
{
public static void Main()
{
var data = GetData();
var result = ExecuteHashJoin(data);
WriteResultToConsole(result);
}
private static void WriteResultToConsole(List<AgeNameNemesis> result)
{
result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}",
ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));
}
private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)
{
return (data.AgeName.Join(data.NameNemesis,
ageName => ageName.Name, nameNemesis => nameNemesis.Name,
(ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))
.ToList();
}
private static DataContext GetData()
{
var context = new DataContext();
context.AgeName.AddRange(new [] {
new AgeName(27, "Jonah"),
new AgeName(18, "Alan"),
new AgeName(28, "Glory"),
new AgeName(18, "Popeye"),
new AgeName(28, "Alan")
});
context.NameNemesis.AddRange(new[]
{
new NameNemesis("Jonah", "Whales"),
new NameNemesis("Jonah", "Spiders"),
new NameNemesis("Alan", "Ghosts"),
new NameNemesis("Alan", "Zombies"),
new NameNemesis("Glory", "Buffy")
});
return context;
}
}
}
| Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"
Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders"
t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts"
t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies"
t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy"
Call hash_join(t_age,1,t_nemesis,0)
Sub hash_join(table_1,index_1,table_2,index_2)
Set hash = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(table_1)
hash.Add i,Array(table_1(i,0),table_1(i,1))
Next
For j = 0 To UBound(table_2)
For Each key In hash.Keys
If hash(key)(index_1) = table_2(j,index_2) Then
WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_
" = " & table_2(j,0) & "," & table_2(j,1)
End If
Next
Next
End Sub
|
Convert this C# block to VB, preserving its control flow and logic. | using System;
using System.Collections.Generic;
using System.Linq;
namespace LatinSquares {
using matrix = List<List<int>>;
class Program {
static void Swap<T>(ref T a, ref T b) {
var t = a;
a = b;
b = t;
}
static matrix DList(int n, int start) {
start--;
var a = Enumerable.Range(0, n).ToArray();
a[start] = a[0];
a[0] = start;
Array.Sort(a, 1, a.Length - 1);
var first = a[1];
matrix r = new matrix();
void recurse(int last) {
if (last == first) {
for (int j = 1; j < a.Length; j++) {
var v = a[j];
if (j == v) {
return;
}
}
var b = a.Select(v => v + 1).ToArray();
r.Add(b.ToList());
return;
}
for (int i = last; i >= 1; i--) {
Swap(ref a[i], ref a[last]);
recurse(last - 1);
Swap(ref a[i], ref a[last]);
}
}
recurse(n - 1);
return r;
}
static ulong ReducedLatinSquares(int n, bool echo) {
if (n <= 0) {
if (echo) {
Console.WriteLine("[]\n");
}
return 0;
} else if (n == 1) {
if (echo) {
Console.WriteLine("[1]\n");
}
return 1;
}
matrix rlatin = new matrix();
for (int i = 0; i < n; i++) {
rlatin.Add(new List<int>());
for (int j = 0; j < n; j++) {
rlatin[i].Add(0);
}
}
for (int j = 0; j < n; j++) {
rlatin[0][j] = j + 1;
}
ulong count = 0;
void recurse(int i) {
var rows = DList(n, i);
for (int r = 0; r < rows.Count; r++) {
rlatin[i - 1] = rows[r];
for (int k = 0; k < i - 1; k++) {
for (int j = 1; j < n; j++) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.Count - 1) {
goto outer;
}
if (i > 2) {
return;
}
}
}
}
if (i < n) {
recurse(i + 1);
} else {
count++;
if (echo) {
PrintSquare(rlatin, n);
}
}
outer: { }
}
}
recurse(2);
return count;
}
static void PrintSquare(matrix latin, int n) {
foreach (var row in latin) {
var it = row.GetEnumerator();
Console.Write("[");
if (it.MoveNext()) {
Console.Write(it.Current);
}
while (it.MoveNext()) {
Console.Write(", {0}", it.Current);
}
Console.WriteLine("]");
}
Console.WriteLine();
}
static ulong Factorial(ulong n) {
if (n <= 0) {
return 1;
}
ulong prod = 1;
for (ulong i = 2; i < n + 1; i++) {
prod *= i;
}
return prod;
}
static void Main() {
Console.WriteLine("The four reduced latin squares of order 4 are:\n");
ReducedLatinSquares(4, true);
Console.WriteLine("The size of the set of reduced latin squares for the following orders");
Console.WriteLine("and hence the total number of latin squares of these orders are:\n");
for (int n = 1; n < 7; n++) {
ulong nu = (ulong)n;
var size = ReducedLatinSquares(n, false);
var f = Factorial(nu - 1);
f *= f * nu * size;
Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f);
}
}
}
}
| Option Strict On
Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim u = a
a = b
b = u
End Sub
Sub PrintSquare(latin As Matrix)
For Each row In latin
Dim it = row.GetEnumerator
Console.Write("[")
If it.MoveNext Then
Console.Write(it.Current)
End If
While it.MoveNext
Console.Write(", ")
Console.Write(it.Current)
End While
Console.WriteLine("]")
Next
Console.WriteLine()
End Sub
Function DList(n As Integer, start As Integer) As Matrix
start -= 1 REM use 0 based indexes
Dim a = Enumerable.Range(0, n).ToArray
a(start) = a(0)
a(0) = start
Array.Sort(a, 1, a.Length - 1)
Dim first = a(1)
REM recursive closure permutes a[1:]
Dim r As New Matrix
Dim Recurse As Action(Of Integer) = Sub(last As Integer)
If last = first Then
REM bottom of recursion. you get here once for each permutation
REM test if permutation is deranged.
For j = 1 To a.Length - 1
Dim v = a(j)
If j = v Then
Return REM no, ignore it
End If
Next
REM yes, save a copy with 1 based indexing
Dim b = a.Select(Function(v) v + 1).ToArray
r.Add(b.ToList)
Return
End If
For i = last To 1 Step -1
Swap(a(i), a(last))
Recurse(last - 1)
Swap(a(i), a(last))
Next
End Sub
Recurse(n - 1)
Return r
End Function
Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong
If n <= 0 Then
If echo Then
Console.WriteLine("[]")
Console.WriteLine()
End If
Return 0
End If
If n = 1 Then
If echo Then
Console.WriteLine("[1]")
Console.WriteLine()
End If
Return 1
End If
Dim rlatin As New Matrix
For i = 0 To n - 1
rlatin.Add(New List(Of Integer))
For j = 0 To n - 1
rlatin(i).Add(0)
Next
Next
REM first row
For j = 0 To n - 1
rlatin(0)(j) = j + 1
Next
Dim count As ULong = 0
Dim Recurse As Action(Of Integer) = Sub(i As Integer)
Dim rows = DList(n, i)
For r = 0 To rows.Count - 1
rlatin(i - 1) = rows(r)
For k = 0 To i - 2
For j = 1 To n - 1
If rlatin(k)(j) = rlatin(i - 1)(j) Then
If r < rows.Count - 1 Then
GoTo outer
End If
If i > 2 Then
Return
End If
End If
Next
Next
If i < n Then
Recurse(i + 1)
Else
count += 1UL
If echo Then
PrintSquare(rlatin)
End If
End If
outer:
While False
REM empty
End While
Next
End Sub
REM remiain rows
Recurse(2)
Return count
End Function
Function Factorial(n As ULong) As ULong
If n <= 0 Then
Return 1
End If
Dim prod = 1UL
For i = 2UL To n
prod *= i
Next
Return prod
End Function
Sub Main()
Console.WriteLine("The four reduced latin squares of order 4 are:")
Console.WriteLine()
ReducedLatinSquares(4, True)
Console.WriteLine("The size of the set of reduced latin squares for the following orders")
Console.WriteLine("and hence the total number of latin squares of these orders are:")
Console.WriteLine()
For n = 1 To 6
Dim nu As ULong = CULng(n)
Dim size = ReducedLatinSquares(n, False)
Dim f = Factorial(nu - 1UL)
f *= f * nu * size
Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f)
Next
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from C# to VB. | using System;
using System.Collections.Generic;
using System.Linq;
namespace LatinSquares {
using matrix = List<List<int>>;
class Program {
static void Swap<T>(ref T a, ref T b) {
var t = a;
a = b;
b = t;
}
static matrix DList(int n, int start) {
start--;
var a = Enumerable.Range(0, n).ToArray();
a[start] = a[0];
a[0] = start;
Array.Sort(a, 1, a.Length - 1);
var first = a[1];
matrix r = new matrix();
void recurse(int last) {
if (last == first) {
for (int j = 1; j < a.Length; j++) {
var v = a[j];
if (j == v) {
return;
}
}
var b = a.Select(v => v + 1).ToArray();
r.Add(b.ToList());
return;
}
for (int i = last; i >= 1; i--) {
Swap(ref a[i], ref a[last]);
recurse(last - 1);
Swap(ref a[i], ref a[last]);
}
}
recurse(n - 1);
return r;
}
static ulong ReducedLatinSquares(int n, bool echo) {
if (n <= 0) {
if (echo) {
Console.WriteLine("[]\n");
}
return 0;
} else if (n == 1) {
if (echo) {
Console.WriteLine("[1]\n");
}
return 1;
}
matrix rlatin = new matrix();
for (int i = 0; i < n; i++) {
rlatin.Add(new List<int>());
for (int j = 0; j < n; j++) {
rlatin[i].Add(0);
}
}
for (int j = 0; j < n; j++) {
rlatin[0][j] = j + 1;
}
ulong count = 0;
void recurse(int i) {
var rows = DList(n, i);
for (int r = 0; r < rows.Count; r++) {
rlatin[i - 1] = rows[r];
for (int k = 0; k < i - 1; k++) {
for (int j = 1; j < n; j++) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.Count - 1) {
goto outer;
}
if (i > 2) {
return;
}
}
}
}
if (i < n) {
recurse(i + 1);
} else {
count++;
if (echo) {
PrintSquare(rlatin, n);
}
}
outer: { }
}
}
recurse(2);
return count;
}
static void PrintSquare(matrix latin, int n) {
foreach (var row in latin) {
var it = row.GetEnumerator();
Console.Write("[");
if (it.MoveNext()) {
Console.Write(it.Current);
}
while (it.MoveNext()) {
Console.Write(", {0}", it.Current);
}
Console.WriteLine("]");
}
Console.WriteLine();
}
static ulong Factorial(ulong n) {
if (n <= 0) {
return 1;
}
ulong prod = 1;
for (ulong i = 2; i < n + 1; i++) {
prod *= i;
}
return prod;
}
static void Main() {
Console.WriteLine("The four reduced latin squares of order 4 are:\n");
ReducedLatinSquares(4, true);
Console.WriteLine("The size of the set of reduced latin squares for the following orders");
Console.WriteLine("and hence the total number of latin squares of these orders are:\n");
for (int n = 1; n < 7; n++) {
ulong nu = (ulong)n;
var size = ReducedLatinSquares(n, false);
var f = Factorial(nu - 1);
f *= f * nu * size;
Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f);
}
}
}
}
| Option Strict On
Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim u = a
a = b
b = u
End Sub
Sub PrintSquare(latin As Matrix)
For Each row In latin
Dim it = row.GetEnumerator
Console.Write("[")
If it.MoveNext Then
Console.Write(it.Current)
End If
While it.MoveNext
Console.Write(", ")
Console.Write(it.Current)
End While
Console.WriteLine("]")
Next
Console.WriteLine()
End Sub
Function DList(n As Integer, start As Integer) As Matrix
start -= 1 REM use 0 based indexes
Dim a = Enumerable.Range(0, n).ToArray
a(start) = a(0)
a(0) = start
Array.Sort(a, 1, a.Length - 1)
Dim first = a(1)
REM recursive closure permutes a[1:]
Dim r As New Matrix
Dim Recurse As Action(Of Integer) = Sub(last As Integer)
If last = first Then
REM bottom of recursion. you get here once for each permutation
REM test if permutation is deranged.
For j = 1 To a.Length - 1
Dim v = a(j)
If j = v Then
Return REM no, ignore it
End If
Next
REM yes, save a copy with 1 based indexing
Dim b = a.Select(Function(v) v + 1).ToArray
r.Add(b.ToList)
Return
End If
For i = last To 1 Step -1
Swap(a(i), a(last))
Recurse(last - 1)
Swap(a(i), a(last))
Next
End Sub
Recurse(n - 1)
Return r
End Function
Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong
If n <= 0 Then
If echo Then
Console.WriteLine("[]")
Console.WriteLine()
End If
Return 0
End If
If n = 1 Then
If echo Then
Console.WriteLine("[1]")
Console.WriteLine()
End If
Return 1
End If
Dim rlatin As New Matrix
For i = 0 To n - 1
rlatin.Add(New List(Of Integer))
For j = 0 To n - 1
rlatin(i).Add(0)
Next
Next
REM first row
For j = 0 To n - 1
rlatin(0)(j) = j + 1
Next
Dim count As ULong = 0
Dim Recurse As Action(Of Integer) = Sub(i As Integer)
Dim rows = DList(n, i)
For r = 0 To rows.Count - 1
rlatin(i - 1) = rows(r)
For k = 0 To i - 2
For j = 1 To n - 1
If rlatin(k)(j) = rlatin(i - 1)(j) Then
If r < rows.Count - 1 Then
GoTo outer
End If
If i > 2 Then
Return
End If
End If
Next
Next
If i < n Then
Recurse(i + 1)
Else
count += 1UL
If echo Then
PrintSquare(rlatin)
End If
End If
outer:
While False
REM empty
End While
Next
End Sub
REM remiain rows
Recurse(2)
Return count
End Function
Function Factorial(n As ULong) As ULong
If n <= 0 Then
Return 1
End If
Dim prod = 1UL
For i = 2UL To n
prod *= i
Next
Return prod
End Function
Sub Main()
Console.WriteLine("The four reduced latin squares of order 4 are:")
Console.WriteLine()
ReducedLatinSquares(4, True)
Console.WriteLine("The size of the set of reduced latin squares for the following orders")
Console.WriteLine("and hence the total number of latin squares of these orders are:")
Console.WriteLine()
For n = 1 To 6
Dim nu As ULong = CULng(n)
Dim size = ReducedLatinSquares(n, False)
Dim f = Factorial(nu - 1UL)
f *= f * nu * size
Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f)
Next
End Sub
End Module
|
Convert this C# snippet to VB and keep its semantics consistent. | class Segment
{
public Segment(PointF p1, PointF p2)
{
P1 = p1;
P2 = p2;
}
public readonly PointF P1;
public readonly PointF P2;
public float Length()
{
return (float)Math.Sqrt(LengthSquared());
}
public float LengthSquared()
{
return (P1.X - P2.X) * (P1.X - P2.X)
+ (P1.Y - P2.Y) * (P1.Y - P2.Y);
}
}
| Option Explicit
Private Type MyPoint
X As Single
Y As Single
End Type
Private Type MyPair
p1 As MyPoint
p2 As MyPoint
End Type
Sub Main()
Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long
Dim T#
Randomize Timer
Nb = 10
Do
ReDim points(1 To Nb)
For i = 1 To Nb
points(i).X = Rnd * Nb
points(i).Y = Rnd * Nb
Next
d = 1000000000000#
T = Timer
BF = BruteForce(points, d)
Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec."
Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y
Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y
Debug.Print "dist : " & d
Debug.Print "--------------------------------------------------"
Nb = Nb * 10
Loop While Nb <= 10000
End Sub
Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair
Dim i As Long, j As Long, d As Single, ClosestPair As MyPair
For i = 1 To UBound(p) - 1
For j = i + 1 To UBound(p)
d = Dist(p(i), p(j))
If d < mindist Then
mindist = d
ClosestPair.p1 = p(i)
ClosestPair.p2 = p(j)
End If
Next
Next
BruteForce = ClosestPair
End Function
Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single
Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)
End Function
|
Translate the given C# code snippet into VB without altering its behavior. | int i = 5;
int* p = &i;
| Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
TheAddress = varptr(MyVar)
MEMSET(TheAddress, 102, SizeOf(byte))
showmessage "MyVar = " + str$(MyVar)
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))
showmessage "SecVar = " + str$(SecVar)
|
Port the following code from C# to VB with equivalent syntax and logic. | class Animal
{
}
class Dog : Animal
{
}
class Lab : Dog
{
}
class Collie : Dog
{
}
class Cat : Animal
{
}
| Class Animal
End Class
Class Dog
Inherits Animal
End Class
Class Lab
Inherits Dog
End Class
Class Collie
Inherits Dog
End Class
Class Cat
Inherits Animal
End Class
|
Preserve the algorithm and functionality while converting the code from C# to VB. | System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";
| Option Explicit
Sub Test()
Dim h As Object
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
Debug.Print h.Item("A")
h.Item("C") = 4
h.Key("C") = "D"
Debug.Print h.exists("C")
h.Remove "B"
Debug.Print h.Count
h.RemoveAll
Debug.Print h.Count
End Sub
|
Translate this program into VB but keep the logic exactly as in C#. |
public MainWindow()
{
InitializeComponent();
RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);
imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);
DrawHue(100);
}
void DrawHue(int saturation)
{
var bmp = (WriteableBitmap)imgMain.Source;
int centerX = (int)bmp.Width / 2;
int centerY = (int)bmp.Height / 2;
int radius = Math.Min(centerX, centerY);
int radius2 = radius - 40;
bmp.Lock();
unsafe{
var buf = bmp.BackBuffer;
IntPtr pixLineStart;
for(int y=0; y < bmp.Height; y++){
pixLineStart = buf + bmp.BackBufferStride * y;
double dy = (y - centerY);
for(int x=0; x < bmp.Width; x++){
double dx = (x - centerX);
double dist = Math.Sqrt(dx * dx + dy * dy);
if (radius2 <= dist && dist <= radius) {
double theta = Math.Atan2(dy, dx);
double hue = (theta + Math.PI) / (2.0 * Math.PI);
*((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);
}
}
}
}
bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));
bmp.Unlock();
}
static int HSB_to_RGB(int h, int s, int v)
{
var rgb = new int[3];
var baseColor = (h + 60) % 360 / 120;
var shift = (h + 60) % 360 - (120 * baseColor + 60 );
var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;
rgb[baseColor] = 255;
rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);
for (var i = 0; i < 3; i++)
rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));
for (var i = 0; i < 3; i++)
rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);
return RGB2int(rgb[0], rgb[1], rgb[2]);
}
public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
| Option explicit
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray()
private filename
private Palette,szpal
public property get xmin():xmin=xmini:end property
public property get ymin():ymin=ymini:end property
public property get xmax():xmax=xmaxi:end property
public property get ymax():ymax=ymaxi:end property
public property let depth(x)
if x<>8 and x<>32 then err.raise 9
Imgdepth=x
end property
public sub set0 (x0,y0)
if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9
xmini=-x0
ymini=-y0
xmaxi=xmini+imgl-1
ymaxi=ymini+imgh-1
end sub
Public Default Function Init(name,w,h,orient,dep,bkg,mipal)
dim i,j
ImgL=w
ImgH=h
tt=timer
loc=getlocale
set0 0,0
redim imgArray(ImgL-1,ImgH-1)
bkclr=bkg
if bkg<>0 then
for i=0 to ImgL-1
for j=0 to ImgH-1
imgarray(i,j)=bkg
next
next
end if
Select Case orient
Case 1: dirx=1 : diry=1
Case 2: dirx=-1 : diry=1
Case 3: dirx=-1 : diry=-1
Case 4: dirx=1 : diry=-1
End select
filename=name
ImgDepth =dep
if imgdepth=8 then
loadpal(mipal)
end if
set init=me
end function
private sub loadpal(mipale)
if isarray(mipale) Then
palette=mipale
szpal=UBound(mipale)+1
Else
szpal=256
, not relevant
End if
End Sub
Private Sub Class_Terminate
if err<>0 then wscript.echo "Error " & err.number
wscript.echo "copying image to bmp file"
savebmp
wscript.echo "opening " & filename & " with your default bmp viewer"
CreateObject("Shell.Application").ShellExecute filename
wscript.echo timer-tt & " iseconds"
End Sub
function long2wstr( x)
dim k1,k2,x1
k1= (x and &hffff&)
k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0))
long2wstr=chrw(k1) & chrw(k2)
end function
function int2wstr(x)
int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))
End Function
Public Sub SaveBMP
Dim s,ostream, x,y,loc
const hdrs=54
dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4)
dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0
with CreateObject("ADODB.Stream")
.Charset = "UTF-16LE"
.Type = 2
.open
.writetext ChrW(&h4d42)
.writetext long2wstr(hdrs+palsize+bms)
.writetext long2wstr(0)
.writetext long2wstr (hdrs+palsize)
.writetext long2wstr(40)
.writetext long2wstr(Imgl)
.writetext long2wstr(imgh)
.writetext int2wstr(1)
.writetext int2wstr(imgdepth)
.writetext long2wstr(&H0)
.writetext long2wstr(bms)
.writetext long2wstr(&Hc4e)
.writetext long2wstr(&hc43)
.writetext long2wstr(szpal)
.writetext long2wstr(&H0)
Dim x1,x2,y1,y2
If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1
If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1
Select Case imgdepth
Case 32
For y=y1 To y2 step diry
For x=x1 To x2 Step dirx
.writetext long2wstr(Imgarray(x,y))
Next
Next
Case 8
For x=0 to szpal-1
.writetext long2wstr(palette(x))
Next
dim pad:pad=ImgL mod 4
For y=y1 to y2 step diry
For x=x1 To x2 step dirx*2
.writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))
Next
if pad and 1 then .writetext chrw(ImgArray(x2,y))
if pad >1 then .writetext chrw(0)
Next
Case Else
WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits"
End Select
Dim outf:Set outf= CreateObject("ADODB.Stream")
outf.Type = 1
outf.Open
.position=2
.CopyTo outf
.close
outf.savetofile filename,2
outf.close
end with
End Sub
end class
function hsv2rgb( Hue, Sat, Value)
dim Angle, Radius,Ur,Vr,Wr,Rdim
dim r,g,b, rgb
Angle = (Hue-150) *0.01745329251994329576923690768489
Ur = Value * 2.55
Radius = Ur * tan(Sat *0.01183199)
Vr = Radius * cos(Angle) *0.70710678
Wr = Radius * sin(Angle) *0.40824829
r = (Ur - Vr - Wr)
g = (Ur + Vr - Wr)
b = (Ur + Wr + Wr)
if r >255 then
Rdim = (Ur - 255) / (Vr + Wr)
r = 255
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
elseif r < 0 then
Rdim = Ur / (Vr + Wr)
r = 0
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
end if
if g >255 then
Rdim = (255 - Ur) / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 255
b = Ur + 2 * Wr * Rdim
elseif g<0 then
Rdim = -Ur / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 0
b = Ur + 2 * Wr * Rdim
end if
if b>255 then
Rdim = (255 - Ur) / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 255
elseif b<0 then
Rdim = -Ur / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 0
end If
hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)
end function
function ang(col,row)
if col =0 then
if row<0 then ang=90 else ang=270 end if
else
if col>0 then
ang=atn(-row/col)*57.2957795130
else
ang=(atn(row/-col)*57.2957795130)+180
end if
end if
ang=(ang+360) mod 360
end function
Dim X,row,col,fn,tt,hr,sat,row2
const h=160
const w=160
const rad=159
const r2=25500
tt=timer
fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp"
Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)
x.set0 w,h
for row=x.xmin+1 to x.xmax
row2=row*row
hr=int(Sqr(r2-row2))
For col=hr To 159
Dim a:a=((col\16 +row\16) And 1)* &hffffff
x.imgArray(col+160,row+160)=a
x.imgArray(-col+160,row+160)=a
next
for col=-hr to hr
sat=100-sqr(row2+col*col)/rad *50
x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)
next
next
Set X = Nothing
|
Maintain the same structure and functionality when rewriting this code in VB. | using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using UI = System.UInt64;
using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;
using Lst = System.Collections.Generic.List<sbyte>;
using DT = System.DateTime;
class Program {
const sbyte MxD = 19;
public struct term { public UI coeff; public sbyte a, b;
public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } }
static int[] digs; static List<UI> res; static sbyte count = 0;
static DT st; static List<List<term>> tLst; static List<LST> lists;
static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il;
static bool odd; static int nd, nd2; static LST ixs;
static int[] cnd, di; static LST dis; static UI Dif;
static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++)
r = r * 10 + (uint)digs[i]; return r; }
static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--)
r = r * 10 + (uint)digs[i]; return Dif + (r << 1); }
static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0)
{ UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; }
static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst();
for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; }
static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0];
digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1;
if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) {
digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; }
if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine("{0,16:n0}{1,4} ({2:n0})",
(DT.Now - st).TotalMilliseconds, ++count, res.Last()); }
else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } }
static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0;
foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]);
else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return;
dis = new LST { Seq(0, fml[cnd[0]].Count - 1) };
foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1));
if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0);
} else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } }
static void init() { UI pow = 1;
tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) {
List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1;
for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) {
terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; }
tLst.Add(terms); }
fml = new Dictionary<int, LST> {
[0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } },
[1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } },
[4] = new LST { new Lst { 4, 0 } },
[6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } };
dmd = new Dictionary<int, LST>();
for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) {
if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j });
else dmd[d] = new LST { new Lst { i, j } }; }
dl = Seq(-9, 9);
zl = Seq( 0, 0);
el = Seq(-8, 8, 2);
ol = Seq(-9, 9, 2);
il = Seq( 0, 9); lists = new List<LST>();
foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); }
static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0;
WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Unordered Rare Numbers");
for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd];
if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); }
else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl);
ixs = new LST();
foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b });
foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); }
WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds); }
res.Sort();
WriteLine("\nThe {0} rare numbers with up to {1} digits are:", res.Count, MxD);
count = 0; foreach (var rare in res) WriteLine("{0,2}:{1,27:n0}", ++count, rare);
if (System.Diagnostics.Debugger.IsAttached) ReadKey(); }
}
| Imports System.Console
Imports DT = System.DateTime
Imports Lsb = System.Collections.Generic.List(Of SByte)
Imports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte))
Imports UI = System.UInt64
Module Module1
Const MxD As SByte = 15
Public Structure term
Public coeff As UI : Public a, b As SByte
Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer)
coeff = c : a = CSByte(a_) : b = CSByte(b_)
End Sub
End Structure
Dim nd, nd2, count As Integer, digs, cnd, di As Integer()
Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term))
Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst)
Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI
Function ToDif() As UI
Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i)
Next : Return r
End Function
Function ToSum() As UI
Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i)
Next : Return Dif + (r << 1)
End Function
Function IsSquare(nmbr As UI) As Boolean
If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _
Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False
End Function
Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb
Dim res As Lsb = New Lsb()
For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res
End Function
Sub Fnpr(ByVal lev As Integer)
If lev = dis.Count Then
digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1)
Dim le As Integer = di.Length, i As Integer = 1
If odd Then le -= 1 : digs(nd >> 1) = di(le)
For Each d As SByte In di.Skip(1).Take(le - 1)
digs(ixs(i)(0)) = dmd(cnd(i))(d)(0)
digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next
If Not IsSquare(ToSum()) Then Return
res.Add(ToDif()) : count += 1
WriteLine("{0,16:n0}{1,4} ({2:n0})", (DT.Now - st).TotalMilliseconds, count, res.Last())
Else
For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next
End If
End Sub
Sub Fnmr(ByVal list As Lst, ByVal lev As Integer)
If lev = list.Count Then
Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2)
If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _
Else Dif += t.coeff * CULng(cnd(i))
i += 1 : Next
If Dif <= 0 OrElse Not IsSquare(Dif) Then Return
dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)}
For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next
If odd Then dis.Add(il)
di = New Integer(dis.Count - 1) {} : Fnpr(0)
Else
For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next
End If
End Sub
Sub init()
Dim pow As UI = 1
tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD)
Dim terms As List(Of term) = New List(Of term)()
pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1
Dim i1 As Integer = 0, i2 As Integer = r - 1
While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2))
p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While
tLst.Add(terms) : Next
fml = New Dictionary(Of Integer, Lst)() From {
{0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}},
{1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}},
{4, New Lst() From {New Lsb() From {4, 0}}},
{6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}}
dmd = New Dictionary(Of Integer, Lst)()
For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i
While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _
Else dmd(d) = New Lst From {New Lsb From {i, j}}
j += 1 : d -= 1 : End While : Next
dl = Seq(-9, 9)
zl = Seq(0, 0)
el = Seq(-8, 8, 2)
ol = Seq(-9, 9, 2)
il = Seq(0, 9)
lists = New List(Of Lst)()
For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next
End Sub
Sub Main(ByVal args As String())
init() : res = New List(Of UI)() : st = DT.Now : count = 0
WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Rare Numbers")
nd = 2 : nd2 = 0 : odd = False : While nd <= MxD
digs = New Integer(nd - 1) {} : If nd = 4 Then
lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol)
ElseIf tLst(nd2).Count > lists(0).Count Then
For Each list As Lst In lists : list.Add(dl) : Next : End If
ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next
For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next
WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds)
nd += 1 : nd2 += 1 : odd = Not odd : End While
res.Sort() : WriteLine(vbLf & "The {0} rare numbers with up to {1} digits are:", res.Count, MxD)
count = 0 : For Each rare In res : count += 1 : WriteLine("{0,2}:{1,27:n0}", count, rare) : Next
If System.Diagnostics.Debugger.IsAttached Then ReadKey()
End Sub
End Module
|
Maintain the same structure and functionality when rewriting this code in VB. | using System;
using System.Drawing;
using System.Windows.Forms;
class MineFieldModel
{
public int RemainingMinesCount{
get{
var count = 0;
ForEachCell((i,j)=>{
if (Mines[i,j] && !Marked[i,j])
count++;
});
return count;
}
}
public bool[,] Mines{get; private set;}
public bool[,] Opened{get;private set;}
public bool[,] Marked{get; private set;}
public int[,] Values{get;private set; }
public int Width{ get{return Mines.GetLength(1);} }
public int Height{ get{return Mines.GetLength(0);} }
public MineFieldModel(bool[,] mines)
{
this.Mines = mines;
this.Opened = new bool[Height, Width];
this.Marked = new bool[Height, Width];
this.Values = CalculateValues();
}
private int[,] CalculateValues()
{
int[,] values = new int[Height, Width];
ForEachCell((i,j) =>{
var value = 0;
ForEachNeighbor(i,j, (i1,j1)=>{
if (Mines[i1,j1])
value++;
});
values[i,j] = value;
});
return values;
}
public void ForEachCell(Action<int,int> action)
{
for (var i = 0; i < Height; i++)
for (var j = 0; j < Width; j++)
action(i,j);
}
public void ForEachNeighbor(int i, int j, Action<int,int> action)
{
for (var i1 = i-1; i1 <= i+1; i1++)
for (var j1 = j-1; j1 <= j+1; j1++)
if (InBounds(j1, i1) && !(i1==i && j1 ==j))
action(i1, j1);
}
private bool InBounds(int x, int y)
{
return y >= 0 && y < Height && x >=0 && x < Width;
}
public event Action Exploded = delegate{};
public event Action Win = delegate{};
public event Action Updated = delegate{};
public void OpenCell(int i, int j){
if(!Opened[i,j]){
if (Mines[i,j])
Exploded();
else{
OpenCellsStartingFrom(i,j);
Updated();
CheckForVictory();
}
}
}
void OpenCellsStartingFrom(int i, int j)
{
Opened[i,j] = true;
ForEachNeighbor(i,j, (i1,j1)=>{
if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1])
OpenCellsStartingFrom(i1, j1);
});
}
void CheckForVictory(){
int notMarked = 0;
int wrongMarked = 0;
ForEachCell((i,j)=>{
if (Mines[i,j] && !Marked[i,j])
notMarked++;
if (!Mines[i,j] && Marked[i,j])
wrongMarked++;
});
if (notMarked == 0 && wrongMarked == 0)
Win();
}
public void Mark(int i, int j){
if (!Opened[i,j])
Marked[i,j] = true;
Updated();
CheckForVictory();
}
}
class MineFieldView: UserControl{
public const int CellSize = 40;
MineFieldModel _model;
public MineFieldModel Model{
get{ return _model; }
set
{
_model = value;
this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2);
}
}
public MineFieldView(){
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true);
this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);
this.MouseUp += (o,e)=>{
Point cellCoords = GetCell(e.Location);
if (Model != null)
{
if (e.Button == MouseButtons.Left)
Model.OpenCell(cellCoords.Y, cellCoords.X);
else if (e.Button == MouseButtons.Right)
Model.Mark(cellCoords.Y, cellCoords.X);
}
};
}
Point GetCell(Point coords)
{
var rgn = ClientRectangle;
var x = (coords.X - rgn.X)/CellSize;
var y = (coords.Y - rgn.Y)/CellSize;
return new Point(x,y);
}
static readonly Brush MarkBrush = new SolidBrush(Color.Blue);
static readonly Brush ValueBrush = new SolidBrush(Color.Black);
static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control);
static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark);
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var g = e.Graphics;
if (Model != null)
{
Model.ForEachCell((i,j)=>
{
var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize);
if (Model.Opened[i,j])
{
g.FillRectangle(OpenBrush, bounds);
if (Model.Values[i,j] > 0)
{
DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds);
}
}
else
{
g.FillRectangle(UnexploredBrush, bounds);
if (Model.Marked[i,j])
{
DrawStringInCenter(g, "?", MarkBrush, bounds);
}
var outlineOffset = 1;
var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset);
g.DrawRectangle(Pens.Gray, outline);
}
g.DrawRectangle(Pens.Black, bounds);
});
}
}
static readonly StringFormat FormatCenter = new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment=StringAlignment.Center
};
void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds)
{
PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2);
g.DrawString(s, this.Font, brush, center, FormatCenter);
}
}
class MineSweepForm: Form
{
MineFieldModel CreateField(int width, int height)
{
var field = new bool[height, width];
int mineCount = (int)(0.2 * height * width);
var rnd = new Random();
while(mineCount > 0)
{
var x = rnd.Next(width);
var y = rnd.Next(height);
if (!field[y,x])
{
field[y,x] = true;
mineCount--;
}
}
return new MineFieldModel(field);
}
public MineSweepForm()
{
var model = CreateField(6, 4);
var counter = new Label{ };
counter.Text = model.RemainingMinesCount.ToString();
var view = new MineFieldView
{
Model = model, BorderStyle = BorderStyle.FixedSingle,
};
var stackPanel = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.TopDown,
Controls = {counter, view}
};
this.Controls.Add(stackPanel);
model.Updated += delegate{
view.Invalidate();
counter.Text = model.RemainingMinesCount.ToString();
};
model.Exploded += delegate {
MessageBox.Show("FAIL!");
Close();
};
model.Win += delegate {
MessageBox.Show("WIN!");
view.Enabled = false;
};
}
}
class Program
{
static void Main()
{
Application.Run(new MineSweepForm());
}
}
| Option Explicit
Public vTime As Single
Public PlaysCount As Long
Sub Main_MineSweeper()
Dim Userf As New cMinesweeper
Userf.Show 0, True
End Sub
|
Write the same code in VB as shown below in C#. | using System;
using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static void Main(string[] args) {
BI i, j, k, d; i = 2; int n = -1; int n0 = -1;
j = (BI)Floor(Sqrt((double)i)); k = j; d = j;
DateTime st = DateTime.Now;
if (args.Length > 0) int.TryParse(args[0], out n);
if (n > 0) n0 = n; else n = 1;
do {
Write(d); i = (i - k * d) * 100; k = 20 * j;
for (d = 1; d <= 10; d++)
if ((k + d) * d > i) { d -= 1; break; }
j = j * 10 + d; k += d; if (n0 > 0) n--;
} while (n > 0);
if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); }
}
| Imports System.Math, System.Console, BI = System.Numerics.BigInteger
Module Module1
Sub Main(ByVal args As String())
Dim i, j, k, d As BI : i = 2
j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
Dim n As Integer = -1, n0 As Integer = -1,
st As DateTime = DateTime.Now
If args.Length > 0 Then Integer.TryParse(args(0), n)
If n > 0 Then n0 = n Else n = 1
Do
Write(d) : i = (i - k * d) * 100 : k = 20 * j
For d = 1 To 10
If (k + d) * d > i Then d -= 1 : Exit For
Next
j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
Loop While n > 0
If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
End Sub
End Module
|
Write a version of this C# function in VB with identical behavior. | using System;
using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static void Main(string[] args) {
BI i, j, k, d; i = 2; int n = -1; int n0 = -1;
j = (BI)Floor(Sqrt((double)i)); k = j; d = j;
DateTime st = DateTime.Now;
if (args.Length > 0) int.TryParse(args[0], out n);
if (n > 0) n0 = n; else n = 1;
do {
Write(d); i = (i - k * d) * 100; k = 20 * j;
for (d = 1; d <= 10; d++)
if ((k + d) * d > i) { d -= 1; break; }
j = j * 10 + d; k += d; if (n0 > 0) n--;
} while (n > 0);
if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); }
}
| Imports System.Math, System.Console, BI = System.Numerics.BigInteger
Module Module1
Sub Main(ByVal args As String())
Dim i, j, k, d As BI : i = 2
j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
Dim n As Integer = -1, n0 As Integer = -1,
st As DateTime = DateTime.Now
If args.Length > 0 Then Integer.TryParse(args(0), n)
If n > 0 Then n0 = n Else n = 1
Do
Write(d) : i = (i - k * d) * 100 : k = 20 * j
For d = 1 To 10
If (k + d) * d > i Then d -= 1 : Exit For
Next
j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
Loop While n > 0
If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
End Sub
End Module
|
Change the programming language of this snippet from C# to VB without modifying what it does. | using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
class Program {
static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static string from10(int b) { string res = ""; int re; while (b > 0) {
b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }
static int to10(string s) { int res = 0; foreach (char i in s)
res = res * ba + chars.IndexOf(i); return res; }
static bool nd(string s) { if (s.Length < 2) return true;
char l = s[0]; for (int i = 1; i < s.Length; i++)
if (chars.IndexOf(l) > chars.IndexOf(s[i]))
return false; else l = s[i] ; return true; }
static void Main(string[] args) { int c, lim = 1000; string s;
foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {
ba = b; c = 0; foreach (var a in PG.Primes(lim))
if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : "");
WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } }
class PG { public static IEnumerable<int> Primes(int lim) {
var flags = new bool[lim + 1]; int j; yield return 2;
for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
| Imports System.Linq
Imports System.Collections.Generic
Imports System.Console
Imports System.Math
Module Module1
Dim ba As Integer
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean, j As Integer : Yield 2
For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
Dim d As Integer = 8, sq As Integer = 9
While sq <= lim
If Not flags(j) Then
Yield j : Dim i As Integer = j << 1
For k As Integer = sq To lim step i : flags(k) = True : Next
End If
j += 2 : d += 8 : sq += d : End While
While j <= lim
If Not flags(j) Then Yield j
j += 2 : End While
End Function
Function from10(ByVal b As Integer) As String
Dim res As String = "", re As Integer
While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
End Function
Function to10(ByVal s As String) As Integer
Dim res As Integer = 0
For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
End Function
Function nd(ByVal s As String) As Boolean
If s.Length < 2 Then Return True
Dim l As Char = s(0)
For i As Integer = 1 To s.Length - 1
If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
Next : Return True
End Function
Sub Main(ByVal args As String())
Dim c As Integer, lim As Integer = 1000, s As String
For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
ba = b : c = 0 : For Each a As Integer In Primes(lim)
s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
Next
WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
Next
End Sub
End Module
|
Please provide an equivalent version of this C# code in VB. | using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
class Program {
static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static string from10(int b) { string res = ""; int re; while (b > 0) {
b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }
static int to10(string s) { int res = 0; foreach (char i in s)
res = res * ba + chars.IndexOf(i); return res; }
static bool nd(string s) { if (s.Length < 2) return true;
char l = s[0]; for (int i = 1; i < s.Length; i++)
if (chars.IndexOf(l) > chars.IndexOf(s[i]))
return false; else l = s[i] ; return true; }
static void Main(string[] args) { int c, lim = 1000; string s;
foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {
ba = b; c = 0; foreach (var a in PG.Primes(lim))
if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : "");
WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } }
class PG { public static IEnumerable<int> Primes(int lim) {
var flags = new bool[lim + 1]; int j; yield return 2;
for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
| Imports System.Linq
Imports System.Collections.Generic
Imports System.Console
Imports System.Math
Module Module1
Dim ba As Integer
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean, j As Integer : Yield 2
For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
Dim d As Integer = 8, sq As Integer = 9
While sq <= lim
If Not flags(j) Then
Yield j : Dim i As Integer = j << 1
For k As Integer = sq To lim step i : flags(k) = True : Next
End If
j += 2 : d += 8 : sq += d : End While
While j <= lim
If Not flags(j) Then Yield j
j += 2 : End While
End Function
Function from10(ByVal b As Integer) As String
Dim res As String = "", re As Integer
While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
End Function
Function to10(ByVal s As String) As Integer
Dim res As Integer = 0
For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
End Function
Function nd(ByVal s As String) As Boolean
If s.Length < 2 Then Return True
Dim l As Char = s(0)
For i As Integer = 1 To s.Length - 1
If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
Next : Return True
End Function
Sub Main(ByVal args As String())
Dim c As Integer, lim As Integer = 1000, s As String
For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
ba = b : c = 0 : For Each a As Integer In Primes(lim)
s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
Next
WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
Next
End Sub
End Module
|
Produce a language-to-language conversion: from C# to VB, same semantics. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class Reflection
{
public static void Main() {
var t = new TestClass();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var prop in GetPropertyValues(t, flags)) {
Console.WriteLine(prop);
}
foreach (var field in GetFieldValues(t, flags)) {
Console.WriteLine(field);
}
}
public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>
from p in typeof(T).GetProperties(flags)
where p.GetIndexParameters().Length == 0
select (p.Name, p.GetValue(obj, null));
public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>
typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));
class TestClass
{
private int privateField = 7;
public int PublicNumber { get; } = 4;
private int PrivateNumber { get; } = 2;
}
}
| Imports System.Reflection
Module Module1
Class TestClass
Private privateField = 7
Public ReadOnly Property PublicNumber = 4
Private ReadOnly Property PrivateNumber = 2
End Class
Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return From p In obj.GetType().GetProperties(flags)
Where p.GetIndexParameters().Length = 0
Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}
End Function
Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})
End Function
Sub Main()
Dim t As New TestClass()
Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance
For Each prop In GetPropertyValues(t, flags)
Console.WriteLine(prop)
Next
For Each field In GetFieldValues(t, flags)
Console.WriteLine(field)
Next
End Sub
End Module
|
Rewrite the snippet below in VB so it works the same as the original C# code. | using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
string[][] table = new string[lines.Length][];
int columns = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].TrimEnd(Separator).Split(Separator);
if (columns < row.Length) columns = row.Length;
table[i] = row;
}
string[][] formattedTable = new string[table.Length][];
for (int i = 0; i < formattedTable.Length; i++)
{
formattedTable[i] = new string[columns];
}
for (int j = 0; j < columns; j++)
{
int columnWidth = 0;
for (int i = 0; i < table.Length; i++)
{
if (j < table[i].Length && columnWidth < table[i][j].Length)
columnWidth = table[i][j].Length;
}
for (int i = 0; i < formattedTable.Length; i++)
{
if (j < table[i].Length)
formattedTable[i][j] = justification(table[i][j], columnWidth);
else
formattedTable[i][j] = new String(' ', columnWidth);
}
}
string[] result = new string[formattedTable.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = String.Join(" ", formattedTable[i]);
}
return result;
}
static string JustifyLeft(string s, int width) { return s.PadRight(width); }
static string JustifyRight(string s, int width) { return s.PadLeft(width); }
static string JustifyCenter(string s, int width)
{
return s.PadLeft((width + s.Length) / 2).PadRight(width);
}
static void Main()
{
string[] input = {
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column.",
};
foreach (string line in AlignColumns(input, JustifyCenter))
{
Console.WriteLine(line);
}
}
}
| Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
MText.WriteLine "are$delineated$by$a$single$
MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
MText.WriteLine "column$are$separated$by$at$least$one$space."
MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column."
DefStr TextLeft, TextRight, TextCenter
DefStr MLine, LWord, Newline = chr$(13)+chr$(10)
DefInt ColWidth(100), ColCount
DefSng NrSpaces
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))
next
next
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
NrSpaces = ColWidth(y) - len(LWord)
TextLeft = TextLeft + LWord + Space$(NrSpaces+1)
TextRight = TextRight + Space$(NrSpaces+1) + LWord
TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))
next
TextLeft = TextLeft + Newline
TextRight = TextRight + Newline
TextCenter = TextCenter + Newline
next
|
Translate the given C# code snippet into VB without altering its behavior. | using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
string[][] table = new string[lines.Length][];
int columns = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].TrimEnd(Separator).Split(Separator);
if (columns < row.Length) columns = row.Length;
table[i] = row;
}
string[][] formattedTable = new string[table.Length][];
for (int i = 0; i < formattedTable.Length; i++)
{
formattedTable[i] = new string[columns];
}
for (int j = 0; j < columns; j++)
{
int columnWidth = 0;
for (int i = 0; i < table.Length; i++)
{
if (j < table[i].Length && columnWidth < table[i][j].Length)
columnWidth = table[i][j].Length;
}
for (int i = 0; i < formattedTable.Length; i++)
{
if (j < table[i].Length)
formattedTable[i][j] = justification(table[i][j], columnWidth);
else
formattedTable[i][j] = new String(' ', columnWidth);
}
}
string[] result = new string[formattedTable.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = String.Join(" ", formattedTable[i]);
}
return result;
}
static string JustifyLeft(string s, int width) { return s.PadRight(width); }
static string JustifyRight(string s, int width) { return s.PadLeft(width); }
static string JustifyCenter(string s, int width)
{
return s.PadLeft((width + s.Length) / 2).PadRight(width);
}
static void Main()
{
string[] input = {
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column.",
};
foreach (string line in AlignColumns(input, JustifyCenter))
{
Console.WriteLine(line);
}
}
}
| Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
MText.WriteLine "are$delineated$by$a$single$
MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
MText.WriteLine "column$are$separated$by$at$least$one$space."
MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column."
DefStr TextLeft, TextRight, TextCenter
DefStr MLine, LWord, Newline = chr$(13)+chr$(10)
DefInt ColWidth(100), ColCount
DefSng NrSpaces
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))
next
next
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
NrSpaces = ColWidth(y) - len(LWord)
TextLeft = TextLeft + LWord + Space$(NrSpaces+1)
TextRight = TextRight + Space$(NrSpaces+1) + LWord
TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))
next
TextLeft = TextLeft + Newline
TextRight = TextRight + Newline
TextCenter = TextCenter + Newline
next
|
Generate an equivalent VB version of this C# code. | using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo:
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql:
ParseUrl("ftp:
ParseUrl("http:
ParseUrl("ldap:
ParseUrl("mailto:John.Doe@example.com");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet:
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
| Function parse_url(url)
parse_url = "URL: " & url
If InStr(url,"//") Then
scheme = Split(url,"//")
parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1)
domain = Split(scheme(1),"/")
If InStr(domain(0),"@") Then
cred = Split(domain(0),"@")
If InStr(cred(0),".") Then
username = Mid(cred(0),1,InStr(1,cred(0),".")-1)
password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),"."))
ElseIf InStr(cred(0),":") Then
username = Mid(cred(0),1,InStr(1,cred(0),":")-1)
password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":"))
End If
parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_
"Password: " & password
If InStr(cred(1),":") Then
host = Mid(cred(1),1,InStr(1,cred(1),":")-1)
port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & cred(1)
End If
ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then
host = Mid(domain(0),1,InStr(1,domain(0),":")-1)
port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then
host = Mid(domain(0),1,InStr(1,domain(0),"]"))
port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & domain(0)
End If
If UBound(domain) > 0 Then
For i = 1 To UBound(domain)
If i < UBound(domain) Then
path = path & domain(i) & "/"
ElseIf InStr(domain(i),"?") Then
path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1)
If InStr(domain(i),"#") Then
query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1)
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment
Else
query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?"))
path = path & vbcrlf & "Query: " & query
End If
ElseIf InStr(domain(i),"#") Then
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_
"Fragment: " & fragment
Else
path = path & domain(i)
End If
Next
parse_url = parse_url & vbCrLf & "Path: " & path
End If
ElseIf InStr(url,":") Then
scheme = Mid(url,1,InStr(1,url,":")-1)
path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":"))
parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path
Else
parse_url = parse_url & vbcrlf & "Invalid!!!"
End If
End Function
WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
|
Transform the following C# implementation into VB, maintaining the same output and logic. | using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo:
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql:
ParseUrl("ftp:
ParseUrl("http:
ParseUrl("ldap:
ParseUrl("mailto:John.Doe@example.com");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet:
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
| Function parse_url(url)
parse_url = "URL: " & url
If InStr(url,"//") Then
scheme = Split(url,"//")
parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1)
domain = Split(scheme(1),"/")
If InStr(domain(0),"@") Then
cred = Split(domain(0),"@")
If InStr(cred(0),".") Then
username = Mid(cred(0),1,InStr(1,cred(0),".")-1)
password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),"."))
ElseIf InStr(cred(0),":") Then
username = Mid(cred(0),1,InStr(1,cred(0),":")-1)
password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":"))
End If
parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_
"Password: " & password
If InStr(cred(1),":") Then
host = Mid(cred(1),1,InStr(1,cred(1),":")-1)
port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & cred(1)
End If
ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then
host = Mid(domain(0),1,InStr(1,domain(0),":")-1)
port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then
host = Mid(domain(0),1,InStr(1,domain(0),"]"))
port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & domain(0)
End If
If UBound(domain) > 0 Then
For i = 1 To UBound(domain)
If i < UBound(domain) Then
path = path & domain(i) & "/"
ElseIf InStr(domain(i),"?") Then
path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1)
If InStr(domain(i),"#") Then
query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1)
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment
Else
query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?"))
path = path & vbcrlf & "Query: " & query
End If
ElseIf InStr(domain(i),"#") Then
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_
"Fragment: " & fragment
Else
path = path & domain(i)
End If
Next
parse_url = parse_url & vbCrLf & "Path: " & path
End If
ElseIf InStr(url,":") Then
scheme = Mid(url,1,InStr(1,url,":")-1)
path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":"))
parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path
Else
parse_url = parse_url & vbcrlf & "Invalid!!!"
End If
End Function
WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
|
Ensure the translated VB code behaves exactly like the original C# snippet. | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
const string HEX = "0123456789ABCDEF";
if (@base < 1 || @base > HEX.Length) {
throw new ArgumentException("Base is out of range.");
}
BigInteger bi = BigInteger.Zero;
foreach (char c in value) {
char c2 = Char.ToUpper(c);
int idx = HEX.IndexOf(c2);
if (idx == -1 || idx >= @base) {
throw new ArgumentOutOfRangeException("Illegal character encountered.");
}
bi = bi * @base + idx;
}
return bi;
}
static string ConvertToBase58(string hash, int @base = 16) {
BigInteger x;
if (@base == 16 && hash.Substring(0, 2) == "0x") {
x = ToBigInteger(hash.Substring(2), @base);
} else {
x = ToBigInteger(hash, @base);
}
StringBuilder sb = new StringBuilder();
while (x > 0) {
BigInteger r = x % 58;
sb.Append(ALPHABET[(int)r]);
x = x / 58;
}
char[] ca = sb.ToString().ToCharArray();
Array.Reverse(ca);
return new string(ca);
}
static void Main(string[] args) {
string s = "25420294593250030202636073700053352635053786165627414518";
string b = ConvertToBase58(s, 10);
Console.WriteLine("{0} -> {1}", s, b);
List<string> hashes = new List<string>() {
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
};
foreach (string hash in hashes) {
string b58 = ConvertToBase58(hash);
Console.WriteLine("{0,-56} -> {1}", hash, b58);
}
}
}
}
| Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Length Then
Throw New ArgumentException("Base is out of range.")
End If
Dim bi = BigInteger.Zero
For Each c In value
Dim c2 = Char.ToUpper(c)
Dim idx = HEX.IndexOf(c2)
If idx = -1 OrElse idx >= base Then
Throw New ArgumentException("Illegal character encountered.")
End If
bi = bi * base + idx
Next
Return bi
End Function
Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String
Dim x As BigInteger
If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then
x = ToBigInteger(hash.Substring(2), base)
Else
x = ToBigInteger(hash, base)
End If
Dim sb As New StringBuilder
While x > 0
Dim r = x Mod 58
sb.Append(ALPHABET(r))
x = x / 58
End While
Dim ca = sb.ToString().ToCharArray()
Array.Reverse(ca)
Return New String(ca)
End Function
Sub Main()
Dim s = "25420294593250030202636073700053352635053786165627414518"
Dim b = ConvertToBase58(s, 10)
Console.WriteLine("{0} -> {1}", s, b)
Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"}
For Each hash In hashes
Dim b58 = ConvertToBase58(hash)
Console.WriteLine("{0,-56} -> {1}", hash, b58)
Next
End Sub
End Module
|
Can you help me rewrite this code in VB instead of C#, keeping it the same logically? | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
const string HEX = "0123456789ABCDEF";
if (@base < 1 || @base > HEX.Length) {
throw new ArgumentException("Base is out of range.");
}
BigInteger bi = BigInteger.Zero;
foreach (char c in value) {
char c2 = Char.ToUpper(c);
int idx = HEX.IndexOf(c2);
if (idx == -1 || idx >= @base) {
throw new ArgumentOutOfRangeException("Illegal character encountered.");
}
bi = bi * @base + idx;
}
return bi;
}
static string ConvertToBase58(string hash, int @base = 16) {
BigInteger x;
if (@base == 16 && hash.Substring(0, 2) == "0x") {
x = ToBigInteger(hash.Substring(2), @base);
} else {
x = ToBigInteger(hash, @base);
}
StringBuilder sb = new StringBuilder();
while (x > 0) {
BigInteger r = x % 58;
sb.Append(ALPHABET[(int)r]);
x = x / 58;
}
char[] ca = sb.ToString().ToCharArray();
Array.Reverse(ca);
return new string(ca);
}
static void Main(string[] args) {
string s = "25420294593250030202636073700053352635053786165627414518";
string b = ConvertToBase58(s, 10);
Console.WriteLine("{0} -> {1}", s, b);
List<string> hashes = new List<string>() {
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
};
foreach (string hash in hashes) {
string b58 = ConvertToBase58(hash);
Console.WriteLine("{0,-56} -> {1}", hash, b58);
}
}
}
}
| Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Length Then
Throw New ArgumentException("Base is out of range.")
End If
Dim bi = BigInteger.Zero
For Each c In value
Dim c2 = Char.ToUpper(c)
Dim idx = HEX.IndexOf(c2)
If idx = -1 OrElse idx >= base Then
Throw New ArgumentException("Illegal character encountered.")
End If
bi = bi * base + idx
Next
Return bi
End Function
Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String
Dim x As BigInteger
If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then
x = ToBigInteger(hash.Substring(2), base)
Else
x = ToBigInteger(hash, base)
End If
Dim sb As New StringBuilder
While x > 0
Dim r = x Mod 58
sb.Append(ALPHABET(r))
x = x / 58
End While
Dim ca = sb.ToString().ToCharArray()
Array.Reverse(ca)
Return New String(ca)
End Function
Sub Main()
Dim s = "25420294593250030202636073700053352635053786165627414518"
Dim b = ConvertToBase58(s, 10)
Console.WriteLine("{0} -> {1}", s, b)
Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"}
For Each hash In hashes
Dim b58 = ConvertToBase58(hash)
Console.WriteLine("{0,-56} -> {1}", hash, b58)
Next
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in VB. | using System;
using System.IO;
using System.Security.Cryptography;
namespace DES {
class Program {
static string ByteArrayToString(byte[] ba) {
return BitConverter.ToString(ba).Replace("-", "");
}
static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {
byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);
CryptoStreamMode mode = CryptoStreamMode.Write;
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(messageBytes, 0, messageBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] encryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
return encryptedMessageBytes;
}
static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {
byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);
CryptoStreamMode mode = CryptoStreamMode.Write;
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] decryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);
return decryptedMessageBytes;
}
static void Main(string[] args) {
byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };
byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };
byte[] encStr = Encrypt(plainBytes, keyBytes);
Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr));
byte[] decBytes = Decrypt(encStr, keyBytes);
Console.WriteLine("Decoded: {0}", ByteArrayToString(decBytes));
}
}
}
| Imports System.IO
Imports System.Security.Cryptography
Module Module1
Function ByteArrayToString(ba As Byte()) As String
Return BitConverter.ToString(ba).Replace("-", "")
End Function
Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()
Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
Dim provider As New DESCryptoServiceProvider
Dim transform = provider.CreateEncryptor(passwordBytes, iv)
Dim mode = CryptoStreamMode.Write
Dim memStream As New MemoryStream
Dim cryptoStream As New CryptoStream(memStream, transform, mode)
cryptoStream.Write(messageBytes, 0, messageBytes.Length)
cryptoStream.FlushFinalBlock()
Dim encryptedMessageBytes(memStream.Length - 1) As Byte
memStream.Position = 0
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
Return encryptedMessageBytes
End Function
Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()
Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
Dim provider As New DESCryptoServiceProvider
Dim transform = provider.CreateDecryptor(passwordBytes, iv)
Dim mode = CryptoStreamMode.Write
Dim memStream As New MemoryStream
Dim cryptoStream As New CryptoStream(memStream, transform, mode)
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
cryptoStream.FlushFinalBlock()
Dim decryptedMessageBytes(memStream.Length - 1) As Byte
memStream.Position = 0
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)
Return decryptedMessageBytes
End Function
Sub Main()
Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}
Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}
Dim encStr = Encrypt(plainBytes, keyBytes)
Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr))
Dim decStr = Decrypt(encStr, keyBytes)
Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr))
End Sub
End Module
|
Produce a language-to-language conversion: from C# to VB, same semantics. | static string[] inputs = {
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"\"-in Aus$+1411.8millions\"",
"===US$0017440 millions=== (in 2000 dollars)"
};
void Main()
{
inputs.Select(s => Commatize(s, 0, 3, ","))
.ToList()
.ForEach(Console.WriteLine);
}
string Commatize(string text, int startPosition, int interval, string separator)
{
var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*");
var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();
return string.Join("", x);
}
string Commatize(Match match, int interval, string separator, string original)
{
if (match.Length <= interval)
return original.Substring(match.Index,
match.Index == original.Length ? 0 : Math.Max(match.Length, 1));
return string.Join(separator, match.Value.Split(interval));
}
public static class Extension
{
public static string[] Split(this string source, int interval)
{
return SplitImpl(source, interval).ToArray();
}
static IEnumerable<string>SplitImpl(string source, int interval)
{
for (int i = 1; i < source.Length; i++)
{
if (i % interval != 0) continue;
yield return source.Substring(i - interval, interval);
}
}
}
| Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3)
Dim l As Integer: l = Len(s)
For i = start To l
If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then
For j = i + 1 To l + 1
If j > l Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
Else
If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
End If
End If
Next j
Exit For
End If
Next i
Debug.Print s
End Sub
Public Sub main()
commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5
commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."
commatize """-in Aus$+1411.8millions"""
commatize "===US$0017440 millions=== (in 2000 dollars)"
commatize "123.e8000 is pretty big."
commatize "The land area of the earth is 57268900(29% of the surface) square miles."
commatize "Ain
commatize "James was never known as 0000000007"
commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe."
commatize " $-140000±100 millions."
commatize "6/9/1946 was a good year for some."
End Sub
|
Please provide an equivalent version of this C# code in VB. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace AruthmeticCoding {
using Freq = Dictionary<char, long>;
using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;
class Program {
static Freq CumulativeFreq(Freq freq) {
long total = 0;
Freq cf = new Freq();
for (int i = 0; i < 256; i++) {
char c = (char)i;
if (freq.ContainsKey(c)) {
long v = freq[c];
cf[c] = total;
total += v;
}
}
return cf;
}
static Triple ArithmeticCoding(string str, long radix) {
Freq freq = new Freq();
foreach (char c in str) {
if (freq.ContainsKey(c)) {
freq[c] += 1;
} else {
freq[c] = 1;
}
}
Freq cf = CumulativeFreq(freq);
BigInteger @base = str.Length;
BigInteger lower = 0;
BigInteger pf = 1;
foreach (char c in str) {
BigInteger x = cf[c];
lower = lower * @base + x * pf;
pf = pf * freq[c];
}
BigInteger upper = lower + pf;
int powr = 0;
BigInteger bigRadix = radix;
while (true) {
pf = pf / bigRadix;
if (pf == 0) break;
powr++;
}
BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));
return new Triple(diff, powr, freq);
}
static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {
BigInteger powr = radix;
BigInteger enc = num * BigInteger.Pow(powr, pwr);
long @base = freq.Values.Sum();
Freq cf = CumulativeFreq(freq);
Dictionary<long, char> dict = new Dictionary<long, char>();
foreach (char key in cf.Keys) {
long value = cf[key];
dict[value] = key;
}
long lchar = -1;
for (long i = 0; i < @base; i++) {
if (dict.ContainsKey(i)) {
lchar = dict[i];
} else if (lchar != -1) {
dict[i] = (char)lchar;
}
}
StringBuilder decoded = new StringBuilder((int)@base);
BigInteger bigBase = @base;
for (long i = @base - 1; i >= 0; --i) {
BigInteger pow = BigInteger.Pow(bigBase, (int)i);
BigInteger div = enc / pow;
char c = dict[(long)div];
BigInteger fv = freq[c];
BigInteger cv = cf[c];
BigInteger diff = enc - pow * cv;
enc = diff / fv;
decoded.Append(c);
}
return decoded.ToString();
}
static void Main(string[] args) {
long radix = 10;
string[] strings = { "DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT" };
foreach (string str in strings) {
Triple encoded = ArithmeticCoding(str, radix);
string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);
Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", str, encoded.Item1, radix, encoded.Item2);
if (str != dec) {
throw new Exception("\tHowever that is incorrect!");
}
}
}
}
}
| Imports System.Numerics
Imports System.Text
Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long)
Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))
Module Module1
Function CumulativeFreq(freq As Freq) As Freq
Dim total As Long = 0
Dim cf As New Freq
For i = 0 To 255
Dim c = Chr(i)
If freq.ContainsKey(c) Then
Dim v = freq(c)
cf(c) = total
total += v
End If
Next
Return cf
End Function
Function ArithmeticCoding(str As String, radix As Long) As Triple
Dim freq As New Freq
For Each c In str
If freq.ContainsKey(c) Then
freq(c) += 1
Else
freq(c) = 1
End If
Next
Dim cf = CumulativeFreq(freq)
Dim base As BigInteger = str.Length
Dim lower As BigInteger = 0
Dim pf As BigInteger = 1
For Each c In str
Dim x = cf(c)
lower = lower * base + x * pf
pf = pf * freq(c)
Next
Dim upper = lower + pf
Dim powr = 0
Dim bigRadix As BigInteger = radix
While True
pf = pf / bigRadix
If pf = 0 Then
Exit While
End If
powr = powr + 1
End While
Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))
Return New Triple(diff, powr, freq)
End Function
Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String
Dim powr As BigInteger = radix
Dim enc = num * BigInteger.Pow(powr, pwr)
Dim base = freq.Values.Sum()
Dim cf = CumulativeFreq(freq)
Dim dict As New Dictionary(Of Long, Char)
For Each key In cf.Keys
Dim value = cf(key)
dict(value) = key
Next
Dim lchar As Long = -1
For i As Long = 0 To base - 1
If dict.ContainsKey(i) Then
lchar = AscW(dict(i))
Else
dict(i) = ChrW(lchar)
End If
Next
Dim decoded As New StringBuilder
Dim bigBase As BigInteger = base
For i As Long = base - 1 To 0 Step -1
Dim pow = BigInteger.Pow(bigBase, i)
Dim div = enc / pow
Dim c = dict(div)
Dim fv = freq(c)
Dim cv = cf(c)
Dim diff = enc - pow * cv
enc = diff / fv
decoded.Append(c)
Next
Return decoded.ToString()
End Function
Sub Main()
Dim radix As Long = 10
Dim strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"}
For Each St In strings
Dim encoded = ArithmeticCoding(St, radix)
Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)
Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", St, encoded.Item1, radix, encoded.Item2)
If St <> dec Then
Throw New Exception(vbTab + "However that is incorrect!")
End If
Next
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from C# to VB. | using System;
using System.Collections.Generic;
class Node
{
public enum Colors
{
Black, White, Gray
}
public Colors color { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
color = Colors.White;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>> Adj { get; }
public void Kosaraju()
{
var L = new HashSet<Node>();
Action<Node> Visit = null;
Visit = (u) =>
{
if (u.color == Node.Colors.White)
{
u.color = Node.Colors.Gray;
foreach (var v in Adj[u])
Visit(v);
L.Add(u);
}
};
Action<Node, Node> Assign = null;
Assign = (u, root) =>
{
if (u.color != Node.Colors.Black)
{
if (u == root)
Console.Write("SCC: ");
Console.Write(u.N + " ");
u.color = Node.Colors.Black;
foreach (var v in Adj[u])
Assign(v, root);
if (u == root)
Console.WriteLine();
}
};
foreach (var u in V)
Visit(u);
foreach (var u in L)
Assign(u, u);
}
}
| Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Integer))
Next
Dim visit As Action(Of Integer) = Sub(u As Integer)
If Not vis(u) Then
vis(u) = True
For Each v In g(u)
visit(v)
t(v).Add(u)
Next
x -= 1
l(x) = u
End If
End Sub
For i = 1 To size
visit(i - 1)
Next
Dim c(size - 1) As Integer
Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)
If vis(u) Then
vis(u) = False
c(u) = root
For Each v In t(u)
assign(v, root)
Next
End If
End Sub
For Each u In l
assign(u, u)
Next
Return c.ToList
End Function
Sub Main()
Dim g = New List(Of List(Of Integer)) From {
New List(Of Integer) From {1},
New List(Of Integer) From {2},
New List(Of Integer) From {0},
New List(Of Integer) From {1, 2, 4},
New List(Of Integer) From {3, 5},
New List(Of Integer) From {2, 6},
New List(Of Integer) From {5},
New List(Of Integer) From {4, 6, 7}
}
Dim output = Kosaraju(g)
Console.WriteLine("[{0}]", String.Join(", ", output))
End Sub
End Module
|
Write the same algorithm in VB as shown in this C# implementation. | using System;
using System.Collections.Generic;
using System.Linq;
public static class TwelveStatements
{
public static void Main() {
Func<Statements, bool>[] checks = {
st => st[1],
st => st[2] == (7.To(12).Count(i => st[i]) == 3),
st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),
st => st[4] == st[5].Implies(st[6] && st[7]),
st => st[5] == (!st[2] && !st[3] && !st[4]),
st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),
st => st[7] == (st[2] != st[3]),
st => st[8] == st[7].Implies(st[5] && st[6]),
st => st[9] == (1.To(6).Count(i => st[i]) == 3),
st => st[10] == (st[11] && st[12]),
st => st[11] == (7.To(9).Count(i => st[i]) == 1),
st => st[12] == (1.To(11).Count(i => st[i]) == 4)
};
for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {
int count = 0;
int falseIndex = 0;
for (int i = 0; i < checks.Length; i++) {
if (checks[i](statements)) count++;
else falseIndex = i;
}
if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}");
else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}");
else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}");
}
}
struct Statements
{
public Statements(int value) : this() { Value = value; }
public int Value { get; }
public bool this[int index] => (Value & (1 << index - 1)) != 0;
public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);
public override string ToString() {
Statements copy = this;
return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F");
}
}
static bool Implies(this bool x, bool y) => !x || y;
static IEnumerable<int> To(this int start, int end, int by = 1) {
while (start <= end) {
yield return start;
start += by;
}
}
}
| Public s As String
Public t As Integer
Function s1()
s1 = Len(s) = 12
End Function
Function s2()
t = 0
For i = 7 To 12
t = t - (Mid(s, i, 1) = "1")
Next i
s2 = t = 3
End Function
Function s3()
t = 0
For i = 2 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s3 = t = 2
End Function
Function s4()
s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1"))
End Function
Function s5()
s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0"
End Function
Function s6()
t = 0
For i = 1 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s6 = t = 4
End Function
Function s7()
s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)
End Function
Function s8()
s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1")
End Function
Function s9()
t = 0
For i = 1 To 6
t = t - (Mid(s, i, 1) = "1")
Next i
s9 = t = 3
End Function
Function s10()
s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1"
End Function
Function s11()
t = 0
For i = 7 To 9
t = t - (Mid(s, i, 1) = "1")
Next i
s11 = t = 1
End Function
Function s12()
t = 0
For i = 1 To 11
t = t - (Mid(s, i, 1) = "1")
Next i
s12 = t = 4
End Function
Public Sub twelve_statements()
For i = 0 To 2 ^ 12 - 1
s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _
& Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)
For b = 1 To 12
Select Case b
Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For
Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For
Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For
Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For
Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For
Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For
Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For
Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For
Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For
Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For
Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For
Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For
End Select
If b = 12 Then Debug.Print s
Next
Next
End Sub
|
Change the following Go code into Python without altering its purpose. | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
| import sys
print(sys.getrecursionlimit())
|
Change the programming language of this snippet from Go to Python without modifying what it does. | package main
import "fmt"
func mod(n, m int) int {
return ((n % m) + m) % m
}
func isPrime(n int) bool {
if n < 2 { return false }
if n % 2 == 0 { return n == 2 }
if n % 3 == 0 { return n == 3 }
d := 5
for d * d <= n {
if n % d == 0 { return false }
d += 2
if n % d == 0 { return false }
d += 4
}
return true
}
func carmichael(p1 int) {
for h3 := 2; h3 < p1; h3++ {
for d := 1; d < h3 + p1; d++ {
if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {
p2 := 1 + (p1 - 1) * (h3 + p1) / d
if !isPrime(p2) { continue }
p3 := 1 + p1 * p2 / h3
if !isPrime(p3) { continue }
if p2 * p3 % (p1 - 1) != 1 { continue }
c := p1 * p2 * p3
fmt.Printf("%2d %4d %5d %d\n", p1, p2, p3, c)
}
}
}
}
func main() {
fmt.Println("The following are Carmichael munbers for p1 <= 61:\n")
fmt.Println("p1 p2 p3 product")
fmt.Println("== == == =======")
for p1 := 2; p1 <= 61; p1++ {
if isPrime(p1) { carmichael(p1) }
}
}
| class Isprime():
multiples = {2}
primes = [2]
nmax = 2
def __init__(self, nmax):
if nmax > self.nmax:
self.check(nmax)
def check(self, n):
if type(n) == float:
if not n.is_integer(): return False
n = int(n)
multiples = self.multiples
if n <= self.nmax:
return n not in multiples
else:
primes, nmax = self.primes, self.nmax
newmax = max(nmax*2, n)
for p in primes:
multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))
for i in range(nmax+1, newmax+1):
if i not in multiples:
primes.append(i)
multiples.update(range(i*2, newmax+1, i))
self.nmax = newmax
return n not in multiples
__call__ = check
def carmichael(p1):
ans = []
if isprime(p1):
for h3 in range(2, p1):
g = h3 + p1
for d in range(1, g):
if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:
p2 = 1 + ((p1 - 1)* g // d)
if isprime(p2):
p3 = 1 + (p1 * p2 // h3)
if isprime(p3):
if (p2 * p3) % (p1 - 1) == 1:
ans += [tuple(sorted((p1, p2, p3)))]
return ans
isprime = Isprime(2)
ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))
print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
|
Generate a Python translation of this Go snippet without changing its computational steps. | package main
import (
"code.google.com/p/x-go-binding/ui/x11"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"os"
"time"
)
var randcol = genrandcol()
func genrandcol() <-chan color.Color {
c := make(chan color.Color)
go func() {
for {
select {
case c <- image.Black:
case c <- image.White:
}
}
}()
return c
}
func gennoise(screen draw.Image) {
for y := 0; y < 240; y++ {
for x := 0; x < 320; x++ {
screen.Set(x, y, <-randcol)
}
}
}
func fps() chan<- bool {
up := make(chan bool)
go func() {
var frames int64
var lasttime time.Time
var totaltime time.Duration
for {
<-up
frames++
now := time.Now()
totaltime += now.Sub(lasttime)
if totaltime > time.Second {
fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
frames = 0
totaltime = 0
}
lasttime = now
}
}()
return up
}
func main() {
win, err := x11.NewWindow()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer win.Close()
go func() {
upfps := fps()
screen := win.Screen()
for {
gennoise(screen)
win.FlushImage()
upfps <- true
}
}()
for _ = range win.EventChan() {
}
}
| black = color(0)
white = color(255)
def setup():
size(320, 240)
def draw():
loadPixels()
for i in range(len(pixels)):
if random(1) < 0.5:
pixels[i] = black
else:
pixels[i] = white
updatePixels()
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frameRate, 5, 15)
|
Keep all operations the same but rewrite the snippet in Python. | package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
|
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
Produce a language-to-language conversion: from Go to Python, same semantics. | package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
|
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
Port the provided Go code into Python while preserving the original functionality. | package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
func isPerfect(n int64) bool {
switch n {
case 6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128:
return true
}
return false
}
func main() {
for n := int64(1); ; n++ {
if isPerfect(n) != computePerfect(n) {
panic("bug")
}
if n%1e3 == 0 {
fmt.Println("tested", n)
}
}
}
| def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
|
Convert this Go snippet to Python and keep its semantics consistent. | package main
import (
"fmt"
"math"
"math/cmplx"
)
type matrix struct {
ele []complex128
cols int
}
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
}
| def conjugate_transpose(m):
return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))
def mmul( ma, mb):
return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)
def mi(size):
'Complex Identity matrix'
sz = range(size)
m = [[0 + 0j for i in sz] for j in sz]
for i in range(size):
m[i][i] = 1 + 0j
return tuple(tuple(row) for row in m)
def __allsame(vector):
first, rest = vector[0], vector[1:]
return all(i == first for i in rest)
def __allnearsame(vector, eps=1e-14):
first, rest = vector[0], vector[1:]
return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps
for i in rest)
def isequal(matrices, eps=1e-14):
'Check any number of matrices for equality within eps'
x = [len(m) for m in matrices]
if not __allsame(x): return False
y = [len(m[0]) for m in matrices]
if not __allsame(y): return False
for s in range(x[0]):
for t in range(y[0]):
if not __allnearsame([m[s][t] for m in matrices], eps): return False
return True
def ishermitian(m, ct):
return isequal([m, ct])
def isnormal(m, ct):
return isequal([mmul(m, ct), mmul(ct, m)])
def isunitary(m, ct):
mct, ctm = mmul(m, ct), mmul(ct, m)
mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])
ident = mi(mctx)
return isequal([mct, ctm, ident])
def printm(comment, m):
print(comment)
fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]
width = max(max(len(f) for f in row) for row in fields)
lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)
print('\n'.join(lines))
if __name__ == '__main__':
for matrix in [
((( 3.000+0.000j), (+2.000+1.000j)),
(( 2.000-1.000j), (+1.000+0.000j))),
((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)),
(( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)),
(( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),
((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)),
(( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)),
(( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:
printm('\nMatrix:', matrix)
ct = conjugate_transpose(matrix)
printm('Its conjugate transpose:', ct)
print('Hermitian? %s.' % ishermitian(matrix, ct))
print('Normal? %s.' % isnormal(matrix, ct))
print('Unitary? %s.' % isunitary(matrix, ct))
|
Preserve the algorithm and functionality while converting the code from Go to Python. | package main
import (
"fmt"
"math"
"math/cmplx"
)
type matrix struct {
ele []complex128
cols int
}
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
}
| def conjugate_transpose(m):
return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))
def mmul( ma, mb):
return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)
def mi(size):
'Complex Identity matrix'
sz = range(size)
m = [[0 + 0j for i in sz] for j in sz]
for i in range(size):
m[i][i] = 1 + 0j
return tuple(tuple(row) for row in m)
def __allsame(vector):
first, rest = vector[0], vector[1:]
return all(i == first for i in rest)
def __allnearsame(vector, eps=1e-14):
first, rest = vector[0], vector[1:]
return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps
for i in rest)
def isequal(matrices, eps=1e-14):
'Check any number of matrices for equality within eps'
x = [len(m) for m in matrices]
if not __allsame(x): return False
y = [len(m[0]) for m in matrices]
if not __allsame(y): return False
for s in range(x[0]):
for t in range(y[0]):
if not __allnearsame([m[s][t] for m in matrices], eps): return False
return True
def ishermitian(m, ct):
return isequal([m, ct])
def isnormal(m, ct):
return isequal([mmul(m, ct), mmul(ct, m)])
def isunitary(m, ct):
mct, ctm = mmul(m, ct), mmul(ct, m)
mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])
ident = mi(mctx)
return isequal([mct, ctm, ident])
def printm(comment, m):
print(comment)
fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]
width = max(max(len(f) for f in row) for row in fields)
lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)
print('\n'.join(lines))
if __name__ == '__main__':
for matrix in [
((( 3.000+0.000j), (+2.000+1.000j)),
(( 2.000-1.000j), (+1.000+0.000j))),
((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)),
(( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)),
(( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),
((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)),
(( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)),
(( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:
printm('\nMatrix:', matrix)
ct = conjugate_transpose(matrix)
printm('Its conjugate transpose:', ct)
print('Hermitian? %s.' % ishermitian(matrix, ct))
print('Normal? %s.' % isnormal(matrix, ct))
print('Unitary? %s.' % isunitary(matrix, ct))
|
Translate this program into Python but keep the logic exactly as in Go. | package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
|
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
def jacobsthal_oblong(n):
return jacobsthal(n)*jacobsthal(n+1)
if __name__ == '__main__':
print("First 30 Jacobsthal numbers:")
for j in range(0, 30):
print(jacobsthal(j), end=" ")
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
for j in range(0, 30):
print(jacobsthal_lucas(j), end = '\t')
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
for j in range(0, 20):
print(jacobsthal_oblong(j), end=" ")
print("\n\nFirst 10 Jacobsthal primes: ")
for j in range(3, 33):
if isPrime(jacobsthal(j)):
print(jacobsthal(j))
|
Write the same code in Python as shown below in Go. | package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
|
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
def jacobsthal_oblong(n):
return jacobsthal(n)*jacobsthal(n+1)
if __name__ == '__main__':
print("First 30 Jacobsthal numbers:")
for j in range(0, 30):
print(jacobsthal(j), end=" ")
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
for j in range(0, 30):
print(jacobsthal_lucas(j), end = '\t')
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
for j in range(0, 20):
print(jacobsthal_oblong(j), end=" ")
print("\n\nFirst 10 Jacobsthal primes: ")
for j in range(3, 33):
if isPrime(jacobsthal(j)):
print(jacobsthal(j))
|
Generate a Python translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
|
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
def jacobsthal_oblong(n):
return jacobsthal(n)*jacobsthal(n+1)
if __name__ == '__main__':
print("First 30 Jacobsthal numbers:")
for j in range(0, 30):
print(jacobsthal(j), end=" ")
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
for j in range(0, 30):
print(jacobsthal_lucas(j), end = '\t')
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
for j in range(0, 20):
print(jacobsthal_oblong(j), end=" ")
print("\n\nFirst 10 Jacobsthal primes: ")
for j in range(3, 33):
if isPrime(jacobsthal(j)):
print(jacobsthal(j))
|
Keep all operations the same but rewrite the snippet in Python. | package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, aMax)
for pole, space := 0, all; pole < aMax; pole++ {
abacus[pole] = space[:len(a)]
space = space[len(a):]
}
var wg sync.WaitGroup
wg.Add(len(a))
for row, n := range a {
go func(row, n int) {
for pole := 0; pole < n; pole++ {
abacus[pole][row] = bead
}
wg.Done()
}(row, n)
}
wg.Wait()
wg.Add(aMax)
for _, pole := range abacus {
go func(pole []byte) {
top := 0
for row, space := range pole {
if space == bead {
pole[row] = 0
pole[top] = bead
top++
}
}
wg.Done()
}(pole)
}
wg.Wait()
for row := range a {
x := 0
for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
x++
}
a[len(a)-1-row] = x
}
}
|
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.