Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a functionally identical C# code for the snippet given in VB.
Module Program Sub Main() Console.WriteLine("Enter two space-delimited integers:") Dim input = Console.ReadLine().Split() Dim rows = Integer.Parse(input(0)) Dim cols = Integer.Parse(input(1)) Dim arr(rows - 1, cols - 1) As Integer arr(0, 0) = 2 Console.WriteLine(arr(0, 0)) End Sub End Module
class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console.ReadLine(); int[,] myArray=new int[(int)s[0],(int)s[2]]; myArray[0, 0] = 2; Console.WriteLine(myArray[0, 0]); Console.ReadLine(); } }
Produce a functionally identical C# code for the snippet given in VB.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Translate this program into C# but keep the logic exactly as in VB.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Transform the following VB implementation into C#, maintaining the same output and logic.
Option Explicit Sub Main() Const VECSIZE As Long = 3350 Const BUFSIZE As Long = 201 Dim buffer(1 To BUFSIZE) As Long Dim vect(1 To VECSIZE) As Long Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long For n = 1 To VECSIZE vect(n) = 2 Next n For n = 1 To BUFSIZE karray = 0 For l = VECSIZE To 1 Step -1 num = 100000 * vect(l) + karray * l karray = num \ (2 * l - 1) vect(l) = num - karray * (2 * l - 1) Next l k = karray \ 100000 buffer(n) = more + k more = karray - k * 100000 Next n Debug.Print CStr(buffer(1)); Debug.Print "." l = 0 For n = 2 To BUFSIZE Debug.Print Format$(buffer(n), "00000"); l = l + 1 If l = 10 Then l = 0 Debug.Print End If Next n End Sub
using System; using System.Numerics; namespace PiCalc { internal class Program { private readonly BigInteger FOUR = new BigInteger(4); private readonly BigInteger SEVEN = new BigInteger(7); private readonly BigInteger TEN = new BigInteger(10); private readonly BigInteger THREE = new BigInteger(3); private readonly BigInteger TWO = new BigInteger(2); private BigInteger k = BigInteger.One; private BigInteger l = new BigInteger(3); private BigInteger n = new BigInteger(3); private BigInteger q = BigInteger.One; private BigInteger r = BigInteger.Zero; private BigInteger t = BigInteger.One; public void CalcPiDigits() { BigInteger nn, nr; bool first = true; while (true) { if ((FOUR*q + r - t).CompareTo(n*t) == -1) { Console.Write(n); if (first) { Console.Write("."); first = false; } nr = TEN*(r - (n*t)); n = TEN*(THREE*q + r)/t - (TEN*n); q *= TEN; r = nr; } else { nr = (TWO*q + r)*l; nn = (q*(SEVEN*k) + TWO + r*l)/(t*l); q *= k; t *= l; l += TWO; k += BigInteger.One; n = nn; r = nr; } } } private static void Main(string[] args) { new Program().CalcPiDigits(); } } }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
using System; static class YCombinator<T, TResult> { private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r); public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x))); } static class Program { static void Main() { var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1)); var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2)); Console.WriteLine(fac(10)); Console.WriteLine(fib(10)); } }
Produce a language-to-language conversion: from VB to C#, same semantics.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
Convert this VB snippet to C# and keep its semantics consistent.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
Produce a functionally identical C# code for the snippet given in VB.
For i = 1 To 10 Console.Write(i) If i Mod 5 = 0 Then Console.WriteLine() Else Console.Write(", ") End If Next
using System; class Program { static void Main(string[] args) { for (int i = 1; i <= 10; i++) { Console.Write(i); if (i % 5 == 0) { Console.WriteLine(); continue; } Console.Write(", "); } } }
Generate an equivalent C# version of this VB code.
For i = 1 To 10 Console.Write(i) If i Mod 5 = 0 Then Console.WriteLine() Else Console.Write(", ") End If Next
using System; class Program { static void Main(string[] args) { for (int i = 1; i <= 10; i++) { Console.Write(i); if (i % 5 == 0) { Console.WriteLine(); continue; } Console.Write(", "); } } }
Write the same algorithm in C# as shown in this VB implementation.
Option Explicit Private Type Choice Number As Integer Name As String End Type Private MaxNumber As Integer Sub Main() Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$ MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1) For i = 1 To 3 U(i) = UserChoice Next For i = 1 To MaxNumber t = vbNullString For j = 1 To 3 If i Mod U(j).Number = 0 Then t = t & U(j).Name Next Debug.Print IIf(t = vbNullString, i, t) Next i End Sub Private Function UserChoice() As Choice Dim ok As Boolean Do While Not ok UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1) UserChoice.Name = InputBox("Enter the corresponding word : ") If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True Loop End Function
using System; public class GeneralFizzBuzz { public static void Main() { int i; int j; int k; int limit; string iString; string jString; string kString; Console.WriteLine("First integer:"); i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("First string:"); iString = Console.ReadLine(); Console.WriteLine("Second integer:"); j = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Second string:"); jString = Console.ReadLine(); Console.WriteLine("Third integer:"); k = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Third string:"); kString = Console.ReadLine(); Console.WriteLine("Limit (inclusive):"); limit = Convert.ToInt32(Console.ReadLine()); for(int n = 1; n<= limit; n++) { bool flag = true; if(n%i == 0) { Console.Write(iString); flag = false; } if(n%j == 0) { Console.Write(jString); flag = false; } if(n%k == 0) { Console.Write(kString); flag = false; } if(flag) Console.Write(n); Console.WriteLine(); } } }
Convert this VB block to C#, preserving its control flow and logic.
Module Module1 Function ToVlq(v As ULong) As ULong Dim array(8) As Byte Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray buffer.CopyTo(array, 0) Return BitConverter.ToUInt64(array, 0) End Function Function FromVlq(v As ULong) As ULong Dim collection = BitConverter.GetBytes(v).Reverse() Return FromVlqCollection(collection) End Function Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte) If v > Math.Pow(2, 56) Then Throw New OverflowException("Integer exceeds max value.") End If Dim index = 7 Dim significantBitReached = False Dim mask = &H7FUL << (index * 7) While index >= 0 Dim buffer = mask And v If buffer > 0 OrElse significantBitReached Then significantBitReached = True buffer >>= index * 7 If index > 0 Then buffer = buffer Or &H80 End If Yield buffer End If mask >>= 7 index -= 1 End While End Function Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong Dim v = 0UL Dim significantBitReached = False Using enumerator = vlq.GetEnumerator Dim index = 0 While enumerator.MoveNext Dim buffer = enumerator.Current If buffer > 0 OrElse significantBitReached Then significantBitReached = True v <<= 7 v = v Or (buffer And &H7FUL) End If index += 1 If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then Exit While End If End While End Using Return v End Function Sub Main() Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF} For Each original In values Console.WriteLine("Original: 0x{0:X}", original) REM collection Dim seq = ToVlqCollection(original) Console.WriteLine("Sequence: 0x{0}", seq.Select(Function(b) b.ToString("X2")).Aggregate(Function(a, b) String.Concat(a, b))) Dim decoded = FromVlqCollection(seq) Console.WriteLine("Decoded: 0x{0:X}", decoded) REM ints Dim encoded = ToVlq(original) Console.WriteLine("Encoded: 0x{0:X}", encoded) decoded = FromVlq(encoded) Console.WriteLine("Decoded: 0x{0:X}", decoded) Console.WriteLine() Next End Sub End Module
namespace Vlq { using System; using System.Collections.Generic; using System.Linq; public static class VarLenQuantity { public static ulong ToVlq(ulong integer) { var array = new byte[8]; var buffer = ToVlqCollection(integer) .SkipWhile(b => b == 0) .Reverse() .ToArray(); Array.Copy(buffer, array, buffer.Length); return BitConverter.ToUInt64(array, 0); } public static ulong FromVlq(ulong integer) { var collection = BitConverter.GetBytes(integer).Reverse(); return FromVlqCollection(collection); } public static IEnumerable<byte> ToVlqCollection(ulong integer) { if (integer > Math.Pow(2, 56)) throw new OverflowException("Integer exceeds max value."); var index = 7; var significantBitReached = false; var mask = 0x7fUL << (index * 7); while (index >= 0) { var buffer = (mask & integer); if (buffer > 0 || significantBitReached) { significantBitReached = true; buffer >>= index * 7; if (index > 0) buffer |= 0x80; yield return (byte)buffer; } mask >>= 7; index--; } } public static ulong FromVlqCollection(IEnumerable<byte> vlq) { ulong integer = 0; var significantBitReached = false; using (var enumerator = vlq.GetEnumerator()) { int index = 0; while (enumerator.MoveNext()) { var buffer = enumerator.Current; if (buffer > 0 || significantBitReached) { significantBitReached = true; integer <<= 7; integer |= (buffer & 0x7fUL); } if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80)) break; } } return integer; } public static void Main() { var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff }; foreach (var original in integers) { Console.WriteLine("Original: 0x{0:X}", original); var seq = ToVlqCollection(original); Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat)); var decoded = FromVlqCollection(seq); Console.WriteLine("Decoded: 0x{0:X}", decoded); var encoded = ToVlq(original); Console.WriteLine("Encoded: 0x{0:X}", encoded); decoded = FromVlq(encoded); Console.WriteLine("Decoded: 0x{0:X}", decoded); Console.WriteLine(); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
Produce a functionally identical C# code for the snippet given in VB.
Sub Main() Const TESTSTRING As String = "alphaBETA" Debug.Print "initial = " _ & TESTSTRING Debug.Print "uppercase = " _ & UCase(TESTSTRING) Debug.Print "lowercase = " _ & LCase(TESTSTRING) Debug.Print "first letter capitalized = " _ & StrConv(TESTSTRING, vbProperCase) Debug.Print "length (in characters) = " _ & CStr(Len(TESTSTRING)) Debug.Print "length (in bytes) = " _ & CStr(LenB(TESTSTRING)) Debug.Print "reversed = " _ & StrReverse(TESTSTRING) Debug.Print "first position of letter A (case-sensitive) = " _ & InStr(1, TESTSTRING, "A", vbBinaryCompare) Debug.Print "first position of letter A (case-insensitive) = " _ & InStr(1, TESTSTRING, "A", vbTextCompare) Debug.Print "concatenated with & TESTSTRING & "123" End Sub
using System; namespace StringCase { class Program { public static void Main() { String input = scope .("alphaBETA"); input.ToUpper(); Console.WriteLine(input); input.ToLower(); Console.WriteLine(input); } } }
Port the provided VB code into C# while preserving the original functionality.
Imports System.Security.Cryptography Imports System.Text Module MD5hash Sub Main(args As String()) Console.WriteLine(GetMD5("Visual Basic .Net")) End Sub Private Function GetMD5(plainText As String) As String Dim hash As String = "" Using hashObject As MD5 = MD5.Create() Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText)) Dim hashBuilder As New StringBuilder For i As Integer = 0 To ptBytes.Length - 1 hashBuilder.Append(ptBytes(i).ToString("X2")) Next hash = hashBuilder.ToString End Using Return hash End Function End Module
using System.Text; using System.Security.Cryptography; byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back"); byte[] hash = MD5.Create().ComputeHash(data); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Imports System.Threading Module Module1 Sub SleepSort(items As IEnumerable(Of Integer)) For Each item In items Task.Factory.StartNew(Sub() Thread.Sleep(1000 * item) Console.WriteLine(item) End Sub) Next End Sub Sub Main() SleepSort({1, 5, 2, 1, 8, 10, 3}) Console.ReadKey() End Sub End Module
using System; using System.Collections.Generic; using System.Linq; using System.Threading; class Program { static void ThreadStart(object item) { Thread.Sleep(1000 * (int)item); Console.WriteLine(item); } static void SleepSort(IEnumerable<int> items) { foreach (var item in items) { new Thread(ThreadStart).Start(item); } } static void Main(string[] arguments) { SleepSort(arguments.Select(int.Parse)); } }
Write a version of this VB function in C# with identical behavior.
Public Sub LoopsNested() Dim a(1 To 10, 1 To 10) As Integer Randomize For i = 1 To 10 For j = 1 To 10 a(i, j) = Int(20 * Rnd) + 1 Next j Next i For i = 1 To 10 For j = 1 To 10 If a(i, j) <> 20 Then Debug.Print a(i, j), Else i = 10 Exit For End If Next j Debug.Print Next i End Sub
using System; class Program { static void Main(string[] args) { int[,] a = new int[10, 10]; Random r = new Random(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { a[i, j] = r.Next(0, 21) + 1; } } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Console.Write(" {0}", a[i, j]); if (a[i, j] == 20) { goto Done; } } Console.WriteLine(); } Done: Console.WriteLine(); } }
Write the same algorithm in C# as shown in this VB implementation.
Option Explicit Sub Main() Dim myArr() As Variant, i As Long myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235)) For i = LBound(myArr) To UBound(myArr) Debug.Print myArr(i) Next End Sub Private Function Remove_Duplicate(Arr As Variant) As Variant() Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long ReDim Temp(UBound(Arr)) For i = LBound(Arr) To UBound(Arr) On Error Resume Next myColl.Add CStr(Arr(i)), CStr(Arr(i)) If Err.Number > 0 Then On Error GoTo 0 Else Temp(cpt) = Arr(i) cpt = cpt + 1 End If Next i ReDim Preserve Temp(cpt - 1) Remove_Duplicate = Temp End Function
int[] nums = { 1, 1, 2, 3, 4, 4 }; List<int> unique = new List<int>(); foreach (int n in nums) if (!unique.Contains(n)) unique.Add(n);
Port the provided VB code into C# while preserving the original functionality.
function looksay( n ) dim i dim accum dim res dim c res = vbnullstring do if n = vbnullstring then exit do accum = 0 c = left( n,1 ) do while left( n, 1 ) = c accum = accum + 1 n = mid(n,2) loop if accum > 0 then res = res & accum & c end if loop looksay = res end function
using System; using System.Text; using System.Linq; class Program { static string lookandsay(string number) { StringBuilder result = new StringBuilder(); char repeat = number[0]; number = number.Substring(1, number.Length-1)+" "; int times = 1; foreach (char actual in number) { if (actual != repeat) { result.Append(Convert.ToString(times)+repeat); times = 1; repeat = actual; } else { times += 1; } } return result.ToString(); } static void Main(string[] args) { string num = "1"; foreach (int i in Enumerable.Range(1, 10)) { Console.WriteLine(num); num = lookandsay(num); } } }
Write a version of this VB function in C# with identical behavior.
Private myStack() Private myStackHeight As Integer Public Function Push(aValue) myStackHeight = myStackHeight + 1 ReDim Preserve myStack(myStackHeight) myStack(myStackHeight) = aValue End Function Public Function Pop() If myStackHeight > 0 Then Pop = myStack(myStackHeight) myStackHeight = myStackHeight - 1 Else MsgBox "Pop: stack is empty!" End If End Function Public Function IsEmpty() As Boolean IsEmpty = (myStackHeight = 0) End Function Property Get Size() As Integer Size = myStackHeight End Property
System.Collections.Stack stack = new System.Collections.Stack(); stack.Push( obj ); bool isEmpty = stack.Count == 0; object top = stack.Peek(); top = stack.Pop(); System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>(); stack.Push(new Foo()); bool isEmpty = stack.Count == 0; Foo top = stack.Peek(); top = stack.Pop();
Transform the following VB implementation into C#, maintaining the same output and logic.
Private Function totient(ByVal n As Long) As Long Dim tot As Long: tot = n Dim i As Long: i = 2 Do While i * i <= n If n Mod i = 0 Then Do While True n = n \ i If n Mod i <> 0 Then Exit Do Loop tot = tot - tot \ i End If i = i + IIf(i = 2, 1, 2) Loop If n > 1 Then tot = tot - tot \ n End If totient = tot End Function Public Sub main() Debug.Print " n phi prime" Debug.Print " --------------" Dim count As Long Dim tot As Integer, n As Long For n = 1 To 25 tot = totient(n) prime = (n - 1 = tot) count = count - prime Debug.Print Format(n, "@@"); Format(tot, "@@@@@"); Format(prime, "@@@@@@@@") Next n Debug.Print Debug.Print "Number of primes up to 25 = "; Format(count, "@@@@") For n = 26 To 100000 count = count - (totient(n) = n - 1) Select Case n Case 100, 1000, 10000, 100000 Debug.Print "Number of primes up to"; n; String$(6 - Len(CStr(n)), " "); "="; Format(count, "@@@@@") Case Else End Select Next n End Sub
using static System.Console; using static System.Linq.Enumerable; public class Program { static void Main() { for (int i = 1; i <= 25; i++) { int t = Totient(i); WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : "")); } WriteLine(); for (int i = 100; i <= 100_000; i *= 10) { WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}"); } } static int Totient(int n) { if (n < 3) return 1; if (n == 3) return 2; int totient = n; if ((n & 1) == 0) { totient >>= 1; while (((n >>= 1) & 1) == 0) ; } for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { totient -= totient / i; while ((n /= i) % i == 0) ; } } if (n > 1) totient -= totient / n; return totient; } }
Port the following code from VB to C# with equivalent syntax and logic.
Sub C_S_If() Dim A$, B$ A = "Hello" B = "World" If A = B Then Debug.Print A & " = " & B If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B _ Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End Sub
if (condition) { } if (condition) { } else if (condition2) { } else { }
Write the same algorithm in C# as shown in this VB implementation.
Imports System Module Sorting_Using_a_Custom_Comparator Function CustomComparator(ByVal x As String, ByVal y As String) As Integer Dim result As Integer result = y.Length - x.Length If result = 0 Then result = String.Compare(x, y, True) End If Return result End Function Sub Main() Dim strings As String() = {"test", "Zoom", "strings", "a"} Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator)) End Sub End Module
using System; using System.Collections.Generic; namespace RosettaCode { class SortCustomComparator { public void CustomSort() { String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; List<String> list = new List<string>(items); DisplayList("Unsorted", list); list.Sort(CustomCompare); DisplayList("Descending Length", list); list.Sort(); DisplayList("Ascending order", list); } public int CustomCompare(String x, String y) { int result = -x.Length.CompareTo(y.Length); if (result == 0) { result = x.ToLower().CompareTo(y.ToLower()); } return result; } public void DisplayList(String header, List<String> theList) { Console.WriteLine(header); Console.WriteLine("".PadLeft(header.Length, '*')); foreach (String str in theList) { Console.WriteLine(str); } Console.WriteLine(); } } }
Generate an equivalent C# version of this VB code.
VERSION 5.00 Begin VB.Form Form1 Begin VB.Timer Timer1 Interval = 250 End Begin VB.Label Label1 AutoSize = -1 Caption = "Hello World! " End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private goRight As Boolean Private Sub Label1_Click() goRight = Not goRight End Sub Private Sub Timer1_Timer() If goRight Then x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1) Else x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1) End If Label1.Caption = x End Sub
using System; using System.Drawing; using System.Windows.Forms; namespace BasicAnimation { class BasicAnimationForm : Form { bool isReverseDirection; Label textLabel; Timer timer; internal BasicAnimationForm() { this.Size = new Size(150, 75); this.Text = "Basic Animation"; textLabel = new Label(); textLabel.Text = "Hello World! "; textLabel.Location = new Point(3,3); textLabel.AutoSize = true; textLabel.Click += new EventHandler(textLabel_OnClick); this.Controls.Add(textLabel); timer = new Timer(); timer.Interval = 500; timer.Tick += new EventHandler(timer_OnTick); timer.Enabled = true; isReverseDirection = false; } private void timer_OnTick(object sender, EventArgs e) { string oldText = textLabel.Text, newText; if(isReverseDirection) newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1); else newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1); textLabel.Text = newText; } private void textLabel_OnClick(object sender, EventArgs e) { isReverseDirection = !isReverseDirection; } } class Program { static void Main() { Application.Run(new BasicAnimationForm()); } } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
Module ListComp Sub Main() Dim ts = From a In Enumerable.Range(1, 20) _ From b In Enumerable.Range(a, 21 - a) _ From c In Enumerable.Range(b, 21 - b) _ Where a * a + b * b = c * c _ Select New With { a, b, c } For Each t In ts System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c) Next End Sub End Module
using System.Linq; static class Program { static void Main() { var ts = from a in Enumerable.Range(1, 20) from b in Enumerable.Range(a, 21 - a) from c in Enumerable.Range(b, 21 - b) where a * a + b * b == c * c select new { a, b, c }; foreach (var t in ts) System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c); } }
Change the following VB code into C# without altering its purpose.
Function Selection_Sort(s) arr = Split(s,",") For i = 0 To UBound(arr) For j = i To UBound(arr) temp = arr(i) If arr(j) < arr(i) Then arr(i) = arr(j) arr(j) = temp End If Next Next Selection_Sort = (Join(arr,",")) End Function WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" WScript.StdOut.WriteLine WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1") WScript.StdOut.WriteLine WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
class SelectionSort<T> where T : IComparable { public T[] Sort(T[] list) { int k; T temp; for (int i = 0; i < list.Length; i++) { k = i; for (int j=i + 1; j < list.Length; j++) { if (list[j].CompareTo(list[k]) < 0) { k = j; } } temp = list[i]; list[i] = list[k]; list[k] = temp; } return list; } }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Function Selection_Sort(s) arr = Split(s,",") For i = 0 To UBound(arr) For j = i To UBound(arr) temp = arr(i) If arr(j) < arr(i) Then arr(i) = arr(j) arr(j) = temp End If Next Next Selection_Sort = (Join(arr,",")) End Function WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" WScript.StdOut.WriteLine WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1") WScript.StdOut.WriteLine WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
class SelectionSort<T> where T : IComparable { public T[] Sort(T[] list) { int k; T temp; for (int i = 0; i < list.Length; i++) { k = i; for (int j=i + 1; j < list.Length; j++) { if (list[j].CompareTo(list[k]) < 0) { k = j; } } temp = list[i]; list[i] = list[k]; list[k] = temp; } return list; } }
Maintain the same structure and functionality when rewriting this code in C#.
Option Explicit Sub Main() Dim arr, i arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next Debug.Print Join(arr, ", ") End Sub Private Function Fibonacci(N) As Variant If N <= 1 Then Fibonacci = N Else Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2) End If End Function
int[] intArray = { 1, 2, 3, 4, 5 }; int[] squares1 = intArray.Select(x => x * x).ToArray(); int[] squares2 = (from x in intArray select x * x).ToArray(); foreach (var i in intArray) Console.WriteLine(i * i);
Generate an equivalent C# version of this VB code.
For i = 10 To 0 Step -1 Debug.Print i Next i
for (int i = 10; i >= 0; i--) { Console.WriteLine(i); }
Convert this VB block to C#, preserving its control flow and logic.
Option Explicit Const strName As String = "MyFileText.txt" Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _ "The reverse of Read entire file—for when you want to update or " & vbCrLf & _ "create a file which you would read in its entirety all at once." Sub Main() Dim Nb As Integer Nb = FreeFile Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb Print #1, Text Close #Nb End Sub
System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
Ensure the translated C# code behaves exactly like the original VB snippet.
Public OutConsole As Scripting.TextStream For i = 0 To 4 For j = 0 To i OutConsole.Write "*" Next j OutConsole.WriteLine Next i
using System; class Program { static void Main(string[] args) { for (int i = 0; i < 5; i++) { for (int j = 0; j <= i; j++) { Console.Write("*"); } Console.WriteLine(); } } }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Function noncontsubseq(l) Dim i, j, g, n, r, s, w, m Dim a, b, c n = Ubound(l) For s = 0 To n-2 For g = s+1 To n-1 a = "[" For i = s To g-1 a = a & l(i) & ", " Next For w = 1 To n-g r = n+1-g-w For i = 1 To 2^r-1 Step 2 b = a For j = 0 To r-1 If i And 2^j Then b=b & l(g+w+j) & ", " Next c = (Left(b, Len(b)-1)) WScript.Echo Left(c, Len(c)-1) & "]" m = m+1 Next Next Next Next noncontsubseq = m End Function list = Array("1", "2", "3", "4") WScript.Echo "List: [" & Join(list, ", ") & "]" nn = noncontsubseq(list) WScript.Echo nn & " non-continuous subsequences"
using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { var sequence = new[] { "A", "B", "C", "D" }; foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) { Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i]))); } } static IEnumerable<List<int>> Subsets(int length) { int[] values = Enumerable.Range(0, length).ToArray(); var stack = new Stack<int>(length); for (int i = 0; stack.Count > 0 || i < length; ) { if (i < length) { stack.Push(i++); yield return (from index in stack.Reverse() select values[index]).ToList(); } else { i = stack.Pop() + 1; if (stack.Count > 0) i = stack.Pop() + 1; } } } static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count; }
Write the same algorithm in C# as shown in this VB implementation.
Function IsPrime(x As Long) As Boolean Dim i As Long If x Mod 2 = 0 Then Exit Function Else For i = 3 To Int(Sqr(x)) Step 2 If x Mod i = 0 Then Exit Function Next i End If IsPrime = True End Function Function TwinPrimePairs(max As Long) As Long Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long p2 = True For i = 5 To max Step 2 p1 = p2 p2 = IsPrime(i) If p1 And p2 Then count = count + 1 Next i TwinPrimePairs = count End Function Sub Test(x As Long) Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x)) End Sub Sub Main() Test 10 Test 100 Test 1000 Test 10000 Test 100000 Test 1000000 Test 10000000 End Sub
using System; class Program { static uint[] res = new uint[10]; static uint ri = 1, p = 10, count = 0; static void TabulateTwinPrimes(uint bound) { if (bound < 5) return; count++; uint cl = (bound - 1) >> 1, i = 1, j, limit = (uint)(Math.Sqrt(bound) - 1) >> 1; var comp = new bool[cl]; bool lp; for (j = 3; j < cl; j += 3) comp[j] = true; while (i < limit) { if (lp = !comp[i]) { uint pr = (i << 1) + 3; for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } if (!comp[++i]) { uint pr = (i << 1) + 3; if (lp) { if (pr > p) { res[ri++] = count; p *= 10; } count++; i++; } for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } } cl--; while (i < cl) { lp = !comp[i++]; if (!comp[i] && lp) { if ((i++ << 1) + 3 > p) { res[ri++] = count; p *= 10; } count++; } } res[ri] = count; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); string fmt = "{0,9:n0} twin primes below {1,-13:n0}"; TabulateTwinPrimes(1_000_000_000); sw.Stop(); p = 1; for (var j = 1; j <= ri; j++) Console.WriteLine(fmt, res[j], p *= 10); Console.Write("{0} sec", sw.Elapsed.TotalSeconds); } }
Change the programming language of this snippet from VB to C# without modifying what it does.
Public Sub roots_of_unity() For n = 2 To 9 Debug.Print n; "th roots of 1:" For r00t = 0 To n - 1 Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _ Sin(2 * WorksheetFunction.Pi() * r00t / n)) Next r00t Debug.Print Next n End Sub
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; class Program { static IEnumerable<Complex> RootsOfUnity(int degree) { return Enumerable .Range(0, degree) .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree)); } static void Main() { var degree = 3; foreach (var root in RootsOfUnity(degree)) { Console.WriteLine(root); } } }
Port the following code from VB to C# with equivalent syntax and logic.
Imports System Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D Structure bd Public hi, lo As Decimal End Structure Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo), String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo)) If Not comma Then Return r Dim rc As String = "" For i As Integer = r.Length - 3 To 0 Step -3 rc = "," & r.Substring(i, 3) & rc : Next toStr = r.Substring(0, r.Length Mod 3) & rc toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0)) End Function Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _ Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas End Function Sub Main(ByVal args As String()) For p As UInteger = 64 To 95 - 1 Step 30 Dim y As bd, x As bd : a = Pow_dec(2D, p) WriteLine("The square of (2^{0}): {1,38:n0}", p, a) x.hi = Math.Floor(a / hm) : x.lo = a Mod hm Dim BS As BI = BI.Pow(CType(a, BI), 2) y.lo = x.lo * x.lo : y.hi = x.hi * x.hi a = x.hi * x.lo * 2D y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm While y.lo > mx : y.lo -= mx : y.hi += 1 : End While WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf, toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to")) Next End Sub End Module
using System; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static decimal mx = 1E28M, hm = 1E14M, a; struct bi { public decimal hi, lo; } static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; } static string toStr(bi a, bool comma = false) { string r = a.hi == 0 ? string.Format("{0:0}", a.lo) : string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo); if (!comma) return r; string rc = ""; for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc; return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; } static decimal Pow_dec(decimal bas, uint exp) { if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp; if ((exp & 1) == 0) return tmp; return tmp * bas; } static void Main(string[] args) { for (uint p = 64; p < 95; p += 30) { bi x = set4sq(a = Pow_dec(2M, p)), y; WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2); y.lo = x.lo * x.lo; y.hi = x.hi * x.hi; a = x.hi * x.lo * 2M; y.hi += Math.Floor(a / hm); y.lo += (a % hm) * hm; while (y.lo > mx) { y.lo -= mx; y.hi++; } WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true), BS.ToString() == toStr(y) ? "does" : "fails to"); } } }
Produce a functionally identical C# code for the snippet given in VB.
Imports System.Numerics Module Module1 Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer) Dim t As BigInteger = a : a = b : b = b * c + t End Sub Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger) Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1, e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1 While True y = r * z - y : z = (n - y * y) / z : r = (x + y) / z Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x) If a * a - n * b * b = 1 Then Exit Sub End While End Sub Sub Main() Dim x As BigInteger, y As BigInteger For Each n As Integer In {61, 109, 181, 277} SolvePell(n, x, y) Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y) Next End Sub End Module
using System; using System.Numerics; static class Program { static void Fun(ref BigInteger a, ref BigInteger b, int c) { BigInteger t = a; a = b; b = b * c + t; } static void SolvePell(int n, ref BigInteger a, ref BigInteger b) { int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1; BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x); if (a * a - n * b * b == 1) return; } } static void Main() { BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 }) { SolvePell(n, ref x, ref y); Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y); } } }
Maintain the same structure and functionality when rewriting this code in C#.
Option Explicit Sub Main_Bulls_and_cows() Dim strNumber As String, strInput As String, strMsg As String, strTemp As String Dim boolEnd As Boolean Dim lngCpt As Long Dim i As Byte, bytCow As Byte, bytBull As Byte Const NUMBER_OF_DIGITS As Byte = 4 Const MAX_LOOPS As Byte = 25 strNumber = Create_Number(NUMBER_OF_DIGITS) Do bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1 If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do strInput = AskToUser(NUMBER_OF_DIGITS) If strInput = "Exit Game" Then strMsg = "User abort": Exit Do For i = 1 To Len(strNumber) If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then bytBull = bytBull + 1 ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then bytCow = bytCow + 1 End If Next i If bytBull = Len(strNumber) Then boolEnd = True: strMsg = "You win in " & lngCpt & " loops!" Else strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows." MsgBox strTemp End If Loop While Not boolEnd MsgBox strMsg End Sub Function Create_Number(NbDigits As Byte) As String Dim myColl As New Collection Dim strTemp As String Dim bytAlea As Byte Randomize Do bytAlea = Int((Rnd * 9) + 1) On Error Resume Next myColl.Add CStr(bytAlea), CStr(bytAlea) If Err <> 0 Then On Error GoTo 0 Else strTemp = strTemp & CStr(bytAlea) End If Loop While Len(strTemp) < NbDigits Create_Number = strTemp End Function Function AskToUser(NbDigits As Byte) As String Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte Do While Not boolGood strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number") If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do If strIn <> "" Then If Len(strIn) = NbDigits Then NbDiff = 0 For i = 1 To Len(strIn) If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then NbDiff = 1 Exit For End If Next i If NbDiff = 0 Then boolGood = True End If End If Loop AskToUser = strIn End Function
using System; namespace BullsnCows { class Program { static void Main(string[] args) { int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; KnuthShuffle<int>(ref nums); int[] chosenNum = new int[4]; Array.Copy(nums, chosenNum, 4); Console.WriteLine("Your Guess ?"); while (!game(Console.ReadLine(), chosenNum)) { Console.WriteLine("Your next Guess ?"); } Console.ReadKey(); } public static void KnuthShuffle<T>(ref T[] array) { System.Random random = new System.Random(); for (int i = 0; i < array.Length; i++) { int j = random.Next(array.Length); T temp = array[i]; array[i] = array[j]; array[j] = temp; } } public static bool game(string guess, int[] num) { char[] guessed = guess.ToCharArray(); int bullsCount = 0, cowsCount = 0; if (guessed.Length != 4) { Console.WriteLine("Not a valid guess."); return false; } for (int i = 0; i < 4; i++) { int curguess = (int) char.GetNumericValue(guessed[i]); if (curguess < 1 || curguess > 9) { Console.WriteLine("Digit must be ge greater 0 and lower 10."); return false; } if (curguess == num[i]) { bullsCount++; } else { for (int j = 0; j < 4; j++) { if (curguess == num[j]) cowsCount++; } } } if (bullsCount == 4) { Console.WriteLine("Congratulations! You have won!"); return true; } else { Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount); return false; } } } }
Preserve the algorithm and functionality while converting the code from VB to C#.
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sortable.Shuffle() Dim swapped As Boolean Do Dim index, bound As Integer bound = sortable.Ubound While index < bound If sortable(index) > sortable(index + 1) Then Dim s As Integer = sortable(index) sortable.Remove(index) sortable.Insert(index + 1, s) swapped = True End If index = index + 1 Wend Loop Until Not swapped
using System; using System.Collections.Generic; namespace RosettaCode.BubbleSort { public static class BubbleSortMethods { public static void BubbleSort<T>(this List<T> list) where T : IComparable { bool madeChanges; int itemCount = list.Count; do { madeChanges = false; itemCount--; for (int i = 0; i < itemCount; i++) { if (list[i].CompareTo(list[i + 1]) > 0) { T temp = list[i + 1]; list[i + 1] = list[i]; list[i] = temp; madeChanges = true; } } } while (madeChanges); } } class Program { static void Main() { List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 }; testList.BubbleSort(); foreach (var t in testList) Console.Write(t + " "); } } }
Write a version of this VB function in C# with identical behavior.
Sub WriteToFile(input As FolderItem, output As FolderItem) Dim tis As TextInputStream Dim tos As TextOutputStream tis = tis.Open(input) tos = tos.Create(output) While Not tis.EOF tos.WriteLine(tis.ReadLine) Wend tis.Close tos.Close End Sub
using System; using System.IO; namespace FileIO { class Program { static void Main() { String s = scope .(); File.ReadAllText("input.txt", s); File.WriteAllText("output.txt", s); } } }
Port the following code from VB to C# with equivalent syntax and logic.
START: INPUT "Enter two integers (a,b):"; a!, b! IF a = 0 THEN END IF b = 0 THEN PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder." GOTO START END IF PRINT PRINT " Sum = "; a + b PRINT " Difference = "; a - b PRINT " Product = "; a * b PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0." PRINT " Remainder = "; a MOD b, , "* Sign matches first operand." PRINT " Exponentiation = "; a ^ b PRINT INPUT "Again? (y/N)"; a$ IF UCASE$(a$) = "Y" THEN CLS: GOTO START CLS END
using System; class Program { static void Main(string[] args) { int a = Convert.ToInt32(args[0]); int b = Convert.ToInt32(args[1]); Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} - {1} = {2}", a, b, a - b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b); Console.WriteLine("{0} / {1} = {2}", a, b, a / b); Console.WriteLine("{0} % {1} = {2}", a, b, a % b); Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b)); } }
Port the provided VB code into C# while preserving the original functionality.
START: INPUT "Enter two integers (a,b):"; a!, b! IF a = 0 THEN END IF b = 0 THEN PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder." GOTO START END IF PRINT PRINT " Sum = "; a + b PRINT " Difference = "; a - b PRINT " Product = "; a * b PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0." PRINT " Remainder = "; a MOD b, , "* Sign matches first operand." PRINT " Exponentiation = "; a ^ b PRINT INPUT "Again? (y/N)"; a$ IF UCASE$(a$) = "Y" THEN CLS: GOTO START CLS END
using System; class Program { static void Main(string[] args) { int a = Convert.ToInt32(args[0]); int b = Convert.ToInt32(args[1]); Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} - {1} = {2}", a, b, a - b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b); Console.WriteLine("{0} / {1} = {2}", a, b, a / b); Console.WriteLine("{0} % {1} = {2}", a, b, a % b); Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b)); } }
Change the following VB code into C# without altering its purpose.
Function transpose(m As Variant) As Variant transpose = WorksheetFunction.transpose(m) End Function
using System; using System.Text; namespace prog { class MainClass { public static void Main (string[] args) { double[,] m = { {1,2,3},{4,5,6},{7,8,9} }; double[,] t = Transpose( m ); for( int i=0; i<t.GetLength(0); i++ ) { for( int j=0; j<t.GetLength(1); j++ ) Console.Write( t[i,j] + " " ); Console.WriteLine(""); } } public static double[,] Transpose( double[,] m ) { double[,] t = new double[m.GetLength(1),m.GetLength(0)]; for( int i=0; i<m.GetLength(0); i++ ) for( int j=0; j<m.GetLength(1); j++ ) t[j,i] = m[i,j]; return t; } } }
Port the following code from VB to C# with equivalent syntax and logic.
Private Function a(i As Variant) As Boolean Debug.Print "a: "; i = 1, a = i End Function Private Function b(j As Variant) As Boolean Debug.Print "b: "; j = 1; b = j End Function Public Sub short_circuit() Dim x As Boolean, y As Boolean Debug.Print "=====AND=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print "======OR=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If Not a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print End Sub
using System; class Program { static bool a(bool value) { Console.WriteLine("a"); return value; } static bool b(bool value) { Console.WriteLine("b"); return value; } static void Main() { foreach (var i in new[] { false, true }) { foreach (var j in new[] { false, true }) { Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j)); Console.WriteLine(); Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j)); Console.WriteLine(); } } } }
Change the following VB code into C# without altering its purpose.
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
Write the same algorithm in C# as shown in this VB implementation.
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
Write a version of this VB function in C# with identical behavior.
Imports System.Drawing.Imaging Public Class frmSnowExercise Dim bRunning As Boolean = True Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _ Or ControlStyles.OptimizedDoubleBuffer, True) UpdateStyles() FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle MaximizeBox = False Width = 320 + Size.Width - ClientSize.Width Height = 240 + Size.Height - ClientSize.Height Show() Activate() Application.DoEvents() RenderLoop() Close() End Sub Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False End Sub Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _ System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing e.Cancel = bRunning bRunning = False End Sub Private Sub RenderLoop() Const cfPadding As Single = 5.0F Dim b As New Bitmap(ClientSize.Width, ClientSize.Width, PixelFormat.Format32bppArgb) Dim g As Graphics = Graphics.FromImage(b) Dim r As New Random(Now.Millisecond) Dim oBMPData As BitmapData = Nothing Dim oPixels() As Integer = Nothing Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb} Dim oStopwatch As New Stopwatch Dim fElapsed As Single = 0.0F Dim iLoops As Integer = 0 Dim sFPS As String = "0.0 FPS" Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font) Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) g.Clear(Color.Black) oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb) Array.Resize(oPixels, b.Width * b.Height) Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oPixels, 0, oPixels.Length) b.UnlockBits(oBMPData) Do fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F oStopwatch.Reset() : oStopwatch.Start() iLoops += 1 If fElapsed >= 1.0F Then sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS" oFPSSize = g.MeasureString(sFPS, Font) oFPSBG = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) fElapsed -= 1.0F iLoops = 0 End If For i As Integer = 0 To oPixels.GetUpperBound(0) oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length)) Next oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb) Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0, oPixels.Length) b.UnlockBits(oBMPData) g.FillRectangle(Brushes.Black, oFPSBG) g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top) BackgroundImage = b Invalidate(ClientRectangle) Application.DoEvents() Loop While bRunning End Sub End Class
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; class Program { static Size size = new Size(320, 240); static Rectangle rectsize = new Rectangle(new Point(0, 0), size); static int numpixels = size.Width * size.Height; static int numbytes = numpixels * 3; static PictureBox pb; static BackgroundWorker worker; static double time = 0; static double frames = 0; static Random rand = new Random(); static byte tmp; static byte white = 255; static byte black = 0; static int halfmax = int.MaxValue / 2; static IEnumerable<byte> YieldVodoo() { for (int i = 0; i < numpixels; i++) { tmp = rand.Next() < halfmax ? black : white; yield return tmp; yield return tmp; yield return tmp; } } static Image Randimg() { var bitmap = new Bitmap(size.Width, size.Height); var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); Marshal.Copy( YieldVodoo().ToArray<byte>(), 0, data.Scan0, numbytes); bitmap.UnlockBits(data); return bitmap; } [STAThread] static void Main() { var form = new Form(); form.AutoSize = true; form.Size = new Size(0, 0); form.Text = "Test"; form.FormClosed += delegate { Application.Exit(); }; worker = new BackgroundWorker(); worker.DoWork += delegate { System.Threading.Thread.Sleep(500); while (true) { var a = DateTime.Now; pb.Image = Randimg(); var b = DateTime.Now; time += (b - a).TotalSeconds; frames += 1; if (frames == 30) { Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time); time = 0; frames = 0; } } }; worker.RunWorkerAsync(); FlowLayoutPanel flp = new FlowLayoutPanel(); form.Controls.Add(flp); pb = new PictureBox(); pb.Size = size; flp.AutoSize = true; flp.Controls.Add(pb); form.Show(); Application.Run(); } }
Produce a functionally identical C# code for the snippet given in VB.
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
static void Main(string[] args) { Console.WriteLine("Perfect numbers from 1 to 33550337:"); for (int x = 0; x < 33550337; x++) { if (IsPerfect(x)) Console.WriteLine(x + " is perfect."); } Console.ReadLine(); } static bool IsPerfect(int num) { int sum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) sum += i; } return sum == num ; }
Produce a functionally identical C# code for the snippet given in VB.
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
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); } }
Port the following code from VB to C# with equivalent syntax and logic.
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
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)); } }
Convert this VB snippet to C# and keep its semantics consistent.
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
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)); } }
Rewrite the snippet below in C# so it works the same as the original VB code.
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
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(); } }
Produce a functionally identical C# code for the snippet given in VB.
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
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(); } }
Produce a functionally identical C# code for the snippet given in VB.
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
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); } } }
Write the same algorithm in C# as shown in this VB implementation.
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
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); } } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
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
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)} ]"); } }
Convert this VB snippet to C# and keep its semantics consistent.
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
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)); } } }
Please provide an equivalent version of this VB code in C#.
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
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 "); } }
Produce a functionally identical C# code for the snippet given in VB.
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
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); } } } } }
Port the provided VB code into C# while preserving the original functionality.
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
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; } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
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
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; } }
Maintain the same structure and functionality when rewriting this code in C#.
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
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(); }
Transform the following VB implementation into C#, maintaining the same output and logic.
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
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", "")); } } }
Write the same code in C# as shown below in VB.
Imports System.Numerics Module Module1 ReadOnly BIG = BigInteger.Pow(10, 50) + 151 Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean) Dim n = BigInteger.Parse(ns) Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG) Dim ls = Function(a0 As 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
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", "")); } } }
Ensure the translated C# code behaves exactly like the original VB snippet.
Debug.Print "Tom said, ""The fox ran away.""" Debug.Print "Tom said,
string path = @"C:\Windows\System32"; string multiline = @"Line 1. Line 2. Line 3.";
Generate an equivalent C# version of this VB code.
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
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}"); } }
Change the programming language of this snippet from VB to C# without modifying what it does.
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
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 }
Preserve the algorithm and functionality while converting the code from VB to C#.
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
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 }; } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
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
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(); } } } }
Convert this VB snippet to C# and keep its semantics consistent.
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
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 }); } } }
Write a version of this VB function in C# with identical behavior.
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
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])); } } }
Generate a C# translation of this VB snippet without changing its computational steps.
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
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)); } } } }
Convert this VB snippet to C# and keep its semantics consistent.
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
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; } } }
Convert this VB snippet to C# and keep its semantics consistent.
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
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"); } } } }
Change the following VB code into C# without altering its purpose.
Set objShell = CreateObject("WScript.Shell") objShell.Run "%comspec% /K dir",3,True
using System.Diagnostics; namespace Execute { class Program { static void Main(string[] args) { Process.Start("cmd.exe", "/c dir"); } } }
Produce a functionally identical C# code for the snippet given in VB.
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)
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); } }
Produce a language-to-language conversion: from VB to C#, same semantics.
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))
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(); } }
Port the following code from VB to C# with equivalent syntax and logic.
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If 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
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; } }
Translate the given VB code snippet into C# without altering its behavior.
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
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()); } }
Port the provided VB code into C# while preserving the original functionality.
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
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(); } }
Maintain the same structure and functionality when rewriting this code in C#.
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
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)); } } }
Port the following code from VB to C# with equivalent syntax and logic.
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
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)); } } }
Please provide an equivalent version of this VB code in C#.
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
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; } }
Rewrite the snippet below in C# so it works the same as the original VB code.
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
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; } }
Port the following code from VB to C# with equivalent syntax and logic.
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
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); } } } }
Maintain the same structure and functionality when rewriting this code in C#.
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
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); } } } }
Preserve the algorithm and functionality while converting the code from VB to C#.
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
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(); } } }
Write a version of this VB function in C# with identical behavior.
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
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(); } }
Convert this VB block to C#, preserving its control flow and logic.
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
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(); } }
Ensure the translated C# code behaves exactly like the original VB snippet.
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
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); } }
Generate a C# translation of this VB snippet without changing its computational steps.
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
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)); } }
Rewrite the snippet below in C# so it works the same as the original VB code.
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
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)); } }
Generate a C# translation of this VB snippet without changing its computational steps.
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
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); } }
Rewrite the snippet below in C# so it works the same as the original VB code.
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
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;
Write the same code in C# as shown below in VB.
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
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;
Produce a language-to-language conversion: from VB to C#, same semantics.
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
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(); } } }
Translate the given VB code snippet into C# without altering its behavior.
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
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); } }
Convert this VB snippet to C# and keep its semantics consistent.
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
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); } }
Write a version of this VB function in C# with identical behavior.
Module Module1 Class Node Public Sub New(Len As Integer) Length = Len Edges = New Dictionary(Of Char, Integer) End Sub Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer) Length = len Edges = If(IsNothing(edg), 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
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); } } }
Change the programming language of this snippet from VB to C# without modifying what it does.
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
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); } } }
Produce a language-to-language conversion: from VB to C#, same semantics.
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
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; } }
Convert this VB block to C#, preserving its control flow and logic.
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
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(); } } } } } }
Translate this program into C# but keep the logic exactly as in VB.
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
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); } } }