Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into C# but keep the logic exactly as in VB.
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var baseData = new Dictionary<string, object> { ["name"] = "Rocket Skates", ["price"] = 12.75, ["color"] = "yellow" }; var updateData = new Dictionary<string, object> { ["price"] = 15.25, ["color"] = "red", ["year"] = 1974 }; var mergedData = new Dictionary<string, object>(); foreach (var entry in baseData.Concat(updateData)) { mergedData[entry.Key] = entry.Value; } foreach (var entry in mergedData) { Console.WriteLine(entry); } } }
Change the programming language of this snippet from VB to C# without modifying what it does.
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
Maintain the same structure and functionality when rewriting this code in C#.
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
Generate an equivalent C# version of this VB code.
Class Branch Public from As Node Public towards As Node Public length As Integer Public distance As Integer Public key As String Class Node Public key As String Public correspondingBranch As Branch Const INFINITY = 32767 Private Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node) Dim a As New Collection Dim b As New Collection Dim c As New Collection Dim I As New Collection Dim II As New Collection Dim III As New Collection Dim u As Node, R_ As Node, dist As Integer For Each n In Nodes c.Add n, n.key Next n For Each e In Branches III.Add e, e.key Next e a.Add P, P.key c.Remove P.key Set u = P Do For Each r In III If r.from Is u Then Set R_ = r.towards If Belongs(R_, c) Then c.Remove R_.key b.Add R_, R_.key Set R_.correspondingBranch = r If u.correspondingBranch Is Nothing Then R_.correspondingBranch.distance = r.length Else R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If III.Remove r.key II.Add r, r.key Else If Belongs(R_, b) Then If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then II.Remove R_.correspondingBranch.key II.Add r, r.key Set R_.correspondingBranch = r R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If End If End If End If Next r dist = INFINITY Set u = Nothing For Each n In b If dist > n.correspondingBranch.distance Then dist = n.correspondingBranch.distance Set u = n End If Next n b.Remove u.key a.Add u, u.key II.Remove u.correspondingBranch.key I.Add u.correspondingBranch, u.correspondingBranch.key Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q) If Not Q Is Nothing Then GetPath Q End Sub Private Function Belongs(n As Node, col As Collection) As Boolean Dim obj As Node On Error GoTo err Belongs = True Set obj = col(n.key) Exit Function err: Belongs = False End Function Private Sub GetPath(Target As Node) Dim path As String If Target.correspondingBranch Is Nothing Then path = "no path" Else path = Target.key Set u = Target Do While Not u.correspondingBranch Is Nothing path = u.correspondingBranch.from.key & " " & path Set u = u.correspondingBranch.from Loop Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path End If End Sub Public Sub test() Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = "ab": ab.distance = INFINITY Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = "ac": ac.distance = INFINITY Set af.from = a: Set af.towards = f: af.length = 14: af.key = "af": af.distance = INFINITY Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = "bc": bc.distance = INFINITY Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = "bd": bd.distance = INFINITY Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = "cd": cd.distance = INFINITY Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = "cf": cf.distance = INFINITY Set de.from = d: Set de.towards = e: de.length = 6: de.key = "de": de.distance = INFINITY Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = "ef": ef.distance = INFINITY a.key = "a" b.key = "b" c.key = "c" d.key = "d" e.key = "e" f.key = "f" Dim testNodes As New Collection Dim testBranches As New Collection testNodes.Add a, "a" testNodes.Add b, "b" testNodes.Add c, "c" testNodes.Add d, "d" testNodes.Add e, "e" testNodes.Add f, "f" testBranches.Add ab, "ab" testBranches.Add ac, "ac" testBranches.Add af, "af" testBranches.Add bc, "bc" testBranches.Add bd, "bd" testBranches.Add cd, "cd" testBranches.Add cf, "cf" testBranches.Add de, "de" testBranches.Add ef, "ef" Debug.Print "From", "To", "Distance", "Path" Dijkstra testNodes, testBranches, a, e Dijkstra testNodes, testBranches, a GetPath f End Sub
using static System.Linq.Enumerable; using static System.String; using static System.Console; using System.Collections.Generic; using System; using EdgeList = System.Collections.Generic.List<(int node, double weight)>; public static class Dijkstra { public static void Main() { Graph graph = new Graph(6); Func<char, int> id = c => c - 'a'; Func<int , char> name = i => (char)(i + 'a'); foreach (var (start, end, cost) in new [] { ('a', 'b', 7), ('a', 'c', 9), ('a', 'f', 14), ('b', 'c', 10), ('b', 'd', 15), ('c', 'd', 11), ('c', 'f', 2), ('d', 'e', 6), ('e', 'f', 9), }) { graph.AddEdge(id(start), id(end), cost); } var path = graph.FindPath(id('a')); for (int d = id('b'); d <= id('f'); d++) { WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse())); } IEnumerable<(double distance, int node)> Path(int start, int destination) { yield return (path[destination].distance, destination); for (int i = destination; i != start; i = path[i].prev) { yield return (path[path[i].prev].distance, path[i].prev); } } } } sealed class Graph { private readonly List<EdgeList> adjacency; public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList(); public int Count => adjacency.Count; public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e); public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0; public bool AddEdge(int s, int e, double weight) { if (HasEdge(s, e)) return false; adjacency[s].Add((e, weight)); return true; } public (double distance, int prev)[] FindPath(int start) { var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray(); info[start].distance = 0; var visited = new System.Collections.BitArray(adjacency.Count); var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance)); heap.Push((start, 0)); while (heap.Count > 0) { var current = heap.Pop(); if (visited[current.node]) continue; var edges = adjacency[current.node]; for (int n = 0; n < edges.Count; n++) { int v = edges[n].node; if (visited[v]) continue; double alt = info[current.node].distance + edges[n].weight; if (alt < info[v].distance) { info[v] = (alt, current.node); heap.Push((v, alt)); } } visited[current.node] = true; } return info; } } sealed class Heap<T> { private readonly IComparer<T> comparer; private readonly List<T> list = new List<T> { default }; public Heap() : this(default(IComparer<T>)) { } public Heap(IComparer<T> comparer) { this.comparer = comparer ?? Comparer<T>.Default; } public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { } public int Count => list.Count - 1; public void Push(T element) { list.Add(element); SiftUp(list.Count - 1); } public T Pop() { T result = list[1]; list[1] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); SiftDown(1); return result; } private static int Parent(int i) => i / 2; private static int Left(int i) => i * 2; private static int Right(int i) => i * 2 + 1; private void SiftUp(int i) { while (i > 1) { int parent = Parent(i); if (comparer.Compare(list[i], list[parent]) > 0) return; (list[parent], list[i]) = (list[i], list[parent]); i = parent; } } private void SiftDown(int i) { for (int left = Left(i); left < list.Count; left = Left(i)) { int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i; int right = Right(i); if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right; if (smallest == i) return; (list[i], list[smallest]) = (list[smallest], list[i]); i = smallest; } } }
Preserve the algorithm and functionality while converting the code from VB to C#.
Option Strict On Imports System.Text Module Module1 Structure Vector Private ReadOnly dims() As Double Public Sub New(da() As Double) dims = da End Sub Public Shared Operator -(v As Vector) As Vector Return v * -1.0 End Operator Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double Array.Copy(lhs.dims, 0, result, 0, lhs.Length) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = lhs(i2) + rhs(i2) Next Return New Vector(result) End Operator Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double For i = 1 To lhs.Length Dim i2 = i - 1 If lhs(i2) <> 0.0 Then For j = 1 To lhs.Length Dim j2 = j - 1 If rhs(j2) <> 0.0 Then Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2) Dim k = i2 Xor j2 result(k) += s End If Next End If Next Return New Vector(result) End Operator Public Shared Operator *(v As Vector, scale As Double) As Vector Dim result = CType(v.dims.Clone, Double()) For i = 1 To result.Length Dim i2 = i - 1 result(i2) *= scale Next Return New Vector(result) End Operator Default Public Property Index(key As Integer) As Double Get Return dims(key) End Get Set(value As Double) dims(key) = value End Set End Property Public ReadOnly Property Length As Integer Get Return dims.Length End Get End Property Public Function Dot(rhs As Vector) As Vector Return (Me * rhs + rhs * Me) * 0.5 End Function Private Shared Function BitCount(i As Integer) As Integer i -= ((i >> 1) And &H55555555) i = (i And &H33333333) + ((i >> 2) And &H33333333) i = (i + (i >> 4)) And &HF0F0F0F i += (i >> 8) i += (i >> 16) Return i And &H3F End Function Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double Dim k = i >> 1 Dim sum = 0 While k <> 0 sum += BitCount(k And j) k >>= 1 End While Return If((sum And 1) = 0, 1.0, -1.0) End Function Public Overrides Function ToString() As String Dim it = dims.GetEnumerator Dim sb As New StringBuilder("[") If it.MoveNext() Then sb.Append(it.Current) End If While it.MoveNext sb.Append(", ") sb.Append(it.Current) End While sb.Append("]") Return sb.ToString End Function End Structure Function DoubleArray(size As Integer) As Double() Dim result(size - 1) As Double For i = 1 To size Dim i2 = i - 1 result(i2) = 0.0 Next Return result End Function Function E(n As Integer) As Vector If n > 4 Then Throw New ArgumentException("n must be less than 5") End If Dim result As New Vector(DoubleArray(32)) result(1 << n) = 1.0 Return result End Function ReadOnly r As New Random() Function RandomVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To 5 Dim i2 = i - 1 Dim singleton() As Double = {r.NextDouble()} result += New Vector(singleton) * E(i2) Next Return result End Function Function RandomMultiVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = r.NextDouble() Next Return result End Function Sub Main() For i = 1 To 5 Dim i2 = i - 1 For j = 1 To 5 Dim j2 = j - 1 If i2 < j2 Then If E(i2).Dot(E(j2))(0) <> 0.0 Then Console.Error.WriteLine("Unexpected non-null scalar product") Return End If ElseIf i2 = j2 Then If E(i2).Dot(E(j2))(0) = 0.0 Then Console.Error.WriteLine("Unexpected null scalar product") Return End If End If Next Next Dim a = RandomMultiVector() Dim b = RandomMultiVector() Dim c = RandomMultiVector() Dim x = RandomVector() Console.WriteLine((a * b) * c) Console.WriteLine(a * (b * c)) Console.WriteLine() Console.WriteLine(a * (b + c)) Console.WriteLine(a * b + a * c) Console.WriteLine() Console.WriteLine((a + b) * c) Console.WriteLine(a * c + b * c) Console.WriteLine() Console.WriteLine(x * x) End Sub End Module
using System; using System.Text; namespace GeometricAlgebra { struct Vector { private readonly double[] dims; public Vector(double[] da) { dims = da; } public static Vector operator -(Vector v) { return v * -1.0; } public static Vector operator +(Vector lhs, Vector rhs) { var result = new double[32]; Array.Copy(lhs.dims, 0, result, 0, lhs.Length); for (int i = 0; i < result.Length; i++) { result[i] = lhs[i] + rhs[i]; } return new Vector(result); } public static Vector operator *(Vector lhs, Vector rhs) { var result = new double[32]; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != 0.0) { for (int j = 0; j < lhs.Length; j++) { if (rhs[j] != 0.0) { var s = ReorderingSign(i, j) * lhs[i] * rhs[j]; var k = i ^ j; result[k] += s; } } } } return new Vector(result); } public static Vector operator *(Vector v, double scale) { var result = (double[])v.dims.Clone(); for (int i = 0; i < result.Length; i++) { result[i] *= scale; } return new Vector(result); } public double this[int key] { get { return dims[key]; } set { dims[key] = value; } } public int Length { get { return dims.Length; } } public Vector Dot(Vector rhs) { return (this * rhs + rhs * this) * 0.5; } private static int BitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } private static double ReorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += BitCount(k & j); k >>= 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } public override string ToString() { var it = dims.GetEnumerator(); StringBuilder sb = new StringBuilder("["); if (it.MoveNext()) { sb.Append(it.Current); } while (it.MoveNext()) { sb.Append(", "); sb.Append(it.Current); } sb.Append(']'); return sb.ToString(); } } class Program { static double[] DoubleArray(uint size) { double[] result = new double[size]; for (int i = 0; i < size; i++) { result[i] = 0.0; } return result; } static Vector E(int n) { if (n > 4) { throw new ArgumentException("n must be less than 5"); } var result = new Vector(DoubleArray(32)); result[1 << n] = 1.0; return result; } static readonly Random r = new Random(); static Vector RandomVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < 5; i++) { var singleton = new double[] { r.NextDouble() }; result += new Vector(singleton) * E(i); } return result; } static Vector RandomMultiVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < result.Length; i++) { result[i] = r.NextDouble(); } return result; } static void Main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (E(i).Dot(E(j))[0] != 0.0) { Console.WriteLine("Unexpected non-null sclar product."); return; } } else if (i == j) { if ((E(i).Dot(E(j)))[0] == 0.0) { Console.WriteLine("Unexpected null sclar product."); } } } } var a = RandomMultiVector(); var b = RandomMultiVector(); var c = RandomMultiVector(); var x = RandomVector(); Console.WriteLine((a * b) * c); Console.WriteLine(a * (b * c)); Console.WriteLine(); Console.WriteLine(a * (b + c)); Console.WriteLine(a * b + a * c); Console.WriteLine(); Console.WriteLine((a + b) * c); Console.WriteLine(a * c + b * c); Console.WriteLine(); Console.WriteLine(x * x); } } }
Convert the following code from VB to C#, ensuring the logic remains intact.
Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 For Each s In h.Keys Debug.Print s Next For Each s In h.Items Debug.Print s Next u = h.Keys v = h.Items For i = 0 To h.Count - 1 Debug.Print u(i), v(i) Next End Sub
using System; using System.Collections.Generic; namespace AssocArrays { class Program { static void Main(string[] args) { Dictionary<string,int> assocArray = new Dictionary<string,int>(); assocArray["Hello"] = 1; assocArray.Add("World", 2); assocArray["!"] = 3; foreach (KeyValuePair<string, int> kvp in assocArray) { Console.WriteLine(kvp.Key + " : " + kvp.Value); } foreach (string key in assocArray.Keys) { Console.WriteLine(key); } foreach (int val in assocArray.Values) { Console.WriteLine(val.ToString()); } } } }
Maintain the same structure and functionality when rewriting this code in C#.
Private mvarValue As Integer Public Property Let Value(ByVal vData As Integer) If (vData > 10) Or (vData < 1) Then Error 380 Else mvarValue = vData End If End Property Public Property Get Value() As Integer Value = mvarValue End Property Private Sub Class_Initialize() mvarValue = 1 End Sub
using System; using System.Globalization; struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable { const int MIN_VALUE = 1; const int MAX_VALUE = 10; public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE); public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE); static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE; readonly int _value; public int Value => this._value == 0 ? MIN_VALUE : this._value; public LimitedInt(int value) { if (!IsValidValue(value)) throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}."); this._value = value; } #region IComparable public int CompareTo(object obj) { if (obj is LimitedInt l) return this.Value.CompareTo(l); throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj)); } #endregion #region IComparable<LimitedInt> public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value); #endregion #region IConvertible public TypeCode GetTypeCode() => this.Value.GetTypeCode(); bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider); byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider); char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider); DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider); decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider); double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider); short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider); int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider); long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider); sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider); float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider); string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider); object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider); ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider); uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider); ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider); #endregion #region IEquatable<LimitedInt> public bool Equals(LimitedInt other) => this == other; #endregion #region IFormattable public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider); #endregion #region operators public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value; public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value; public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value; public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value; public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value; public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value; public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1); public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1); public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value); public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value); public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value); public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value); public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value); public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value); public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value); public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value); public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value; public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right); public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right); public static implicit operator int(LimitedInt value) => value.Value; public static explicit operator LimitedInt(int value) { if (!IsValidValue(value)) throw new OverflowException(); return new LimitedInt(value); } #endregion public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) => this.Value.TryFormat(destination, out charsWritten, format, provider); public override int GetHashCode() => this.Value.GetHashCode(); public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l); public override string ToString() => this.Value.ToString(); #region static methods public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider); public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s) => int.Parse(s); public static int Parse(string s, NumberStyles style) => int.Parse(s, style); public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider); public static bool TryParse(string s, ref int result) => int.TryParse(s, out result); #endregion }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Dim t_age(4,1) t_age(0,0) = 27 : t_age(0,1) = "Jonah" t_age(1,0) = 18 : t_age(1,1) = "Alan" t_age(2,0) = 28 : t_age(2,1) = "Glory" t_age(3,0) = 18 : t_age(3,1) = "Popeye" t_age(4,0) = 28 : t_age(4,1) = "Alan" Dim t_nemesis(4,1) t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders" t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts" t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies" t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy" Call hash_join(t_age,1,t_nemesis,0) Sub hash_join(table_1,index_1,table_2,index_2) Set hash = CreateObject("Scripting.Dictionary") For i = 0 To UBound(table_1) hash.Add i,Array(table_1(i,0),table_1(i,1)) Next For j = 0 To UBound(table_2) For Each key In hash.Keys If hash(key)(index_1) = table_2(j,index_2) Then WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_ " = " & table_2(j,0) & "," & table_2(j,1) End If Next Next End Sub
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; private set; } } public class NameNemesis { public NameNemesis(string name, string nemesis) { Name = name; Nemesis = nemesis; } public string Name { get; private set; } public string Nemesis { get; private set; } } public class DataContext { public DataContext() { AgeName = new List<AgeName>(); NameNemesis = new List<NameNemesis>(); } public List<AgeName> AgeName { get; set; } public List<NameNemesis> NameNemesis { get; set; } } public class AgeNameNemesis { public AgeNameNemesis(byte age, string name, string nemesis) { Age = age; Name = name; Nemesis = nemesis; } public byte Age { get; private set; } public string Name { get; private set; } public string Nemesis { get; private set; } } class Program { public static void Main() { var data = GetData(); var result = ExecuteHashJoin(data); WriteResultToConsole(result); } private static void WriteResultToConsole(List<AgeNameNemesis> result) { result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); } private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data) { return (data.AgeName.Join(data.NameNemesis, ageName => ageName.Name, nameNemesis => nameNemesis.Name, (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) .ToList(); } private static DataContext GetData() { var context = new DataContext(); context.AgeName.AddRange(new [] { new AgeName(27, "Jonah"), new AgeName(18, "Alan"), new AgeName(28, "Glory"), new AgeName(18, "Popeye"), new AgeName(28, "Alan") }); context.NameNemesis.AddRange(new[] { new NameNemesis("Jonah", "Whales"), new NameNemesis("Jonah", "Spiders"), new NameNemesis("Alan", "Ghosts"), new NameNemesis("Alan", "Zombies"), new NameNemesis("Glory", "Buffy") }); return context; } } }
Convert the following code from VB to C#, ensuring the logic remains intact.
Option Strict On Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer)) Module Module1 Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim u = a a = b b = u End Sub Sub PrintSquare(latin As Matrix) For Each row In latin Dim it = row.GetEnumerator Console.Write("[") If it.MoveNext Then Console.Write(it.Current) End If While it.MoveNext Console.Write(", ") Console.Write(it.Current) End While Console.WriteLine("]") Next Console.WriteLine() End Sub Function DList(n As Integer, start As Integer) As Matrix start -= 1 REM use 0 based indexes Dim a = Enumerable.Range(0, n).ToArray a(start) = a(0) a(0) = start Array.Sort(a, 1, a.Length - 1) Dim first = a(1) REM recursive closure permutes a[1:] Dim r As New Matrix Dim Recurse As Action(Of Integer) = Sub(last As Integer) If last = first Then REM bottom of recursion. you get here once for each permutation REM test if permutation is deranged. For j = 1 To a.Length - 1 Dim v = a(j) If j = v Then Return REM no, ignore it End If Next REM yes, save a copy with 1 based indexing Dim b = a.Select(Function(v) v + 1).ToArray r.Add(b.ToList) Return End If For i = last To 1 Step -1 Swap(a(i), a(last)) Recurse(last - 1) Swap(a(i), a(last)) Next End Sub Recurse(n - 1) Return r End Function Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong If n <= 0 Then If echo Then Console.WriteLine("[]") Console.WriteLine() End If Return 0 End If If n = 1 Then If echo Then Console.WriteLine("[1]") Console.WriteLine() End If Return 1 End If Dim rlatin As New Matrix For i = 0 To n - 1 rlatin.Add(New List(Of Integer)) For j = 0 To n - 1 rlatin(i).Add(0) Next Next REM first row For j = 0 To n - 1 rlatin(0)(j) = j + 1 Next Dim count As ULong = 0 Dim Recurse As Action(Of Integer) = Sub(i As Integer) Dim rows = DList(n, i) For r = 0 To rows.Count - 1 rlatin(i - 1) = rows(r) For k = 0 To i - 2 For j = 1 To n - 1 If rlatin(k)(j) = rlatin(i - 1)(j) Then If r < rows.Count - 1 Then GoTo outer End If If i > 2 Then Return End If End If Next Next If i < n Then Recurse(i + 1) Else count += 1UL If echo Then PrintSquare(rlatin) End If End If outer: While False REM empty End While Next End Sub REM remiain rows Recurse(2) Return count End Function Function Factorial(n As ULong) As ULong If n <= 0 Then Return 1 End If Dim prod = 1UL For i = 2UL To n prod *= i Next Return prod End Function Sub Main() Console.WriteLine("The four reduced latin squares of order 4 are:") Console.WriteLine() ReducedLatinSquares(4, True) Console.WriteLine("The size of the set of reduced latin squares for the following orders") Console.WriteLine("and hence the total number of latin squares of these orders are:") Console.WriteLine() For n = 1 To 6 Dim nu As ULong = CULng(n) Dim size = ReducedLatinSquares(n, False) Dim f = Factorial(nu - 1UL) f *= f * nu * size Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f) Next End Sub End Module
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; matrix r = new matrix(); void recurse(int last) { if (last == first) { for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; } } var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f); } } } }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Option Strict On Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer)) Module Module1 Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim u = a a = b b = u End Sub Sub PrintSquare(latin As Matrix) For Each row In latin Dim it = row.GetEnumerator Console.Write("[") If it.MoveNext Then Console.Write(it.Current) End If While it.MoveNext Console.Write(", ") Console.Write(it.Current) End While Console.WriteLine("]") Next Console.WriteLine() End Sub Function DList(n As Integer, start As Integer) As Matrix start -= 1 REM use 0 based indexes Dim a = Enumerable.Range(0, n).ToArray a(start) = a(0) a(0) = start Array.Sort(a, 1, a.Length - 1) Dim first = a(1) REM recursive closure permutes a[1:] Dim r As New Matrix Dim Recurse As Action(Of Integer) = Sub(last As Integer) If last = first Then REM bottom of recursion. you get here once for each permutation REM test if permutation is deranged. For j = 1 To a.Length - 1 Dim v = a(j) If j = v Then Return REM no, ignore it End If Next REM yes, save a copy with 1 based indexing Dim b = a.Select(Function(v) v + 1).ToArray r.Add(b.ToList) Return End If For i = last To 1 Step -1 Swap(a(i), a(last)) Recurse(last - 1) Swap(a(i), a(last)) Next End Sub Recurse(n - 1) Return r End Function Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong If n <= 0 Then If echo Then Console.WriteLine("[]") Console.WriteLine() End If Return 0 End If If n = 1 Then If echo Then Console.WriteLine("[1]") Console.WriteLine() End If Return 1 End If Dim rlatin As New Matrix For i = 0 To n - 1 rlatin.Add(New List(Of Integer)) For j = 0 To n - 1 rlatin(i).Add(0) Next Next REM first row For j = 0 To n - 1 rlatin(0)(j) = j + 1 Next Dim count As ULong = 0 Dim Recurse As Action(Of Integer) = Sub(i As Integer) Dim rows = DList(n, i) For r = 0 To rows.Count - 1 rlatin(i - 1) = rows(r) For k = 0 To i - 2 For j = 1 To n - 1 If rlatin(k)(j) = rlatin(i - 1)(j) Then If r < rows.Count - 1 Then GoTo outer End If If i > 2 Then Return End If End If Next Next If i < n Then Recurse(i + 1) Else count += 1UL If echo Then PrintSquare(rlatin) End If End If outer: While False REM empty End While Next End Sub REM remiain rows Recurse(2) Return count End Function Function Factorial(n As ULong) As ULong If n <= 0 Then Return 1 End If Dim prod = 1UL For i = 2UL To n prod *= i Next Return prod End Function Sub Main() Console.WriteLine("The four reduced latin squares of order 4 are:") Console.WriteLine() ReducedLatinSquares(4, True) Console.WriteLine("The size of the set of reduced latin squares for the following orders") Console.WriteLine("and hence the total number of latin squares of these orders are:") Console.WriteLine() For n = 1 To 6 Dim nu As ULong = CULng(n) Dim size = ReducedLatinSquares(n, False) Dim f = Factorial(nu - 1UL) f *= f * nu * size Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f) Next End Sub End Module
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; matrix r = new matrix(); void recurse(int last) { if (last == first) { for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; } } var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f); } } } }
Write the same algorithm in C# as shown in this VB implementation.
Option Explicit Private Type MyPoint X As Single Y As Single End Type Private Type MyPair p1 As MyPoint p2 As MyPoint End Type Sub Main() Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long Dim T# Randomize Timer Nb = 10 Do ReDim points(1 To Nb) For i = 1 To Nb points(i).X = Rnd * Nb points(i).Y = Rnd * Nb Next d = 1000000000000# T = Timer BF = BruteForce(points, d) Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec." Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y Debug.Print "dist : " & d Debug.Print "--------------------------------------------------" Nb = Nb * 10 Loop While Nb <= 10000 End Sub Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair Dim i As Long, j As Long, d As Single, ClosestPair As MyPair For i = 1 To UBound(p) - 1 For j = i + 1 To UBound(p) d = Dist(p(i), p(j)) If d < mindist Then mindist = d ClosestPair.p1 = p(i) ClosestPair.p2 = p(j) End If Next Next BruteForce = ClosestPair End Function Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2) End Function
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; } public readonly PointF P1; public readonly PointF P2; public float Length() { return (float)Math.Sqrt(LengthSquared()); } public float LengthSquared() { return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y); } }
Can you help me rewrite this code in C# instead of VB, keeping it the same logically?
Dim TheAddress as long Dim SecVar as byte Dim MyVar as byte MyVar = 10 TheAddress = varptr(MyVar) MEMSET(TheAddress, 102, SizeOf(byte)) showmessage "MyVar = " + str$(MyVar) MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte)) showmessage "SecVar = " + str$(SecVar)
int i = 5; int* p = &i;
Change the following VB code into C# without altering its purpose.
Class Animal End Class Class Dog Inherits Animal End Class Class Lab Inherits Dog End Class Class Collie Inherits Dog End Class Class Cat Inherits Animal End Class
class Animal { } class Dog : Animal { } class Lab : Dog { } class Collie : Dog { } class Cat : Animal { }
Preserve the algorithm and functionality while converting the code from VB to C#.
Option Explicit Sub Test() Dim h As Object Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 Debug.Print h.Item("A") h.Item("C") = 4 h.Key("C") = "D" Debug.Print h.exists("C") h.Remove "B" Debug.Print h.Count h.RemoveAll Debug.Print h.Count End Sub
System.Collections.HashTable map = new System.Collections.HashTable(); map["key1"] = "foo";
Translate this program into C# but keep the logic exactly as in VB.
Option explicit Class ImgClass Private ImgL,ImgH,ImgDepth,bkclr,loc,tt private xmini,xmaxi,ymini,ymaxi,dirx,diry public ImgArray() private filename private Palette,szpal public property get xmin():xmin=xmini:end property public property get ymin():ymin=ymini:end property public property get xmax():xmax=xmaxi:end property public property get ymax():ymax=ymaxi:end property public property let depth(x) if x<>8 and x<>32 then err.raise 9 Imgdepth=x end property public sub set0 (x0,y0) if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 xmini=-x0 ymini=-y0 xmaxi=xmini+imgl-1 ymaxi=ymini+imgh-1 end sub Public Default Function Init(name,w,h,orient,dep,bkg,mipal) dim i,j ImgL=w ImgH=h tt=timer loc=getlocale set0 0,0 redim imgArray(ImgL-1,ImgH-1) bkclr=bkg if bkg<>0 then for i=0 to ImgL-1 for j=0 to ImgH-1 imgarray(i,j)=bkg next next end if Select Case orient Case 1: dirx=1 : diry=1 Case 2: dirx=-1 : diry=1 Case 3: dirx=-1 : diry=-1 Case 4: dirx=1 : diry=-1 End select filename=name ImgDepth =dep if imgdepth=8 then loadpal(mipal) end if set init=me end function private sub loadpal(mipale) if isarray(mipale) Then palette=mipale szpal=UBound(mipale)+1 Else szpal=256 , not relevant End if End Sub Private Sub Class_Terminate if err<>0 then wscript.echo "Error " & err.number wscript.echo "copying image to bmp file" savebmp wscript.echo "opening " & filename & " with your default bmp viewer" CreateObject("Shell.Application").ShellExecute filename wscript.echo timer-tt & " iseconds" End Sub function long2wstr( x) dim k1,k2,x1 k1= (x and &hffff&) k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0)) long2wstr=chrw(k1) & chrw(k2) end function function int2wstr(x) int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0))) End Function Public Sub SaveBMP Dim s,ostream, x,y,loc const hdrs=54 dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4) dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0 with CreateObject("ADODB.Stream") .Charset = "UTF-16LE" .Type = 2 .open .writetext ChrW(&h4d42) .writetext long2wstr(hdrs+palsize+bms) .writetext long2wstr(0) .writetext long2wstr (hdrs+palsize) .writetext long2wstr(40) .writetext long2wstr(Imgl) .writetext long2wstr(imgh) .writetext int2wstr(1) .writetext int2wstr(imgdepth) .writetext long2wstr(&H0) .writetext long2wstr(bms) .writetext long2wstr(&Hc4e) .writetext long2wstr(&hc43) .writetext long2wstr(szpal) .writetext long2wstr(&H0) Dim x1,x2,y1,y2 If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1 If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 Select Case imgdepth Case 32 For y=y1 To y2 step diry For x=x1 To x2 Step dirx .writetext long2wstr(Imgarray(x,y)) Next Next Case 8 For x=0 to szpal-1 .writetext long2wstr(palette(x)) Next dim pad:pad=ImgL mod 4 For y=y1 to y2 step diry For x=x1 To x2 step dirx*2 .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255)) Next if pad and 1 then .writetext chrw(ImgArray(x2,y)) if pad >1 then .writetext chrw(0) Next Case Else WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits" End Select Dim outf:Set outf= CreateObject("ADODB.Stream") outf.Type = 1 outf.Open .position=2 .CopyTo outf .close outf.savetofile filename,2 outf.close end with End Sub end class function hsv2rgb( Hue, Sat, Value) dim Angle, Radius,Ur,Vr,Wr,Rdim dim r,g,b, rgb Angle = (Hue-150) *0.01745329251994329576923690768489 Ur = Value * 2.55 Radius = Ur * tan(Sat *0.01183199) Vr = Radius * cos(Angle) *0.70710678 Wr = Radius * sin(Angle) *0.40824829 r = (Ur - Vr - Wr) g = (Ur + Vr - Wr) b = (Ur + Wr + Wr) if r >255 then Rdim = (Ur - 255) / (Vr + Wr) r = 255 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim elseif r < 0 then Rdim = Ur / (Vr + Wr) r = 0 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim end if if g >255 then Rdim = (255 - Ur) / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 255 b = Ur + 2 * Wr * Rdim elseif g<0 then Rdim = -Ur / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 0 b = Ur + 2 * Wr * Rdim end if if b>255 then Rdim = (255 - Ur) / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 255 elseif b<0 then Rdim = -Ur / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 0 end If hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff) end function function ang(col,row) if col =0 then if row<0 then ang=90 else ang=270 end if else if col>0 then ang=atn(-row/col)*57.2957795130 else ang=(atn(row/-col)*57.2957795130)+180 end if end if ang=(ang+360) mod 360 end function Dim X,row,col,fn,tt,hr,sat,row2 const h=160 const w=160 const rad=159 const r2=25500 tt=timer fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp" Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0) x.set0 w,h for row=x.xmin+1 to x.xmax row2=row*row hr=int(Sqr(r2-row2)) For col=hr To 159 Dim a:a=((col\16 +row\16) And 1)* &hffffff x.imgArray(col+160,row+160)=a x.imgArray(-col+160,row+160)=a next for col=-hr to hr sat=100-sqr(row2+col*col)/rad *50 x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat) next next Set X = Nothing
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality); imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null); DrawHue(100); } void DrawHue(int saturation) { var bmp = (WriteableBitmap)imgMain.Source; int centerX = (int)bmp.Width / 2; int centerY = (int)bmp.Height / 2; int radius = Math.Min(centerX, centerY); int radius2 = radius - 40; bmp.Lock(); unsafe{ var buf = bmp.BackBuffer; IntPtr pixLineStart; for(int y=0; y < bmp.Height; y++){ pixLineStart = buf + bmp.BackBufferStride * y; double dy = (y - centerY); for(int x=0; x < bmp.Width; x++){ double dx = (x - centerX); double dist = Math.Sqrt(dx * dx + dy * dy); if (radius2 <= dist && dist <= radius) { double theta = Math.Atan2(dy, dx); double hue = (theta + Math.PI) / (2.0 * Math.PI); *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100); } } } } bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480)); bmp.Unlock(); } static int HSB_to_RGB(int h, int s, int v) { var rgb = new int[3]; var baseColor = (h + 60) % 360 / 120; var shift = (h + 60) % 360 - (120 * baseColor + 60 ); var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3; rgb[baseColor] = 255; rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f); for (var i = 0; i < 3; i++) rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f)); for (var i = 0; i < 3; i++) rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f); return RGB2int(rgb[0], rgb[1], rgb[2]); } public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
Preserve the algorithm and functionality while converting the code from VB to C#.
Imports System.Console Imports DT = System.DateTime Imports Lsb = System.Collections.Generic.List(Of SByte) Imports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte)) Imports UI = System.UInt64 Module Module1 Const MxD As SByte = 15 Public Structure term Public coeff As UI : Public a, b As SByte Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer) coeff = c : a = CSByte(a_) : b = CSByte(b_) End Sub End Structure Dim nd, nd2, count As Integer, digs, cnd, di As Integer() Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term)) Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst) Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI Function ToDif() As UI Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i) Next : Return r End Function Function ToSum() As UI Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i) Next : Return Dif + (r << 1) End Function Function IsSquare(nmbr As UI) As Boolean If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _ Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False End Function Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb Dim res As Lsb = New Lsb() For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res End Function Sub Fnpr(ByVal lev As Integer) If lev = dis.Count Then digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1) Dim le As Integer = di.Length, i As Integer = 1 If odd Then le -= 1 : digs(nd >> 1) = di(le) For Each d As SByte In di.Skip(1).Take(le - 1) digs(ixs(i)(0)) = dmd(cnd(i))(d)(0) digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next If Not IsSquare(ToSum()) Then Return res.Add(ToDif()) : count += 1 WriteLine("{0,16:n0}{1,4} ({2:n0})", (DT.Now - st).TotalMilliseconds, count, res.Last()) Else For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next End If End Sub Sub Fnmr(ByVal list As Lst, ByVal lev As Integer) If lev = list.Count Then Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2) If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _ Else Dif += t.coeff * CULng(cnd(i)) i += 1 : Next If Dif <= 0 OrElse Not IsSquare(Dif) Then Return dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)} For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next If odd Then dis.Add(il) di = New Integer(dis.Count - 1) {} : Fnpr(0) Else For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next End If End Sub Sub init() Dim pow As UI = 1 tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD) Dim terms As List(Of term) = New List(Of term)() pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1 Dim i1 As Integer = 0, i2 As Integer = r - 1 While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2)) p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While tLst.Add(terms) : Next fml = New Dictionary(Of Integer, Lst)() From { {0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}}, {1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}}, {4, New Lst() From {New Lsb() From {4, 0}}}, {6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}} dmd = New Dictionary(Of Integer, Lst)() For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _ Else dmd(d) = New Lst From {New Lsb From {i, j}} j += 1 : d -= 1 : End While : Next dl = Seq(-9, 9) zl = Seq(0, 0) el = Seq(-8, 8, 2) ol = Seq(-9, 9, 2) il = Seq(0, 9) lists = New List(Of Lst)() For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next End Sub Sub Main(ByVal args As String()) init() : res = New List(Of UI)() : st = DT.Now : count = 0 WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Rare Numbers") nd = 2 : nd2 = 0 : odd = False : While nd <= MxD digs = New Integer(nd - 1) {} : If nd = 4 Then lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol) ElseIf tLst(nd2).Count > lists(0).Count Then For Each list As Lst In lists : list.Add(dl) : Next : End If ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds) nd += 1 : nd2 += 1 : odd = Not odd : End While res.Sort() : WriteLine(vbLf & "The {0} rare numbers with up to {1} digits are:", res.Count, MxD) count = 0 : For Each rare In res : count += 1 : WriteLine("{0,2}:{1,27:n0}", count, rare) : Next If System.Diagnostics.Debugger.IsAttached Then ReadKey() End Sub End Module
using System; using System.Collections.Generic; using System.Linq; using static System.Console; using UI = System.UInt64; using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>; using Lst = System.Collections.Generic.List<sbyte>; using DT = System.DateTime; class Program { const sbyte MxD = 19; public struct term { public UI coeff; public sbyte a, b; public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } } static int[] digs; static List<UI> res; static sbyte count = 0; static DT st; static List<List<term>> tLst; static List<LST> lists; static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il; static bool odd; static int nd, nd2; static LST ixs; static int[] cnd, di; static LST dis; static UI Dif; static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++) r = r * 10 + (uint)digs[i]; return r; } static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--) r = r * 10 + (uint)digs[i]; return Dif + (r << 1); } static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0) { UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; } static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst(); for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; } static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0]; digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1; if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) { digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; } if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine("{0,16:n0}{1,4} ({2:n0})", (DT.Now - st).TotalMilliseconds, ++count, res.Last()); } else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } } static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0; foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]); else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return; dis = new LST { Seq(0, fml[cnd[0]].Count - 1) }; foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1)); if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0); } else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } } static void init() { UI pow = 1; tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) { List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1; for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) { terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; } tLst.Add(terms); } fml = new Dictionary<int, LST> { [0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } }, [1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } }, [4] = new LST { new Lst { 4, 0 } }, [6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } }; dmd = new Dictionary<int, LST>(); for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) { if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j }); else dmd[d] = new LST { new Lst { i, j } }; } dl = Seq(-9, 9); zl = Seq( 0, 0); el = Seq(-8, 8, 2); ol = Seq(-9, 9, 2); il = Seq( 0, 9); lists = new List<LST>(); foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); } static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0; WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Unordered Rare Numbers"); for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd]; if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); } else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl); ixs = new LST(); foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b }); foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); } WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds); } res.Sort(); WriteLine("\nThe {0} rare numbers with up to {1} digits are:", res.Count, MxD); count = 0; foreach (var rare in res) WriteLine("{0,2}:{1,27:n0}", ++count, rare); if (System.Diagnostics.Debugger.IsAttached) ReadKey(); } }
Produce a functionally identical C# code for the snippet given in VB.
Option Explicit Public vTime As Single Public PlaysCount As Long Sub Main_MineSweeper() Dim Userf As New cMinesweeper Userf.Show 0, True End Sub
using System; using System.Drawing; using System.Windows.Forms; class MineFieldModel { public int RemainingMinesCount{ get{ var count = 0; ForEachCell((i,j)=>{ if (Mines[i,j] && !Marked[i,j]) count++; }); return count; } } public bool[,] Mines{get; private set;} public bool[,] Opened{get;private set;} public bool[,] Marked{get; private set;} public int[,] Values{get;private set; } public int Width{ get{return Mines.GetLength(1);} } public int Height{ get{return Mines.GetLength(0);} } public MineFieldModel(bool[,] mines) { this.Mines = mines; this.Opened = new bool[Height, Width]; this.Marked = new bool[Height, Width]; this.Values = CalculateValues(); } private int[,] CalculateValues() { int[,] values = new int[Height, Width]; ForEachCell((i,j) =>{ var value = 0; ForEachNeighbor(i,j, (i1,j1)=>{ if (Mines[i1,j1]) value++; }); values[i,j] = value; }); return values; } public void ForEachCell(Action<int,int> action) { for (var i = 0; i < Height; i++) for (var j = 0; j < Width; j++) action(i,j); } public void ForEachNeighbor(int i, int j, Action<int,int> action) { for (var i1 = i-1; i1 <= i+1; i1++) for (var j1 = j-1; j1 <= j+1; j1++) if (InBounds(j1, i1) && !(i1==i && j1 ==j)) action(i1, j1); } private bool InBounds(int x, int y) { return y >= 0 && y < Height && x >=0 && x < Width; } public event Action Exploded = delegate{}; public event Action Win = delegate{}; public event Action Updated = delegate{}; public void OpenCell(int i, int j){ if(!Opened[i,j]){ if (Mines[i,j]) Exploded(); else{ OpenCellsStartingFrom(i,j); Updated(); CheckForVictory(); } } } void OpenCellsStartingFrom(int i, int j) { Opened[i,j] = true; ForEachNeighbor(i,j, (i1,j1)=>{ if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1]) OpenCellsStartingFrom(i1, j1); }); } void CheckForVictory(){ int notMarked = 0; int wrongMarked = 0; ForEachCell((i,j)=>{ if (Mines[i,j] && !Marked[i,j]) notMarked++; if (!Mines[i,j] && Marked[i,j]) wrongMarked++; }); if (notMarked == 0 && wrongMarked == 0) Win(); } public void Mark(int i, int j){ if (!Opened[i,j]) Marked[i,j] = true; Updated(); CheckForVictory(); } } class MineFieldView: UserControl{ public const int CellSize = 40; MineFieldModel _model; public MineFieldModel Model{ get{ return _model; } set { _model = value; this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2); } } public MineFieldView(){ this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true); this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold); this.MouseUp += (o,e)=>{ Point cellCoords = GetCell(e.Location); if (Model != null) { if (e.Button == MouseButtons.Left) Model.OpenCell(cellCoords.Y, cellCoords.X); else if (e.Button == MouseButtons.Right) Model.Mark(cellCoords.Y, cellCoords.X); } }; } Point GetCell(Point coords) { var rgn = ClientRectangle; var x = (coords.X - rgn.X)/CellSize; var y = (coords.Y - rgn.Y)/CellSize; return new Point(x,y); } static readonly Brush MarkBrush = new SolidBrush(Color.Blue); static readonly Brush ValueBrush = new SolidBrush(Color.Black); static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control); static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark); protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var g = e.Graphics; if (Model != null) { Model.ForEachCell((i,j)=> { var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize); if (Model.Opened[i,j]) { g.FillRectangle(OpenBrush, bounds); if (Model.Values[i,j] > 0) { DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds); } } else { g.FillRectangle(UnexploredBrush, bounds); if (Model.Marked[i,j]) { DrawStringInCenter(g, "?", MarkBrush, bounds); } var outlineOffset = 1; var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset); g.DrawRectangle(Pens.Gray, outline); } g.DrawRectangle(Pens.Black, bounds); }); } } static readonly StringFormat FormatCenter = new StringFormat { LineAlignment = StringAlignment.Center, Alignment=StringAlignment.Center }; void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds) { PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2); g.DrawString(s, this.Font, brush, center, FormatCenter); } } class MineSweepForm: Form { MineFieldModel CreateField(int width, int height) { var field = new bool[height, width]; int mineCount = (int)(0.2 * height * width); var rnd = new Random(); while(mineCount > 0) { var x = rnd.Next(width); var y = rnd.Next(height); if (!field[y,x]) { field[y,x] = true; mineCount--; } } return new MineFieldModel(field); } public MineSweepForm() { var model = CreateField(6, 4); var counter = new Label{ }; counter.Text = model.RemainingMinesCount.ToString(); var view = new MineFieldView { Model = model, BorderStyle = BorderStyle.FixedSingle, }; var stackPanel = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, Controls = {counter, view} }; this.Controls.Add(stackPanel); model.Updated += delegate{ view.Invalidate(); counter.Text = model.RemainingMinesCount.ToString(); }; model.Exploded += delegate { MessageBox.Show("FAIL!"); Close(); }; model.Win += delegate { MessageBox.Show("WIN!"); view.Enabled = false; }; } } class Program { static void Main() { Application.Run(new MineSweepForm()); } }
Write the same code in C# as shown below in VB.
Imports System.Math, System.Console, BI = System.Numerics.BigInteger Module Module1 Sub Main(ByVal args As String()) Dim i, j, k, d As BI : i = 2 j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j Dim n As Integer = -1, n0 As Integer = -1, st As DateTime = DateTime.Now If args.Length > 0 Then Integer.TryParse(args(0), n) If n > 0 Then n0 = n Else n = 1 Do Write(d) : i = (i - k * d) * 100 : k = 20 * j For d = 1 To 10 If (k + d) * d > i Then d -= 1 : Exit For Next j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1 Loop While n > 0 If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st) End Sub End Module
using System; using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { BI i, j, k, d; i = 2; int n = -1; int n0 = -1; j = (BI)Floor(Sqrt((double)i)); k = j; d = j; DateTime st = DateTime.Now; if (args.Length > 0) int.TryParse(args[0], out n); if (n > 0) n0 = n; else n = 1; do { Write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d++) if ((k + d) * d > i) { d -= 1; break; } j = j * 10 + d; k += d; if (n0 > 0) n--; } while (n > 0); if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); } }
Maintain the same structure and functionality when rewriting this code in C#.
Imports System.Math, System.Console, BI = System.Numerics.BigInteger Module Module1 Sub Main(ByVal args As String()) Dim i, j, k, d As BI : i = 2 j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j Dim n As Integer = -1, n0 As Integer = -1, st As DateTime = DateTime.Now If args.Length > 0 Then Integer.TryParse(args(0), n) If n > 0 Then n0 = n Else n = 1 Do Write(d) : i = (i - k * d) * 100 : k = 20 * j For d = 1 To 10 If (k + d) * d > i Then d -= 1 : Exit For Next j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1 Loop While n > 0 If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st) End Sub End Module
using System; using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { BI i, j, k, d; i = 2; int n = -1; int n0 = -1; j = (BI)Floor(Sqrt((double)i)); k = j; d = j; DateTime st = DateTime.Now; if (args.Length > 0) int.TryParse(args[0], out n); if (n > 0) n0 = n; else n = 1; do { Write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d++) if ((k + d) * d > i) { d -= 1; break; } j = j * 10 + d; k += d; if (n0 > 0) n--; } while (n > 0); if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); } }
Write the same code in C# as shown below in VB.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean, j As Integer : Yield 2 For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3 Dim d As Integer = 8, sq As Integer = 9 While sq <= lim If Not flags(j) Then Yield j : Dim i As Integer = j << 1 For k As Integer = sq To lim step i : flags(k) = True : Next End If j += 2 : d += 8 : sq += d : End While While j <= lim If Not flags(j) Then Yield j j += 2 : End While End Function Function from10(ByVal b As Integer) As String Dim res As String = "", re As Integer While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res End Function Function to10(ByVal s As String) As Integer Dim res As Integer = 0 For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res End Function Function nd(ByVal s As String) As Boolean If s.Length < 2 Then Return True Dim l As Char = s(0) For i As Integer = 1 To s.Length - 1 If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i) Next : Return True End Function Sub Main(ByVal args As String()) Dim c As Integer, lim As Integer = 1000, s As String For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 } ba = b : c = 0 : For Each a As Integer In Primes(lim) s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, "")) Next WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim)) Next End Sub End Module
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; } static int to10(string s) { int res = 0; foreach (char i in s) res = res * ba + chars.IndexOf(i); return res; } static bool nd(string s) { if (s.Length < 2) return true; char l = s[0]; for (int i = 1; i < s.Length; i++) if (chars.IndexOf(l) > chars.IndexOf(s[i])) return false; else l = s[i] ; return true; } static void Main(string[] args) { int c, lim = 1000; string s; foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) { ba = b; c = 0; foreach (var a in PG.Primes(lim)) if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : ""); WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j; yield return 2; for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Generate an equivalent C# version of this VB code.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean, j As Integer : Yield 2 For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3 Dim d As Integer = 8, sq As Integer = 9 While sq <= lim If Not flags(j) Then Yield j : Dim i As Integer = j << 1 For k As Integer = sq To lim step i : flags(k) = True : Next End If j += 2 : d += 8 : sq += d : End While While j <= lim If Not flags(j) Then Yield j j += 2 : End While End Function Function from10(ByVal b As Integer) As String Dim res As String = "", re As Integer While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res End Function Function to10(ByVal s As String) As Integer Dim res As Integer = 0 For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res End Function Function nd(ByVal s As String) As Boolean If s.Length < 2 Then Return True Dim l As Char = s(0) For i As Integer = 1 To s.Length - 1 If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i) Next : Return True End Function Sub Main(ByVal args As String()) Dim c As Integer, lim As Integer = 1000, s As String For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 } ba = b : c = 0 : For Each a As Integer In Primes(lim) s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, "")) Next WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim)) Next End Sub End Module
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; } static int to10(string s) { int res = 0; foreach (char i in s) res = res * ba + chars.IndexOf(i); return res; } static bool nd(string s) { if (s.Length < 2) return true; char l = s[0]; for (int i = 1; i < s.Length; i++) if (chars.IndexOf(l) > chars.IndexOf(s[i])) return false; else l = s[i] ; return true; } static void Main(string[] args) { int c, lim = 1000; string s; foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) { ba = b; c = 0; foreach (var a in PG.Primes(lim)) if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : ""); WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j; yield return 2; for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Translate the given VB code snippet into C# without altering its behavior.
Imports System.Reflection Module Module1 Class TestClass Private privateField = 7 Public ReadOnly Property PublicNumber = 4 Private ReadOnly Property PrivateNumber = 2 End Class Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return From p In obj.GetType().GetProperties(flags) Where p.GetIndexParameters().Length = 0 Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)} End Function Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)}) End Function Sub Main() Dim t As New TestClass() Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance For Each prop In GetPropertyValues(t, flags) Console.WriteLine(prop) Next For Each field In GetFieldValues(t, flags) Console.WriteLine(field) Next End Sub End Module
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetPropertyValues(t, flags)) { Console.WriteLine(prop); } foreach (var field in GetFieldValues(t, flags)) { Console.WriteLine(field); } } public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) => from p in typeof(T).GetProperties(flags) where p.GetIndexParameters().Length == 0 select (p.Name, p.GetValue(obj, null)); public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) => typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj))); class TestClass { private int privateField = 7; public int PublicNumber { get; } = 4; private int PrivateNumber { get; } = 2; } }
Preserve the algorithm and functionality while converting the code from VB to C#.
Dim MText as QMemorystream MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" MText.WriteLine "are$delineated$by$a$single$ MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" MText.WriteLine "column$are$separated$by$at$least$one$space." MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$" MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column." DefStr TextLeft, TextRight, TextCenter DefStr MLine, LWord, Newline = chr$(13)+chr$(10) DefInt ColWidth(100), ColCount DefSng NrSpaces MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y)) next next MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) NrSpaces = ColWidth(y) - len(LWord) TextLeft = TextLeft + LWord + Space$(NrSpaces+1) TextRight = TextRight + Space$(NrSpaces+1) + LWord TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2)) next TextLeft = TextLeft + Newline TextRight = TextRight + Newline TextCenter = TextCenter + Newline next
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width); static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; string[][] table = new string[lines.Length][]; int columns = 0; for (int i = 0; i < lines.Length; i++) { string[] row = lines[i].TrimEnd(Separator).Split(Separator); if (columns < row.Length) columns = row.Length; table[i] = row; } string[][] formattedTable = new string[table.Length][]; for (int i = 0; i < formattedTable.Length; i++) { formattedTable[i] = new string[columns]; } for (int j = 0; j < columns; j++) { int columnWidth = 0; for (int i = 0; i < table.Length; i++) { if (j < table[i].Length && columnWidth < table[i][j].Length) columnWidth = table[i][j].Length; } for (int i = 0; i < formattedTable.Length; i++) { if (j < table[i].Length) formattedTable[i][j] = justification(table[i][j], columnWidth); else formattedTable[i][j] = new String(' ', columnWidth); } } string[] result = new string[formattedTable.Length]; for (int i = 0; i < result.Length; i++) { result[i] = String.Join(" ", formattedTable[i]); } return result; } static string JustifyLeft(string s, int width) { return s.PadRight(width); } static string JustifyRight(string s, int width) { return s.PadLeft(width); } static string JustifyCenter(string s, int width) { return s.PadLeft((width + s.Length) / 2).PadRight(width); } static void Main() { string[] input = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column.", }; foreach (string line in AlignColumns(input, JustifyCenter)) { Console.WriteLine(line); } } }
Write the same algorithm in C# as shown in this VB implementation.
Dim MText as QMemorystream MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" MText.WriteLine "are$delineated$by$a$single$ MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" MText.WriteLine "column$are$separated$by$at$least$one$space." MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$" MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column." DefStr TextLeft, TextRight, TextCenter DefStr MLine, LWord, Newline = chr$(13)+chr$(10) DefInt ColWidth(100), ColCount DefSng NrSpaces MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y)) next next MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) NrSpaces = ColWidth(y) - len(LWord) TextLeft = TextLeft + LWord + Space$(NrSpaces+1) TextRight = TextRight + Space$(NrSpaces+1) + LWord TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2)) next TextLeft = TextLeft + Newline TextRight = TextRight + Newline TextCenter = TextCenter + Newline next
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width); static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; string[][] table = new string[lines.Length][]; int columns = 0; for (int i = 0; i < lines.Length; i++) { string[] row = lines[i].TrimEnd(Separator).Split(Separator); if (columns < row.Length) columns = row.Length; table[i] = row; } string[][] formattedTable = new string[table.Length][]; for (int i = 0; i < formattedTable.Length; i++) { formattedTable[i] = new string[columns]; } for (int j = 0; j < columns; j++) { int columnWidth = 0; for (int i = 0; i < table.Length; i++) { if (j < table[i].Length && columnWidth < table[i][j].Length) columnWidth = table[i][j].Length; } for (int i = 0; i < formattedTable.Length; i++) { if (j < table[i].Length) formattedTable[i][j] = justification(table[i][j], columnWidth); else formattedTable[i][j] = new String(' ', columnWidth); } } string[] result = new string[formattedTable.Length]; for (int i = 0; i < result.Length; i++) { result[i] = String.Join(" ", formattedTable[i]); } return result; } static string JustifyLeft(string s, int width) { return s.PadRight(width); } static string JustifyRight(string s, int width) { return s.PadLeft(width); } static string JustifyCenter(string s, int width) { return s.PadLeft((width + s.Length) / 2).PadRight(width); } static void Main() { string[] input = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column.", }; foreach (string line in AlignColumns(input, JustifyCenter)) { Console.WriteLine(line); } } }
Rewrite the snippet below in C# so it works the same as the original VB code.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Change the following VB code into C# without altering its purpose.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Generate an equivalent C# version of this VB code.
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
Write a version of this VB function in C# with identical behavior.
Imports System.IO Imports System.Security.Cryptography Module Module1 Function ByteArrayToString(ba As Byte()) As String Return BitConverter.ToString(ba).Replace("-", "") End Function Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte() Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} Dim provider As New DESCryptoServiceProvider Dim transform = provider.CreateEncryptor(passwordBytes, iv) Dim mode = CryptoStreamMode.Write Dim memStream As New MemoryStream Dim cryptoStream As New CryptoStream(memStream, transform, mode) cryptoStream.Write(messageBytes, 0, messageBytes.Length) cryptoStream.FlushFinalBlock() Dim encryptedMessageBytes(memStream.Length - 1) As Byte memStream.Position = 0 memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length) Return encryptedMessageBytes End Function Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte() Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} Dim provider As New DESCryptoServiceProvider Dim transform = provider.CreateDecryptor(passwordBytes, iv) Dim mode = CryptoStreamMode.Write Dim memStream As New MemoryStream Dim cryptoStream As New CryptoStream(memStream, transform, mode) cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length) cryptoStream.FlushFinalBlock() Dim decryptedMessageBytes(memStream.Length - 1) As Byte memStream.Position = 0 memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length) Return decryptedMessageBytes End Function Sub Main() Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73} Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87} Dim encStr = Encrypt(plainBytes, keyBytes) Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr)) Dim decStr = Decrypt(encStr, keyBytes) Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr)) End Sub End Module
using System; using System.IO; using System.Security.Cryptography; namespace DES { class Program { static string ByteArrayToString(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); } static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) { byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv); CryptoStreamMode mode = CryptoStreamMode.Write; MemoryStream memStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode); cryptoStream.Write(messageBytes, 0, messageBytes.Length); cryptoStream.FlushFinalBlock(); byte[] encryptedMessageBytes = new byte[memStream.Length]; memStream.Position = 0; memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length); return encryptedMessageBytes; } static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) { byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv); CryptoStreamMode mode = CryptoStreamMode.Write; MemoryStream memStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode); cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length); cryptoStream.FlushFinalBlock(); byte[] decryptedMessageBytes = new byte[memStream.Length]; memStream.Position = 0; memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length); return decryptedMessageBytes; } static void Main(string[] args) { byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 }; byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 }; byte[] encStr = Encrypt(plainBytes, keyBytes); Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr)); byte[] decBytes = Decrypt(encStr, keyBytes); Console.WriteLine("Decoded: {0}", ByteArrayToString(decBytes)); } } }
Translate this program into C# but keep the logic exactly as in VB.
Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3) Dim l As Integer: l = Len(s) For i = start To l If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then For j = i + 1 To l + 1 If j > l Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For Else If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For End If End If Next j Exit For End If Next i Debug.Print s End Sub Public Sub main() commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5 commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "." commatize """-in Aus$+1411.8millions""" commatize "===US$0017440 millions=== (in 2000 dollars)" commatize "123.e8000 is pretty big." commatize "The land area of the earth is 57268900(29% of the surface) square miles." commatize "Ain commatize "James was never known as 0000000007" commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." commatize " $-140000±100 millions." commatize "6/9/1946 was a good year for some." End Sub
static string[] inputs = { "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "\"-in Aus$+1411.8millions\"", "===US$0017440 millions=== (in 2000 dollars)" }; void Main() { inputs.Select(s => Commatize(s, 0, 3, ",")) .ToList() .ForEach(Console.WriteLine); } string Commatize(string text, int startPosition, int interval, string separator) { var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*"); var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList(); return string.Join("", x); } string Commatize(Match match, int interval, string separator, string original) { if (match.Length <= interval) return original.Substring(match.Index, match.Index == original.Length ? 0 : Math.Max(match.Length, 1)); return string.Join(separator, match.Value.Split(interval)); } public static class Extension { public static string[] Split(this string source, int interval) { return SplitImpl(source, interval).ToArray(); } static IEnumerable<string>SplitImpl(string source, int interval) { for (int i = 1; i < source.Length; i++) { if (i % interval != 0) continue; yield return source.Substring(i - interval, interval); } } }
Rewrite this program in C# while keeping its functionality equivalent to the VB version.
Imports System.Numerics Imports System.Text Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long) Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long)) Module Module1 Function CumulativeFreq(freq As Freq) As Freq Dim total As Long = 0 Dim cf As New Freq For i = 0 To 255 Dim c = Chr(i) If freq.ContainsKey(c) Then Dim v = freq(c) cf(c) = total total += v End If Next Return cf End Function Function ArithmeticCoding(str As String, radix As Long) As Triple Dim freq As New Freq For Each c In str If freq.ContainsKey(c) Then freq(c) += 1 Else freq(c) = 1 End If Next Dim cf = CumulativeFreq(freq) Dim base As BigInteger = str.Length Dim lower As BigInteger = 0 Dim pf As BigInteger = 1 For Each c In str Dim x = cf(c) lower = lower * base + x * pf pf = pf * freq(c) Next Dim upper = lower + pf Dim powr = 0 Dim bigRadix As BigInteger = radix While True pf = pf / bigRadix If pf = 0 Then Exit While End If powr = powr + 1 End While Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)) Return New Triple(diff, powr, freq) End Function Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String Dim powr As BigInteger = radix Dim enc = num * BigInteger.Pow(powr, pwr) Dim base = freq.Values.Sum() Dim cf = CumulativeFreq(freq) Dim dict As New Dictionary(Of Long, Char) For Each key In cf.Keys Dim value = cf(key) dict(value) = key Next Dim lchar As Long = -1 For i As Long = 0 To base - 1 If dict.ContainsKey(i) Then lchar = AscW(dict(i)) Else dict(i) = ChrW(lchar) End If Next Dim decoded As New StringBuilder Dim bigBase As BigInteger = base For i As Long = base - 1 To 0 Step -1 Dim pow = BigInteger.Pow(bigBase, i) Dim div = enc / pow Dim c = dict(div) Dim fv = freq(c) Dim cv = cf(c) Dim diff = enc - pow * cv enc = diff / fv decoded.Append(c) Next Return decoded.ToString() End Function Sub Main() Dim radix As Long = 10 Dim strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"} For Each St In strings Dim encoded = ArithmeticCoding(St, radix) Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3) Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", St, encoded.Item1, radix, encoded.Item2) If St <> dec Then Throw New Exception(vbTab + "However that is incorrect!") End If Next End Sub End Module
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; namespace AruthmeticCoding { using Freq = Dictionary<char, long>; using Triple = Tuple<BigInteger, int, Dictionary<char, long>>; class Program { static Freq CumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; i++) { char c = (char)i; if (freq.ContainsKey(c)) { long v = freq[c]; cf[c] = total; total += v; } } return cf; } static Triple ArithmeticCoding(string str, long radix) { Freq freq = new Freq(); foreach (char c in str) { if (freq.ContainsKey(c)) { freq[c] += 1; } else { freq[c] = 1; } } Freq cf = CumulativeFreq(freq); BigInteger @base = str.Length; BigInteger lower = 0; BigInteger pf = 1; foreach (char c in str) { BigInteger x = cf[c]; lower = lower * @base + x * pf; pf = pf * freq[c]; } BigInteger upper = lower + pf; int powr = 0; BigInteger bigRadix = radix; while (true) { pf = pf / bigRadix; if (pf == 0) break; powr++; } BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)); return new Triple(diff, powr, freq); } static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = radix; BigInteger enc = num * BigInteger.Pow(powr, pwr); long @base = freq.Values.Sum(); Freq cf = CumulativeFreq(freq); Dictionary<long, char> dict = new Dictionary<long, char>(); foreach (char key in cf.Keys) { long value = cf[key]; dict[value] = key; } long lchar = -1; for (long i = 0; i < @base; i++) { if (dict.ContainsKey(i)) { lchar = dict[i]; } else if (lchar != -1) { dict[i] = (char)lchar; } } StringBuilder decoded = new StringBuilder((int)@base); BigInteger bigBase = @base; for (long i = @base - 1; i >= 0; --i) { BigInteger pow = BigInteger.Pow(bigBase, (int)i); BigInteger div = enc / pow; char c = dict[(long)div]; BigInteger fv = freq[c]; BigInteger cv = cf[c]; BigInteger diff = enc - pow * cv; enc = diff / fv; decoded.Append(c); } return decoded.ToString(); } static void Main(string[] args) { long radix = 10; string[] strings = { "DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT" }; foreach (string str in strings) { Triple encoded = ArithmeticCoding(str, radix); string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3); Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", str, encoded.Item1, radix, encoded.Item2); if (str != dec) { throw new Exception("\tHowever that is incorrect!"); } } } } }
Preserve the algorithm and functionality while converting the code from VB to C#.
Module Module1 Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer) Dim size = g.Count Dim vis(size - 1) As Boolean Dim l(size - 1) As Integer Dim x = size Dim t As New List(Of List(Of Integer)) For i = 1 To size t.Add(New List(Of Integer)) Next Dim visit As Action(Of Integer) = Sub(u As Integer) If Not vis(u) Then vis(u) = True For Each v In g(u) visit(v) t(v).Add(u) Next x -= 1 l(x) = u End If End Sub For i = 1 To size visit(i - 1) Next Dim c(size - 1) As Integer Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer) If vis(u) Then vis(u) = False c(u) = root For Each v In t(u) assign(v, root) Next End If End Sub For Each u In l assign(u, u) Next Return c.ToList End Function Sub Main() Dim g = New List(Of List(Of Integer)) From { New List(Of Integer) From {1}, New List(Of Integer) From {2}, New List(Of Integer) From {0}, New List(Of Integer) From {1, 2, 4}, New List(Of Integer) From {3, 5}, New List(Of Integer) From {2, 6}, New List(Of Integer) From {5}, New List(Of Integer) From {4, 6, 7} } Dim output = Kosaraju(g) Console.WriteLine("[{0}]", String.Join(", ", output)) End Sub End Module
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
Write the same code in C# as shown below in VB.
Public s As String Public t As Integer Function s1() s1 = Len(s) = 12 End Function Function s2() t = 0 For i = 7 To 12 t = t - (Mid(s, i, 1) = "1") Next i s2 = t = 3 End Function Function s3() t = 0 For i = 2 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s3 = t = 2 End Function Function s4() s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1")) End Function Function s5() s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0" End Function Function s6() t = 0 For i = 1 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s6 = t = 4 End Function Function s7() s7 = Mid(s, 2, 1) <> Mid(s, 3, 1) End Function Function s8() s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1") End Function Function s9() t = 0 For i = 1 To 6 t = t - (Mid(s, i, 1) = "1") Next i s9 = t = 3 End Function Function s10() s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1" End Function Function s11() t = 0 For i = 7 To 9 t = t - (Mid(s, i, 1) = "1") Next i s11 = t = 1 End Function Function s12() t = 0 For i = 1 To 11 t = t - (Mid(s, i, 1) = "1") Next i s12 = t = 4 End Function Public Sub twelve_statements() For i = 0 To 2 ^ 12 - 1 s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _ & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7) For b = 1 To 12 Select Case b Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For End Select If b = 12 Then Debug.Print s Next Next End Sub
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
Please provide an equivalent version of this Python code in Go.
import sys print(sys.getrecursionlimit())
package main import ( "flag" "fmt" "runtime/debug" ) func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) } func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
Convert this Python block to Go, preserving its control flow and logic.
class Isprime(): multiples = {2} primes = [2] nmax = 2 def __init__(self, nmax): if nmax > self.nmax: self.check(nmax) def check(self, n): if type(n) == float: if not n.is_integer(): return False n = int(n) multiples = self.multiples if n <= self.nmax: return n not in multiples else: primes, nmax = self.primes, self.nmax newmax = max(nmax*2, n) for p in primes: multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p)) for i in range(nmax+1, newmax+1): if i not in multiples: primes.append(i) multiples.update(range(i*2, newmax+1, i)) self.nmax = newmax return n not in multiples __call__ = check def carmichael(p1): ans = [] if isprime(p1): for h3 in range(2, p1): g = h3 + p1 for d in range(1, g): if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3: p2 = 1 + ((p1 - 1)* g // d) if isprime(p2): p3 = 1 + (p1 * p2 // h3) if isprime(p3): if (p2 * p3) % (p1 - 1) == 1: ans += [tuple(sorted((p1, p2, p3)))] return ans isprime = Isprime(2) ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), [])) print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
package main import "fmt" func mod(n, m int) int { return ((n % m) + m) % m } func isPrime(n int) bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } d := 5 for d * d <= n { if n % d == 0 { return false } d += 2 if n % d == 0 { return false } d += 4 } return true } func carmichael(p1 int) { for h3 := 2; h3 < p1; h3++ { for d := 1; d < h3 + p1; d++ { if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 { p2 := 1 + (p1 - 1) * (h3 + p1) / d if !isPrime(p2) { continue } p3 := 1 + p1 * p2 / h3 if !isPrime(p3) { continue } if p2 * p3 % (p1 - 1) != 1 { continue } c := p1 * p2 * p3 fmt.Printf("%2d %4d %5d %d\n", p1, p2, p3, c) } } } } func main() { fmt.Println("The following are Carmichael munbers for p1 <= 61:\n") fmt.Println("p1 p2 p3 product") fmt.Println("== == == =======") for p1 := 2; p1 <= 61; p1++ { if isPrime(p1) { carmichael(p1) } } }
Produce a language-to-language conversion: from Python to Go, same semantics.
black = color(0) white = color(255) def setup(): size(320, 240) def draw(): loadPixels() for i in range(len(pixels)): if random(1) < 0.5: pixels[i] = black else: pixels[i] = white updatePixels() fill(0, 128) rect(0, 0, 60, 20) fill(255) text(frameRate, 5, 15)
package main import ( "code.google.com/p/x-go-binding/ui/x11" "fmt" "image" "image/color" "image/draw" "log" "os" "time" ) var randcol = genrandcol() func genrandcol() <-chan color.Color { c := make(chan color.Color) go func() { for { select { case c <- image.Black: case c <- image.White: } } }() return c } func gennoise(screen draw.Image) { for y := 0; y < 240; y++ { for x := 0; x < 320; x++ { screen.Set(x, y, <-randcol) } } } func fps() chan<- bool { up := make(chan bool) go func() { var frames int64 var lasttime time.Time var totaltime time.Duration for { <-up frames++ now := time.Now() totaltime += now.Sub(lasttime) if totaltime > time.Second { fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds()) frames = 0 totaltime = 0 } lasttime = now } }() return up } func main() { win, err := x11.NewWindow() if err != nil { fmt.Println(err) os.Exit(1) } defer win.Close() go func() { upfps := fps() screen := win.Screen() for { gennoise(screen) win.FlushImage() upfps <- true } }() for _ = range win.EventChan() { } }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch print "Press Y or N to continue" while True: char = getch() if char.lower() in ("y", "n"): print char break
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() var k gc.Key for { gc.FlushInput() s.MovePrint(20, 0, "Press y/n ") s.Refresh() switch k = s.GetChar(); k { default: continue case 'y', 'Y', 'n', 'N': } break } s.Printf("\nThanks for the %c!\n", k) s.Refresh() s.GetChar() }
Transform the following Python implementation into Go, maintaining the same output and logic.
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch print "Press Y or N to continue" while True: char = getch() if char.lower() in ("y", "n"): print char break
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() var k gc.Key for { gc.FlushInput() s.MovePrint(20, 0, "Press y/n ") s.Refresh() switch k = s.GetChar(); k { default: continue case 'y', 'Y', 'n', 'N': } break } s.Printf("\nThanks for the %c!\n", k) s.Refresh() s.GetChar() }
Change the programming language of this snippet from Python to Go without modifying what it does.
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
package main import "fmt" func computePerfect(n int64) bool { var sum int64 for i := int64(1); i < n; i++ { if n%i == 0 { sum += i } } return sum == n } func isPerfect(n int64) bool { switch n { case 6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128: return true } return false } func main() { for n := int64(1); ; n++ { if isPerfect(n) != computePerfect(n) { panic("bug") } if n%1e3 == 0 { fmt.Println("tested", n) } } }
Convert this Python block to Go, preserving its control flow and logic.
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian? %s.' % ishermitian(matrix, ct)) print('Normal? %s.' % isnormal(matrix, ct)) print('Unitary? %s.' % isunitary(matrix, ct))
package main import ( "fmt" "math" "math/cmplx" ) type matrix struct { ele []complex128 cols int } func (m *matrix) conjTranspose() *matrix { r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} rx := 0 for _, e := range m.ele { r.ele[rx] = cmplx.Conj(e) rx += r.cols if rx >= len(r.ele) { rx -= len(r.ele) - 1 } } return r } func main() { show("h", matrixFromRows([][]complex128{ {3, 2 + 1i}, {2 - 1i, 1}})) show("n", matrixFromRows([][]complex128{ {1, 1, 0}, {0, 1, 1}, {1, 0, 1}})) show("u", matrixFromRows([][]complex128{ {math.Sqrt2 / 2, math.Sqrt2 / 2, 0}, {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0}, {0, 0, 1i}})) } func show(name string, m *matrix) { m.print(name) ct := m.conjTranspose() ct.print(name + "_ct") fmt.Println("Hermitian:", m.equal(ct, 1e-14)) mct := m.mult(ct) ctm := ct.mult(m) fmt.Println("Normal:", mct.equal(ctm, 1e-14)) i := eye(m.cols) fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14)) } func matrixFromRows(rows [][]complex128) *matrix { m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])} for rx, row := range rows { copy(m.ele[rx*m.cols:(rx+1)*m.cols], row) } return m } func eye(n int) *matrix { r := &matrix{make([]complex128, n*n), n} n++ for x := 0; x < len(r.ele); x += n { r.ele[x] = 1 } return r } func (m *matrix) print(heading string) { fmt.Print("\n", heading, "\n") for e := 0; e < len(m.ele); e += m.cols { fmt.Printf("%6.3f ", m.ele[e:e+m.cols]) fmt.Println() } } func (a *matrix) equal(b *matrix, ε float64) bool { for x, aEle := range a.ele { if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε || math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε { return false } } return true } func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) { m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols} for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols { for m2r0 := 0; m2r0 < m2.cols; m2r0++ { for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols { m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] m1x++ } m3x++ } } return m3 }
Convert this Python snippet to Go and keep its semantics consistent.
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian? %s.' % ishermitian(matrix, ct)) print('Normal? %s.' % isnormal(matrix, ct)) print('Unitary? %s.' % isunitary(matrix, ct))
package main import ( "fmt" "math" "math/cmplx" ) type matrix struct { ele []complex128 cols int } func (m *matrix) conjTranspose() *matrix { r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} rx := 0 for _, e := range m.ele { r.ele[rx] = cmplx.Conj(e) rx += r.cols if rx >= len(r.ele) { rx -= len(r.ele) - 1 } } return r } func main() { show("h", matrixFromRows([][]complex128{ {3, 2 + 1i}, {2 - 1i, 1}})) show("n", matrixFromRows([][]complex128{ {1, 1, 0}, {0, 1, 1}, {1, 0, 1}})) show("u", matrixFromRows([][]complex128{ {math.Sqrt2 / 2, math.Sqrt2 / 2, 0}, {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0}, {0, 0, 1i}})) } func show(name string, m *matrix) { m.print(name) ct := m.conjTranspose() ct.print(name + "_ct") fmt.Println("Hermitian:", m.equal(ct, 1e-14)) mct := m.mult(ct) ctm := ct.mult(m) fmt.Println("Normal:", mct.equal(ctm, 1e-14)) i := eye(m.cols) fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14)) } func matrixFromRows(rows [][]complex128) *matrix { m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])} for rx, row := range rows { copy(m.ele[rx*m.cols:(rx+1)*m.cols], row) } return m } func eye(n int) *matrix { r := &matrix{make([]complex128, n*n), n} n++ for x := 0; x < len(r.ele); x += n { r.ele[x] = 1 } return r } func (m *matrix) print(heading string) { fmt.Print("\n", heading, "\n") for e := 0; e < len(m.ele); e += m.cols { fmt.Printf("%6.3f ", m.ele[e:e+m.cols]) fmt.Println() } } func (a *matrix) equal(b *matrix, ε float64) bool { for x, aEle := range a.ele { if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε || math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε { return false } } return true } func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) { m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols} for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols { for m2r0 := 0; m2r0 < m2.cols; m2r0++ { for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols { m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] m1x++ } m3x++ } } return m3 }
Port the provided Python code into Go while preserving the original functionality.
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) def jacobsthal_oblong(n): return jacobsthal(n)*jacobsthal(n+1) if __name__ == '__main__': print("First 30 Jacobsthal numbers:") for j in range(0, 30): print(jacobsthal(j), end=" ") print("\n\nFirst 30 Jacobsthal-Lucas numbers: ") for j in range(0, 30): print(jacobsthal_lucas(j), end = '\t') print("\n\nFirst 20 Jacobsthal oblong numbers: ") for j in range(0, 20): print(jacobsthal_oblong(j), end=" ") print("\n\nFirst 10 Jacobsthal primes: ") for j in range(3, 33): if isPrime(jacobsthal(j)): print(jacobsthal(j))
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
Preserve the algorithm and functionality while converting the code from Python to Go.
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) def jacobsthal_oblong(n): return jacobsthal(n)*jacobsthal(n+1) if __name__ == '__main__': print("First 30 Jacobsthal numbers:") for j in range(0, 30): print(jacobsthal(j), end=" ") print("\n\nFirst 30 Jacobsthal-Lucas numbers: ") for j in range(0, 30): print(jacobsthal_lucas(j), end = '\t') print("\n\nFirst 20 Jacobsthal oblong numbers: ") for j in range(0, 20): print(jacobsthal_oblong(j), end=" ") print("\n\nFirst 10 Jacobsthal primes: ") for j in range(3, 33): if isPrime(jacobsthal(j)): print(jacobsthal(j))
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
Translate the given Python code snippet into Go without altering its behavior.
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) def jacobsthal_oblong(n): return jacobsthal(n)*jacobsthal(n+1) if __name__ == '__main__': print("First 30 Jacobsthal numbers:") for j in range(0, 30): print(jacobsthal(j), end=" ") print("\n\nFirst 30 Jacobsthal-Lucas numbers: ") for j in range(0, 30): print(jacobsthal_lucas(j), end = '\t') print("\n\nFirst 20 Jacobsthal oblong numbers: ") for j in range(0, 20): print(jacobsthal_oblong(j), end=" ") print("\n\nFirst 10 Jacobsthal primes: ") for j in range(3, 33): if isPrime(jacobsthal(j)): print(jacobsthal(j))
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
Convert this Python block to Go, preserving its control flow and logic.
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, aMax) for pole, space := 0, all; pole < aMax; pole++ { abacus[pole] = space[:len(a)] space = space[len(a):] } var wg sync.WaitGroup wg.Add(len(a)) for row, n := range a { go func(row, n int) { for pole := 0; pole < n; pole++ { abacus[pole][row] = bead } wg.Done() }(row, n) } wg.Wait() wg.Add(aMax) for _, pole := range abacus { go func(pole []byte) { top := 0 for row, space := range pole { if space == bead { pole[row] = 0 pole[top] = bead top++ } } wg.Done() }(pole) } wg.Wait() for row := range a { x := 0 for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ { x++ } a[len(a)-1-row] = x } }
Convert this Python block to Go, preserving its control flow and logic.
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
Generate an equivalent Go version of this Python code.
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
Please provide an equivalent version of this Python code in Go.
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
package main import ( "fmt" "math/big" ) func main() { x := big.NewInt(2) x = x.Exp(big.NewInt(3), x, nil) x = x.Exp(big.NewInt(4), x, nil) x = x.Exp(big.NewInt(5), x, nil) str := x.String() fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n", len(str), str[:20], str[len(str)-20:], ) }
Translate the given Python code snippet into Go without altering its behavior.
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Translate this program into Go but keep the logic exactly as in Python.
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Please provide an equivalent version of this Python code in Go.
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
package main import ( "bufio" "bytes" "errors" "fmt" "io" "os" ) var index map[string][]int var indexed []doc type doc struct { file string title string } func main() { index = make(map[string][]int) if err := indexDir("docs"); err != nil { fmt.Println(err) return } ui() } func indexDir(dir string) error { df, err := os.Open(dir) if err != nil { return err } fis, err := df.Readdir(-1) if err != nil { return err } if len(fis) == 0 { return errors.New(fmt.Sprintf("no files in %s", dir)) } indexed := 0 for _, fi := range fis { if !fi.IsDir() { if indexFile(dir + "/" + fi.Name()) { indexed++ } } } return nil } func indexFile(fn string) bool { f, err := os.Open(fn) if err != nil { fmt.Println(err) return false } x := len(indexed) indexed = append(indexed, doc{fn, fn}) pdoc := &indexed[x] r := bufio.NewReader(f) lines := 0 for { b, isPrefix, err := r.ReadLine() switch { case err == io.EOF: return true case err != nil: fmt.Println(err) return true case isPrefix: fmt.Printf("%s: unexpected long line\n", fn) return true case lines < 20 && bytes.HasPrefix(b, []byte("Title:")): pdoc.title = string(b[7:]) } wordLoop: for _, bword := range bytes.Fields(b) { bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@") if len(bword) > 0 { word := string(bword) dl := index[word] for _, d := range dl { if d == x { continue wordLoop } } index[word] = append(dl, x) } } } return true } func ui() { fmt.Println(len(index), "words indexed in", len(indexed), "files") fmt.Println("enter single words to search for") fmt.Println("enter a blank line when done") var word string for { fmt.Print("search word: ") wc, _ := fmt.Scanln(&word) if wc == 0 { return } switch dl := index[word]; len(dl) { case 0: fmt.Println("no match") case 1: fmt.Println("one match:") fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title) default: fmt.Println(len(dl), "matches:") for _, d := range dl { fmt.Println(" ", indexed[d].file, indexed[d].title) } } } }
Change the programming language of this snippet from Python to Go without modifying what it does.
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
Preserve the algorithm and functionality while converting the code from Python to Go.
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
Produce a functionally identical Go code for the snippet given in Python.
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print("First 10 Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 print("F{} = {}".format(chr(i + 0x2080) , fermat)) print("\nFactors of first few Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 fac = factors(fermat) if len(fac) == 1: print("F{} -> IS PRIME".format(chr(i + 0x2080))) else: print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac))
package main import ( "fmt" "github.com/jbarham/primegen" "math" "math/big" "math/rand" "sort" "time" ) const ( maxCurves = 10000 maxRnd = 1 << 31 maxB1 = uint64(43 * 1e7) maxB2 = uint64(2 * 1e10) ) var ( zero = big.NewInt(0) one = big.NewInt(1) two = big.NewInt(2) three = big.NewInt(3) four = big.NewInt(4) five = big.NewInt(5) ) func pollardRho(n *big.Int) (*big.Int, error) { g := func(x, n *big.Int) *big.Int { x2 := new(big.Int) x2.Mul(x, x) x2.Add(x2, one) return x2.Mod(x2, n) } x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one) t, z := new(big.Int), new(big.Int).Set(one) count := 0 for { x = g(x, n) y = g(g(y, n), n) t.Sub(x, y) t.Abs(t) t.Mod(t, n) z.Mul(z, t) count++ if count == 100 { d.GCD(nil, nil, z, n) if d.Cmp(one) != 0 { break } z.Set(one) count = 0 } } if d.Cmp(n) == 0 { return nil, fmt.Errorf("Pollard's rho failure") } return d, nil } func getPrimes(n uint64) []uint64 { pg := primegen.New() var primes []uint64 for { prime := pg.Next() if prime < n { primes = append(primes, prime) } else { break } } return primes } func computeBounds(n *big.Int) (uint64, uint64) { le := len(n.String()) var b1, b2 uint64 switch { case le <= 30: b1, b2 = 2000, 147396 case le <= 40: b1, b2 = 11000, 1873422 case le <= 50: b1, b2 = 50000, 12746592 case le <= 60: b1, b2 = 250000, 128992510 case le <= 70: b1, b2 = 1000000, 1045563762 case le <= 80: b1, b2 = 3000000, 5706890290 default: b1, b2 = maxB1, maxB2 } return b1, b2 } func pointAdd(px, pz, qx, qz, rx, rz, n *big.Int) (*big.Int, *big.Int) { t := new(big.Int).Sub(px, pz) u := new(big.Int).Add(qx, qz) u.Mul(t, u) t.Add(px, pz) v := new(big.Int).Sub(qx, qz) v.Mul(t, v) upv := new(big.Int).Add(u, v) umv := new(big.Int).Sub(u, v) x := new(big.Int).Mul(upv, upv) x.Mul(x, rz) if x.Cmp(n) >= 0 { x.Mod(x, n) } z := new(big.Int).Mul(umv, umv) z.Mul(z, rx) if z.Cmp(n) >= 0 { z.Mod(z, n) } return x, z } func pointDouble(px, pz, n, a24 *big.Int) (*big.Int, *big.Int) { u2 := new(big.Int).Add(px, pz) u2.Mul(u2, u2) v2 := new(big.Int).Sub(px, pz) v2.Mul(v2, v2) t := new(big.Int).Sub(u2, v2) x := new(big.Int).Mul(u2, v2) if x.Cmp(n) >= 0 { x.Mod(x, n) } z := new(big.Int).Mul(a24, t) z.Add(v2, z) z.Mul(t, z) if z.Cmp(n) >= 0 { z.Mod(z, n) } return x, z } func scalarMultiply(k, px, pz, n, a24 *big.Int) (*big.Int, *big.Int) { sk := fmt.Sprintf("%b", k) lk := len(sk) qx := new(big.Int).Set(px) qz := new(big.Int).Set(pz) rx, rz := pointDouble(px, pz, n, a24) for i := 1; i < lk; i++ { if sk[i] == '1' { qx, qz = pointAdd(rx, rz, qx, qz, px, pz, n) rx, rz = pointDouble(rx, rz, n, a24) } else { rx, rz = pointAdd(qx, qz, rx, rz, px, pz, n) qx, qz = pointDouble(qx, qz, n, a24) } } return qx, qz } func ecm(n *big.Int) (*big.Int, error) { if n.Cmp(one) == 0 || n.ProbablyPrime(10) { return n, nil } b1, b2 := computeBounds(n) dd := uint64(math.Sqrt(float64(b2))) beta := make([]*big.Int, dd+1) for i := 0; i < len(beta); i++ { beta[i] = new(big.Int) } s := make([]*big.Int, 2*dd+2) for i := 0; i < len(s); i++ { s[i] = new(big.Int) } curves := 0 logB1 := math.Log(float64(b1)) primes := getPrimes(b2) numPrimes := len(primes) idxB1 := sort.Search(len(primes), func(i int) bool { return primes[i] >= b1 }) k := big.NewInt(1) for i := 0; i < idxB1; i++ { p := primes[i] bp := new(big.Int).SetUint64(p) t := uint64(logB1 / math.Log(float64(p))) bt := new(big.Int).SetUint64(t) bt.Exp(bp, bt, nil) k.Mul(k, bt) } g := big.NewInt(1) for (g.Cmp(one) == 0 || g.Cmp(n) == 0) && curves <= maxCurves { curves++ st := int64(6 + rand.Intn(maxRnd-5)) sigma := big.NewInt(st) u := new(big.Int).Mul(sigma, sigma) u.Sub(u, five) u.Mod(u, n) v := new(big.Int).Mul(four, sigma) v.Mod(v, n) vmu := new(big.Int).Sub(v, u) a := new(big.Int).Mul(vmu, vmu) a.Mul(a, vmu) t := new(big.Int).Mul(three, u) t.Add(t, v) a.Mul(a, t) t.Mul(four, u) t.Mul(t, u) t.Mul(t, u) t.Mul(t, v) a.Quo(a, t) a.Sub(a, two) a.Mod(a, n) a24 := new(big.Int).Add(a, two) a24.Quo(a24, four) px := new(big.Int).Mul(u, u) px.Mul(px, u) t.Mul(v, v) t.Mul(t, v) px.Quo(px, t) px.Mod(px, n) pz := big.NewInt(1) qx, qz := scalarMultiply(k, px, pz, n, a24) g.GCD(nil, nil, n, qz) if g.Cmp(one) != 0 && g.Cmp(n) != 0 { return g, nil } s[1], s[2] = pointDouble(qx, qz, n, a24) s[3], s[4] = pointDouble(s[1], s[2], n, a24) beta[1].Mul(s[1], s[2]) beta[1].Mod(beta[1], n) beta[2].Mul(s[3], s[4]) beta[2].Mod(beta[2], n) for d := uint64(3); d <= dd; d++ { d2 := 2 * d s[d2-1], s[d2] = pointAdd(s[d2-3], s[d2-2], s[1], s[2], s[d2-5], s[d2-4], n) beta[d].Mul(s[d2-1], s[d2]) beta[d].Mod(beta[d], n) } g.SetUint64(1) b := new(big.Int).SetUint64(b1 - 1) rx, rz := scalarMultiply(b, qx, qz, n, a24) t.Mul(two, new(big.Int).SetUint64(dd)) t.Sub(b, t) tx, tz := scalarMultiply(t, qx, qz, n, a24) q, step := idxB1, 2*dd for r := b1 - 1; r < b2; r += step { alpha := new(big.Int).Mul(rx, rz) alpha.Mod(alpha, n) limit := r + step for q < numPrimes && primes[q] <= limit { d := (primes[q] - r) / 2 t := new(big.Int).Sub(rx, s[2*d-1]) f := new(big.Int).Add(rz, s[2*d]) f.Mul(t, f) f.Sub(f, alpha) f.Add(f, beta[d]) g.Mul(g, f) g.Mod(g, n) q++ } trx := new(big.Int).Set(rx) trz := new(big.Int).Set(rz) rx, rz = pointAdd(rx, rz, s[2*dd-1], s[2*dd], tx, tz, n) tx.Set(trx) tz.Set(trz) } g.GCD(nil, nil, n, g) } if curves > maxCurves { return zero, fmt.Errorf("maximum curves exceeded before a factor was found") } return g, nil } func primeFactors(n *big.Int) ([]*big.Int, error) { var res []*big.Int if n.ProbablyPrime(10) { return append(res, n), nil } le := len(n.String()) var factor1 *big.Int var err error if le > 20 && le <= 60 { factor1, err = ecm(n) } else { factor1, err = pollardRho(n) } if err != nil { return nil, err } if !factor1.ProbablyPrime(10) { return nil, fmt.Errorf("first factor is not prime") } factor2 := new(big.Int) factor2.Quo(n, factor1) if !factor2.ProbablyPrime(10) { return nil, fmt.Errorf("%d (second factor is not prime)", factor1) } return append(res, factor1, factor2), nil } func fermatNumbers(n int) (res []*big.Int) { f := new(big.Int).SetUint64(3) for i := 0; i < n; i++ { t := new(big.Int).Set(f) res = append(res, t) f.Sub(f, one) f.Mul(f, f) f.Add(f, one) } return res } func main() { start := time.Now() rand.Seed(time.Now().UnixNano()) fns := fermatNumbers(10) fmt.Println("First 10 Fermat numbers:") for i, f := range fns { fmt.Printf("F%c = %d\n", 0x2080+i, f) } fmt.Println("\nFactors of first 10 Fermat numbers:") for i, f := range fns { fmt.Printf("F%c = ", 0x2080+i) factors, err := primeFactors(f) if err != nil { fmt.Println(err) continue } for _, factor := range factors { fmt.Printf("%d ", factor) } if len(factors) == 1 { fmt.Println("- prime") } else { fmt.Println() } } fmt.Printf("\nTook %s\n", time.Since(start)) }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
package main import "fmt" import "math/rand" import "time" func main() { rand.Seed(time.Now().UnixNano()) for { a := rand.Intn(20) fmt.Println(a) if a == 10 { break } b := rand.Intn(20) fmt.Println(b) } }
Change the programming language of this snippet from Python to Go without modifying what it does.
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
Produce a functionally identical Go code for the snippet given in Python.
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print("highest_left: ", highest_left) print("highest_right: ", highest_right) print("water_level: ", water_level) print("tower_level: ", tower) print("total_water: ", sum(water_level)) print("") return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
package main import "fmt" func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func min(a,b []int) []int { res := make([]int,len(a)) for i := 0; i < len(a);i++{ if a[i] >= b[i]{ res[i] = b[i] }else { res[i] = a[i] } } return res } func diff(hm, min []int) []int { res := make([]int,len(hm)) for i := 0; i < len(hm);i++{ if min[i] > hm[i]{ res[i] = min[i] - hm[i] } } return res } func sum(a []int) int { res := 0 for i := 0; i < len(a);i++{ res += a[i] } return res } func waterCollected(hm []int) int { maxr := maxr(hm) maxl := maxl(hm) min := min(maxr,maxl) diff := diff(hm,min) sum := sum(diff) return sum } func main() { fmt.Println(waterCollected([]int{1, 5, 3, 7, 2})) fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2})) fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1})) fmt.Println(waterCollected([]int{5, 5, 5, 5})) fmt.Println(waterCollected([]int{5, 6, 7, 8})) fmt.Println(waterCollected([]int{8, 7, 7, 6})) fmt.Println(waterCollected([]int{6, 7, 10, 7, 6})) }
Rewrite the snippet below in Go so it works the same as the original Python code.
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, len(c)) copy(t, c) combs = append(combs, t) return } for i := start; i <= end && end-i+1 >= k-index; i++ { c[index] = a[i] combine(i+1, end, index+1) } } combine(0, n-1, 0) return combs } func powerset(a []int) (res [][]int) { if len(a) == 0 { return } for i := 1; i <= len(a); i++ { res = append(res, combinations(a, i)...) } return } func main() { ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) var descPrimes []int for i := 1; i < len(ps); i++ { s := "" for _, e := range ps[i] { s += string(e + '0') } p, _ := strconv.Atoi(s) if rcu.IsPrime(p) { descPrimes = append(descPrimes, p) } } sort.Ints(descPrimes) fmt.Println("There are", len(descPrimes), "descending primes, namely:") for i := 0; i < len(descPrimes); i++ { fmt.Printf("%8d ", descPrimes[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
Convert this Python block to Go, preserving its control flow and logic.
import math def SquareFree ( _number ) : max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number % ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( "{}\t".format(i), end="" ) count += 1 print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count)) ListSquareFrees( 1, 100 ) ListSquareFrees( 1000000000000, 1000000000145 )
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } for i := uint64(3); i <= limit; i += 2 { if !c[i] { primes = append(primes, i) } } return primes } func squareFree(from, to uint64) (results []uint64) { limit := uint64(math.Sqrt(float64(to))) primes := sieve(limit) outer: for i := from; i <= to; i++ { for _, p := range primes { p2 := p * p if p2 > i { break } if i%p2 == 0 { continue outer } } results = append(results, i) } return } const trillion uint64 = 1000000000000 func main() { fmt.Println("Square-free integers from 1 to 145:") sf := squareFree(1, 145) for i := 0; i < len(sf); i++ { if i > 0 && i%20 == 0 { fmt.Println() } fmt.Printf("%4d", sf[i]) } fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145) sf = squareFree(trillion, trillion+145) for i := 0; i < len(sf); i++ { if i > 0 && i%5 == 0 { fmt.Println() } fmt.Printf("%14d", sf[i]) } fmt.Println("\n\nNumber of square-free integers:\n") a := [...]uint64{100, 1000, 10000, 100000, 1000000} for _, n := range a { fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n))) } }
Keep all operations the same but rewrite the snippet in Go.
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in range(s_len): start = max(0, i - match_distance) end = min(i + match_distance + 1, t_len) for j in range(start, end): if t_matches[j]: continue if s[i] != t[j]: continue s_matches[i] = True t_matches[j] = True matches += 1 break if matches == 0: return 0 k = 0 for i in range(s_len): if not s_matches[i]: continue while not t_matches[k]: k += 1 if s[i] != t[k]: transpositions += 1 k += 1 return ((matches / s_len) + (matches / t_len) + ((matches - transpositions / 2) / matches)) / 3 def main(): for s, t in [('MARTHA', 'MARHTA'), ('DIXON', 'DICKSONX'), ('JELLYFISH', 'SMELLYFISH')]: print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t))) if __name__ == '__main__': main()
package main import "fmt" func jaro(str1, str2 string) float64 { if len(str1) == 0 && len(str2) == 0 { return 1 } if len(str1) == 0 || len(str2) == 0 { return 0 } match_distance := len(str1) if len(str2) > match_distance { match_distance = len(str2) } match_distance = match_distance/2 - 1 str1_matches := make([]bool, len(str1)) str2_matches := make([]bool, len(str2)) matches := 0. transpositions := 0. for i := range str1 { start := i - match_distance if start < 0 { start = 0 } end := i + match_distance + 1 if end > len(str2) { end = len(str2) } for k := start; k < end; k++ { if str2_matches[k] { continue } if str1[i] != str2[k] { continue } str1_matches[i] = true str2_matches[k] = true matches++ break } } if matches == 0 { return 0 } k := 0 for i := range str1 { if !str1_matches[i] { continue } for !str2_matches[k] { k++ } if str1[i] != str2[k] { transpositions++ } k++ } transpositions /= 2 return (matches/float64(len(str1)) + matches/float64(len(str2)) + (matches-transpositions)/matches) / 3 } func main() { fmt.Printf("%f\n", jaro("MARTHA", "MARHTA")) fmt.Printf("%f\n", jaro("DIXON", "DICKSONX")) fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")) }
Generate an equivalent Go version of this Python code.
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))] product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1] sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1] print(final_pairs)
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all) var sPairs []pair pairs: for _, p := range all { s := p.x + p.y for a := 2; a < s/2+s&1; a++ { b := s - a if products[a*b] == 1 { continue pairs } } sPairs = append(sPairs, p) } fmt.Println("S starts with", len(sPairs), "possible pairs.") sProducts := countProducts(sPairs) var pPairs []pair for _, p := range sPairs { if sProducts[p.x*p.y] == 1 { pPairs = append(pPairs, p) } } fmt.Println("P then has", len(pPairs), "possible pairs.") pSums := countSums(pPairs) var final []pair for _, p := range pPairs { if pSums[p.x+p.y] == 1 { final = append(final, p) } } switch len(final) { case 1: fmt.Println("Answer:", final[0].x, "and", final[0].y) case 0: fmt.Println("No possible answer.") default: fmt.Println(len(final), "possible answers:", final) } } func countProducts(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x*p.y]++ } return m } func countSums(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x+p.y]++ } return m } func decomposeSum(s int) []pair { pairs := make([]pair, 0, s/2) for a := 2; a < s/2+s&1; a++ { pairs = append(pairs, pair{a, s - a}) } return pairs }
Generate a Go translation of this Python snippet without changing its computational steps.
from itertools import count, islice def _basechange_int(num, b): if num == 0: return [0] result = [] while num != 0: num, d = divmod(num, b) result.append(d) return result[::-1] def fairshare(b=2): for i in count(): yield sum(_basechange_int(i, b)) % b if __name__ == '__main__': for b in (2, 3, 5, 11): print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } return res } func turns(n int, fss []int) string { m := make(map[int]int) for _, fs := range fss { m[fs]++ } m2 := make(map[int]int) for _, v := range m { m2[v]++ } res := []int{} sum := 0 for k, v := range m2 { sum += v res = append(res, k) } if sum != n { return fmt.Sprintf("only %d have a turn", sum) } sort.Ints(res) res2 := make([]string, len(res)) for i := range res { res2[i] = strconv.Itoa(res[i]) } return strings.Join(res2, " or ") } func main() { for _, base := range []int{2, 3, 5, 11} { fmt.Printf("%2d : %2d\n", base, fairshare(25, base)) } fmt.Println("\nHow many times does each get a turn in 50000 iterations?") for _, base := range []int{191, 1377, 49999, 50000, 50001} { t := turns(base, fairshare(50000, base)) fmt.Printf(" With %d people: %s\n", base, t) } }
Convert this Python snippet to Go and keep its semantics consistent.
import numpy as np class Revolver: def __init__(self): self.cylinder = np.array([False] * 6) def unload(self): self.cylinder[:] = False def load(self): while self.cylinder[1]: self.cylinder[:] = np.roll(self.cylinder, 1) self.cylinder[1] = True def spin(self): self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7)) def fire(self): shot = self.cylinder[0] self.cylinder[:] = np.roll(self.cylinder, 1) return shot def LSLSFSF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LSLSFF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False def LLSFSF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LLSFF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False if __name__ == '__main__': REV = Revolver() TESTCOUNT = 100000 for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF], ['load, spin, load, spin, fire, fire', REV.LSLSFF], ['load, load, spin, fire, spin, fire', REV.LLSFSF], ['load, load, spin, fire, fire', REV.LLSFF]]: percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT print("Method", name, "produces", percentage, "per cent deaths.")
package main import ( "fmt" "math/rand" "strings" "time" ) var cylinder = [6]bool{} func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t } func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } func load() { for cylinder[0] { rshift() } cylinder[0] = true rshift() } func spin() { var lim = 1 + rand.Intn(6) for i := 1; i < lim; i++ { rshift() } } func fire() bool { shot := cylinder[0] rshift() return shot } func method(s string) int { unload() for _, c := range s { switch c { case 'L': load() case 'S': spin() case 'F': if fire() { return 1 } } } return 0 } func mstring(s string) string { var l []string for _, c := range s { switch c { case 'L': l = append(l, "load") case 'S': l = append(l, "spin") case 'F': l = append(l, "fire") } } return strings.Join(l, ", ") } func main() { rand.Seed(time.Now().UnixNano()) tests := 100000 for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} { sum := 0 for t := 1; t <= tests; t++ { sum += method(m) } pc := float64(sum) * 100 / float64(tests) fmt.Printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc) } }
Write a version of this Python function in Go with identical behavior.
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) case ")": var op string for { op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break } rpn += " " + op } default: if o1, isOp := opa[tok]; isOp { for len(stack) > 0 { op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } stack = stack[:len(stack)-1] rpn += " " + op } stack = append(stack, tok) } else { if rpn > "" { rpn += " " } rpn += tok } } } for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
Write the same code in Go as shown below in Python.
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) case ")": var op string for { op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break } rpn += " " + op } default: if o1, isOp := opa[tok]; isOp { for len(stack) > 0 { op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } stack = stack[:len(stack)-1] rpn += " " + op } stack = append(stack, tok) } else { if rpn > "" { rpn += " " } rpn += tok } } } for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
Translate the given Python code snippet into Go without altering its behavior.
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
package main import ( "fmt" "log" "math" ) func main() { fmt.Print("Enter 11 numbers: ") var s [11]float64 for i := 0; i < 11; { if n, _ := fmt.Scan(&s[i]); n > 0 { i++ } } for i, item := range s[:5] { s[i], s[10-i] = s[10-i], item } for _, item := range s { if result, overflow := f(item); overflow { log.Printf("f(%g) overflow", item) } else { fmt.Printf("f(%g) = %g\n", item, result) } } } func f(x float64) (float64, bool) { result := math.Sqrt(math.Abs(x)) + 5*x*x*x return result, result > 400 }
Write a version of this Python function in Go with identical behavior.
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
package m3 import ( "errors" "strconv" ) var ( ErrorLT3 = errors.New("N of at least three digits required.") ErrorEven = errors.New("N with odd number of digits required.") ) func Digits(i int) (string, error) { if i < 0 { i = -i } if i < 100 { return "", ErrorLT3 } s := strconv.Itoa(i) if len(s)%2 == 0 { return "", ErrorEven } m := len(s) / 2 return s[m-1 : m+2], nil }
Write the same algorithm in Go as shown in this Python implementation.
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 primes(): ii = 1 while True: ii += 1 if is_prime(ii): yield ii def prime(n): generator = primes() for ii in range(n - 1): generator.__next__() return generator.__next__() def n_divisors(n): ii = 0 while True: ii += 1 if len(divisors(ii)) == n: yield ii def sequence(max_n=None): if max_n is not None: for ii in range(1, max_n + 1): if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() else: ii = 1 while True: ii += 1 if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() if __name__ == '__main__': for item in sequence(15): print(item)
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if isPrime(i) { primes[count] = i count++ } } return primes } func countDivisors(n int) int { count := 1 for n%2 == 0 { n >>= 1 count++ } for d := 3; d*d <= n; d += 2 { q, r := n/d, n%d if r == 0 { dc := 0 for r == 0 { dc += count n = q q, r = n/d, n%d } count += dc } } if n != 1 { count *= 2 } return count } func main() { const max = 33 primes := generateSmallPrimes(max) z := new(big.Int) p := new(big.Int) fmt.Println("The first", max, "terms in the sequence are:") for i := 1; i <= max; i++ { if isPrime(i) { z.SetUint64(uint64(primes[i-1])) p.SetUint64(uint64(i - 1)) z.Exp(z, p, nil) fmt.Printf("%2d : %d\n", i, z) } else { count := 0 for j := 1; ; j++ { if i%2 == 1 { sq := int(math.Sqrt(float64(j))) if sq*sq != j { continue } } if countDivisors(j) == i { count++ if count == i { fmt.Printf("%2d : %d\n", i, j) break } } } } } }
Maintain the same structure and functionality when rewriting this code in Go.
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 sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break if __name__ == '__main__': for item in sequence(15): print(item)
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 seq := make([]int, max) fmt.Println("The first", max, "terms of the sequence are:") for i, n := 1, 0; n < max; i++ { if k := countDivisors(i); k <= max && seq[k-1] == 0 { seq[k-1] = i n++ } } fmt.Println(seq) }
Rewrite the snippet below in Go so it works the same as the original Python code.
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: init_stack = tuple(range(1, n + 1)) stack_flips = {init_stack: 0} queue = deque([init_stack]) while queue: stack = queue.popleft() flips = stack_flips[stack] + 1 for i in range(2, n + 1): flipped = flip(stack, i) if flipped not in stack_flips: stack_flips[flipped] = flips queue.append(flipped) return max(stack_flips.items(), key=itemgetter(1)) if __name__ == "__main__": start = time.time() for n in range(1, 10): pancakes, p = pancake(n) print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}") print(f"\nTook {time.time() - start:.3} seconds.")
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) = %2d ", n, pancake(n)) } fmt.Println() } }
Generate an equivalent Go version of this Python code.
import random board = [[" " for x in range(8)] for y in range(8)] piece_list = ["R", "N", "B", "Q", "P"] def place_kings(brd): while True: rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7) diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)] if sum(diff_list) > 2 or set(diff_list) == set([0, 2]): brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k" break def populate_board(brd, wp, bp): for x in range(2): if x == 0: piece_amount = wp pieces = piece_list else: piece_amount = bp pieces = [s.lower() for s in piece_list] while piece_amount != 0: piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7) piece = random.choice(pieces) if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False: brd[piece_rank][piece_file] = piece piece_amount -= 1 def fen_from_board(brd): fen = "" for x in brd: n = 0 for y in x: if y == " ": n += 1 else: if n != 0: fen += str(n) fen += y n = 0 if n != 0: fen += str(n) fen += "/" if fen.count("/") < 7 else "" fen += " w - - 0 1\n" return fen def pawn_on_promotion_square(pc, pr): if pc == "P" and pr == 0: return True elif pc == "p" and pr == 7: return True return False def start(): piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15) place_kings(board) populate_board(board, piece_amount_white, piece_amount_black) print(fen_from_board(board)) for x in board: print(x) start()
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) placePieces("RNBQBNR", false) placePieces("rnbqbnr", false) return toFen() } func placeKings() { for { r1 := rand.Intn(8) c1 := rand.Intn(8) r2 := rand.Intn(8) c2 := rand.Intn(8) if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 { grid[r1][c1] = 'K' grid[r2][c2] = 'k' return } } } func placePieces(pieces string, isPawn bool) { numToPlace := rand.Intn(len(pieces)) for n := 0; n < numToPlace; n++ { var r, c int for { r = rand.Intn(8) c = rand.Intn(8) if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) { break } } grid[r][c] = pieces[n] } } func toFen() string { var fen strings.Builder countEmpty := 0 for r := 0; r < 8; r++ { for c := 0; c < 8; c++ { ch := grid[r][c] if ch == '\000' { ch = '.' } fmt.Printf("%2c ", ch) if ch == '.' { countEmpty++ } else { if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteByte(ch) } } if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteString("/") fmt.Println() } fen.WriteString(" w - - 0 1") return fen.String() } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(createFen()) }
Translate the given Python code snippet into Go without altering its behavior.
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str def esthetic_nums(base: int) -> Iterator[int]: queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) while True: num, lsd = queue.pop() yield num new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base) num *= base queue.extendleft((num + d, d) for d in new_lsds) def to_digits(num: int, base: int) -> Digits: digits: list[str] = [] while num: num, d = divmod(num, base) digits.append("0123456789abcdef"[d]) return "".join(reversed(digits)) if digits else "0" def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None: joined = ", ".join(it) lines = wrap(joined, width=width - indent) for line in lines: print(f"{indent*' '}{line}") print() def task_2() -> None: nums: Iterator[int] for base in range(2, 16 + 1): start, stop = 4 * base, 6 * base nums = esthetic_nums(base) nums = islice(nums, start - 1, stop) print( f"Base-{base} esthetic numbers from " f"index {start} through index {stop} inclusive:\n" ) pprint_it(to_digits(num, base) for num in nums) def task_3(lower: int, upper: int, base: int = 10) -> None: nums: Iterator[int] = esthetic_nums(base) nums = dropwhile(lambda num: num < lower, nums) nums = takewhile(lambda num: num <= upper, nums) print( f"Base-{base} esthetic numbers with " f"magnitude between {lower:,} and {upper:,}:\n" ) pprint_it(to_digits(num, base) for num in nums) if __name__ == "__main__": print("======\nTask 2\n======\n") task_2() print("======\nTask 3\n======\n") task_3(1_000, 9_999) print("======\nTask 4\n======\n") task_3(100_000_000, 130_000_000)
package main import ( "fmt" "strconv" ) func uabs(a, b uint64) uint64 { if a > b { return a - b } return b - a } func isEsthetic(n, b uint64) bool { if n == 0 { return false } i := n % b n /= b for n > 0 { j := n % b if uabs(i, j) != 1 { return false } n /= b i = j } return true } var esths []uint64 func dfs(n, m, i uint64) { if i >= n && i <= m { esths = append(esths, i) } if i == 0 || i > m { return } d := i % 10 i1 := i*10 + d - 1 i2 := i1 + 2 if d == 0 { dfs(n, m, i2) } else if d == 9 { dfs(n, m, i1) } else { dfs(n, m, i1) dfs(n, m, i2) } } func listEsths(n, n2, m, m2 uint64, perLine int, all bool) { esths = esths[:0] for i := uint64(0); i < 10; i++ { dfs(n2, m2, i) } le := len(esths) fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n", commatize(uint64(le)), commatize(n), commatize(m)) if all { for c, esth := range esths { fmt.Printf("%d ", esth) if (c+1)%perLine == 0 { fmt.Println() } } } else { for i := 0; i < perLine; i++ { fmt.Printf("%d ", esths[i]) } fmt.Println("\n............\n") for i := le - perLine; i < le; i++ { fmt.Printf("%d ", esths[i]) } } fmt.Println("\n") } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { for b := uint64(2); b <= 16; b++ { fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b) for n, c := uint64(1), uint64(0); c < 6*b; n++ { if isEsthetic(n, b) { c++ if c >= 4*b { fmt.Printf("%s ", strconv.FormatUint(n, int(b))) } } } fmt.Println("\n") } listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true) listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false) listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false) listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false) }
Change the following Python code into Go without altering its purpose.
>>> from itertools import permutations >>> def f1(p): i = 0 while True: p0 = p[0] if p0 == 1: break p[:p0] = p[:p0][::-1] i += 1 return i >>> def fannkuch(n): return max(f1(list(p)) for p in permutations(range(1, n+1))) >>> for n in range(1, 11): print(n,fannkuch(n)) 1 0 2 1 3 2 4 4 5 7 6 10 7 16 8 22 9 30 10 38 >>>
package main import "fmt" const ( maxn = 10 maxl = 50 ) func main() { for i := 1; i <= maxn; i++ { fmt.Printf("%d: %d\n", i, steps(i)) } } func steps(n int) int { var a, b [maxl][maxn + 1]int var x [maxl]int a[0][0] = 1 var m int for l := 0; ; { x[l]++ k := int(x[l]) if k >= n { if l <= 0 { break } l-- continue } if a[l][k] == 0 { if b[l][k+1] != 0 { continue } } else if a[l][k] != k+1 { continue } a[l+1] = a[l] for j := 1; j <= k; j++ { a[l+1][j] = a[l][k-j] } b[l+1] = b[l] a[l+1][0] = k + 1 b[l+1][k+1] = 1 if l > m-1 { m = l + 1 } l++ x[l] = 0 } return m }
Maintain the same structure and functionality when rewriting this code in Go.
from sys import argv unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445, "versta": 1066.8} if __name__ == '__main__': assert len(argv) == 3, 'ERROR. Need two arguments - number then units' try: value = float(argv[1]) except: print('ERROR. First argument must be a (float) number') raise unit = argv[2] assert unit in unit2mult, ( 'ERROR. Only know the following units: ' + ' '.join(unit2mult.keys()) ) print("%g %s to:" % (value, unit)) for unt, mlt in sorted(unit2mult.items()): print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt))
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000, } scanner := bufio.NewScanner(os.Stdin) for { for i, u := range units { fmt.Printf("%2d %s\n", i+1, u) } fmt.Println() var unit int var err error for { fmt.Print("Please choose a unit 1 to 13 : ") scanner.Scan() unit, err = strconv.Atoi(scanner.Text()) if err == nil && unit >= 1 && unit <= 13 { break } } unit-- var value float64 for { fmt.Print("Now enter a value in that unit : ") scanner.Scan() value, err = strconv.ParseFloat(scanner.Text(), 32) if err == nil && value >= 0 { break } } fmt.Println("\nThe equivalent in the remaining units is:\n") for i, u := range units { if i == unit { continue } fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i]) } fmt.Println() yn := "" for yn != "y" && yn != "n" { fmt.Print("Do another one y/n : ") scanner.Scan() yn = strings.ToLower(scanner.Text()) } if yn == "n" { return } } }
Convert the following code from Python to Go, ensuring the logic remains intact.
import subprocess import time class Tlogger(object): def __init__(self): self.counts = 0 self.tottime = 0.0 self.laststart = 0.0 self.lastreport = time.time() def logstart(self): self.laststart = time.time() def logend(self): self.counts +=1 self.tottime += (time.time()-self.laststart) if (time.time()-self.lastreport)>5.0: self.report() def report(self): if ( self.counts > 4*self.tottime): print "Subtask execution rate: %f times/second"% (self.counts/self.tottime); else: print "Average execution time: %f seconds"%(self.tottime/self.counts); self.lastreport = time.time() def taskTimer( n, subproc_args ): logger = Tlogger() for x in range(n): logger.logstart() p = subprocess.Popen(subproc_args) p.wait() logger.logend() logger.report() import timeit import sys def main( ): s = timer = timeit.Timer(s) rzlts = timer.repeat(5, 5000) for t in rzlts: print "Time for 5000 executions of statement = ",t print " print "Command:",sys.argv[2:] print "" for k in range(3): taskTimer( int(sys.argv[1]), sys.argv[2:]) main()
package main import ( "fmt" "math/rand" "time" ) type rateStateS struct { lastFlush time.Time period time.Duration tickCount int } func ticRate(pRate *rateStateS) { pRate.tickCount++ now := time.Now() if now.Sub(pRate.lastFlush) >= pRate.period { tps := 0. if pRate.tickCount > 0 { tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds() } fmt.Println(tps, "tics per second.") pRate.tickCount = 0 pRate.lastFlush = now } } func somethingWeDo() { time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) } func main() { start := time.Now() rateWatch := rateStateS{ lastFlush: start, period: 5 * time.Second, } latest := start for latest.Sub(start) < 20*time.Second { somethingWeDo() ticRate(&rateWatch) latest = time.Now() } }
Convert this Python snippet to Go and keep its semantics consistent.
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 sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii previous = ii break if __name__ == '__main__': for item in sequence(15): print(item)
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 fmt.Println("The first", max, "terms of the sequence are:") for i, next := 1, 1; next <= max; i++ { if next == countDivisors(i) { fmt.Printf("%d ", i) next++ } } fmt.Println() }
Write the same algorithm in Go as shown in this Python implementation.
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 def padovan_f(n: int) -> int: return floor(_p**(n-1) / _s + .5) def padovan_l(start: str='A', rules: Dict[str, str]=dict(A='B', B='C', C='AB') ) -> Generator[str, None, None]: axiom = start while True: yield axiom axiom = ''.join(rules[ch] for ch in axiom) if __name__ == "__main__": from itertools import islice print("The first twenty terms of the sequence.") print(str([padovan_f(n) for n in range(20)])[1:-1]) r_generator = padovan_r() if all(next(r_generator) == padovan_f(n) for n in range(64)): print("\nThe recurrence and floor based algorithms match to n=63 .") else: print("\nThe recurrence and floor based algorithms DIFFER!") print("\nThe first 10 L-system string-lengths and strings") l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) print('\n'.join(f" {len(string):3} {repr(string)}" for string in islice(l_generator, 10))) r_generator = padovan_r() l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) for n in range(32)): print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") else: print("\nThe L-system, recurrence and floor based algorithms DIFFER!")
package main import ( "fmt" "math" "math/big" "strings" ) func padovanRecur(n int) []int { p := make([]int, n) p[0], p[1], p[2] = 1, 1, 1 for i := 3; i < n; i++ { p[i] = p[i-2] + p[i-3] } return p } func padovanFloor(n int) []int { var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat) p, _ = p.SetString("1.324717957244746025960908854") s, _ = s.SetString("1.0453567932525329623") f := make([]int, n) pow := new(big.Rat).SetInt64(1) u = u.SetFrac64(1, 2) t.Quo(pow, p) t.Quo(t, s) t.Add(t, u) v, _ := t.Float64() f[0] = int(math.Floor(v)) for i := 1; i < n; i++ { t.Quo(pow, s) t.Add(t, u) v, _ = t.Float64() f[i] = int(math.Floor(v)) pow.Mul(pow, p) } return f } type LSystem struct { rules map[string]string init, current string } func step(lsys *LSystem) string { var sb strings.Builder if lsys.current == "" { lsys.current = lsys.init } else { for _, c := range lsys.current { sb.WriteString(lsys.rules[string(c)]) } lsys.current = sb.String() } return lsys.current } func padovanLSys(n int) []string { rules := map[string]string{"A": "B", "B": "C", "C": "AB"} lsys := &LSystem{rules, "A", ""} p := make([]string, n) for i := 0; i < n; i++ { p[i] = step(lsys) } return p } func areSame(l1, l2 []int) bool { for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { fmt.Println("First 20 members of the Padovan sequence:") fmt.Println(padovanRecur(20)) recur := padovanRecur(64) floor := padovanFloor(64) same := areSame(recur, floor) s := "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.") p := padovanLSys(32) lsyst := make([]int, 32) for i := 0; i < 32; i++ { lsyst[i] = len(p[i]) } fmt.Println("\nFirst 10 members of the Padovan L-System:") fmt.Println(p[:10]) fmt.Println("\nand their lengths:") fmt.Println(lsyst[:10]) same = areSame(recur[:32], lsyst) s = "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
Write the same algorithm in Go as shown in this Python implementation.
def setup(): size(800, 400) background(255) stroke(0, 255, 0) tree(width / 2.3, height, width / 1.8, height, 10) def tree(x1, y1, x2, y2, depth): if depth <= 0: return dx = (x2 - x1) dy = (y1 - y2) x3 = (x2 - dy) y3 = (y2 - dx) x4 = (x1 - dy) y4 = (y1 - dx) x5 = (x4 + 0.5 * (dx - dy)) y5 = (y4 - 0.5 * (dx + dy)) beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x1, y1) vertex(x2, y2) vertex(x3, y3) vertex(x4, y4) vertex(x1, y1) endShape() beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x3, y3) vertex(x4, y4) vertex(x5, y5) vertex(x3, y3) endShape() tree(x4, y4, x5, y5, depth - 1) tree(x5, y5, x3, y3, depth - 1)
package main import ( "image" "image/color" "image/draw" "image/png" "log" "os" ) const ( width, height = 800, 600 maxDepth = 11 colFactor = uint8(255 / maxDepth) fileName = "pythagorasTree.png" ) func main() { img := image.NewNRGBA(image.Rect(0, 0, width, height)) bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) drawSquares(340, 550, 460, 550, img, 0) imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close() if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } } func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) { if depth > maxDepth { return } dx, dy := bx-ax, ay-by x3, y3 := bx-dy, by-dx x4, y4 := ax-dy, ay-dx x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2 col := color.RGBA{0, uint8(depth) * colFactor, 0, 255} drawLine(ax, ay, bx, by, img, col) drawLine(bx, by, x3, y3, img, col) drawLine(x3, y3, x4, y4, img, col) drawLine(x4, y4, ax, ay, img, col) drawSquares(x4, y4, x5, y5, img, depth+1) drawSquares(x5, y5, x3, y3, img, depth+1) } func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) { dx := abs(x1 - x0) dy := abs(y1 - y0) var sx, sy int = -1, -1 if x0 < x1 { sx = 1 } if y0 < y1 { sy = 1 } err := dx - dy for { img.Set(x0, y0, col) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 > -dy { err -= dy x0 += sx } if e2 < dx { err += dx y0 += sy } } } func abs(x int) int { if x < 0 { return -x } return x }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
package main import ( "bytes" "fmt" "io" "os" "unicode" ) func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() } func owp(dst io.Writer, src io.Reader) { byte_in := func () byte { bs := make([]byte, 1) src.Read(bs) return bs[0] } byte_out := func (b byte) { dst.Write([]byte{b}) } var odd func() byte odd = func() byte { s := byte_in() if unicode.IsPunct(rune(s)) { return s } b := odd() byte_out(s) return b } for { for { b := byte_in() byte_out(b) if b == '.' { return } if unicode.IsPunct(rune(b)) { break } } b := odd() byte_out(b) if b == '.' { return } } }
Transform the following Python implementation into Go, maintaining the same output and logic.
a1 = [0, 1403580, -810728] m1 = 2**32 - 209 a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a(): def __init__(self, seed_state=123): self.seed(seed_state) def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 = [seed_state, 0, 0] self.x2 = [seed_state, 0, 0] def next_int(self): "return random int in range 0..d" x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1 x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2 self.x1 = [x1i] + self.x1[:2] self.x2 = [x2i] + self.x2[:2] z = (x1i - x2i) % m1 answer = (z + 1) return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / d if __name__ == '__main__': random_gen = MRG32k3a() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
package main import ( "fmt" "log" "math" ) var a1 = []int64{0, 1403580, -810728} var a2 = []int64{527612, 0, -1370589} const m1 = int64((1 << 32) - 209) const m2 = int64((1 << 32) - 22853) const d = m1 + 1 func mod(x, y int64) int64 { m := x % y if m < 0 { if y < 0 { return m - y } else { return m + y } } return m } type MRG32k3a struct{ x1, x2 [3]int64 } func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} } func (mrg *MRG32k3a) seed(seedState int64) { if seedState <= 0 || seedState >= d { log.Fatalf("Argument must be in the range [0, %d].\n", d) } mrg.x1 = [3]int64{seedState, 0, 0} mrg.x2 = [3]int64{seedState, 0, 0} } func (mrg *MRG32k3a) nextInt() int64 { x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1) x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2) mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} return mod(x1i-x2i, m1) + 1 } func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) } func main() { randomGen := MRG32k3aNew() randomGen.seed(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
Write the same code in Go as shown below in Python.
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
package main import ( "fmt" "rcu" "strconv" ) func isColorful(n int) bool { if n < 0 { return false } if n < 10 { return true } digits := rcu.Digits(n, 10) for _, d := range digits { if d == 0 || d == 1 { return false } } set := make(map[int]bool) for _, d := range digits { set[d] = true } dc := len(digits) if len(set) < dc { return false } for k := 2; k <= dc; k++ { for i := 0; i <= dc-k; i++ { prod := 1 for j := i; j <= i+k-1; j++ { prod *= digits[j] } if ok := set[prod]; ok { return false } set[prod] = true } } return true } var count = make([]int, 9) var used = make([]bool, 11) var largest = 0 func countColorful(taken int, n string) { if taken == 0 { for digit := 0; digit < 10; digit++ { dx := digit + 1 used[dx] = true t := 1 if digit < 2 { t = 9 } countColorful(t, string(digit+48)) used[dx] = false } } else { nn, _ := strconv.Atoi(n) if isColorful(nn) { ln := len(n) count[ln]++ if nn > largest { largest = nn } } if taken < 9 { for digit := 2; digit < 10; digit++ { dx := digit + 1 if !used[dx] { used[dx] = true countColorful(taken+1, n+string(digit+48)) used[dx] = false } } } } } func main() { var cn []int for i := 0; i < 100; i++ { if isColorful(i) { cn = append(cn, i) } } fmt.Println("The", len(cn), "colorful numbers less than 100 are:") for i := 0; i < len(cn); i++ { fmt.Printf("%2d ", cn[i]) if (i+1)%10 == 0 { fmt.Println() } } countColorful(0, "") fmt.Println("\n\nThe largest possible colorful number is:") fmt.Println(rcu.Commatize(largest)) fmt.Println("\nCount of colorful numbers for each order of magnitude:") pow := 10 for dc := 1; dc < len(count); dc++ { cdc := rcu.Commatize(count[dc]) pc := 100 * float64(count[dc]) / float64(pow) fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc) if pow == 10 { pow = 90 } else { pow *= 10 } } sum := 0 for _, c := range count { sum += c } fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum)) }
Please provide an equivalent version of this Python code in Go.
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
package main import ( "fmt" "rcu" "strconv" ) func isColorful(n int) bool { if n < 0 { return false } if n < 10 { return true } digits := rcu.Digits(n, 10) for _, d := range digits { if d == 0 || d == 1 { return false } } set := make(map[int]bool) for _, d := range digits { set[d] = true } dc := len(digits) if len(set) < dc { return false } for k := 2; k <= dc; k++ { for i := 0; i <= dc-k; i++ { prod := 1 for j := i; j <= i+k-1; j++ { prod *= digits[j] } if ok := set[prod]; ok { return false } set[prod] = true } } return true } var count = make([]int, 9) var used = make([]bool, 11) var largest = 0 func countColorful(taken int, n string) { if taken == 0 { for digit := 0; digit < 10; digit++ { dx := digit + 1 used[dx] = true t := 1 if digit < 2 { t = 9 } countColorful(t, string(digit+48)) used[dx] = false } } else { nn, _ := strconv.Atoi(n) if isColorful(nn) { ln := len(n) count[ln]++ if nn > largest { largest = nn } } if taken < 9 { for digit := 2; digit < 10; digit++ { dx := digit + 1 if !used[dx] { used[dx] = true countColorful(taken+1, n+string(digit+48)) used[dx] = false } } } } } func main() { var cn []int for i := 0; i < 100; i++ { if isColorful(i) { cn = append(cn, i) } } fmt.Println("The", len(cn), "colorful numbers less than 100 are:") for i := 0; i < len(cn); i++ { fmt.Printf("%2d ", cn[i]) if (i+1)%10 == 0 { fmt.Println() } } countColorful(0, "") fmt.Println("\n\nThe largest possible colorful number is:") fmt.Println(rcu.Commatize(largest)) fmt.Println("\nCount of colorful numbers for each order of magnitude:") pow := 10 for dc := 1; dc < len(count); dc++ { cdc := rcu.Commatize(count[dc]) pc := 100 * float64(count[dc]) / float64(pow) fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc) if pow == 10 { pow = 90 } else { pow *= 10 } } sum := 0 for _, c := range count { sum += c } fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum)) }
Maintain the same structure and functionality when rewriting this code in Go.
from datetime import date, timedelta from math import floor, sin, pi def biorhythms(birthdate,targetdate): print("Born: "+birthdate+" Target: "+targetdate) birthdate = date.fromisoformat(birthdate) targetdate = date.fromisoformat(targetdate) days = (targetdate - birthdate).days print("Day: "+str(days)) cycle_labels = ["Physical", "Emotional", "Mental"] cycle_lengths = [23, 28, 33] quadrants = [("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")] for i in range(3): label = cycle_labels[i] length = cycle_lengths[i] position = days % length quadrant = int(floor((4 * position) / length)) percentage = int(round(100 * sin(2 * pi * position / length),0)) transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position) trend, next = quadrants[quadrant] if percentage > 95: description = "peak" elif percentage < -95: description = "valley" elif abs(percentage) < 5: description = "critical transition" else: description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")" print(label+" day "+str(position)+": "+description) biorhythms("1943-03-09","1972-07-11")
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and falling", "valley"}, {"down but rising", "transition"}, } func check(err error) { if err != nil { log.Fatal(err) } } func biorhythms(birthDate, targetDate string) { bd, err := time.Parse(layout, birthDate) check(err) td, err := time.Parse(layout, targetDate) check(err) days := int(td.Sub(bd).Hours() / 24) fmt.Printf("Born %s, Target %s\n", birthDate, targetDate) fmt.Println("Day", days) for i := 0; i < 3; i++ { length := lengths[i] cycle := cycles[i] position := days % length quadrant := position * 4 / length percent := math.Sin(2 * math.Pi * float64(position) / float64(length)) percent = math.Floor(percent*1000) / 10 descript := "" if percent > 95 { descript = " peak" } else if percent < -95 { descript = " valley" } else if math.Abs(percent) < 5 { descript = " critical transition" } else { daysToAdd := (quadrant+1)*length/4 - position transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd)) trend := quadrants[quadrant][0] next := quadrants[quadrant][1] transStr := transition.Format(layout) descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr) } fmt.Printf("%s %2d : %s\n", cycle, position, descript) } fmt.Println() } func main() { datePairs := [][2]string{ {"1943-03-09", "1972-07-11"}, {"1809-01-12", "1863-11-19"}, {"1809-02-12", "1863-11-19"}, } for _, datePair := range datePairs { biorhythms(datePair[0], datePair[1]) } }
Translate the given Python code snippet into Go without altering its behavior.
from datetime import date, timedelta from math import floor, sin, pi def biorhythms(birthdate,targetdate): print("Born: "+birthdate+" Target: "+targetdate) birthdate = date.fromisoformat(birthdate) targetdate = date.fromisoformat(targetdate) days = (targetdate - birthdate).days print("Day: "+str(days)) cycle_labels = ["Physical", "Emotional", "Mental"] cycle_lengths = [23, 28, 33] quadrants = [("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")] for i in range(3): label = cycle_labels[i] length = cycle_lengths[i] position = days % length quadrant = int(floor((4 * position) / length)) percentage = int(round(100 * sin(2 * pi * position / length),0)) transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position) trend, next = quadrants[quadrant] if percentage > 95: description = "peak" elif percentage < -95: description = "valley" elif abs(percentage) < 5: description = "critical transition" else: description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")" print(label+" day "+str(position)+": "+description) biorhythms("1943-03-09","1972-07-11")
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and falling", "valley"}, {"down but rising", "transition"}, } func check(err error) { if err != nil { log.Fatal(err) } } func biorhythms(birthDate, targetDate string) { bd, err := time.Parse(layout, birthDate) check(err) td, err := time.Parse(layout, targetDate) check(err) days := int(td.Sub(bd).Hours() / 24) fmt.Printf("Born %s, Target %s\n", birthDate, targetDate) fmt.Println("Day", days) for i := 0; i < 3; i++ { length := lengths[i] cycle := cycles[i] position := days % length quadrant := position * 4 / length percent := math.Sin(2 * math.Pi * float64(position) / float64(length)) percent = math.Floor(percent*1000) / 10 descript := "" if percent > 95 { descript = " peak" } else if percent < -95 { descript = " valley" } else if math.Abs(percent) < 5 { descript = " critical transition" } else { daysToAdd := (quadrant+1)*length/4 - position transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd)) trend := quadrants[quadrant][0] next := quadrants[quadrant][1] transStr := transition.Format(layout) descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr) } fmt.Printf("%s %2d : %s\n", cycle, position, descript) } fmt.Println() } func main() { datePairs := [][2]string{ {"1943-03-09", "1972-07-11"}, {"1809-01-12", "1863-11-19"}, {"1809-02-12", "1863-11-19"}, } for _, datePair := range datePairs { biorhythms(datePair[0], datePair[1]) } }
Convert this Python block to Go, preserving its control flow and logic.
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute() <sqlite3.Cursor object at 0x013265C0> >>>
package main import ( "database/sql" "fmt" "log" _ "github.com/mattn/go-sqlite3" ) func main() { db, err := sql.Open("sqlite3", "rc.db") if err != nil { log.Print(err) return } defer db.Close() _, err = db.Exec(`create table addr ( id int unique, street text, city text, state text, zip text )`) if err != nil { log.Print(err) return } rows, err := db.Query(`pragma table_info(addr)`) if err != nil { log.Print(err) return } var field, storage string var ignore sql.RawBytes for rows.Next() { err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore) if err != nil { log.Print(err) return } fmt.Println(field, storage) } }
Port the following code from Python to Go with equivalent syntax and logic.
import os from math import pi, sin au_header = bytearray( [46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1]) def f(x, freq): "Compute sine wave as 16-bit integer" return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536 def play_sine(freq=440, duration=5, oname="pysine.au"): "Play a sine wave for `duration` seconds" out = open(oname, 'wb') out.write(au_header) v = [f(x, freq) for x in range(duration * 44100 + 1)] s = [] for i in v: s.append(i >> 8) s.append(i % 256) out.write(bytearray(s)) out.close() os.system("vlc " + oname) play_sine()
package main import ( "fmt" "os/exec" ) func main() { synthType := "sine" duration := "5" frequency := "440" cmd := exec.Command("play", "-n", "synth", duration, synthType, frequency) err := cmd.Run() if err != nil { fmt.Println(err) } }
Write the same algorithm in Go as shown in this Python implementation.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
package main import ( "bufio" "encoding/binary" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { enumText string nodeType NodeType opcode code } var atrs = []atr{ {"Identifier", ndIdent, 255}, {"String", ndString, 255}, {"Integer", ndInteger, 255}, {"Sequence", ndSequence, 255}, {"If", ndIf, 255}, {"Prtc", ndPrtc, 255}, {"Prts", ndPrts, 255}, {"Prti", ndPrti, 255}, {"While", ndWhile, 255}, {"Assign", ndAssign, 255}, {"Negate", ndNegate, neg}, {"Not", ndNot, not}, {"Multiply", ndMul, mul}, {"Divide", ndDiv, div}, {"Mod", ndMod, mod}, {"Add", ndAdd, add}, {"Subtract", ndSub, sub}, {"Less", ndLss, lt}, {"LessEqual", ndLeq, le}, {"Greater", ndGtr, gt}, {"GreaterEqual", ndGeq, ge}, {"Equal", ndEql, eq}, {"NotEqual", ndNeq, ne}, {"And", ndAnd, and}, {"Or", ndOr, or}, } var ( stringPool []string globals []string object []code ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func nodeType2Op(nodeType NodeType) code { return atrs[nodeType].opcode } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } func emitWordAt(at, n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for i := at; i < at+4; i++ { object[i] = code(bs[i-at]) } } func hole() int { t := len(object) emitWord(0) return t } func fetchVarOffset(id string) int { for i := 0; i < len(globals); i++ { if globals[i] == id { return i } } globals = append(globals, id) return len(globals) - 1 } func fetchStringOffset(st string) int { for i := 0; i < len(stringPool); i++ { if stringPool[i] == st { return i } } stringPool = append(stringPool, st) return len(stringPool) - 1 } func codeGen(x *Tree) { if x == nil { return } var n, p1, p2 int switch x.nodeType { case ndIdent: emitByte(fetch) n = fetchVarOffset(x.value) emitWord(n) case ndInteger: emitByte(push) n, err = strconv.Atoi(x.value) check(err) emitWord(n) case ndString: emitByte(push) n = fetchStringOffset(x.value) emitWord(n) case ndAssign: n = fetchVarOffset(x.left.value) codeGen(x.right) emitByte(store) emitWord(n) case ndIf: codeGen(x.left) emitByte(jz) p1 = hole() codeGen(x.right.left) if x.right.right != nil { emitByte(jmp) p2 = hole() } emitWordAt(p1, len(object)-p1) if x.right.right != nil { codeGen(x.right.right) emitWordAt(p2, len(object)-p2) } case ndWhile: p1 = len(object) codeGen(x.left) emitByte(jz) p2 = hole() codeGen(x.right) emitByte(jmp) emitWord(p1 - len(object)) emitWordAt(p2, len(object)-p2) case ndSequence: codeGen(x.left) codeGen(x.right) case ndPrtc: codeGen(x.left) emitByte(prtc) case ndPrti: codeGen(x.left) emitByte(prti) case ndPrts: codeGen(x.left) emitByte(prts) case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq, ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod: codeGen(x.left) codeGen(x.right) emitByte(nodeType2Op(x.nodeType)) case ndNegate, ndNot: codeGen(x.left) emitByte(nodeType2Op(x.nodeType)) default: msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType) reportError(msg) } } func codeFinish() { emitByte(halt) } func listCode() { fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool)) for _, s := range stringPool { fmt.Println(s) } pc := 0 for pc < len(object) { fmt.Printf("%5d ", pc) op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("fetch [%d]\n", x) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("store [%d]\n", x) pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("push %d\n", x) pc += 4 case add: fmt.Println("add") case sub: fmt.Println("sub") case mul: fmt.Println("mul") case div: fmt.Println("div") case mod: fmt.Println("mod") case lt: fmt.Println("lt") case gt: fmt.Println("gt") case le: fmt.Println("le") case ge: fmt.Println("ge") case eq: fmt.Println("eq") case ne: fmt.Println("ne") case and: fmt.Println("and") case or: fmt.Println("or") case neg: fmt.Println("neg") case not: fmt.Println("not") case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x) pc += 4 case jz: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jz (%d) %d\n", x, int32(pc)+x) pc += 4 case prtc: fmt.Println("prtc") case prti: fmt.Println("prti") case prts: fmt.Println("prts") case halt: fmt.Println("halt") default: reportError(fmt.Sprintf("listCode: Unknown opcode %d", op)) } } } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { return makeLeaf(nodeType, s) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) codeGen(loadAst()) codeFinish() listCode() }
Convert this Python block to Go, preserving its control flow and logic.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
package main import ( "bufio" "encoding/binary" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { enumText string nodeType NodeType opcode code } var atrs = []atr{ {"Identifier", ndIdent, 255}, {"String", ndString, 255}, {"Integer", ndInteger, 255}, {"Sequence", ndSequence, 255}, {"If", ndIf, 255}, {"Prtc", ndPrtc, 255}, {"Prts", ndPrts, 255}, {"Prti", ndPrti, 255}, {"While", ndWhile, 255}, {"Assign", ndAssign, 255}, {"Negate", ndNegate, neg}, {"Not", ndNot, not}, {"Multiply", ndMul, mul}, {"Divide", ndDiv, div}, {"Mod", ndMod, mod}, {"Add", ndAdd, add}, {"Subtract", ndSub, sub}, {"Less", ndLss, lt}, {"LessEqual", ndLeq, le}, {"Greater", ndGtr, gt}, {"GreaterEqual", ndGeq, ge}, {"Equal", ndEql, eq}, {"NotEqual", ndNeq, ne}, {"And", ndAnd, and}, {"Or", ndOr, or}, } var ( stringPool []string globals []string object []code ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func nodeType2Op(nodeType NodeType) code { return atrs[nodeType].opcode } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } func emitWordAt(at, n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for i := at; i < at+4; i++ { object[i] = code(bs[i-at]) } } func hole() int { t := len(object) emitWord(0) return t } func fetchVarOffset(id string) int { for i := 0; i < len(globals); i++ { if globals[i] == id { return i } } globals = append(globals, id) return len(globals) - 1 } func fetchStringOffset(st string) int { for i := 0; i < len(stringPool); i++ { if stringPool[i] == st { return i } } stringPool = append(stringPool, st) return len(stringPool) - 1 } func codeGen(x *Tree) { if x == nil { return } var n, p1, p2 int switch x.nodeType { case ndIdent: emitByte(fetch) n = fetchVarOffset(x.value) emitWord(n) case ndInteger: emitByte(push) n, err = strconv.Atoi(x.value) check(err) emitWord(n) case ndString: emitByte(push) n = fetchStringOffset(x.value) emitWord(n) case ndAssign: n = fetchVarOffset(x.left.value) codeGen(x.right) emitByte(store) emitWord(n) case ndIf: codeGen(x.left) emitByte(jz) p1 = hole() codeGen(x.right.left) if x.right.right != nil { emitByte(jmp) p2 = hole() } emitWordAt(p1, len(object)-p1) if x.right.right != nil { codeGen(x.right.right) emitWordAt(p2, len(object)-p2) } case ndWhile: p1 = len(object) codeGen(x.left) emitByte(jz) p2 = hole() codeGen(x.right) emitByte(jmp) emitWord(p1 - len(object)) emitWordAt(p2, len(object)-p2) case ndSequence: codeGen(x.left) codeGen(x.right) case ndPrtc: codeGen(x.left) emitByte(prtc) case ndPrti: codeGen(x.left) emitByte(prti) case ndPrts: codeGen(x.left) emitByte(prts) case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq, ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod: codeGen(x.left) codeGen(x.right) emitByte(nodeType2Op(x.nodeType)) case ndNegate, ndNot: codeGen(x.left) emitByte(nodeType2Op(x.nodeType)) default: msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType) reportError(msg) } } func codeFinish() { emitByte(halt) } func listCode() { fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool)) for _, s := range stringPool { fmt.Println(s) } pc := 0 for pc < len(object) { fmt.Printf("%5d ", pc) op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("fetch [%d]\n", x) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("store [%d]\n", x) pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("push %d\n", x) pc += 4 case add: fmt.Println("add") case sub: fmt.Println("sub") case mul: fmt.Println("mul") case div: fmt.Println("div") case mod: fmt.Println("mod") case lt: fmt.Println("lt") case gt: fmt.Println("gt") case le: fmt.Println("le") case ge: fmt.Println("ge") case eq: fmt.Println("eq") case ne: fmt.Println("ne") case and: fmt.Println("and") case or: fmt.Println("or") case neg: fmt.Println("neg") case not: fmt.Println("not") case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x) pc += 4 case jz: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jz (%d) %d\n", x, int32(pc)+x) pc += 4 case prtc: fmt.Println("prtc") case prti: fmt.Println("prti") case prts: fmt.Println("prts") case halt: fmt.Println("halt") default: reportError(fmt.Sprintf("listCode: Unknown opcode %d", op)) } } } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { return makeLeaf(nodeType, s) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) codeGen(loadAst()) codeFinish() listCode() }
Write the same algorithm in Go as shown in this Python implementation.
import one
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
import one
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
Translate the given Python code snippet into Go without altering its behavior.
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
package main import ( "fmt" "sternbrocot" ) func main() { g := sb.Generator() fmt.Println("First 15:") for i := 1; i <= 15; i++ { fmt.Printf("%2d: %d\n", i, g()) } s := sb.New() fmt.Println("First 15:", s.FirstN(15)) for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} { fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x)) } fmt.Println("1-based indexes: gcd") for n, f := range s.FirstN(1000)[:999] { g := gcd(f, (*s)[n+1]) fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g) if g != 1 { panic("oh no!") return } } } func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x }
Convert this Python snippet to Go and keep its semantics consistent.
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 ± delta' return super().__new__(_cls, float(value), abs(float(delta))) def reciprocal(self): return I(1. / self.value, self.delta / (self.value**2)) def __str__(self): 'Shorter form of Imprecise as string' return 'I(%g, %g)' % self def __neg__(self): return I(-self.value, self.delta) def __add__(self, other): if type(other) == I: return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value + c, self.delta) def __sub__(self, other): return self + (-other) def __radd__(self, other): return I.__add__(self, other) def __mul__(self, other): if type(other) == I: a1,b1 = self a2,b2 = other f = a1 * a2 return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value * c, self.delta * c) def __pow__(self, other): if type(other) == I: return NotImplemented try: c = float(other) except: return NotImplemented f = self.value ** c return I(f, f * c * (self.delta / self.value)) def __rmul__(self, other): return I.__mul__(self, other) def __truediv__(self, other): if type(other) == I: return self.__mul__(other.reciprocal()) try: c = float(other) except: return NotImplemented return I(self.value / c, self.delta / c) def __rtruediv__(self, other): return other * self.reciprocal() __div__, __rdiv__ = __truediv__, __rtruediv__ Imprecise = I def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 x1 = I(100, 1.1) x2 = I(200, 2.2) y1 = I( 50, 1.2) y2 = I(100, 2.3) p1, p2 = (x1, y1), (x2, y2) print("Distance between points\n p1: %s\n and p2: %s\n = %r" % ( p1, p2, distance(p1, p2)))
package main import ( "fmt" "math" ) type unc struct { n float64 s float64 } func newUnc(n, s float64) *unc { return &unc{n, s * s} } func (z *unc) errorTerm() float64 { return math.Sqrt(z.s) } func (z *unc) addC(a *unc, c float64) *unc { *z = *a z.n += c return z } func (z *unc) subC(a *unc, c float64) *unc { *z = *a z.n -= c return z } func (z *unc) addU(a, b *unc) *unc { z.n = a.n + b.n z.s = a.s + b.s return z } func (z *unc) subU(a, b *unc) *unc { z.n = a.n - b.n z.s = a.s + b.s return z } func (z *unc) mulC(a *unc, c float64) *unc { z.n = a.n * c z.s = a.s * c * c return z } func (z *unc) divC(a *unc, c float64) *unc { z.n = a.n / c z.s = a.s / (c * c) return z } func (z *unc) mulU(a, b *unc) *unc { prod := a.n * b.n z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } func (z *unc) divU(a, b *unc) *unc { quot := a.n / b.n z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } func (z *unc) expC(a *unc, c float64) *unc { f := math.Pow(a.n, c) g := f * c / a.n z.n = f z.s = a.s * g * g return z } func main() { x1 := newUnc(100, 1.1) x2 := newUnc(200, 2.2) y1 := newUnc(50, 1.2) y2 := newUnc(100, 2.3) var d, d2 unc d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5) fmt.Println("d: ", d.n) fmt.Println("error:", d.errorTerm()) }
Keep all operations the same but rewrite the snippet in Go.
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') sdx3 = sdx2[0:4].ljust(4,'0') return sdx3
package main import ( "errors" "fmt" "unicode" ) var code = []byte("01230127022455012623017202") func soundex(s string) (string, error) { var sx [4]byte var sxi int var cx, lastCode byte for i, c := range s { switch { case !unicode.IsLetter(c): if c < ' ' || c == 127 { return "", errors.New("ASCII control characters disallowed") } if i == 0 { return "", errors.New("initial character must be a letter") } lastCode = '0' continue case c >= 'A' && c <= 'Z': cx = byte(c - 'A') case c >= 'a' && c <= 'z': cx = byte(c - 'a') default: return "", errors.New("non-ASCII letters unsupported") } if i == 0 { sx[0] = cx + 'A' sxi = 1 continue } switch x := code[cx]; x { case '7', lastCode: case '0': lastCode = '0' default: sx[sxi] = x if sxi == 3 { return string(sx[:]), nil } sxi++ lastCode = x } } if sxi == 0 { return "", errors.New("no letters present") } for ; sxi < 4; sxi++ { sx[sxi] = '0' } return string(sx[:]), nil } func main() { for _, s := range []string{ "Robert", "Rupert", "Rubin", "ashcroft", "ashcraft", "moses", "O'Mally", "d jay", "R2-D2", "12p2", "naïve", "", "bump\t", } { if x, err := soundex(s); err == nil { fmt.Println("soundex", s, "=", x) } else { fmt.Printf("\"%s\" fail. %s\n", s, err) } } }
Please provide an equivalent version of this Python code in Go.
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i) return out def replace_brackets(s): depth,out = 0,[] for c in s: if c == '(': out.append("([{"[depth%3]) depth += 1 else: depth -= 1 out.append(")]}"[depth%3]) return "".join(out) for x in bags(5): print(replace_brackets(x[1]))
package main import ( "fmt" "log" "os" "strconv" ) type tree uint64 var ( list []tree offset = [32]uint{1: 1} ) func add(t tree) { list = append(list, 1|t<<1) } func show(t tree, l uint) { for ; l > 0; t >>= 1 { l-- var paren byte if (t & 1) != 0 { paren = '(' } else { paren = ')' } fmt.Printf("%c", paren) } } func listTrees(n uint) { for i := offset[n]; i < offset[n+1]; i++ { show(list[i], n*2) fmt.Println() } } func assemble(n uint, t tree, sl, pos, rem uint) { if rem == 0 { add(t) return } if sl > rem { sl = rem pos = offset[sl] } else if pos >= offset[sl+1] { sl-- if sl == 0 { return } pos = offset[sl] } assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl) assemble(n, t, sl, pos+1, rem) } func mktrees(n uint) { if offset[n+1] > 0 { return } if n > 0 { mktrees(n - 1) } assemble(n, 0, n-1, offset[n-1], n-1) offset[n+1] = uint(len(list)) } func main() { if len(os.Args) != 2 { log.Fatal("There must be exactly 1 command line argument") } n, err := strconv.Atoi(os.Args[1]) if err != nil { log.Fatal("Argument is not a valid number") } if n <= 0 || n > 19 { n = 5 } add(0) mktrees(uint(n)) fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n]) listTrees(uint(n)) }
Change the programming language of this snippet from Python to Go without modifying what it does.
class Doc(object): def method(self, num): pass
package example var ( X, Y, Z int ) func XP() { } func nonXP() {} var MEMEME int
Port the provided Python code into Go while preserving the original functionality.
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: c.execute('insert into stocks values (?,?,?,?,?)', t) <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> >>> >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') <sqlite3.Cursor object at 0x01326530> >>> for row in c: print row (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) (u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0) >>>
package main import ( "encoding/binary" "encoding/json" "fmt" "github.com/boltdb/bolt" "log" ) type StockTrans struct { Id int Date string Trans string Symbol string Quantity int Price float32 Settled bool } func (st *StockTrans) save(db *bolt.DB, bucket string) error { err := db.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucket)) id, _ := b.NextSequence() st.Id = int(id) encoded, err := json.Marshal(st) if err != nil { return err } return b.Put(itob(st.Id), encoded) }) return err } func itob(i int) []byte { b := make([]byte, 8) binary.BigEndian.PutUint64(b, uint64(i)) return b } func check(err error) { if err != nil { log.Fatal(err) } } func main() { db, err := bolt.Open("store.db", 0600, nil) check(err) defer db.Close() err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte("stocks")) return err }) check(err) transactions := []*StockTrans{ {0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true}, {0, "2006-03-28", "BUY", "IBM", 1000, 45, true}, {0, "2006-04-06", "SELL", "IBM", 500, 53, true}, {0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false}, } for _, trans := range transactions { err := trans.save(db, "stocks") check(err) } fmt.Println("Id Date Trans Sym Qty Price Settled") fmt.Println("------------------------------------------------") db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("stocks")) b.ForEach(func(k, v []byte) error { st := new(StockTrans) err := json.Unmarshal(v, st) check(err) fmt.Printf("%d %s  %-4s  %-5s %4d %2.2f %t\n", st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled) return nil }) return nil }) }
Rewrite the snippet below in Go so it works the same as the original Python code.
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: c.execute('insert into stocks values (?,?,?,?,?)', t) <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> >>> >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') <sqlite3.Cursor object at 0x01326530> >>> for row in c: print row (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) (u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0) >>>
package main import ( "encoding/binary" "encoding/json" "fmt" "github.com/boltdb/bolt" "log" ) type StockTrans struct { Id int Date string Trans string Symbol string Quantity int Price float32 Settled bool } func (st *StockTrans) save(db *bolt.DB, bucket string) error { err := db.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucket)) id, _ := b.NextSequence() st.Id = int(id) encoded, err := json.Marshal(st) if err != nil { return err } return b.Put(itob(st.Id), encoded) }) return err } func itob(i int) []byte { b := make([]byte, 8) binary.BigEndian.PutUint64(b, uint64(i)) return b } func check(err error) { if err != nil { log.Fatal(err) } } func main() { db, err := bolt.Open("store.db", 0600, nil) check(err) defer db.Close() err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte("stocks")) return err }) check(err) transactions := []*StockTrans{ {0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true}, {0, "2006-03-28", "BUY", "IBM", 1000, 45, true}, {0, "2006-04-06", "SELL", "IBM", 500, 53, true}, {0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false}, } for _, trans := range transactions { err := trans.save(db, "stocks") check(err) } fmt.Println("Id Date Trans Sym Qty Price Settled") fmt.Println("------------------------------------------------") db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("stocks")) b.ForEach(func(k, v []byte) error { st := new(StockTrans) err := json.Unmarshal(v, st) check(err) fmt.Printf("%d %s  %-4s  %-5s %4d %2.2f %t\n", st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled) return nil }) return nil }) }
Convert this Python block to Go, preserving its control flow and logic.
from collections import namedtuple import math Circle = namedtuple('Circle', 'x, y, r') def solveApollonius(c1, c2, c3, s1, s2, s3): x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3 v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1 v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2 w12 = v12/v11 w13 = v13/v11 w14 = v14/v11 w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14 P = -w23/w22 Q = w24/w22 M = -w12*P-w13 N = w14 - w12*Q a = N*N + Q*Q - 1 b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1 D = b*b-4*a*c rs = (-b-math.sqrt(D))/(2*a) xs = M+N*rs ys = P+Q*rs return Circle(xs, ys, rs) if __name__ == '__main__': c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2) print(solveApollonius(c1, c2, c3, 1, 1, 1)) print(solveApollonius(c1, c2, c3, -1, -1, -1))
package main import ( "fmt" "math" ) type circle struct { x, y, r float64 } func main() { c1 := circle{0, 0, 1} c2 := circle{4, 0, 1} c3 := circle{2, 4, 2} fmt.Println(ap(c1, c2, c3, true)) fmt.Println(ap(c1, c2, c3, false)) } func ap(c1, c2, c3 circle, s bool) circle { x1sq := c1.x * c1.x y1sq := c1.y * c1.y r1sq := c1.r * c1.r x2sq := c2.x * c2.x y2sq := c2.y * c2.y r2sq := c2.r * c2.r x3sq := c3.x * c3.x y3sq := c3.y * c3.y r3sq := c3.r * c3.r v11 := 2 * (c2.x - c1.x) v12 := 2 * (c2.y - c1.y) v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq v14 := 2 * (c2.r - c1.r) v21 := 2 * (c3.x - c2.x) v22 := 2 * (c3.y - c2.y) v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq v24 := 2 * (c3.r - c2.r) if s { v14 = -v14 v24 = -v24 } w12 := v12 / v11 w13 := v13 / v11 w14 := v14 / v11 w22 := v22/v21 - w12 w23 := v23/v21 - w13 w24 := v24/v21 - w14 p := -w23 / w22 q := w24 / w22 m := -w12*p - w13 n := w14 - w12*q a := n*n + q*q - 1 b := m*n - n*c1.x + p*q - q*c1.y if s { b -= c1.r } else { b += c1.r } b *= 2 c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq d := b*b - 4*a*c rs := (-b - math.Sqrt(d)) / (2 * a) return circle{m + n*rs, p + q*rs, rs} }
Port the following code from Python to Go with equivalent syntax and logic.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
package main import "fmt" func main() { list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9} list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18} list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27} var list [9]int for i := 0; i < 9; i++ { list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i] } fmt.Println(list) }