Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from VB to C# with equivalent syntax and logic.
$Include "Rapidq.inc" dim file as qfilestream if file.open("c:\A Test.txt", fmOpenRead) then while not File.eof print File.readline wend else print "Cannot read file" end if input "Press enter to exit: ";a$
foreach (string readLine in File.ReadLines("FileName")) DoSomething(readLine);
Convert this VB snippet to C# and keep its semantics consistent.
Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T) Dim node As New Node(Of T)(value) a.Next = node node.Previous = a b.Previous = node node.Next = b End Sub
static void InsertAfter(Link prev, int i) { if (prev.next != null) { prev.next.prev = new Link() { item = i, prev = prev, next = prev.next }; prev.next = prev.next.prev; } else prev.next = new Link() { item = i, prev = prev }; }
Convert this VB snippet to C# and keep its semantics consistent.
Dim s As Variant Private Function quick_select(ByRef s As Variant, k As Integer) As Integer Dim left As Integer, right As Integer, pos As Integer Dim pivotValue As Integer, tmp As Integer left = 1: right = UBound(s) Do While left < right pivotValue = s(k) tmp = s(k) s(k) = s(right) s(right) = tmp pos = left For i = left To right If s(i) < pivotValue Then tmp = s(i) s(i) = s(pos) s(pos) = tmp pos = pos + 1 End If Next i tmp = s(right) s(right) = s(pos) s(pos) = tmp If pos = k Then Exit Do End If If pos < k Then left = pos + 1 Else right = pos - 1 End If Loop quick_select = s(k) End Function Public Sub main() Dim r As Integer, i As Integer s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}] For i = 1 To 10 r = quick_select(s, i) Debug.Print IIf(i < 10, r & ", ", "" & r); Next i End Sub
using System; using System.Collections.Generic; using System.Linq; namespace QuickSelect { internal static class Program { #region Static Members private static void Main() { var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; Console.WriteLine( "Loop quick select 10 times." ); for( var i = 0 ; i < 10 ; i++ ) { Console.Write( inputArray.NthSmallestElement( i ) ); if( i < 9 ) Console.Write( ", " ); } Console.WriteLine(); Console.WriteLine( "Just sort 10 elements." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "Get 4 smallest and sort them." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } internal static class ArrayExtension { #region Static Members public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T> { if( count < 0 ) throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." ); if( count == 0 ) return new T[0]; if( array.Length <= count ) return array; return QuickSelectSmallest( array, count - 1 ).Take( count ); } public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T> { if( n < 0 || n > array.Length - 1 ) throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) ); if( array.Length == 0 ) throw new ArgumentException( "Array is empty.", "array" ); if( array.Length == 1 ) return array[ 0 ]; return QuickSelectSmallest( array, n )[ n ]; } private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T> { var partiallySortedArray = (T[]) input.Clone(); var startIndex = 0; var endIndex = input.Length - 1; var pivotIndex = n; var r = new Random(); while( endIndex > startIndex ) { pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex ); if( pivotIndex == n ) break; if( pivotIndex > n ) endIndex = pivotIndex - 1; else startIndex = pivotIndex + 1; pivotIndex = r.Next( startIndex, endIndex ); } return partiallySortedArray; } private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T> { var pivotValue = array[ pivotIndex ]; array.Swap( pivotIndex, endIndex ); for( var i = startIndex ; i < endIndex ; i++ ) { if( array[ i ].CompareTo( pivotValue ) > 0 ) continue; array.Swap( i, startIndex ); startIndex++; } array.Swap( endIndex, startIndex ); return startIndex; } private static void Swap<T>( this T[] array, int index1, int index2 ) { if( index1 == index2 ) return; var temp = array[ index1 ]; array[ index1 ] = array[ index2 ]; array[ index2 ] = temp; } #endregion } }
Port the following code from VB to C# with equivalent syntax and logic.
Private Function to_base(ByVal number As Long, base As Integer) As String Dim digits As String, result As String Dim i As Integer, digit As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" Do While number > 0 digit = number Mod base result = Mid(digits, digit + 1, 1) & result number = number \ base Loop to_base = result End Function Private Function from_base(number As String, base As Integer) As Long Dim digits As String, result As Long Dim i As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1) For i = 2 To Len(number) result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1) Next i from_base = result End Function Public Sub Non_decimal_radices_Convert() Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16) End Sub
public static class BaseConverter { public static long stringToLong(string s, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); checked { int slen = s.Length; long result = 0; bool isNegative = false; for ( int i = 0; i < slen; i++ ) { char c = s[i]; int num; if ( c == '-' ) { if ( i != 0 ) throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s"); isNegative = true; continue; } if ( c > 0x2F && c < 0x3A ) num = c - 0x30; else if ( c > 0x40 && c < 0x5B ) num = c - 0x37; else if ( c > 0x60 && c < 0x7B ) num = c - 0x57; else throw new ArgumentException("The string contains an invalid character '" + c + "'", "s"); if ( num >= b ) throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s"); result *= b; result += num; } if ( isNegative ) result = -result; return result; } } public static string longToString(long n, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); if ( b == 10 ) return n.ToString(); checked { long longBase = b; StringBuilder sb = new StringBuilder(); if ( n < 0 ) { n = -n; sb.Append('-'); } long div = 1; while ( n / div >= b ) div *= b; while ( true ) { byte digit = (byte) (n / div); if ( digit < 10 ) sb.Append((char) (digit + 0x30)); else sb.Append((char) (digit + 0x57)); if ( div == 1 ) break; n %= div; div /= b; } return sb.ToString(); } } }
Convert this VB snippet to C# and keep its semantics consistent.
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Maintain the same structure and functionality when rewriting this code in C#.
dim crctbl(255) const crcc =&hEDB88320 sub gencrctable for i= 0 to 255 k=i for j=1 to 8 if k and 1 then k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) k=k xor crcc else k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) end if next crctbl(i)=k next end sub function crc32 (buf) dim r,r1,i r=&hffffffff for i=1 to len(buf) r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0) r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) next crc32=r xor &hffffffff end function gencrctable wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
Keep all operations the same but rewrite the snippet in C#.
dim crctbl(255) const crcc =&hEDB88320 sub gencrctable for i= 0 to 255 k=i for j=1 to 8 if k and 1 then k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) k=k xor crcc else k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) end if next crctbl(i)=k next end sub function crc32 (buf) dim r,r1,i r=&hffffffff for i=1 to len(buf) r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0) r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) next crc32=r xor &hffffffff end function gencrctable wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
Rewrite the snippet below in C# so it works the same as the original VB code.
Class NumberContainer Private TheNumber As Integer Sub Constructor(InitialNumber As Integer) TheNumber = InitialNumber End Sub Function Number() As Integer Return TheNumber End Function Sub Number(Assigns NewNumber As Integer) TheNumber = NewNumber End Sub End Class
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { MyClass instance = new MyClass(); instance.SomeMethod(); instance.Variable = 99; System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
Maintain the same structure and functionality when rewriting this code in C#.
Module Module1 ReadOnly max As ULong = 1000000 Function Kaprekar(n As ULong) As Boolean If n = 1 Then Return True Dim sq = n * n Dim sq_str = Str(sq) Dim l = Len(sq_str) For x = l - 1 To 1 Step -1 If sq_str(x) = "0" Then l = l - 1 Else Exit For End If Next For x = 1 To l - 1 Dim p2 = Val(Mid(sq_str, x + 1)) If p2 > n Then Continue For End If Dim p1 = Val(Left(sq_str, x)) If p1 > n Then Return False If (p1 + p2) = n Then Return True Next Return False End Function Sub Main() Dim count = 0 Console.WriteLine("Kaprekar numbers below 10000") For n = 1 To max - 1 If Kaprekar(n) Then count = count + 1 If n < 10000 Then Console.WriteLine("{0,2} {1,4}", count, n) End If End If Next Console.WriteLine() Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max) End Sub End Module
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Convert this VB block to C#, preserving its control flow and logic.
Module Module1 ReadOnly max As ULong = 1000000 Function Kaprekar(n As ULong) As Boolean If n = 1 Then Return True Dim sq = n * n Dim sq_str = Str(sq) Dim l = Len(sq_str) For x = l - 1 To 1 Step -1 If sq_str(x) = "0" Then l = l - 1 Else Exit For End If Next For x = 1 To l - 1 Dim p2 = Val(Mid(sq_str, x + 1)) If p2 > n Then Continue For End If Dim p1 = Val(Left(sq_str, x)) If p1 > n Then Return False If (p1 + p2) = n Then Return True Next Return False End Function Sub Main() Dim count = 0 Console.WriteLine("Kaprekar numbers below 10000") For n = 1 To max - 1 If Kaprekar(n) Then count = count + 1 If n < 10000 Then Console.WriteLine("{0,2} {1,4}", count, n) End If End If Next Console.WriteLine() Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max) End Sub End Module
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Convert this VB snippet to C# and keep its semantics consistent.
Private Function ffr(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j Next i ffr = R(n) Set R = Nothing Set S = Nothing End Function Private Function ffs(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j If S.Count >= n Then Exit For Next i ffs = S(n) Set R = Nothing Set S = Nothing End Function Public Sub main() Dim i As Long Debug.Print "The first ten values of R are:" For i = 1 To 10 Debug.Print ffr(i); Next i Debug.Print Dim x As New Collection For i = 1 To 1000 x.Add i, CStr(i) Next i For i = 1 To 40 x.Remove CStr(ffr(i)) Next i For i = 1 To 960 x.Remove CStr(ffs(i)) Next i Debug.Print "The first 40 values of ffr plus the first 960 values of ffs " Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0) End Sub
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Generate an equivalent C# version of this VB code.
Private Function ffr(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j Next i ffr = R(n) Set R = Nothing Set S = Nothing End Function Private Function ffs(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j If S.Count >= n Then Exit For Next i ffs = S(n) Set R = Nothing Set S = Nothing End Function Public Sub main() Dim i As Long Debug.Print "The first ten values of R are:" For i = 1 To 10 Debug.Print ffr(i); Next i Debug.Print Dim x As New Collection For i = 1 To 1000 x.Add i, CStr(i) Next i For i = 1 To 40 x.Remove CStr(ffr(i)) Next i For i = 1 To 960 x.Remove CStr(ffs(i)) Next i Debug.Print "The first 40 values of ffr plus the first 960 values of ffs " Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0) End Sub
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Translate this program into C# but keep the logic exactly as in VB.
Sub Main() Debug.Print F(-10) Debug.Print F(10) End Sub Private Function F(N As Long) As Variant If N < 0 Then F = "Error. Negative argument" ElseIf N <= 1 Then F = N Else F = F(N - 1) + F(N - 2) End If End Function
static int Fib(int n) { if (n < 0) throw new ArgumentException("Must be non negativ", "n"); Func<int, int> fib = null; fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p; return fib(n); }
Write a version of this VB function in C# with identical behavior.
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
Generate a C# translation of this VB snippet without changing its computational steps.
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
Write the same code in C# as shown below in VB.
Public Sub create_file() Dim FileNumber As Integer FileNumber = FreeFile MkDir "docs" Open "docs\output.txt" For Output As #FreeFile Close #FreeFile MkDir "C:\docs" Open "C:\docs\output.txt" For Output As #FreeFile Close #FreeFile End Sub
using System; using System.IO; class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt"); Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\docs"); } }
Translate the given VB code snippet into C# without altering its behavior.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"}, {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"}, {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"}, {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"}, {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"}, {"z", "BBAAB"}, {" ", "BBBAA"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "bacon "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
Generate a C# translation of this VB snippet without changing its computational steps.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"}, {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"}, {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"}, {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"}, {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"}, {"z", "BBAAB"}, {" ", "BBBAA"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "bacon "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
Write a version of this VB function in C# with identical behavior.
Function build_spiral(n) botcol = 0 : topcol = n - 1 botrow = 0 : toprow = n - 1 Dim matrix() ReDim matrix(topcol,toprow) dir = 0 : col = 0 : row = 0 For i = 0 To n*n-1 matrix(col,row) = i Select Case dir Case 0 If col < topcol Then col = col + 1 Else dir = 1 : row = row + 1 : botrow = botrow + 1 End If Case 1 If row < toprow Then row = row + 1 Else dir = 2 : col = col - 1 : topcol = topcol - 1 End If Case 2 If col > botcol Then col = col - 1 Else dir = 3 : row = row - 1 : toprow = toprow - 1 End If Case 3 If row > botrow Then row = row - 1 Else dir = 0 : col = col + 1 : botcol = botcol + 1 End If End Select Next For y = 0 To n-1 For x = 0 To n-1 WScript.StdOut.Write matrix(x,y) & vbTab Next WScript.StdOut.WriteLine Next End Function build_spiral(CInt(WScript.Arguments(0)))
public int[,] Spiral(int n) { int[,] result = new int[n, n]; int pos = 0; int count = n; int value = -n; int sum = -1; do { value = -1 * value / n; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } value *= n; count--; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } } while (count > 0); return result; } public void PrintArray(int[,] array) { int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1; for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { Console.Write(array[i, j].ToString().PadLeft(n, ' ')); } Console.WriteLine(); } }
Translate this program into C# but keep the logic exactly as in VB.
Module Module1 Class Frac Private ReadOnly num As Long Private ReadOnly denom As Long Public Shared ReadOnly ZERO = New Frac(0, 1) Public Shared ReadOnly ONE = New Frac(1, 1) Public Sub New(n As Long, d As Long) If d = 0 Then Throw New ArgumentException("d must not be zero") End If Dim nn = n Dim dd = d If nn = 0 Then dd = 1 ElseIf dd < 0 Then nn = -nn dd = -dd End If Dim g = Math.Abs(Gcd(nn, dd)) If g > 1 Then nn /= g dd /= g End If num = nn denom = dd End Sub Private Shared Function Gcd(a As Long, b As Long) As Long If b = 0 Then Return a Else Return Gcd(b, a Mod b) End If End Function Public Shared Operator -(self As Frac) As Frac Return New Frac(-self.num, self.denom) End Operator Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom) End Operator Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac Return lhs + -rhs End Operator Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom) End Operator Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x < y End Operator Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x > y End Operator Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom End Operator Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom End Operator Public Overrides Function ToString() As String If denom = 1 Then Return num.ToString Else Return String.Format("{0}/{1}", num, denom) End If End Function Public Overrides Function Equals(obj As Object) As Boolean Dim frac = CType(obj, Frac) Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom End Function End Class Function Bernoulli(n As Integer) As Frac If n < 0 Then Throw New ArgumentException("n may not be negative or zero") End If Dim a(n + 1) As Frac For m = 0 To n a(m) = New Frac(1, m + 1) For j = m To 1 Step -1 a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1) Next Next If n <> 1 Then Return a(0) Else Return -a(0) End If End Function Function Binomial(n As Integer, k As Integer) As Integer If n < 0 OrElse k < 0 OrElse n < k Then Throw New ArgumentException() End If If n = 0 OrElse k = 0 Then Return 1 End If Dim num = 1 For i = k + 1 To n num *= i Next Dim denom = 1 For i = 2 To n - k denom *= i Next Return num \ denom End Function Function FaulhaberTriangle(p As Integer) As Frac() Dim coeffs(p + 1) As Frac For i = 1 To p + 1 coeffs(i - 1) = Frac.ZERO Next Dim q As New Frac(1, p + 1) Dim sign = -1 For j = 0 To p sign *= -1 coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j) Next Return coeffs End Function Sub Main() For i = 1 To 10 Dim coeffs = FaulhaberTriangle(i - 1) For Each coeff In coeffs Console.Write("{0,5} ", coeff) Next Console.WriteLine() Next End Sub End Module
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static Frac[] FaulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; for (int i = 0; i < p + 1; i++) { coeffs[i] = Frac.ZERO; } Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); } return coeffs; } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Frac[] coeffs = FaulhaberTriangle(i); foreach (Frac coeff in coeffs) { Console.Write("{0,5} ", coeff); } Console.WriteLine(); } } } }
Translate this program into C# but keep the logic exactly as in VB.
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Convert the following code from VB to C#, ensuring the logic remains intact.
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Ensure the translated C# code behaves exactly like the original VB snippet.
DEFINT A(1 to 4) = {1, 2, 3, 4} DEFINT B(1 to 4) = {10, 20, 30, 40} Redim A(1 to 8) as integer MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
using System; namespace C_Sharp_Console { class example { static void Main() { string word; int num; Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.ReadLine(); } } }
Produce a language-to-language conversion: from VB to C#, same semantics.
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _ "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _ "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _ "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
using System; using System.Collections.Generic; namespace Tests_With_Framework_4 { class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400; public Bag() { items = new List<Item>(); } void AddItem(Item i) { if ((TotalWeight + i.Weight) <= MaxWeightAllowed) items.Add(i); } public void Calculate(List<Item> items) { foreach (Item i in Sorte(items)) { AddItem(i); } } List<Item> Sorte(List<Item> inputItems) { List<Item> choosenItems = new List<Item>(); for (int i = 0; i < inputItems.Count; i++) { int j = -1; if (i == 0) { choosenItems.Add(inputItems[i]); } if (i > 0) { if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j)) { choosenItems.Add(inputItems[i]); } } } return choosenItems; } bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd) { if (!(lastBound < 0)) { if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV ) { indxToAdd = lastBound; } return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd); } if (indxToAdd > -1) { choosenItems.Insert(indxToAdd, knapsackItems[i]); return true; } return false; } #region IEnumerable<Item> Members IEnumerator<Item> IEnumerable<Item>.GetEnumerator() { foreach (Item i in items) yield return i; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return items.GetEnumerator(); } #endregion public int TotalWeight { get { var sum = 0; foreach (Item i in this) { sum += i.Weight; } return sum; } } public class Item { public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } } public override string ToString() { return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV; } } } class Program { static void Main(string[] args) {List<Bag.Item> knapsackItems = new List<Bag.Item>(); knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 }); knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 }); knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 }); knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 }); knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 }); knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 }); knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 }); knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 }); knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 }); knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 }); knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 }); Bag b = new Bag(); b.Calculate(knapsackItems); b.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine(b.Sum(x => x.Weight)); Console.ReadKey(); } } }
Convert the following code from VB to C#, ensuring the logic remains intact.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Generate an equivalent C# version of this VB code.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Translate this program into C# but keep the logic exactly as in VB.
dim _proper_divisors(100) sub proper_divisors(n) dim i dim _proper_divisors_count = 0 if n <> 1 then for i = 1 to (n \ 2) if n %% i = 0 then _proper_divisors_count = _proper_divisors_count + 1 _proper_divisors(_proper_divisors_count) = i end if next end if return _proper_divisors_count end sub sub show_proper_divisors(n, tabbed) dim cnt = proper_divisors(n) print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) "; dim j for j = 1 to cnt if tabbed then print str$(_proper_divisors(j)), else print str$(_proper_divisors(j)); end if if (j < cnt) then print ","; next print end sub dim i for i = 1 to 10 show_proper_divisors(i, false) next dim c dim maxindex = 0 dim maxlength = 0 for t = 1 to 20000 c = proper_divisors(t) if c > maxlength then maxindex = t maxlength = c end if next print "A maximum at "; show_proper_divisors(maxindex, false)
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
Module XMLOutput Sub Main() Dim charRemarks As New Dictionary(Of String, String) charRemarks.Add("April", "Bubbly: I charRemarks.Add("Tam O charRemarks.Add("Emily", "Short & shrift") Dim xml = <CharacterRemarks> <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %> </CharacterRemarks> Console.WriteLine(xml) End Sub End Module
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Program { static string CreateXML(Dictionary<string, string> characterRemarks) { var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key))); var xml = new XElement("CharacterRemarks", remarks); return xml.ToString(); } static void Main(string[] args) { var characterRemarks = new Dictionary<string, string> { { "April", "Bubbly: I'm > Tam and <= Emily" }, { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" }, { "Emily", "Short & shrift" } }; string xml = CreateXML(characterRemarks); Console.WriteLine(xml); } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
text = "I need more coffee!!!" Set regex = New RegExp regex.Global = True regex.Pattern = "\s" If regex.Test(text) Then WScript.StdOut.Write regex.Replace(text,vbCrLf) Else WScript.StdOut.Write "No matching pattern" End If
using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string str = "I am a string"; if (new Regex("string$").IsMatch(str)) { Console.WriteLine("Ends with string."); } str = new Regex(" a ").Replace(str, " another "); Console.WriteLine(str); } }
Transform the following VB implementation into C#, maintaining the same output and logic.
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
static class Program { static void Main() { System.Collections.Hashtable h = new System.Collections.Hashtable(); string[] keys = { "foo", "bar", "val" }; string[] values = { "little", "miss", "muffet" }; System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); for (int i = 0; i < keys.Length; i++) { h.Add(keys[i], values[i]); } } }
Convert the following code from VB to C#, ensuring the logic remains intact.
option explicit const dt = 0.15 const length=23 dim ans0:ans0=chr(27)&"[" dim Veloc,Accel,angle,olr,olc,r,c const r0=1 const c0=40 cls angle=0.7 while 1 wscript.sleep(50) Accel = -.9 * sin(Angle) Veloc = Veloc + Accel * dt Angle = Angle + Veloc * dt r = r0 + int(cos(Angle) * Length) c = c0+ int(2*sin(Angle) * Length) cls draw_line r,c,r0,c0 toxy r,c,"O" olr=r :olc=c wend sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub Sub draw_line(r1,c1, r2,c2) Dim x,y,xf,yf,dx,dy,sx,sy,err,err2 x =r1 : y =c1 xf=r2 : yf=c2 dx=Abs(xf-x) : dy=Abs(yf-y) If x<xf Then sx=+1: Else sx=-1 If y<yf Then sy=+1: Else sy=-1 err=dx-dy Do toxy x,y,"." If x=xf And y=yf Then Exit Do err2=err+err If err2>-dy Then err=err-dy: x=x+sx If err2< dx Then err=err+dx: y=y+sy Loop End Sub
using System; using System.Drawing; using System.Windows.Forms; class CSharpPendulum { Form _form; Timer _timer; double _angle = Math.PI / 2, _angleAccel, _angleVelocity = 0, _dt = 0.1; int _length = 50; [STAThread] static void Main() { var p = new CSharpPendulum(); } public CSharpPendulum() { _form = new Form() { Text = "Pendulum", Width = 200, Height = 200 }; _timer = new Timer() { Interval = 30 }; _timer.Tick += delegate(object sender, EventArgs e) { int anchorX = (_form.Width / 2) - 12, anchorY = _form.Height / 4, ballX = anchorX + (int)(Math.Sin(_angle) * _length), ballY = anchorY + (int)(Math.Cos(_angle) * _length); _angleAccel = -9.81 / _length * Math.Sin(_angle); _angleVelocity += _angleAccel * _dt; _angle += _angleVelocity * _dt; Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height); Graphics g = Graphics.FromImage(dblBuffer); Graphics f = Graphics.FromHwnd(_form.Handle); g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY)); g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7); g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14); f.Clear(Color.White); f.DrawImage(dblBuffer, new Point(0, 0)); }; _timer.Start(); Application.Run(_form); } }
Convert this VB block to C#, preserving its control flow and logic.
class playingcard dim suit dim pips end class class carddeck private suitnames private pipnames private cardno private deck(52) private nTop sub class_initialize dim suit dim pips suitnames = split("H,D,C,S",",") pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") cardno = 0 for suit = 1 to 4 for pips = 1 to 13 set deck(cardno) = new playingcard deck(cardno).suit = suitnames(suit-1) deck(cardno).pips = pipnames(pips-1) cardno = cardno + 1 next next nTop = 0 end sub public sub showdeck dim a redim a(51-nTop) for i = nTop to 51 a(i) = deck(i).pips & deck(i).suit next wscript.echo join( a, ", ") end sub public sub shuffle dim r randomize timer for i = nTop to 51 r = int( rnd * ( 52 - nTop ) ) if r <> i then objswap deck(i),deck(r) end if next end sub public function deal() set deal = deck( nTop ) nTop = nTop + 1 end function public property get cardsRemaining cardsRemaining = 52 - nTop end property private sub objswap( a, b ) dim tmp set tmp = a set a = b set b = tmp end sub end class
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"; } public class Deck : IEnumerable<Card> { static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; readonly List<Card> cards; public Deck() { cards = (from suit in suits from rank in ranks select new Card(rank, suit)).ToList(); } public int Count => cards.Count; public void Shuffle() { var random = new Random(); for (int i = 0; i < cards.Count; i++) { int r = random.Next(i, cards.Count); var temp = cards[i]; cards[i] = cards[r]; cards[r] = temp; } } public Card Deal() { int last = cards.Count - 1; Card card = cards[last]; cards.RemoveAt(last); return card; } public IEnumerator<Card> GetEnumerator() { for (int i = cards.Count - 1; i >= 0; i--) yield return cards[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); }
Convert the following code from VB to C#, ensuring the logic remains intact.
Const Order = 4 Function InCarpet(ByVal x As Integer, ByVal y As Integer) Do While x <> 0 And y <> 0 If x Mod 3 = 1 And y Mod 3 = 1 Then InCarpet = " " Exit Function End If x = x \ 3 y = y \ 3 Loop InCarpet = "#" End Function Public Sub sierpinski_carpet() Dim i As Integer, j As Integer For i = 0 To 3 ^ Order - 1 For j = 0 To 3 ^ Order - 1 Debug.Print InCarpet(i, j); Next j Debug.Print Next i End Sub
using System; using System.Collections.Generic; using System.Linq; class Program { static List<string> NextCarpet(List<string> carpet) { return carpet.Select(x => x + x + x) .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x)) .Concat(carpet.Select(x => x + x + x)).ToList(); } static List<string> SierpinskiCarpet(int n) { return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet)); } static void Main(string[] args) { foreach (string s in SierpinskiCarpet(3)) Console.WriteLine(s); } }
Generate a C# translation of this VB snippet without changing its computational steps.
Private Function Knuth(a As Variant) As Variant Dim t As Variant, i As Integer If Not IsMissing(a) Then For i = UBound(a) To LBound(a) + 1 Step -1 j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a)) t = a(i) a(i) = a(j) a(j) = t Next i End If Knuth = a End Function Private Function inOrder(s As Variant) i = 2 Do While i <= UBound(s) If s(i) < s(i - 1) Then inOrder = False Exit Function End If i = i + 1 Loop inOrder = True End Function Private Function bogosort(ByVal s As Variant) As Variant Do While Not inOrder(s) Debug.Print Join(s, ", ") s = Knuth(s) Loop bogosort = s End Function Public Sub main() Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ") End Sub
using System; using System.Collections.Generic; namespace RosettaCode.BogoSort { public static class BogoSorter { public static void Sort<T>(List<T> list) where T:IComparable { while (!list.isSorted()) { list.Shuffle(); } } private static bool isSorted<T>(this IList<T> list) where T:IComparable { if(list.Count<=1) return true; for (int i = 1 ; i < list.Count; i++) if(list[i].CompareTo(list[i-1])<0) return false; return true; } private static void Shuffle<T>(this IList<T> list) { Random rand = new Random(); for (int i = 0; i < list.Count; i++) { int swapIndex = rand.Next(list.Count); T temp = list[swapIndex]; list[swapIndex] = list[i]; list[i] = temp; } } } class TestProgram { static void Main() { List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 }; BogoSorter.Sort(testList); foreach (int i in testList) Console.Write(i + " "); } } }
Transform the following VB implementation into C#, maintaining the same output and logic.
Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer) Dim t As Integer Debug.Print " Step "; step; ": ", Do While t <= end_t If t Mod 10 = 0 Then Debug.Print Format(y, "0.000"), y = y + step * Application.Run(f, y) t = t + step Loop Debug.Print End Sub Sub analytic() Debug.Print " Time: ", For t = 0 To 100 Step 10 Debug.Print " "; t, Next t Debug.Print Debug.Print "Analytic: ", For t = 0 To 100 Step 10 Debug.Print Format(20 + 80 * Exp(-0.07 * t), "0.000"), Next t Debug.Print End Sub Private Function cooling(temp As Double) As Double cooling = -0.07 * (temp - 20) End Function Public Sub euler_method() Dim r_cooling As String r_cooling = "cooling" analytic ivp_euler r_cooling, 100, 2, 100 ivp_euler r_cooling, 100, 5, 100 ivp_euler r_cooling, 100, 10, 100 End Sub
using System; namespace prog { class MainClass { const float T0 = 100f; const float TR = 20f; const float k = 0.07f; readonly static float[] delta_t = {2.0f,5.0f,10.0f}; const int n = 100; public delegate float func(float t); static float NewtonCooling(float t) { return -k * (t-TR); } public static void Main (string[] args) { func f = new func(NewtonCooling); for(int i=0; i<delta_t.Length; i++) { Console.WriteLine("delta_t = " + delta_t[i]); Euler(f,T0,n,delta_t[i]); } } public static void Euler(func f, float y, int n, float h) { for(float x=0; x<=n; x+=h) { Console.WriteLine("\t" + x + "\t" + y); y += h * f(y); } } } }
Preserve the algorithm and functionality while converting the code from VB to C#.
Sub Main() Dim i&, c&, j#, s$ Const N& = 1000000 s = "values for n in the range 1 to 22 : " For i = 1 To 22 s = s & ns(i) & ", " Next For i = 1 To N j = Sqr(ns(i)) If j = CInt(j) Then c = c + 1 Next Debug.Print s Debug.Print c & " squares less than " & N End Sub Private Function ns(l As Long) As Long ns = l + Int(1 / 2 + Sqr(l)) End Function
using System; using System.Diagnostics; namespace sons { class Program { static void Main(string[] args) { for (int i = 1; i < 23; i++) Console.WriteLine(nonsqr(i)); for (int i = 1; i < 1000000; i++) { double j = Math.Sqrt(nonsqr(i)); Debug.Assert(j != Math.Floor(j),"Square"); } } static int nonsqr(int i) { return (int)(i + Math.Floor(0.5 + Math.Sqrt(i))); } } }
Produce a functionally identical C# code for the snippet given in VB.
Public Sub substring() sentence = "the last thing the man said was the" n = 10: m = 5 Debug.Print Mid(sentence, n, 5) Debug.Print Right(sentence, Len(sentence) - n + 1) Debug.Print Left(sentence, Len(sentence) - 1) k = InStr(1, sentence, "m") Debug.Print Mid(sentence, k, 5) k = InStr(1, sentence, "aid") Debug.Print Mid(sentence, k, 5) End Sub
using System; namespace SubString { class Program { static void Main(string[] args) { string s = "0123456789"; const int n = 3; const int m = 2; const char c = '3'; const string z = "345"; Console.WriteLine(s.Substring(n, m)); Console.WriteLine(s.Substring(n, s.Length - n)); Console.WriteLine(s.Substring(0, s.Length - 1)); Console.WriteLine(s.Substring(s.IndexOf(c), m)); Console.WriteLine(s.Substring(s.IndexOf(z), m)); } } }
Write a version of this VB function in C# with identical behavior.
Function JortSort(s) JortSort = True arrPreSort = Split(s,",") Set arrSorted = CreateObject("System.Collections.ArrayList") For i = 0 To UBound(arrPreSort) arrSorted.Add(arrPreSort(i)) Next arrSorted.Sort() For j = 0 To UBound(arrPreSort) If arrPreSort(j) <> arrSorted(j) Then JortSort = False Exit For End If Next End Function WScript.StdOut.Write JortSort("1,2,3,4,5") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("1,2,3,5,4") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,b,c") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,c,b")
using System; class Program { public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T> { T[] originalArray = (T[]) array.Clone(); Array.Sort(array); for (var i = 0; i < originalArray.Length; i++) { if (!Equals(originalArray[i], array[i])) { return false; } } return true; } }
Maintain the same structure and functionality when rewriting this code in C#.
Public Function Leap_year(year As Integer) As Boolean Leap_year = (Month(DateSerial(year, 2, 29)) = 2) End Function
using System; class Program { static void Main() { foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year }) { Console.WriteLine("{0} is {1}a leap year.", year, DateTime.IsLeapYear(year) ? string.Empty : "not "); } } }
Convert this VB block to C#, preserving its control flow and logic.
Public Function sortlexicographically(N As Integer) Dim arrList As Object Set arrList = CreateObject("System.Collections.ArrayList") For i = 1 To N arrList.Add CStr(i) Next i arrList.Sort Dim item As Variant For Each item In arrList Debug.Print item & ", "; Next End Function Public Sub main() Call sortlexicographically(13) End Sub
using static System.Console; using static System.Linq.Enumerable; public class Program { public static void Main() { foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}"); } public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString()); }
Write a version of this VB function in C# with identical behavior.
Public twenties As Variant Public decades As Variant Public orders As Variant Private Sub init() twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}] decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}] orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}] End Sub Private Function Twenty(N As Variant) Twenty = twenties(N Mod 20 + 1) End Function Private Function Decade(N As Variant) Decade = decades(N Mod 10 - 1) End Function Private Function Hundred(N As Variant) If N < 20 Then Hundred = Twenty(N) Exit Function Else If N Mod 10 = 0 Then Hundred = Decade((N \ 10) Mod 10) Exit Function End If End If Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10) End Function Private Function Thousand(N As Variant, withand As String) If N < 100 Then Thousand = withand & Hundred(N) Exit Function Else If N Mod 100 = 0 Then Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred" Exit Function End If End If Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100) End Function Private Function Triplet(N As Variant) Dim Order, High As Variant, Low As Variant Dim Name As String, res As String For i = 1 To UBound(orders) Order = orders(i, 1) Name = orders(i, 2) High = WorksheetFunction.Floor_Precise(N / Order) Low = N - High * Order If High <> 0 Then res = res & Thousand(High, "") & " " & Name End If N = Low If Low = 0 Then Exit For If Len(res) And High <> 0 Then res = res & ", " End If Next i If N <> 0 Or res = "" Then res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and ")) N = N - Int(N) If N > 0.000001 Then res = res & " point" For i = 1 To 10 n_ = WorksheetFunction.Floor_Precise(N * 10.0000001) res = res & " " & twenties(n_ + 1) N = N * 10 - n_ If Abs(N) < 0.000001 Then Exit For Next i End If End If Triplet = res End Function Private Function spell(N As Variant) Dim res As String If N < 0 Then res = "minus " N = -N End If res = res & Triplet(N) spell = res End Function Private Function smartp(N As Variant) Dim res As String If N = WorksheetFunction.Floor_Precise(N) Then smartp = CStr(N) Exit Function End If res = CStr(N) If InStr(1, res, ".") Then res = Left(res, InStr(1, res, ".")) End If smartp = res End Function Sub Main() Dim si As Variant init Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}] Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}] For i = 1 To UBound(Samples1) si = Samples1(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i For i = 1 To UBound(Samples2) si = Samples2(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i End Sub
using System; class NumberNamer { static readonly string[] incrementsOfOne = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; static readonly string[] incrementsOfTen = { "", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const string millionName = "million", thousandName = "thousand", hundredName = "hundred", andName = "and"; public static string GetName( int i ) { string output = ""; if( i >= 1000000 ) { output += ParseTriplet( i / 1000000 ) + " " + millionName; i %= 1000000; if( i == 0 ) return output; } if( i >= 1000 ) { if( output.Length > 0 ) { output += ", "; } output += ParseTriplet( i / 1000 ) + " " + thousandName; i %= 1000; if( i == 0 ) return output; } if( output.Length > 0 ) { output += ", "; } output += ParseTriplet( i ); return output; } static string ParseTriplet( int i ) { string output = ""; if( i >= 100 ) { output += incrementsOfOne[i / 100] + " " + hundredName; i %= 100; if( i == 0 ) return output; } if( output.Length > 0 ) { output += " " + andName + " "; } if( i >= 20 ) { output += incrementsOfTen[i / 10]; i %= 10; if( i == 0 ) return output; } if( output.Length > 0 ) { output += " "; } output += incrementsOfOne[i]; return output; } } class Program { static void Main( string[] args ) { Console.WriteLine( NumberNamer.GetName( 1 ) ); Console.WriteLine( NumberNamer.GetName( 234 ) ); Console.WriteLine( NumberNamer.GetName( 31337 ) ); Console.WriteLine( NumberNamer.GetName( 987654321 ) ); } }
Maintain the same structure and functionality when rewriting this code in C#.
TYPE regChar Character AS STRING * 3 Count AS LONG END TYPE DIM iChar AS INTEGER DIM iCL AS INTEGER DIM iCountChars AS INTEGER DIM iFile AS INTEGER DIM i AS INTEGER DIM lMUC AS LONG DIM iMUI AS INTEGER DIM lLUC AS LONG DIM iLUI AS INTEGER DIM iMaxIdx AS INTEGER DIM iP AS INTEGER DIM iPause AS INTEGER DIM iPMI AS INTEGER DIM iPrint AS INTEGER DIM lHowMany AS LONG DIM lTotChars AS LONG DIM sTime AS SINGLE DIM strFile AS STRING DIM strTxt AS STRING DIM strDate AS STRING DIM strTime AS STRING DIM strKey AS STRING CONST LngReg = 256 CONST Letters = 1 CONST FALSE = 0 CONST TRUE = NOT FALSE strDate = DATE$ strTime = TIME$ iFile = FREEFILE DO CLS PRINT "This program counts letters or characters in a text file." PRINT INPUT "File to open: ", strFile OPEN strFile FOR BINARY AS #iFile IF LOF(iFile) > 0 THEN PRINT "Count: 1) Letters 2) Characters (1 or 2)"; DO strKey = INKEY$ LOOP UNTIL strKey = "1" OR strKey = "2" PRINT ". Option selected: "; strKey iCL = VAL(strKey) sTime = TIMER iP = POS(0) lHowMany = LOF(iFile) strTxt = SPACE$(LngReg) IF iCL = Letters THEN iMaxIdx = 26 ELSE iMaxIdx = 255 END IF IF iMaxIdx <> iPMI THEN iPMI = iMaxIdx REDIM rChar(0 TO iMaxIdx) AS regChar FOR i = 0 TO iMaxIdx IF iCL = Letters THEN strTxt = CHR$(i + 65) IF i = 26 THEN strTxt = CHR$(165) ELSE SELECT CASE i CASE 0: strTxt = "nul" CASE 7: strTxt = "bel" CASE 9: strTxt = "tab" CASE 10: strTxt = "lf" CASE 11: strTxt = "vt" CASE 12: strTxt = "ff" CASE 13: strTxt = "cr" CASE 28: strTxt = "fs" CASE 29: strTxt = "gs" CASE 30: strTxt = "rs" CASE 31: strTxt = "us" CASE 32: strTxt = "sp" CASE ELSE: strTxt = CHR$(i) END SELECT END IF rChar(i).Character = strTxt NEXT i ELSE FOR i = 0 TO iMaxIdx rChar(i).Count = 0 NEXT i END IF PRINT "Looking for "; IF iCL = Letters THEN PRINT "letters."; ELSE PRINT "characters."; PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7) DO WHILE LOC(iFile) < LOF(iFile) IF LOC(iFile) + LngReg > LOF(iFile) THEN strTxt = SPACE$(LOF(iFile) - LOC(iFile)) END IF GET #iFile, , strTxt FOR i = 1 TO LEN(strTxt) IF iCL = Letters THEN iChar = ASC(UCASE$(MID$(strTxt, i, 1))) SELECT CASE iChar CASE 164: iChar = 165 CASE 160: iChar = 65 CASE 130, 144: iChar = 69 CASE 161: iChar = 73 CASE 162: iChar = 79 CASE 163, 129: iChar = 85 END SELECT iChar = iChar - 65 IF iChar >= 0 AND iChar <= 25 THEN rChar(iChar).Count = rChar(iChar).Count + 1 ELSEIF iChar = 100 THEN rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1 END IF ELSE iChar = ASC(MID$(strTxt, i, 1)) rChar(iChar).Count = rChar(iChar).Count + 1 END IF NEXT i LOOP CLOSE #iFile lMUC = 0 iMUI = 0 lLUC = 2147483647 iLUI = 0 iPrint = FALSE lTotChars = 0 iCountChars = 0 iPause = FALSE CLS IF iCL = Letters THEN PRINT "Letters found: "; ELSE PRINT "Characters found: "; FOR i = 0 TO iMaxIdx IF lMUC < rChar(i).Count THEN lMUC = rChar(i).Count iMUI = i END IF IF rChar(i).Count > 0 THEN strTxt = "" IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character)) strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count)) iP = POS(0) IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN PRINT "," IF CSRLIN >= 23 AND NOT iPause THEN iPause = TRUE PRINT "Press a key to continue..." DO strKey = INKEY$ LOOP UNTIL strKey <> "" END IF strTxt = MID$(strTxt, 3) END IF PRINT strTxt; lTotChars = lTotChars + rChar(i).Count iCountChars = iCountChars + 1 IF lLUC > rChar(i).Count THEN lLUC = rChar(i).Count iLUI = i END IF END IF NEXT i PRINT "." PRINT PRINT "File analyzed....................: "; strFile PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters" PRINT "Total characters in file.........:"; lHowMany PRINT "Total characters counted.........:"; lTotChars IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1 PRINT "Most used character was..........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lMUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)" PRINT "Least used character was.........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lLUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)" PRINT "Time spent in the process........:"; TIMER - sTime; "seconds" ELSE CLOSE #iFile KILL strFile PRINT PRINT "File does not exist." END IF PRINT PRINT "Again? (Y/n)" DO strTxt = UCASE$(INKEY$) LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27) LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27) CLS PRINT "End of execution." PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "." END
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items) { var dictionary = new SortedDictionary<TItem, int>(); foreach (var item in items) { if (dictionary.ContainsKey(item)) { dictionary[item]++; } else { dictionary[item] = 1; } } return dictionary; } static void Main(string[] arguments) { var file = arguments.FirstOrDefault(); if (File.Exists(file)) { var text = File.ReadAllText(file); foreach (var entry in GetFrequencies(text)) { Console.WriteLine("{0}: {1}", entry.Key, entry.Value); } } } }
Write a version of this VB function in C# with identical behavior.
Dim s As String = "123" s = CStr(CInt("123") + 1) s = (CInt("123") + 1).ToString
string s = "12345"; s = (int.Parse(s) + 1).ToString(); using System.Numerics; string bis = "123456789012345678999999999"; bis = (BigInteger.Parse(bis) + 1).ToString();
Translate this program into C# but keep the logic exactly as in VB.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
using System; public static string RemoveCharactersFromString(string testString, string removeChars) { char[] charAry = removeChars.ToCharArray(); string returnString = testString; foreach (char c in charAry) { while (returnString.IndexOf(c) > -1) { returnString = returnString.Remove(returnString.IndexOf(c), 1); } } return returnString; }
Convert this VB snippet to C# and keep its semantics consistent.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
using System; public static string RemoveCharactersFromString(string testString, string removeChars) { char[] charAry = removeChars.ToCharArray(); string returnString = testString; foreach (char c in charAry) { while (returnString.IndexOf(c) > -1) { returnString = returnString.Remove(returnString.IndexOf(c), 1); } } return returnString; }
Convert this VB snippet to C# and keep its semantics consistent.
Private Function mean(v() As Double, ByVal leng As Integer) As Variant Dim sum As Double, i As Integer sum = 0: i = 0 For i = 0 To leng - 1 sum = sum + vv Next i If leng = 0 Then mean = CVErr(xlErrDiv0) Else mean = sum / leng End If End Function Public Sub main() Dim v(4) As Double Dim i As Integer, leng As Integer v(0) = 1# v(1) = 2# v(2) = 2.178 v(3) = 3# v(4) = 3.142 For leng = 5 To 0 Step -1 Debug.Print "mean["; For i = 0 To leng - 1 Debug.Print IIf(i, "; " & v(i), "" & v(i)); Next i Debug.Print "] = "; mean(v, leng) Next leng End Sub
using System; using System.Linq; class Program { static void Main() { Console.WriteLine(new[] { 1, 2, 3 }.Average()); } }
Port the following code from VB to C# with equivalent syntax and logic.
Private Function tokenize(s As String, sep As String, esc As String) As Collection Dim ret As New Collection Dim this As String Dim skip As Boolean If Len(s) <> 0 Then For i = 1 To Len(s) si = Mid(s, i, 1) If skip Then this = this & si skip = False Else If si = esc Then skip = True Else If si = sep Then ret.Add this this = "" Else this = this & si End If End If End If Next i ret.Add this End If Set tokenize = ret End Function Public Sub main() Dim out As Collection Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") Dim outstring() As String ReDim outstring(out.Count - 1) For i = 0 To out.Count - 1 outstring(i) = out(i + 1) Next i Debug.Print Join(outstring, ", ") End Sub
using System; using System.Text; using System.Collections.Generic; public class TokenizeAStringWithEscaping { public static void Main() { string testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) { Console.WriteLine(": " + token); } } } public static class Extensions { public static IEnumerable<string> Tokenize(this string input, char separator, char escape) { if (input == null) yield break; var buffer = new StringBuilder(); bool escaping = false; foreach (char c in input) { if (escaping) { buffer.Append(c); escaping = false; } else if (c == escape) { escaping = true; } else if (c == separator) { yield return buffer.Flush(); } else { buffer.Append(c); } } if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush(); } public static string Flush(this StringBuilder stringBuilder) { string result = stringBuilder.ToString(); stringBuilder.Clear(); return result; } }
Translate this program into C# but keep the logic exactly as in VB.
Public Sub hello_world_text Debug.Print "Hello World!" End Sub
Using System; namespace HelloWorld { class Program { static void Main() { Console.Writeln("Hello World!"); } } }
Rewrite the snippet below in C# so it works the same as the original VB code.
Module ForwardDifference Sub Main() Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}) For i As UInteger = 0 To 9 Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray())) Next Console.ReadKey() End Sub Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer) If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers") For i As Integer = 1 To Level Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _ Select Numbers(n + 1) - Numbers(n)).ToList() Next Return Numbers End Function End Module
using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u) { switch (order) { case 0u: return sequence; case 1u: return sequence.Skip(1).Zip(sequence, (next, current) => next - current); default: return ForwardDifference(ForwardDifference(sequence), order - 1u); } } static void Main() { IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 }; do { Console.WriteLine(string.Join(", ", sequence)); } while ((sequence = ForwardDifference(sequence)).Any()); } }
Convert this VB snippet to C# and keep its semantics consistent.
Option Explicit Sub FirstTwentyPrimes() Dim count As Integer, i As Long, t(19) As String Do i = i + 1 If IsPrime(i) Then t(count) = i count = count + 1 End If Loop While count <= UBound(t) Debug.Print Join(t, ", ") End Sub Function IsPrime(Nb As Long) As Boolean If Nb = 2 Then IsPrime = True ElseIf Nb < 2 Or Nb Mod 2 = 0 Then Exit Function Else Dim i As Long For i = 3 To Sqr(Nb) Step 2 If Nb Mod i = 0 Then Exit Function Next IsPrime = True End If End Function
static bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; }
Write the same code in C# as shown below in VB.
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
using System; namespace BinomialCoefficients { class Program { static void Main(string[] args) { ulong n = 1000000, k = 3; ulong result = biCoefficient(n, k); Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result); Console.ReadLine(); } static int fact(int n) { if (n == 0) return 1; else return n * fact(n - 1); } static ulong biCoefficient(ulong n, ulong k) { if (k > n - k) { k = n - k; } ulong c = 1; for (uint i = 0; i < k; i++) { c = c * (n - i); c = c / (i + 1); } return c; } } }
Write the same code in C# as shown below in VB.
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
using System; namespace BinomialCoefficients { class Program { static void Main(string[] args) { ulong n = 1000000, k = 3; ulong result = biCoefficient(n, k); Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result); Console.ReadLine(); } static int fact(int n) { if (n == 0) return 1; else return n * fact(n - 1); } static ulong biCoefficient(ulong n, ulong k) { if (k > n - k) { k = n - k; } ulong c = 1; for (uint i = 0; i < k; i++) { c = c * (n - i); c = c / (i + 1); } return c; } } }
Change the following VB code into C# without altering its purpose.
Dim coll As New Collection coll.Add "apple" coll.Add "banana"
int[] intArray = new int[5] { 1, 2, 3, 4, 5 }; int[] intArray = new int[]{ 1, 2, 3, 4, 5 }; int[] intArray = { 1, 2, 3, 4, 5 }; string[] stringArr = new string[5]; stringArr[0] = "string";
Ensure the translated C# code behaves exactly like the original VB snippet.
Private Sub Iterate(ByVal list As LinkedList(Of Integer)) Dim node = list.First Do Until node Is Nothing node = node.Next Loop End Sub
var current = [head of list to traverse] while(current != null) { current = current.Next; }
Convert this VB snippet to C# and keep its semantics consistent.
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Keep all operations the same but rewrite the snippet in C#.
Option Explicit Sub DeleteFileOrDirectory() Dim myPath As String myPath = "C:\Users\surname.name\Desktop\Docs" Kill myPath & "\input.txt" RmDir myPath End Sub
using System; using System.IO; namespace DeleteFile { class Program { static void Main() { File.Delete("input.txt"); Directory.Delete("docs"); File.Delete("/input.txt"); Directory.Delete("/docs"); } } }
Change the following VB code into C# without altering its purpose.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
public class AverageLoopLength { private static int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.Next(n); } var seen = new HashSet<double>(n); int current = 0; int length = 0; while (seen.Add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void Main(string[] args) { Console.WriteLine(" N average analytical (error)"); Console.WriteLine("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { var average = AverageLoopLength.average(i); var analytical = AverageLoopLength.analytical(i); Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100); } } }
Preserve the algorithm and functionality while converting the code from VB to C#.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
public class AverageLoopLength { private static int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.Next(n); } var seen = new HashSet<double>(n); int current = 0; int length = 0; while (seen.Add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void Main(string[] args) { Console.WriteLine(" N average analytical (error)"); Console.WriteLine("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { var average = AverageLoopLength.average(i); var analytical = AverageLoopLength.analytical(i); Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100); } } }
Write a version of this VB function in C# with identical behavior.
Dim name as String = "J. Doe" Dim balance as Double = 123.45 Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance) Console.WriteLine(prompt)
class Program { static void Main() { string extra = "little"; string formatted = $"Mary had a {extra} lamb."; System.Console.WriteLine(formatted); } }
Port the following code from VB to C# with equivalent syntax and logic.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
Port the following code from VB to C# with equivalent syntax and logic.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
Generate a C# translation of this VB snippet without changing its computational steps.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
Write a version of this VB function in C# with identical behavior.
Imports System.IO Module Notes Function Main(ByVal cmdArgs() As String) As Integer Try If cmdArgs.Length = 0 Then Using sr As New StreamReader("NOTES.TXT") Console.WriteLine(sr.ReadToEnd) End Using Else Using sw As New StreamWriter("NOTES.TXT", True) sw.WriteLine(Date.Now.ToString()) sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs)) End Using End If Catch End Try End Function End Module
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
Public Function CommonDirectoryPath(ParamArray Paths()) As String Dim v As Variant Dim Path() As String, s As String Dim i As Long, j As Long, k As Long Const PATH_SEPARATOR As String = "/" For Each v In Paths ReDim Preserve Path(0 To i) Path(i) = v i = i + 1 Next v k = 1 Do For i = 0 To UBound(Path) If i Then If InStr(k, Path(i), PATH_SEPARATOR) <> j Then Exit Do ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then Exit Do End If Else j = InStr(k, Path(i), PATH_SEPARATOR) If j = 0 Then Exit Do End If End If Next i s = Left$(Path(0), j + CLng(k <> 1)) k = j + 1 Loop CommonDirectoryPath = s End Function Sub Main() Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/home/user1/tmp" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members", _ "/home/user1/abc/coven/members") = _ "/home/user1" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/hope/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/" End Sub
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( ); foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } } return CommonPath; } } }
Produce a functionally identical C# code for the snippet given in VB.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
Port the following code from VB to C# with equivalent syntax and logic.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
Produce a functionally identical Go code for the snippet given in Python.
def bitwise_built_ins(width, a, b): mask = (1 << width) - 1 print(f) def rotr(width, a, n): "Rotate a, n times to the right" if n < 0: return rotl(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return ((a >> n) | ((a & ((1 << n) - 1)) << (width - n))) def rotl(width, a, n): "Rotate a, n times to the left" if n < 0: return rotr(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return (((a << n) & mask) | (a >> (width - n))) def asr(width, a, n): "Arithmetic shift a, n times to the right. (sign preserving)." mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) if n < 0: return (a << -n) & mask elif n == 0: return a elif n >= width: return mask if a & top_bit_mask else 0 else: a = a & mask if a & top_bit_mask: signs = (1 << n) - 1 return a >> n | (signs << width - n) else: return a >> n def helper_funcs(width, a): mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) aa = a | top_bit_mask print(f) if __name__ == '__main__': bitwise_built_ins(8, 27, 125) helper_funcs(8, 27)
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
Write a version of this Python function in Go with identical behavior.
l = 3 ints = 13 def setup(): size(700, 600) background(0, 0, 255) translate(150, 100) stroke(255) turn_left(l, ints) turn_right(l, ints) def turn_right(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(90)) turn_right(l, ints - 1) def turn_left(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(-90)) turn_right(l, ints - 1)
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) const sep = 512 const depth = 14 var s = math.Sqrt2 / 2 var sin = []float64{0, s, 1, s, 0, -s, -1, -s} var cos = []float64{1, s, 0, -s, -1, -s, 0, s} var p = color.NRGBA{64, 192, 96, 255} var b *image.NRGBA func main() { width := sep * 11 / 6 height := sep * 4 / 3 bounds := image.Rect(0, 0, width, height) b = image.NewNRGBA(bounds) draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src) dragon(14, 0, 1, sep, sep/2, sep*5/6) f, err := os.Create("dragon.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, b); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } } func dragon(n, a, t int, d, x, y float64) { if n <= 1 { x1 := int(x + .5) y1 := int(y + .5) x2 := int(x + d*cos[a] + .5) y2 := int(y + d*sin[a] + .5) xInc := 1 if x1 > x2 { xInc = -1 } yInc := 1 if y1 > y2 { yInc = -1 } for x, y := x1, y1; ; x, y = x+xInc, y+yInc { b.Set(x, y, p) if x == x2 { break } } return } d *= s a1 := (a - t) & 7 a2 := (a + t) & 7 dragon(n-1, a1, 1, d, x, y) dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1]) }
Write a version of this Python function in Go with identical behavior.
for line in lines open('input.txt'): print line
package main import ( "bufio" "fmt" "log" "os" ) func init() { log.SetFlags(log.Lshortfile) } func main() { inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) } defer inputFile.Close() scanner := bufio.NewScanner(inputFile) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(scanner.Err()) } }
Write the same algorithm in Go as shown in this Python implementation.
def insert(anchor, new): new.next = anchor.next new.prev = anchor anchor.next.prev = new anchor.next = new
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) }
Generate a Go translation of this Python snippet without changing its computational steps.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def digit_check(n): if len(str(n))<2: return True else: for digit in str(n): if not is_prime(int(digit)): return False return True def sequence(max_n=None): ii = 0 n = 0 while True: ii += 1 if is_prime(ii): if max_n is not None: if n>max_n: break if digit_check(ii): n += 1 yield ii if __name__ == '__main__': generator = sequence(100) for index, item in zip(range(1, 16), generator): print(index, item) for index, item in zip(range(16, 100), generator): pass print(100, generator.__next__())
package main import ( "fmt" "math/big" ) var b = new(big.Int) func isSPDSPrime(n uint64) bool { nn := n for nn > 0 { r := nn % 10 if r != 2 && r != 3 && r != 5 && r != 7 { return false } nn /= 10 } b.SetUint64(n) if b.ProbablyPrime(0) { return true } return false } func listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 { count := countFrom for n := startFrom; ; n += 2 { if isSPDSPrime(n) { count++ if !printOne { fmt.Printf("%2d. %d\n", count, n) } if count == countTo { if printOne { fmt.Println(n) } return n } } } } func main() { fmt.Println("The first 25 terms of the Smarandache prime-digital sequence are:") fmt.Println(" 1. 2") n := listSPDSPrimes(3, 1, 25, false) fmt.Println("\nHigher terms:") indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000} for i := 1; i < len(indices); i++ { fmt.Printf("%6d. ", indices[i]) n = listSPDSPrimes(n+2, indices[i-1], indices[i], true) } }
Maintain the same structure and functionality when rewriting this code in Go.
import random def partition(vector, left, right, pivotIndex): pivotValue = vector[pivotIndex] vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] storeIndex = left for i in range(left, right): if vector[i] < pivotValue: vector[storeIndex], vector[i] = vector[i], vector[storeIndex] storeIndex += 1 vector[right], vector[storeIndex] = vector[storeIndex], vector[right] return storeIndex def _select(vector, left, right, k): "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive." while True: pivotIndex = random.randint(left, right) pivotNewIndex = partition(vector, left, right, pivotIndex) pivotDist = pivotNewIndex - left if pivotDist == k: return vector[pivotNewIndex] elif k < pivotDist: right = pivotNewIndex - 1 else: k -= pivotDist + 1 left = pivotNewIndex + 1 def select(vector, k, left=None, right=None): if left is None: left = 0 lv1 = len(vector) - 1 if right is None: right = lv1 assert vector and k >= 0, "Either null vector or k < 0 " assert 0 <= left <= lv1, "left is out of range" assert left <= right <= lv1, "right is out of range" return _select(vector, left, right, k) if __name__ == '__main__': v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] print([select(v, i) for i in range(10)])
package main import "fmt" func quickselect(list []int, k int) int { for { px := len(list) / 2 pv := list[px] last := len(list) - 1 list[px], list[last] = list[last], list[px] i := 0 for j := 0; j < last; j++ { if list[j] < pv { list[i], list[j] = list[j], list[i] i++ } } if i == k { return pv } if k < i { list = list[:i] } else { list[i], list[last] = list[last], list[i] list = list[i+1:] k -= i + 1 } } } func main() { for i := 0; ; i++ { v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4} if i == len(v) { return } fmt.Println(quickselect(v, i)) } }
Write the same code in Go as shown below in Python.
i = int('1a',16)
package main import ( "fmt" "math/big" "strconv" ) func main () { s := strconv.FormatInt(26, 16) fmt.Println(s) i, err := strconv.ParseInt("1a", 16, 64) if err == nil { fmt.Println(i) } b, ok := new(big.Int).SetString("1a", 16) if ok { fmt.Println(b) } }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Change the following Python code into Go without altering its purpose.
k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ] k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ] k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ] k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ] k4 = [ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 ] k3 = [ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 ] k2 = [ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 ] k1 = [ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 ] k87 = [0] * 256 k65 = [0] * 256 k43 = [0] * 256 k21 = [0] * 256 def kboxinit(): for i in range(256): k87[i] = k8[i >> 4] << 4 | k7[i & 15] k65[i] = k6[i >> 4] << 4 | k5[i & 15] k43[i] = k4[i >> 4] << 4 | k3[i & 15] k21[i] = k2[i >> 4] << 4 | k1[i & 15] def f(x): x = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255] ) return x<<11 | x>>(32-11)
package main import "fmt" type sBox [8][16]byte type gost struct { k87, k65, k43, k21 [256]byte enc []byte } func newGost(s *sBox) *gost { var g gost for i := range g.k87 { g.k87[i] = s[7][i>>4]<<4 | s[6][i&15] g.k65[i] = s[5][i>>4]<<4 | s[4][i&15] g.k43[i] = s[3][i>>4]<<4 | s[2][i&15] g.k21[i] = s[1][i>>4]<<4 | s[0][i&15] } g.enc = make([]byte, 8) return &g } func (g *gost) f(x uint32) uint32 { x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 | uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255]) return x<<11 | x>>(32-11) } var cbrf = sBox{ {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3}, {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9}, {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11}, {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3}, {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2}, {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14}, {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12}, {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12}, } func u32(b []byte) uint32 { return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 } func b4(u uint32, b []byte) { b[0] = byte(u) b[1] = byte(u >> 8) b[2] = byte(u >> 16) b[3] = byte(u >> 24) } func (g *gost) mainStep(input []byte, key []byte) { key32 := u32(key) input1 := u32(input[:4]) input2 := u32(input[4:]) b4(g.f(key32+input1)^input2, g.enc[:4]) copy(g.enc[4:], input[:4]) } func main() { input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04} key := []byte{0xF9, 0x04, 0xC1, 0xE2} g := newGost(&cbrf) g.mainStep(input, key) for _, b := range g.enc { fmt.Printf("[%02x]", b) } fmt.Println() }
Port the provided Python code into Go while preserving the original functionality.
from collections import defaultdict states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", ] states = sorted(set(states)) smap = defaultdict(list) for i, s1 in enumerate(states[:-1]): for s2 in states[i + 1:]: smap["".join(sorted(s1 + s2))].append(s1 + " + " + s2) for pairs in sorted(smap.itervalues()): if len(pairs) > 1: print " = ".join(pairs)
package main import ( "fmt" "unicode" ) var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"} func main() { play(states) play(append(states, "New Kory", "Wen Kory", "York New", "Kory New", "New Kory")) } func play(states []string) { fmt.Println(len(states), "states:") set := make(map[string]bool, len(states)) for _, s := range states { set[s] = true } s := make([]string, len(set)) h := make([][26]byte, len(set)) var i int for us := range set { s[i] = us for _, c := range us { if u := uint(unicode.ToLower(c)) - 'a'; u < 26 { h[i][u]++ } } i++ } type pair struct { i1, i2 int } m := make(map[string][]pair) b := make([]byte, 26) for i1, h1 := range h { for i2 := i1 + 1; i2 < len(h); i2++ { for i := range b { b[i] = h1[i] + h[i2][i] } k := string(b) for _, x := range m[k] { if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 { fmt.Printf("%s, %s = %s, %s\n", s[i1], s[i2], s[x.i1], s[x.i2]) } } m[k] = append(m[k], pair{i1, i2}) } } }
Rewrite the snippet below in Go so it works the same as the original Python code.
>>> s = 'The quick brown fox jumps over the lazy dog' >>> import zlib >>> hex(zlib.crc32(s)) '0x414fa339' >>> import binascii >>> hex(binascii.crc32(s)) '0x414fa339'
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
Produce a language-to-language conversion: from Python to Go, same semantics.
csvtxt = from cgi import escape def _row2tr(row, attr=None): cols = escape(row).split(',') return ('<TR>' + ''.join('<TD>%s</TD>' % data for data in cols) + '</TR>') def csv2html(txt): htmltxt = '<TABLE summary="csv2html program output">\n' for rownum, row in enumerate(txt.split('\n')): htmlrow = _row2tr(row) htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow htmltxt += htmlrow htmltxt += '</TABLE>\n' return htmltxt htmltxt = csv2html(csvtxt) print(htmltxt)
package main import ( "bytes" "encoding/csv" "fmt" "html/template" "strings" ) var c = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!` func main() { if h, err := csvToHtml(c); err != nil { fmt.Println(err) } else { fmt.Print(h) } } func csvToHtml(c string) (string, error) { data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll() if err != nil { return "", err } var b strings.Builder err = template.Must(template.New("").Parse(`<table> {{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr> {{end}}</table> `)).Execute(&b, data) return b.String(), err }
Convert this Python snippet to Go and keep its semantics consistent.
csvtxt = from cgi import escape def _row2tr(row, attr=None): cols = escape(row).split(',') return ('<TR>' + ''.join('<TD>%s</TD>' % data for data in cols) + '</TR>') def csv2html(txt): htmltxt = '<TABLE summary="csv2html program output">\n' for rownum, row in enumerate(txt.split('\n')): htmlrow = _row2tr(row) htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow htmltxt += htmlrow htmltxt += '</TABLE>\n' return htmltxt htmltxt = csv2html(csvtxt) print(htmltxt)
package main import ( "bytes" "encoding/csv" "fmt" "html/template" "strings" ) var c = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!` func main() { if h, err := csvToHtml(c); err != nil { fmt.Println(err) } else { fmt.Print(h) } } func csvToHtml(c string) (string, error) { data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll() if err != nil { return "", err } var b strings.Builder err = template.Must(template.New("").Parse(`<table> {{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr> {{end}}</table> `)).Execute(&b, data) return b.String(), err }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
class MyClass: name2 = 2 def __init__(self): self.name1 = 0 def someMethod(self): self.name1 = 1 MyClass.name2 = 3 myclass = MyClass() class MyOtherClass: count = 0 def __init__(self, name, gender="Male", age=None): MyOtherClass.count += 1 self.name = name self.gender = gender if age is not None: self.age = age def __del__(self): MyOtherClass.count -= 1 person1 = MyOtherClass("John") print person1.name, person1.gender print person1.age person2 = MyOtherClass("Jane", "Female", 23) print person2.name, person2.gender, person2.age
package main import "fmt" type picnicBasket struct { nServings int corkscrew bool } func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew } func newPicnicBasket(nPeople int) *picnicBasket { return &picnicBasket{nPeople, nPeople > 0} } func main() { var pb picnicBasket pbl := picnicBasket{} pbp := &picnicBasket{} pbn := new(picnicBasket) forTwo := newPicnicBasket(2) forToo := &picnicBasket{nServings: 2, corkscrew: true} fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
Translate the given Python code snippet into Go without altering its behavior.
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Port the provided Python code into Go while preserving the original functionality.
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def compress(uncompressed): dict_size = 256 dictionary = dict((chr(i), i) for i in range(dict_size)) w = "" result = [] for c in uncompressed: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) dictionary[wc] = dict_size dict_size += 1 w = c if w: result.append(dictionary[w]) return result def decompress(compressed): from io import StringIO dict_size = 256 dictionary = dict((i, chr(i)) for i in range(dict_size)) result = StringIO() w = chr(compressed.pop(0)) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry) dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry return result.getvalue() compressed = compress('TOBEORNOTTOBEORTOBEORNOT') print (compressed) decompressed = decompress(compressed) print (decompressed)
package main import ( "fmt" "log" "strings" ) func compress(uncompressed string) []int { dictSize := 256 dictionary := make(map[string]int, dictSize) for i := 0; i < dictSize; i++ { dictionary[string([]byte{byte(i)})] = i } var result []int var w []byte for i := 0; i < len(uncompressed); i++ { c := uncompressed[i] wc := append(w, c) if _, ok := dictionary[string(wc)]; ok { w = wc } else { result = append(result, dictionary[string(w)]) dictionary[string(wc)] = dictSize dictSize++ wc[0] = c w = wc[:1] } } if len(w) > 0 { result = append(result, dictionary[string(w)]) } return result } type BadSymbolError int func (e BadSymbolError) Error() string { return fmt.Sprint("Bad compressed symbol ", int(e)) } func decompress(compressed []int) (string, error) { dictSize := 256 dictionary := make(map[int][]byte, dictSize) for i := 0; i < dictSize; i++ { dictionary[i] = []byte{byte(i)} } var result strings.Builder var w []byte for _, k := range compressed { var entry []byte if x, ok := dictionary[k]; ok { entry = x[:len(x):len(x)] } else if k == dictSize && len(w) > 0 { entry = append(w, w[0]) } else { return result.String(), BadSymbolError(k) } result.Write(entry) if len(w) > 0 { w = append(w, entry[0]) dictionary[dictSize] = w dictSize++ } w = entry } return result.String(), nil } func main() { compressed := compress("TOBEORNOTTOBEORTOBEORNOT") fmt.Println(compressed) decompressed, err := decompress(compressed) if err != nil { log.Fatal(err) } fmt.Println(decompressed) }
Convert the following code from Python to Go, ensuring the logic remains intact.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
package main import "fmt" var ffr, ffs func(int) int func init() { r := []int{0, 1} s := []int{0, 2} ffr = func(n int) int { for len(r) <= n { nrk := len(r) - 1 rNxt := r[nrk] + s[nrk] r = append(r, rNxt) for sn := r[nrk] + 2; sn < rNxt; sn++ { s = append(s, sn) } s = append(s, rNxt+1) } return r[n] } ffs = func(n int) int { for len(s) <= n { ffr(len(r)) } return s[n] } } func main() { for n := 1; n <= 10; n++ { fmt.Printf("r(%d): %d\n", n, ffr(n)) } var found [1001]int for n := 1; n <= 40; n++ { found[ffr(n)]++ } for n := 1; n <= 960; n++ { found[ffs(n)]++ } for i := 1; i <= 1000; i++ { if found[i] != 1 { fmt.Println("task 4: FAIL") return } } fmt.Println("task 4: PASS") }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
package main import "fmt" var ffr, ffs func(int) int func init() { r := []int{0, 1} s := []int{0, 2} ffr = func(n int) int { for len(r) <= n { nrk := len(r) - 1 rNxt := r[nrk] + s[nrk] r = append(r, rNxt) for sn := r[nrk] + 2; sn < rNxt; sn++ { s = append(s, sn) } s = append(s, rNxt+1) } return r[n] } ffs = func(n int) int { for len(s) <= n { ffr(len(r)) } return s[n] } } func main() { for n := 1; n <= 10; n++ { fmt.Printf("r(%d): %d\n", n, ffr(n)) } var found [1001]int for n := 1; n <= 40; n++ { found[ffr(n)]++ } for n := 1; n <= 960; n++ { found[ffs(n)]++ } for i := 1; i <= 1000; i++ { if found[i] != 1 { fmt.Println("task 4: FAIL") return } } fmt.Println("task 4: PASS") }
Preserve the algorithm and functionality while converting the code from Python to Go.
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
package main import ( "fmt" "log" ) func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m } func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
Write a version of this Python function in Go with identical behavior.
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
package main import ( "fmt" "log" ) func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m } func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
Convert this Python snippet to Go and keep its semantics consistent.
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
package main import ( "fmt" "log" "os/exec" ) func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x } func yellowstone(n int) []int { m := make(map[int]bool) a := make([]int, n+1) for i := 1; i < 4; i++ { a[i] = i m[i] = true } min := 4 for c := 4; c <= n; c++ { for i := min; ; i++ { if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 { a[c] = i m[i] = true if i == min { min++ } break } } } return a[1:] } func check(err error) { if err != nil { log.Fatal(err) } } func main() { x := make([]int, 100) for i := 0; i < 100; i++ { x[i] = i + 1 } y := yellowstone(100) fmt.Println("The first 30 Yellowstone numbers are:") fmt.Println(y[:30]) g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() check(err) check(g.Start()) fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %d\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
Keep all operations the same but rewrite the snippet in Go.
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
package main import ( "fmt" "log" "os/exec" ) func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x } func yellowstone(n int) []int { m := make(map[int]bool) a := make([]int, n+1) for i := 1; i < 4; i++ { a[i] = i m[i] = true } min := 4 for c := 4; c <= n; c++ { for i := min; ; i++ { if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 { a[c] = i m[i] = true if i == min { min++ } break } } } return a[1:] } func check(err error) { if err != nil { log.Fatal(err) } } func main() { x := make([]int, 100) for i := 0; i < 100; i++ { x[i] = i + 1 } y := yellowstone(100) fmt.Println("The first 30 Yellowstone numbers are:") fmt.Println(y[:30]) g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() check(err) check(g.Start()) fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %d\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
Write a version of this Python function in Go with identical behavior.
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
package main import ( "fmt" "log" "os/exec" ) func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x } func yellowstone(n int) []int { m := make(map[int]bool) a := make([]int, n+1) for i := 1; i < 4; i++ { a[i] = i m[i] = true } min := 4 for c := 4; c <= n; c++ { for i := min; ; i++ { if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 { a[c] = i m[i] = true if i == min { min++ } break } } } return a[1:] } func check(err error) { if err != nil { log.Fatal(err) } } func main() { x := make([]int, 100) for i := 0; i < 100; i++ { x[i] = i + 1 } y := yellowstone(100) fmt.Println("The first 30 Yellowstone numbers are:") fmt.Println(y[:30]) g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() check(err) check(g.Start()) fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %d\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
Generate a Go translation of this Python snippet without changing its computational steps.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d := range dir { if grid[t+next[i]] == 0 { walk(y+d[0], x+d[1]) } } grid[t]-- grid[last-t]-- } func solve(hh, ww, recur int) int { h = hh w = ww if h&1 != 0 { h, w = w, h } switch { case h&1 == 1: return 0 case w == 1: return 1 case w == 2: return h case h == 2: return w } cy := h / 2 cx := w / 2 grid = make([]byte, (h+1)*(w+1)) last = len(grid) - 1 next[0] = -1 next[1] = -w - 1 next[2] = 1 next[3] = w + 1 if recur != 0 { cnt = 0 } for x := cx + 1; x < w; x++ { t := cy*(w+1) + x grid[t] = 1 grid[last-t] = 1 walk(cy-1, x) } cnt++ if h == w { cnt *= 2 } else if w&1 == 0 && recur != 0 { solve(w, h, 0) } return cnt } func main() { for y := 1; y <= 10; y++ { for x := 1; x <= y; x++ { if x&1 == 0 || y&1 == 0 { fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1)) } } } }
Convert this Python block to Go, preserving its control flow and logic.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d := range dir { if grid[t+next[i]] == 0 { walk(y+d[0], x+d[1]) } } grid[t]-- grid[last-t]-- } func solve(hh, ww, recur int) int { h = hh w = ww if h&1 != 0 { h, w = w, h } switch { case h&1 == 1: return 0 case w == 1: return 1 case w == 2: return h case h == 2: return w } cy := h / 2 cx := w / 2 grid = make([]byte, (h+1)*(w+1)) last = len(grid) - 1 next[0] = -1 next[1] = -w - 1 next[2] = 1 next[3] = w + 1 if recur != 0 { cnt = 0 } for x := cx + 1; x < w; x++ { t := cy*(w+1) + x grid[t] = 1 grid[last-t] = 1 walk(cy-1, x) } cnt++ if h == w { cnt *= 2 } else if w&1 == 0 && recur != 0 { solve(w, h, 0) } return cnt } func main() { for y := 1; y <= 10; y++ { for x := 1; x <= y; x++ { if x&1 == 0 || y&1 == 0 { fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1)) } } } }
Convert the following code from Python to Go, ensuring the logic remains intact.
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m ms = mertens(1000) print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: print("{:2d}".format(n), end=' ') col += 1 if col == 10: print() col = 0 zeroes = sum(x==0 for x in ms) crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:])) print("M(N) equals zero {} times.".format(zeroes)) print("M(N) crosses zero {} times.".format(crosses))
package main import "fmt" func mertens(to int) ([]int, int, int) { if to < 1 { to = 1 } merts := make([]int, to+1) primes := []int{2} var sum, zeros, crosses int for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break } if j%p == 0 { j /= p cp++ } if j%p == 0 { spf = true break } } if cp == 0 && i > 2 { cp = 1 primes = append(primes, i) } if !spf { if cp%2 == 0 { sum++ } else { sum-- } } merts[i] = sum if sum == 0 { zeros++ if i > 1 && merts[i-1] != 0 { crosses++ } } } return merts, zeros, crosses } func main() { merts, zeros, crosses := mertens(1000) fmt.Println("Mertens sequence - First 199 terms:") for i := 0; i < 200; i++ { if i == 0 { fmt.Print(" ") continue } if i%20 == 0 { fmt.Println() } fmt.Printf("  % d", merts[i]) } fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000") fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000") }
Transform the following Python implementation into Go, maintaining the same output and logic.
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m ms = mertens(1000) print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: print("{:2d}".format(n), end=' ') col += 1 if col == 10: print() col = 0 zeroes = sum(x==0 for x in ms) crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:])) print("M(N) equals zero {} times.".format(zeroes)) print("M(N) crosses zero {} times.".format(crosses))
package main import "fmt" func mertens(to int) ([]int, int, int) { if to < 1 { to = 1 } merts := make([]int, to+1) primes := []int{2} var sum, zeros, crosses int for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break } if j%p == 0 { j /= p cp++ } if j%p == 0 { spf = true break } } if cp == 0 && i > 2 { cp = 1 primes = append(primes, i) } if !spf { if cp%2 == 0 { sum++ } else { sum-- } } merts[i] = sum if sum == 0 { zeros++ if i > 1 && merts[i-1] != 0 { crosses++ } } } return merts, zeros, crosses } func main() { merts, zeros, crosses := mertens(1000) fmt.Println("Mertens sequence - First 199 terms:") for i := 0; i < 200; i++ { if i == 0 { fmt.Print(" ") continue } if i%20 == 0 { fmt.Println() } fmt.Printf("  % d", merts[i]) } fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000") fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000") }
Port the following code from Python to Go with equivalent syntax and logic.
def _insort_right(a, x, q): lo, hi = 0, len(a) while lo < hi: mid = (lo+hi)//2 q += 1 less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y' if less: hi = mid else: lo = mid+1 a.insert(lo, x) return q def order(items): ordered, q = [], 0 for item in items: q = _insort_right(ordered, item, q) return ordered, q if __name__ == '__main__': items = 'violet red green indigo blue yellow orange'.split() ans, questions = order(items) print('\n' + ' '.join(ans))
package main import ( "fmt" "sort" "strings" ) var count int = 0 func interactiveCompare(s1, s2 string) bool { count++ fmt.Printf("(%d) Is %s < %s? ", count, s1, s2) var response string _, err := fmt.Scanln(&response) return err == nil && strings.HasPrefix(response, "y") } func main() { items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"} var sortedItems []string for _, item := range items { fmt.Printf("Inserting '%s' into %s\n", item, sortedItems) spotToInsert := sort.Search(len(sortedItems), func(i int) bool { return interactiveCompare(item, sortedItems[i]) }) sortedItems = append(sortedItems[:spotToInsert], append([]string{item}, sortedItems[spotToInsert:]...)...) } fmt.Println(sortedItems) }
Maintain the same structure and functionality when rewriting this code in Go.
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
Write a version of this Python function in Go with identical behavior.
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
Convert the following code from Python to Go, ensuring the logic remains intact.
import time, calendar, sched, winsound duration = 750 freq = 1280 bellchar = "\u2407" watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',') def gap(n=1): time.sleep(n * duration / 1000) off = gap def on(n=1): winsound.Beep(freq, n * duration) def bong(): on(); off(0.5) def bongs(m): for i in range(m): print(bellchar, end=' ') bong() if i % 2: print(' ', end='') off(0.5) print('') scheds = sched.scheduler(time.time, time.sleep) def ships_bell(now=None): def adjust_to_half_hour(atime): atime[4] = (atime[4] // 30) * 30 atime[5] = 0 return atime debug = now is not None rightnow = time.gmtime() if not debug: now = adjust_to_half_hour( list(rightnow) ) then = now[::] then[4] += 30 hr, mn = now[3:5] watch, b = divmod(int(2 * hr + mn // 30 - 1), 8) b += 1 bells = '%i bell%s' % (b, 's' if b > 1 else ' ') if debug: print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ') else: print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ') bongs(b) if not debug: scheds.enterabs(calendar.timegm(then), 0, ships_bell) scheds.run() def dbg_tester(): for h in range(24): for m in (0, 30): if (h,m) == (24,30): break ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] ) if __name__ == '__main__': ships_bell()
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m == 30) && s == 0 { bell := 0 if m == 30 { bell = 1 } bells := (h*2 + bell) % 8 watch := h/4 + 1 if bells == 0 { bells = 8 watch-- } sound := strings.Repeat("\a", bells) pl := "s" if bells == 1 { pl = " " } w := watches[watch] + " watch" if watch == 5 { if bells < 5 { w = "First " + w } else { w = "Last " + w } } fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w) } time.Sleep(1 * time.Second) } }