Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the programming language of this snippet from Go to C# without modifying what it does.
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() }
using System; class Program { static bool ispr(uint n) { if ((n & 1) == 0 || n < 2) return n == 2; for (uint j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } static void Main(string[] args) { uint c = 0; int nc; var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var nxt = new uint[128]; while (true) { nc = 0; foreach (var a in ps) { if (ispr(a)) Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " "); for (uint b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) { Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); } else break; } Console.WriteLine("\n{0} descending primes found", c); } }
Convert the following code from Go to C#, ensuring the logic remains intact.
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 }
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { const int maxSum = 100; var pairs = ( from X in 2.To(maxSum / 2 - 1) from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum) select new { X, Y, S = X + Y, P = X * Y } ).ToHashSet(); Console.WriteLine(pairs.Count); var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet(); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); foreach (var pair in pairs) Console.WriteLine(pair); } } public static class Extensions { public static IEnumerable<int> To(this int start, int end) { for (int i = start; i <= end; i++) yield return i; } public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source); }
Keep all operations the same but rewrite the snippet in C#.
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 }
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators = new (string symbol, int precedence, bool rightAssociative) [] { ("^", 4, true), ("*", 3, false), ("/", 3, false), ("+", 2, false), ("-", 2, false) }.ToDictionary(op => op.symbol); public static string ToPostfix(this string infix) { string[] tokens = infix.Split(' '); var stack = new Stack<string>(); var output = new List<string>(); foreach (string token in tokens) { if (int.TryParse(token, out _)) { output.Add(token); Print(token); } else if (operators.TryGetValue(token, out var op1)) { while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { int c = op1.precedence.CompareTo(op2.precedence); if (c < 0 || !op1.rightAssociative && c <= 0) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); Print(token); } else if (token == "(") { stack.Push(token); Print(token); } else if (token == ")") { string top = ""; while (stack.Count > 0 && (top = stack.Pop()) != "(") { output.Add(top); } if (top != "(") throw new ArgumentException("No matching left parenthesis."); Print(token); } } while (stack.Count > 0) { var top = stack.Pop(); if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); output.Add(top); } Print("pop"); return string.Join(" ", output); void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); } }
Convert this Go snippet to C# and keep its semantics consistent.
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 }
using System; namespace RosettaCode { class Program { static void Main(string[] args) { string text = Math.Abs(int.Parse(Console.ReadLine())).ToString(); Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3)); } } }
Convert this Go block to C#, preserving its control flow and logic.
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 }
using System; namespace RosettaCode { class Program { static void Main(string[] args) { string text = Math.Abs(int.Parse(Console.ReadLine())).ToString(); Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3)); } } }
Produce a functionally identical C# code for the snippet given in Go.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
Produce a language-to-language conversion: from Go to C#, same semantics.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
Keep all operations the same but rewrite the snippet in C#.
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 }
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<int> l = new List<int>() { 1, 1 }; static int gcd(int a, int b) { return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; } static void Main(string[] args) { int max = 1000; int take = 15; int i = 1; int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 }; do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; } while (l.Count < max || l[l.Count - 2] != selection.Last()); Console.Write("The first {0} items In the Stern-Brocot sequence: ", take); Console.WriteLine("{0}\n", string.Join(", ", l.Take(take))); Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:"); foreach (int ii in selection) { int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); } Console.WriteLine(); bool good = true; for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } } Console.WriteLine("The greatest common divisor of all the two consecutive items of the" + " series up to the {0}th item is {1}always one.", max, good ? "" : "not "); } }
Translate the given Go code snippet into C# without altering its behavior.
package example var ( X, Y, Z int ) func XP() { } func nonXP() {} var MEMEME int
public static class XMLSystem { static XMLSystem() { } public static XmlDocument GetXML(string name) { return null; } }
Generate a C# translation of this Go snippet without changing its computational steps.
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} }
using System; namespace ApolloniusProblemCalc { class Program { static float rs = 0; static float xs = 0; static float ys = 0; public static void Main(string[] args) { float gx1; float gy1; float gr1; float gx2; float gy2; float gr2; float gx3; float gy3; float gr3; gx1 = 0; gy1 = 0; gr1 = 1; gx2 = 4; gy2 = 0; gr2 = 1; gx3 = 2; gy3 = 4; gr3 = 2; for (int i = 1; i <= 8; i++) { SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3); if (i == 1) { Console.WriteLine("X of point of the " + i + "st solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "st solution: " + ys.ToString()); Console.WriteLine(i + "st Solution circle's radius: " + rs.ToString()); } else if (i == 2) { Console.WriteLine("X of point of the " + i + "ed solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "ed solution: " + ys.ToString()); Console.WriteLine(i + "ed Solution circle's radius: " + rs.ToString()); } else if(i == 3) { Console.WriteLine("X of point of the " + i + "rd solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "rd solution: " + ys.ToString()); Console.WriteLine(i + "rd Solution circle's radius: " + rs.ToString()); } else { Console.WriteLine("X of point of the " + i + "th solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "th solution: " + ys.ToString()); Console.WriteLine(i + "th Solution circle's radius: " + rs.ToString()); } Console.WriteLine(); } Console.ReadKey(true); } private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3) { float s1 = 1; float s2 = 1; float s3 = 1; if (calcCounter == 2) { s1 = -1; s2 = -1; s3 = -1; } else if (calcCounter == 3) { s1 = 1; s2 = -1; s3 = -1; } else if (calcCounter == 4) { s1 = -1; s2 = 1; s3 = -1; } else if (calcCounter == 5) { s1 = -1; s2 = -1; s3 = 1; } else if (calcCounter == 6) { s1 = 1; s2 = 1; s3 = -1; } else if (calcCounter == 7) { s1 = -1; s2 = 1; s3 = 1; } else if (calcCounter == 8) { s1 = 1; s2 = -1; s3 = 1; } float v11 = 2 * x2 - 2 * x1; float v12 = 2 * y2 - 2 * y1; float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2; float v14 = 2 * s2 * r2 - 2 * s1 * r1; float v21 = 2 * x3 - 2 * x2; float v22 = 2 * y3 - 2 * y2; float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3; float v24 = 2 * s3 * r3 - 2 * s2 * r2; float w12 = v12 / v11; float w13 = v13 / v11; float w14 = v14 / v11; float w22 = v22 / v21 - w12; float w23 = v23 / v21 - w13; float w24 = v24 / v21 - w14; float P = -w23 / w22; float Q = w24 / w22; float M = -w12 * P - w13; float N = w14 - w12 * Q; float a = N * N + Q * Q - 1; float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1; float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1; float D = b * b - 4 * a * c; rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString())); xs = M + N * rs; ys = P + Q * rs; } } }
Write the same code in C# as shown below in Go.
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Write the same code in C# as shown below in Go.
package main import ( "bufio" "fmt" "os" ) func main() { f, err := os.Open("rc.fasta") if err != nil { fmt.Println(err) return } defer f.Close() s := bufio.NewScanner(f) headerFound := false for s.Scan() { line := s.Text() switch { case line == "": continue case line[0] != '>': if !headerFound { fmt.Println("missing header") return } fmt.Print(line) case headerFound: fmt.Println() fallthrough default: fmt.Printf("%s: ", line[1:]) headerFound = true } } if headerFound { fmt.Println() } if err := s.Err(); err != nil { fmt.Println(err) } }
using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { public class FastaEntry { public string Name { get; set; } public StringBuilder Sequence { get; set; } } static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile) { FastaEntry f = null; string line; while ((line = fastaFile.ReadLine()) != null) { if (line.StartsWith(";")) continue; if (line.StartsWith(">")) { if (f != null) yield return f; f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() }; } else if (f != null) f.Sequence.Append(line); } yield return f; } static void Main(string[] args) { try { using (var fastaFile = new StreamReader("fasta.txt")) { foreach (FastaEntry f in ParseFasta(fastaFile)) Console.WriteLine("{0}: {1}", f.Name, f.Sequence); } } catch (FileNotFoundException e) { Console.WriteLine(e); } Console.ReadLine(); } }
Preserve the algorithm and functionality while converting the code from Go to C#.
package main import ( "fmt" "strconv" "time" ) func isPalindrome2(n uint64) bool { x := uint64(0) if (n & 1) == 0 { return n == 0 } for x < n { x = (x << 1) | (n & 1) n >>= 1 } return n == x || n == (x>>1) } func reverse3(n uint64) uint64 { x := uint64(0) for n != 0 { x = x*3 + (n % 3) n /= 3 } return x } func show(n uint64) { fmt.Println("Decimal :", n) fmt.Println("Binary  :", strconv.FormatUint(n, 2)) fmt.Println("Ternary :", strconv.FormatUint(n, 3)) fmt.Println("Time  :", time.Since(start)) fmt.Println() } func min(a, b uint64) uint64 { if a < b { return a } return b } func max(a, b uint64) uint64 { if a > b { return a } return b } var start time.Time func main() { start = time.Now() fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n") show(0) cnt := 1 var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1 for { i := lo for ; i < hi; i++ { n := (i*3+1)*pow3 + reverse3(i) if !isPalindrome2(n) { continue } show(n) cnt++ if cnt >= 7 { return } } if i == pow3 { pow3 *= 3 } else { pow2 *= 4 } for { for pow2 <= pow3 { pow2 *= 4 } lo2 := (pow2/pow3 - 1) / 3 hi2 := (pow2*2/pow3-1)/3 + 1 lo3 := pow3 / 3 hi3 := pow3 if lo2 >= hi3 { pow3 *= 3 } else if lo3 >= hi2 { pow2 *= 4 } else { lo = max(lo2, lo3) hi = min(hi2, hi3) break } } } }
using System; using System.Collections.Generic; using System.Linq; public class FindPalindromicNumbers { static void Main(string[] args) { var query = PalindromicTernaries() .Where(IsPalindromicBinary) .Take(6); foreach (var x in query) { Console.WriteLine("Decimal: " + x); Console.WriteLine("Ternary: " + ToTernary(x)); Console.WriteLine("Binary: " + Convert.ToString(x, 2)); Console.WriteLine(); } } public static IEnumerable<long> PalindromicTernaries() { yield return 0; yield return 1; yield return 13; yield return 23; var f = new List<long> {0}; long fMiddle = 9; while (true) { for (long edge = 1; edge < 3; edge++) { int i; do { long result = fMiddle; long fLeft = fMiddle * 3; long fRight = fMiddle / 3; for (int j = f.Count - 1; j >= 0; j--) { result += (fLeft + fRight) * f[j]; fLeft *= 3; fRight /= 3; } result += (fLeft + fRight) * edge; yield return result; for (i = f.Count - 1; i >= 0; i--) { if (f[i] == 2) { f[i] = 0; } else { f[i]++; break; } } } while (i >= 0); } f.Add(0); fMiddle *= 3; } } public static bool IsPalindromicBinary(long number) { long n = number; long reverse = 0; while (n != 0) { reverse <<= 1; if ((n & 1) == 1) reverse++; n >>= 1; } return reverse == number; } public static string ToTernary(long n) { if (n == 0) return "0"; string result = ""; while (n > 0) { { result = (n % 3) + result; n /= 3; } return result; } }
Preserve the algorithm and functionality while converting the code from Go to C#.
package main import ( "fmt" "strconv" "time" ) func isPalindrome2(n uint64) bool { x := uint64(0) if (n & 1) == 0 { return n == 0 } for x < n { x = (x << 1) | (n & 1) n >>= 1 } return n == x || n == (x>>1) } func reverse3(n uint64) uint64 { x := uint64(0) for n != 0 { x = x*3 + (n % 3) n /= 3 } return x } func show(n uint64) { fmt.Println("Decimal :", n) fmt.Println("Binary  :", strconv.FormatUint(n, 2)) fmt.Println("Ternary :", strconv.FormatUint(n, 3)) fmt.Println("Time  :", time.Since(start)) fmt.Println() } func min(a, b uint64) uint64 { if a < b { return a } return b } func max(a, b uint64) uint64 { if a > b { return a } return b } var start time.Time func main() { start = time.Now() fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n") show(0) cnt := 1 var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1 for { i := lo for ; i < hi; i++ { n := (i*3+1)*pow3 + reverse3(i) if !isPalindrome2(n) { continue } show(n) cnt++ if cnt >= 7 { return } } if i == pow3 { pow3 *= 3 } else { pow2 *= 4 } for { for pow2 <= pow3 { pow2 *= 4 } lo2 := (pow2/pow3 - 1) / 3 hi2 := (pow2*2/pow3-1)/3 + 1 lo3 := pow3 / 3 hi3 := pow3 if lo2 >= hi3 { pow3 *= 3 } else if lo3 >= hi2 { pow2 *= 4 } else { lo = max(lo2, lo3) hi = min(hi2, hi3) break } } } }
using System; using System.Collections.Generic; using System.Linq; public class FindPalindromicNumbers { static void Main(string[] args) { var query = PalindromicTernaries() .Where(IsPalindromicBinary) .Take(6); foreach (var x in query) { Console.WriteLine("Decimal: " + x); Console.WriteLine("Ternary: " + ToTernary(x)); Console.WriteLine("Binary: " + Convert.ToString(x, 2)); Console.WriteLine(); } } public static IEnumerable<long> PalindromicTernaries() { yield return 0; yield return 1; yield return 13; yield return 23; var f = new List<long> {0}; long fMiddle = 9; while (true) { for (long edge = 1; edge < 3; edge++) { int i; do { long result = fMiddle; long fLeft = fMiddle * 3; long fRight = fMiddle / 3; for (int j = f.Count - 1; j >= 0; j--) { result += (fLeft + fRight) * f[j]; fLeft *= 3; fRight /= 3; } result += (fLeft + fRight) * edge; yield return result; for (i = f.Count - 1; i >= 0; i--) { if (f[i] == 2) { f[i] = 0; } else { f[i]++; break; } } } while (i >= 0); } f.Add(0); fMiddle *= 3; } } public static bool IsPalindromicBinary(long number) { long n = number; long reverse = 0; while (n != 0) { reverse <<= 1; if ((n & 1) == 1) reverse++; n >>= 1; } return reverse == number; } public static string ToTernary(long n) { if (n == 0) return "0"; string result = ""; while (n > 0) { { result = (n % 3) + result; n /= 3; } return result; } }
Preserve the algorithm and functionality while converting the code from Go to C#.
package main import ( "fmt" "os" "golang.org/x/crypto/ssh/terminal" ) func main() { w, h, err := terminal.GetSize(int(os.Stdout.Fd())) if err != nil { fmt.Println(err) return } fmt.Println(h, w) }
static void Main(string[] args) { int bufferHeight = Console.BufferHeight; int bufferWidth = Console.BufferWidth; int windowHeight = Console.WindowHeight; int windowWidth = Console.WindowWidth; Console.Write("Buffer Height: "); Console.WriteLine(bufferHeight); Console.Write("Buffer Width: "); Console.WriteLine(bufferWidth); Console.Write("Window Height: "); Console.WriteLine(windowHeight); Console.Write("Window Width: "); Console.WriteLine(windowWidth); Console.ReadLine(); }
Translate the given Go code snippet into C# without altering its behavior.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { return } var a, ω2 int for a = 0; ; a++ { ω2 = (a*a + p - n) % p if ls(ω2) == p-1 { break } } type point struct{ x, y int } mul := func(a, b point) point { return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p} } r := point{1, 0} s := point{a, 1} for n := (p + 1) >> 1 % p; n > 0; n >>= 1 { if n&1 == 1 { r = mul(r, s) } s = mul(s, s) } if r.y != 0 { return } if r.x*r.x%p != n { return } return r.x, p - r.x, true } func main() { fmt.Println(c(10, 13)) fmt.Println(c(56, 101)) fmt.Println(c(8218, 10007)) fmt.Println(c(8219, 10007)) fmt.Println(c(331575, 1000003)) }
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
Write the same algorithm in C# as shown in this Go implementation.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { return } var a, ω2 int for a = 0; ; a++ { ω2 = (a*a + p - n) % p if ls(ω2) == p-1 { break } } type point struct{ x, y int } mul := func(a, b point) point { return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p} } r := point{1, 0} s := point{a, 1} for n := (p + 1) >> 1 % p; n > 0; n >>= 1 { if n&1 == 1 { r = mul(r, s) } s = mul(s, s) } if r.y != 0 { return } if r.x*r.x%p != n { return } return r.x, p - r.x, true } func main() { fmt.Println(c(10, 13)) fmt.Println(c(56, 101)) fmt.Println(c(8218, 10007)) fmt.Println(c(8219, 10007)) fmt.Println(c(331575, 1000003)) }
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
Can you help me rewrite this code in C# instead of Go, keeping it the same logically?
package main import ( "fmt" "rcu" ) func main() { numbers1 := [5]int{5, 45, 23, 21, 67} numbers2 := [5]int{43, 22, 78, 46, 38} numbers3 := [5]int{9, 98, 12, 54, 53} primes := [5]int{} for n := 0; n < 5; n++ { max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n]) if max % 2 == 0 { max++ } for !rcu.IsPrime(max) { max += 2 } primes[n] = max } fmt.Println(primes) }
using System; using System.Linq; using static System.Console; class Program { static int nxtPrime(int x) { int j = 2; do { if (x % j == 0) { j = 2; x++; } else j += j < 3 ? 1 : 2; } while (j * j <= x); return x; } static void Main(string[] args) { WriteLine("working..."); int[] Num1 = new int[]{ 5, 45, 23, 21, 67 }, Num2 = new int[]{ 43, 22, 78, 46, 38 }, Num3 = new int[]{ 9, 98, 12, 54, 53 }; int n = Num1.Length; int[] Nums = new int[n]; for (int i = 0; i < n; i++) Nums[i] = nxtPrime(new int[]{ Num1[i], Num2[i], Num3[i] }.Max()); WriteLine("The minimum prime numbers of three lists = [{0}]", string.Join(",", Nums)); Write("done..."); } }
Ensure the translated C# code behaves exactly like the original Go snippet.
ch := 'z' ch = 122 ch = '\x7a' ch = '\u007a' ch = '\U0000007a' ch = '\172'
string path = @"C:\Windows\System32"; string multiline = @"Line 1. Line 2. Line 3.";
Change the programming language of this snippet from Go to C# without modifying what it does.
package main import ( "fmt" "github.com/go-vgo/robotgo" ) func main() { w, h := robotgo.GetScreenSize() fmt.Printf("Screen size: %d x %d\n", w, h) fpid, err := robotgo.FindIds("firefox") if err == nil && len(fpid) > 0 { pid := fpid[0] robotgo.ActivePID(pid) robotgo.MaxWindow(pid) _, _, w, h = robotgo.GetBounds(pid) fmt.Printf("Max usable : %d x %d\n", w, h) } }
using System; using System.Drawing; using System.Windows.Forms; static class Program { static void Main() { Rectangle bounds = Screen.PrimaryScreen.Bounds; Console.WriteLine($"Primary screen bounds: {bounds.Width}x{bounds.Height}"); Rectangle workingArea = Screen.PrimaryScreen.WorkingArea; Console.WriteLine($"Primary screen working area: {workingArea.Width}x{workingArea.Height}"); } }
Produce a language-to-language conversion: from Go to C#, same semantics.
const ( apple = iota banana cherry )
enum fruits { apple, banana, cherry } enum fruits { apple = 0, banana = 1, cherry = 2 } enum fruits : int { apple = 0, banana = 1, cherry = 2 } [FlagsAttribute] enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
Convert the following code from Go to C#, ensuring the logic remains intact.
package main import "fmt" type Item struct { Name string Value int Weight, Volume float64 } type Result struct { Counts []int Sum int } func min(a, b int) int { if a < b { return a } return b } func Knapsack(items []Item, weight, volume float64) (best Result) { if len(items) == 0 { return } n := len(items) - 1 maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume)) for count := 0; count <= maxCount; count++ { sol := Knapsack(items[:n], weight-float64(count)*items[n].Weight, volume-float64(count)*items[n].Volume) sol.Sum += items[n].Value * count if sol.Sum > best.Sum { sol.Counts = append(sol.Counts, count) best = sol } } return } func main() { items := []Item{ {"Panacea", 3000, 0.3, 0.025}, {"Ichor", 1800, 0.2, 0.015}, {"Gold", 2500, 2.0, 0.002}, } var sumCount, sumValue int var sumWeight, sumVolume float64 result := Knapsack(items, 25, 0.25) for i := range result.Counts { fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n", items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]), items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i]) sumCount += result.Counts[i] sumValue += items[i].Value * result.Counts[i] sumWeight += items[i].Weight * float64(result.Counts[i]) sumVolume += items[i].Volume * float64(result.Counts[i]) } fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n", sumCount, sumWeight, sumVolume, sumValue) }
using System; class Program { static void Main() { uint[] r = items1(); Console.WriteLine(r[0] + " v " + r[1] + " a " + r[2] + " b"); var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 1000; i > 0; i--) items1(); Console.Write(sw.Elapsed); Console.Read(); } static uint[] items0() { uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0; for (a = 0; a <= 10; a++) for (b = 0; a * 5 + b * 3 <= 50; b++) for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++) if (v0 < (v = a * 30 + b * 18 + c * 25)) { v0 = v; a0 = a; b0 = b; c0 = c; } return new uint[] { a0, b0, c0 }; } static uint[] items1() { uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0; for (a = 0; a <= 10; a++) for (b = 0; a * 5 + b * 3 <= 50; b++) { c = (250 - a * 25 - b * 15) / 2; if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1; if (v0 < (v = a * 30 + b * 18 + c * 25)) { v0 = v; a0 = a; b0 = b; c0 = c; } } return new uint[] { a0, b0, c0 }; } }
Write the same algorithm in C# as shown in this Go implementation.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
Change the following Go code into C# without altering its purpose.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
Port the following code from Go to C# with equivalent syntax and logic.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import ( "errors" "fmt" "strconv" "strings" ) func main() { rf, err := rangeFormat([]int{ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, }) if err != nil { fmt.Println(err) return } fmt.Println("range format:", rf) } func rangeFormat(a []int) (string, error) { if len(a) == 0 { return "", nil } var parts []string for n1 := 0; ; { n2 := n1 + 1 for n2 < len(a) && a[n2] == a[n2-1]+1 { n2++ } s := strconv.Itoa(a[n1]) if n2 == n1+2 { s += "," + strconv.Itoa(a[n2-1]) } else if n2 > n1+2 { s += "-" + strconv.Itoa(a[n2-1]) } parts = append(parts, s) if n2 == len(a) { break } if a[n2] == a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence repeats value %d", a[n2])) } if a[n2] < a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence not ordered: %d < %d", a[n2], a[n2-1])) } n1 = n2 } return strings.Join(parts, ","), nil }
using System; using System.Collections.Generic; using System.Linq; class RangeExtraction { static void Main() { const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39"; var result = String.Join(",", RangesToStrings(GetRanges(testString))); Console.Out.WriteLine(result); } public static IEnumerable<IEnumerable<int>> GetRanges(string testString) { var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x)); var current = new List<int>(); foreach (var n in numbers) { if (current.Count == 0) { current.Add(n); } else { if (current.Max() + 1 == n) { current.Add(n); } else { yield return current; current = new List<int> { n }; } } } yield return current; } public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges) { foreach (var range in ranges) { if (range.Count() == 1) { yield return range.Single().ToString(); } else if (range.Count() == 2) { yield return range.Min() + "," + range.Max(); } else { yield return range.Min() + "-" + range.Max(); } } } }
Convert this Go block to C#, preserving its control flow and logic.
package main import "fmt" type any = interface{} func showType(a any) { switch a.(type) { case rune: fmt.Printf("The type of '%c' is %T\n", a, a) default: fmt.Printf("The type of '%v' is %T\n", a, a) } } func main() { values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"} for _, value := range values { showType(value) } }
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); ShowType(7.5); ShowType('d'); ShowType(true); ShowType("Rosetta"); ShowType(new C()); ShowType(new S()); ShowType(E.NONE); ShowType(new int[] { 1, 2, 3 }); } } }
Port the provided Go code into C# while preserving the original functionality.
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
using System; namespace RosetaCode { class MainClass { public static void Main (string[] args) { int[,] list = new int[18,19]; string input = @"55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"; var charArray = input.Split ('\n'); for (int i=0; i < charArray.Length; i++) { var numArr = charArray[i].Trim().Split(' '); for (int j = 0; j<numArr.Length; j++) { int number = Convert.ToInt32 (numArr[j]); list [i, j] = number; } } for (int i = 16; i >= 0; i--) { for (int j = 0; j < 18; j++) { list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]); } } Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0])); } } }
Rewrite this program in C# while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "time" "os" "os/exec" "strconv" ) func main() { tput("clear") tput("cup", "6", "3") time.Sleep(1 * time.Second) tput("cub1") time.Sleep(1 * time.Second) tput("cuf1") time.Sleep(1 * time.Second) tput("cuu1") time.Sleep(1 * time.Second) tput("cud", "1") time.Sleep(1 * time.Second) tput("cr") time.Sleep(1 * time.Second) var h, w int cmd := exec.Command("stty", "size") cmd.Stdin = os.Stdin d, _ := cmd.Output() fmt.Sscan(string(d), &h, &w) tput("hpa", strconv.Itoa(w-1)) time.Sleep(2 * time.Second) tput("home") time.Sleep(2 * time.Second) tput("cup", strconv.Itoa(h-1), strconv.Itoa(w-1)) time.Sleep(3 * time.Second) } func tput(args ...string) error { cmd := exec.Command("tput", args...) cmd.Stdout = os.Stdout return cmd.Run() }
static void Main(string[] args) { Console.Write("\n\n\n\n Cursor is here --> "); System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.CursorLeft - 1; System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.CursorLeft + 1; System.Threading.Thread.Sleep(3000); Console.CursorTop = Console.CursorTop - 1; System.Threading.Thread.Sleep(3000); Console.CursorTop = Console.CursorTop + 1; System.Threading.Thread.Sleep(3000); Console.CursorLeft = 0; System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.BufferWidth - 1; System.Threading.Thread.Sleep(3000); Console.SetCursorPosition(0,0); System.Threading.Thread.Sleep(3000); Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); System.Threading.Thread.Sleep(3000); }
Produce a functionally identical C# code for the snippet given in Go.
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks.FourBitAdder { public struct BitAdderOutput { public bool S { get; set; } public bool C { get; set; } public override string ToString ( ) { return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" ); } } public struct Nibble { public bool _1 { get; set; } public bool _2 { get; set; } public bool _3 { get; set; } public bool _4 { get; set; } public override string ToString ( ) { return ( _4 ? "1" : "0" ) + ( _3 ? "1" : "0" ) + ( _2 ? "1" : "0" ) + ( _1 ? "1" : "0" ); } } public struct FourBitAdderOutput { public Nibble N { get; set; } public bool C { get; set; } public override string ToString ( ) { return N.ToString ( ) + "c" + ( C ? "1" : "0" ); } } public static class LogicGates { public static bool Not ( bool A ) { return !A; } public static bool And ( bool A, bool B ) { return A && B; } public static bool Or ( bool A, bool B ) { return A || B; } public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); } } public static class ConstructiveBlocks { public static BitAdderOutput HalfAdder ( bool A, bool B ) { return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) }; } public static BitAdderOutput FullAdder ( bool A, bool B, bool CI ) { BitAdderOutput HA1 = HalfAdder ( CI, A ); BitAdderOutput HA2 = HalfAdder ( HA1.S, B ); return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) }; } public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI ) { BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI ); BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C ); BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C ); BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C ); return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C }; } public static void Test ( ) { Console.WriteLine ( "Four Bit Adder" ); for ( int i = 0; i < 256; i++ ) { Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; if ( (i & 1) == 1) { A._1 = true; } if ( ( i & 2 ) == 2 ) { A._2 = true; } if ( ( i & 4 ) == 4 ) { A._3 = true; } if ( ( i & 8 ) == 8 ) { A._4 = true; } if ( ( i & 16 ) == 16 ) { B._1 = true; } if ( ( i & 32 ) == 32) { B._2 = true; } if ( ( i & 64 ) == 64 ) { B._3 = true; } if ( ( i & 128 ) == 128 ) { B._4 = true; } Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) ); } Console.WriteLine ( ); } } }
Translate this program into C# but keep the logic exactly as in Go.
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks.FourBitAdder { public struct BitAdderOutput { public bool S { get; set; } public bool C { get; set; } public override string ToString ( ) { return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" ); } } public struct Nibble { public bool _1 { get; set; } public bool _2 { get; set; } public bool _3 { get; set; } public bool _4 { get; set; } public override string ToString ( ) { return ( _4 ? "1" : "0" ) + ( _3 ? "1" : "0" ) + ( _2 ? "1" : "0" ) + ( _1 ? "1" : "0" ); } } public struct FourBitAdderOutput { public Nibble N { get; set; } public bool C { get; set; } public override string ToString ( ) { return N.ToString ( ) + "c" + ( C ? "1" : "0" ); } } public static class LogicGates { public static bool Not ( bool A ) { return !A; } public static bool And ( bool A, bool B ) { return A && B; } public static bool Or ( bool A, bool B ) { return A || B; } public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); } } public static class ConstructiveBlocks { public static BitAdderOutput HalfAdder ( bool A, bool B ) { return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) }; } public static BitAdderOutput FullAdder ( bool A, bool B, bool CI ) { BitAdderOutput HA1 = HalfAdder ( CI, A ); BitAdderOutput HA2 = HalfAdder ( HA1.S, B ); return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) }; } public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI ) { BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI ); BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C ); BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C ); BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C ); return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C }; } public static void Test ( ) { Console.WriteLine ( "Four Bit Adder" ); for ( int i = 0; i < 256; i++ ) { Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; if ( (i & 1) == 1) { A._1 = true; } if ( ( i & 2 ) == 2 ) { A._2 = true; } if ( ( i & 4 ) == 4 ) { A._3 = true; } if ( ( i & 8 ) == 8 ) { A._4 = true; } if ( ( i & 16 ) == 16 ) { B._1 = true; } if ( ( i & 32 ) == 32) { B._2 = true; } if ( ( i & 64 ) == 64 ) { B._3 = true; } if ( ( i & 128 ) == 128 ) { B._4 = true; } Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) ); } Console.WriteLine ( ); } } }
Rewrite this program in C# while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "log" "os" "sort" ) func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Unix_ls { public class UnixLS { public static void Main(string[] args) { UnixLS ls = new UnixLS(); ls.list(args.Length.Equals(0) ? "." : args[0]); } private void list(string folder) { foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly)) { Console.WriteLine(fileSystemInfo.Name); } } } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import ( "bytes" "encoding/hex" "fmt" "log" "strings" ) var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, } func main() { for _, tc := range testCases { u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } e := encodeUTF8(tc.rune) d := decodeUTF8(b) fmt.Printf("%c  %-7s %X\n", d, u, e) if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } } const ( b2Lead = 0xC0 b2Mask = 0x1F b3Lead = 0xE0 b3Mask = 0x0F b4Lead = 0xF0 b4Mask = 0x07 mbLead = 0x80 mbMask = 0x3F ) func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: return []byte{byte(r)} case i <= 1<<11-1: return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } } func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
using System; using System.Text; namespace Rosetta { class Program { static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint)); static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes); static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; foreach (int unicodePoint in new int[] { 0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] asUtf8bytes = MyEncoder(unicodePoint); string theCharacter = MyDecoder(asUtf8bytes); Console.WriteLine("{0,8} {1,5} {2,-15}", unicodePoint.ToString("X4"), theCharacter, BitConverter.ToString(asUtf8bytes)); } } } }
Keep all operations the same but rewrite the snippet in C#.
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
using System; namespace MagicSquareDoublyEven { class Program { static void Main(string[] args) { int n = 8; var result = MagicSquareDoublyEven(n); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) Console.Write("{0,2} ", result[i, j]); Console.WriteLine(); } Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2); Console.ReadLine(); } private static int[,] MagicSquareDoublyEven(int n) { if (n < 4 || n % 4 != 0) throw new ArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[,] result = new int[n, n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } } }
Keep all operations the same but rewrite the snippet in C#.
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
using System; using System.Collections.Generic; using System.Linq; namespace Same_Fringe { class Program { static void Main() { var rnd = new Random(110456); var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList(); var bt1 = new BinTree<int>(randList); Shuffle(randList, 428); var bt2 = new BinTree<int>(randList); Console.WriteLine(bt1.CompareTo(bt2) ? "True compare worked" : "True compare failed"); bt1.Insert(0); Console.WriteLine(bt1.CompareTo(bt2) ? "False compare failed" : "False compare worked"); } static void Shuffle<T>(List<T> values, int seed) { var rnd = new Random(seed); for (var i = 0; i < values.Count - 2; i++) { var iSwap = rnd.Next(values.Count - i) + i; var tmp = values[iSwap]; values[iSwap] = values[i]; values[i] = tmp; } } } class BinTree<T> where T:IComparable { private BinTree<T> _left; private BinTree<T> _right; private T _value; private BinTree<T> Left { get { return _left; } } private BinTree<T> Right { get { return _right; } } private T Value { get { return _value; } } public bool IsLeaf { get { return Left == null; } } private BinTree(BinTree<T> left, BinTree<T> right, T value) { _left = left; _right = right; _value = value; } public BinTree(T value) : this(null, null, value) { } public BinTree(IEnumerable<T> values) { _value = values.First(); foreach (var value in values.Skip(1)) { Insert(value); } } public void Insert(T value) { if (IsLeaf) { if (value.CompareTo(Value) < 0) { _left = new BinTree<T>(value); _right = new BinTree<T>(Value); } else { _left = new BinTree<T>(Value); _right = new BinTree<T>(value); _value = value; } } else { if (value.CompareTo(Value) < 0) { Left.Insert(value); } else { Right.Insert(value); } } } public IEnumerable<T> GetLeaves() { if (IsLeaf) { yield return Value; yield break; } foreach (var val in Left.GetLeaves()) { yield return val; } foreach (var val in Right.GetLeaves()) { yield return val; } } internal bool CompareTo(BinTree<T> other) { return other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f); } } }
Maintain the same structure and functionality when rewriting this code in C#.
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
using System; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3) Console.WriteLine("{1,43} {0,-20}", x, x * x); } }
Rewrite this program in C# while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
using System; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3) Console.WriteLine("{1,43} {0,-20}", x, x * x); } }
Write the same code in C# as shown below in Go.
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false } func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false } func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white } for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") } func main() { nms := [][2]int{ {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, } for _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.Println("No solution exists.\n") } } }
using System; using System.Collections.Generic; namespace PeacefulChessQueenArmies { using Position = Tuple<int, int>; enum Piece { Empty, Black, White } class Program { static bool IsAttacking(Position queen, Position pos) { return queen.Item1 == pos.Item1 || queen.Item2 == pos.Item2 || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2); } static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { var pos = new Position(i, j); foreach (var queen in pBlackQueens) { if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) { goto inner; } } foreach (var queen in pWhiteQueens) { if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.Add(pos); placingBlack = false; } else { pWhiteQueens.Add(pos); if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.RemoveAt(pBlackQueens.Count - 1); pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1); placingBlack = true; } inner: { } } } if (!placingBlack) { pBlackQueens.RemoveAt(pBlackQueens.Count - 1); } return false; } static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { var board = new Piece[n * n]; foreach (var queen in blackQueens) { board[queen.Item1 * n + queen.Item2] = Piece.Black; } foreach (var queen in whiteQueens) { board[queen.Item1 * n + queen.Item2] = Piece.White; } for (int i = 0; i < board.Length; i++) { if (i != 0 && i % n == 0) { Console.WriteLine(); } switch (board[i]) { case Piece.Black: Console.Write("B "); break; case Piece.White: Console.Write("W "); break; case Piece.Empty: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { Console.Write(" "); } else { Console.Write("# "); } break; } } Console.WriteLine("\n"); } static void Main() { var nms = new int[,] { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (int i = 0; i < nms.GetLength(0); i++) { Console.WriteLine("{0} black and {0} white queens on a {1} x {1} board:", nms[i, 1], nms[i, 0]); List<Position> blackQueens = new List<Position>(); List<Position> whiteQueens = new List<Position>(); if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) { PrintBoard(nms[i, 0], blackQueens, whiteQueens); } else { Console.WriteLine("No solution exists.\n"); } } } } }
Rewrite the snippet below in C# so it works the same as the original Go code.
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
while (true) { Console.WriteLine("SPAM"); }
Generate an equivalent C# version of this Go code.
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
using System; using System.Collections.Generic; using System.Text; namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); } private static void moveToFront(int charIndex) { char toFront = symbolTable[charIndex]; for (int j = charIndex; j > 0; j--) { symbolTable[j] = symbolTable[j - 1]; } symbolTable[0] = toFront; } public static int[] Encode(string input) { setSymbolTable(); var output = new List<int>(); foreach (char c in input) { for (int i = 0; i < 26; i++) { if (symbolTable[i] == c) { output.Add(i); moveToFront(i); break; } } } return output.ToArray(); } public static string Decode(int[] input) { setSymbolTable(); var output = new StringBuilder(input.Length); foreach (int n in input) { output.Append(symbolTable[n]); moveToFront(n); } return output.ToString(); } static void Main(string[] args) { string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" }; int[] encoding; foreach (string s in testInputs) { Console.WriteLine($"Encoding for '{s}':"); encoding = Encode(s); foreach (int i in encoding) { Console.Write($"{i} "); } Console.WriteLine($"\nDecoding for '{s}':"); Console.WriteLine($"{Decode(encoding)}\n"); } } } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "rcu" ) func main() { fmt.Println("Cumulative sums of the first 50 cubes:") sum := 0 for n := 0; n < 50; n++ { sum += n * n * n fmt.Printf("%9s ", rcu.Commatize(sum)) if n%10 == 9 { fmt.Println() } } fmt.Println()
using System; using static System.Console; class Program { static void Main(string[] args) { for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6) Write("{0,-7}{1}",s, (i+=i==3?-4:1)==0?"\n":" "); } }
Convert this Go block to C#, preserving its control flow and logic.
package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
using System.Diagnostics; namespace Execute { class Program { static void Main(string[] args) { Process.Start("cmd.exe", "/c dir"); } } }
Keep all operations the same but rewrite the snippet in C#.
package main import ( "fmt" "github.com/lestrrat-go/libxml2" "github.com/lestrrat-go/libxml2/xsd" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { xsdfile := "shiporder.xsd" f, err := os.Open(xsdfile) check(err) defer f.Close() buf, err := ioutil.ReadAll(f) check(err) s, err := xsd.Parse(buf) check(err) defer s.Free() xmlfile := "shiporder.xml" f2, err := os.Open(xmlfile) check(err) defer f2.Close() buf2, err := ioutil.ReadAll(f2) check(err) d, err := libxml2.Parse(buf2) check(err) if err := s.Validate(d); err != nil { for _, e := range err.(xsd.SchemaValidationError).Errors() { log.Printf("error: %s", e.Error()) } return } fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!") }
using System; using System.Xml; using System.Xml.Schema; using System.IO; public class Test { public static void Main() { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add(null, "http: XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = sc; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); XmlReader reader = XmlReader.Create("http: while (reader.Read()); Console.WriteLine("The XML file is valid for the given xsd file"); } private static void ValidationCallBack(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: {0}", e.Message); } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse(); private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) { if (index == values.Count) return current; if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0) return FindRecImpl(values, current, index + 1, comparer); return Max( FindRecImpl(values, current, index + 1, comparer), FindRecImpl(values, current + values[index], index + 1, comparer) ); } private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a; class Sequence<T> : IEnumerable<T> { public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null); public Sequence(T value, Sequence<T> tail) { Value = value; Tail = tail; Length = tail == null ? 0 : tail.Length + 1; } public T Value { get; } public Sequence<T> Tail { get; } public int Length { get; } public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s); public IEnumerator<T> GetEnumerator() { for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
Ensure the translated C# code behaves exactly like the original Go snippet.
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } type Sequence []Expander func (seq Sequence) Expand() []string { if len(seq) == 0 { return nil } out := seq[0].Expand() for _, e := range seq[1:] { out = combine(out, e.Expand()) } return out } func combine(al, bl []string) []string { out := make([]string, 0, len(al)*len(bl)) for _, a := range al { for _, b := range bl { out = append(out, a+b) } } return out } const ( escape = '\\' altStart = '{' altEnd = '}' altSep = ',' ) type piT struct{ pos, cnt, depth int } type Brace string func Expand(s string) []string { return Brace(s).Expand() } func (b Brace) Expand() []string { return b.Expander().Expand() } func (b Brace) Expander() Expander { s := string(b) var posInfo []piT var stack []int removePosInfo := func(i int) { end := len(posInfo) - 1 copy(posInfo[i:end], posInfo[i+1:]) posInfo = posInfo[:end] } inEscape := false for i, r := range s { if inEscape { inEscape = false continue } switch r { case escape: inEscape = true case altStart: stack = append(stack, len(posInfo)) posInfo = append(posInfo, piT{i, 0, len(stack)}) case altEnd: if len(stack) == 0 { continue } si := len(stack) - 1 pi := stack[si] if posInfo[pi].cnt == 0 { removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == len(stack) { removePosInfo(pi) } else { pi++ } } } else { posInfo = append(posInfo, piT{i, -2, len(stack)}) } stack = stack[:si] case altSep: if len(stack) == 0 { continue } posInfo = append(posInfo, piT{i, -1, len(stack)}) posInfo[stack[len(stack)-1]].cnt++ } } for len(stack) > 0 { si := len(stack) - 1 pi := stack[si] depth := posInfo[pi].depth removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == depth { removePosInfo(pi) } else { pi++ } } stack = stack[:si] } return buildExp(s, 0, posInfo) } func buildExp(s string, off int, info []piT) Expander { if len(info) == 0 { return Text(s) } var seq Sequence i := 0 var dj, j, depth int for dk, piK := range info { k := piK.pos - off switch s[k] { case altStart: if depth == 0 { dj = dk j = k depth = piK.depth } case altEnd: if piK.depth != depth { continue } if j > i { seq = append(seq, Text(s[i:j])) } alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk]) seq = append(seq, alt) i = k + 1 depth = 0 } } if j := len(s); j > i { seq = append(seq, Text(s[i:j])) } if len(seq) == 1 { return seq[0] } return seq } func buildAlt(s string, depth, off int, info []piT) Alternation { var alt Alternation i := 0 var di int for dk, piK := range info { if piK.depth != depth { continue } if k := piK.pos - off; s[k] == altSep { sub := buildExp(s[i:k], i+off, info[di:dk]) alt = append(alt, sub) i = k + 1 di = dk + 1 } } sub := buildExp(s[i:], i+off, info[di:]) alt = append(alt, sub) return alt }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using static System.Linq.Enumerable; public static class BraceExpansion { enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat } const char L = '{', R = '}', S = ','; public static void Main() { string[] input = { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", @"{,{,gotta have{ ,\, again\, }}more }cowbell!", @"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" }; foreach (string text in input) Expand(text); } static void Expand(string input) { Token token = Tokenize(input); foreach (string value in token) Console.WriteLine(value); Console.WriteLine(); } static Token Tokenize(string input) { var tokens = new List<Token>(); var buffer = new StringBuilder(); bool escaping = false; int level = 0; foreach (char c in input) { (escaping, level, tokens, buffer) = c switch { _ when escaping => (false, level, tokens, buffer.Append(c)), '\\' => (true, level, tokens, buffer.Append(c)), L => (escaping, level + 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer), S when level > 0 => (escaping, level, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer), R when level > 0 => (escaping, level - 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer), _ => (escaping, level, tokens, buffer.Append(c)) }; } if (buffer.Length > 0) tokens.Add(buffer.Flush()); for (int i = 0; i < tokens.Count; i++) { if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) { tokens[i] = tokens[i].Value; } } return new Token(tokens, TokenType.Concat); } static List<Token> Merge(this List<Token> list) { int separators = 0; int last = list.Count - 1; for (int i = list.Count - 3; i >= 0; i--) { if (list[i].Type == TokenType.Separator) { separators++; Concat(list, i + 1, last); list.RemoveAt(i); last = i; } else if (list[i].Type == TokenType.OpenBrace) { Concat(list, i + 1, last); if (separators > 0) { list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate); list.RemoveRange(i+1, list.Count - i - 1); } else { list[i] = L.ToString(); list[^1] = R.ToString(); Concat(list, i, list.Count); } break; } } return list; } static void Concat(List<Token> list, int s, int e) { for (int i = e - 2; i >= s; i--) { (Token a, Token b) = (list[i], list[i+1]); switch (a.Type, b.Type) { case (TokenType.Text, TokenType.Text): list[i] = a.Value + b.Value; list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Concat): a.SubTokens.AddRange(b.SubTokens); list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Text) when b.Value == "": list.RemoveAt(i+1); break; case (TokenType.Text, TokenType.Concat) when a.Value == "": list.RemoveAt(i); break; default: list[i] = new Token(new [] { a, b }, TokenType.Concat); list.RemoveAt(i+1); break; } } } private struct Token : IEnumerable<string> { private List<Token>? _subTokens; public string Value { get; } public TokenType Type { get; } public List<Token> SubTokens => _subTokens ??= new List<Token>(); public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null); public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList()); public static implicit operator Token(string value) => new Token(value, TokenType.Text); public IEnumerator<string> GetEnumerator() => (Type switch { TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)), TokenType.Alternate => from t in SubTokens from s in t select s, _ => Repeat(Value, 1) }).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } static List<Token> With(this List<Token> list, Token token) { list.Add(token); return list; } static IEnumerable<Token> Range(this List<Token> list, Range range) { int start = range.Start.GetOffset(list.Count); int end = range.End.GetOffset(list.Count); for (int i = start; i < end; i++) yield return list[i]; } static string Flush(this StringBuilder builder) { string result = builder.ToString(); builder.Clear(); return result; } }
Rewrite this program in C# while keeping its functionality equivalent to the Go version.
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str string) (int64, bool) { i, err := strconv.ParseInt(str, 10, 64) if err != nil { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid value", ) dialog.Run() dialog.Destroy() return 0, false } return i, true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create box:") box.SetBorderWidth(1) label, err := gtk.LabelNew("Value:") check(err, "Unable to create label:") entry, err := gtk.EntryNew() check(err, "Unable to create entry:") entry.SetText("0") entry.Connect("activate", func() { str, _ := entry.GetText() validateInput(window, str) }) ib, err := gtk.ButtonNewWithLabel("Increment") check(err, "Unable to create increment button:") ib.Connect("clicked", func() { str, _ := entry.GetText() if i, ok := validateInput(window, str); ok { entry.SetText(strconv.FormatInt(i+1, 10)) } }) rb, err := gtk.ButtonNewWithLabel("Random") check(err, "Unable to create random button:") rb.Connect("clicked", func() { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Set random value", ) answer := dialog.Run() dialog.Destroy() if answer == gtk.RESPONSE_YES { entry.SetText(strconv.Itoa(rand.Intn(10000))) } }) box.PackStart(label, false, false, 2) box.PackStart(entry, false, false, 2) box.PackStart(ib, false, false, 2) box.PackStart(rb, false, false, 2) window.Add(box) window.ShowAll() gtk.Main() }
using System; using System.ComponentModel; using System.Windows.Forms; class RosettaInteractionForm : Form { class NumberModel: INotifyPropertyChanged { Random rnd = new Random(); public event PropertyChangedEventHandler PropertyChanged = delegate {}; int _value; public int Value { get { return _value; } set { _value = value; PropertyChanged(this, new PropertyChangedEventArgs("Value")); } } public void ResetToRandom(){ Value = rnd.Next(5000); } } NumberModel model = new NumberModel{ Value = 0}; RosettaInteractionForm() { var tbNumber = new MaskedTextBox { Mask="0000", ResetOnSpace = false, Dock = DockStyle.Top }; tbNumber.DataBindings.Add("Text", model, "Value"); var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom}; btIncrement.Click += delegate { model.Value++; }; var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom}; btDecrement.Click += delegate { model.Value--; }; var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom }; btRandom.Click += delegate { if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes) model.ResetToRandom(); }; Controls.Add(tbNumber); Controls.Add(btIncrement); Controls.Add(btDecrement); Controls.Add(btRandom); } static void Main() { Application.Run(new RosettaInteractionForm()); } }
Transform the following Go implementation into C#, maintaining the same output and logic.
package main import ( "bufio" "fmt" "io" "math/rand" "time" ) func choseLineRandomly(r io.Reader) (s string, ln int, err error) { br := bufio.NewReader(r) s, err = br.ReadString('\n') if err != nil { return } ln = 1 lnLast := 1. var sLast string for { sLast, err = br.ReadString('\n') if err == io.EOF { return s, ln, nil } if err != nil { break } lnLast++ if rand.Float64() < 1/lnLast { s = sLast ln = int(lnLast) } } return } func oneOfN(n int, file io.Reader) int { _, ln, err := choseLineRandomly(file) if err != nil { panic(err) } return ln } type simReader int func (r *simReader) Read(b []byte) (int, error) { if *r <= 0 { return 0, io.EOF } b[0] = '\n' *r-- return 1, nil } func main() { n := 10 freq := make([]int, n) rand.Seed(time.Now().UnixNano()) for times := 0; times < 1e6; times++ { sr := simReader(n) freq[oneOfN(n, &sr)-1]++ } fmt.Println(freq) }
class Program { private static Random rnd = new Random(); public static int one_of_n(int n) { int currentChoice = 1; for (int i = 2; i <= n; i++) { double outerLimit = 1D / (double)i; if (rnd.NextDouble() < outerLimit) currentChoice = i; } return currentChoice; } static void Main(string[] args) { Dictionary<int, int> results = new Dictionary<int, int>(); for (int i = 1; i < 11; i++) results.Add(i, 0); for (int i = 0; i < 1000000; i++) { int result = one_of_n(10); results[result] = results[result] + 1; } for (int i = 1; i < 11; i++) Console.WriteLine("{0}\t{1}", i, results[i]); Console.ReadLine(); } }
Convert this Go snippet to C# and keep its semantics consistent.
package main import "fmt" var example []int func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func checkSeq(pos, n, minLen int, seq []int) (int, int) { switch { case pos > minLen || seq[0] > n: return minLen, 0 case seq[0] == n: example = seq return pos, 1 case pos < minLen: return tryPerm(0, pos, n, minLen, seq) default: return minLen, 0 } } func tryPerm(i, pos, n, minLen int, seq []int) (int, int) { if i > pos { return minLen, 0 } seq2 := make([]int, len(seq)+1) copy(seq2[1:], seq) seq2[0] = seq[0] + seq[i] res11, res12 := checkSeq(pos+1, n, minLen, seq2) res21, res22 := tryPerm(i+1, pos, n, res11, seq) switch { case res21 < res11: return res21, res22 case res21 == res11: return res21, res12 + res22 default: fmt.Println("Error in tryPerm") return 0, 0 } } func initTryPerm(x, minLen int) (int, int) { return tryPerm(0, 0, x, minLen, []int{1}) } func findBrauer(num, minLen, nbLimit int) { actualMin, brauer := initTryPerm(num, minLen) fmt.Println("\nN =", num) fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin) fmt.Println("Number of minimum length Brauer chains :", brauer) if brauer > 0 { reverse(example) fmt.Println("Brauer example :", example) } example = nil if num <= nbLimit { nonBrauer := findNonBrauer(num, actualMin+1, brauer) fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer) if nonBrauer > 0 { fmt.Println("Non-Brauer example :", example) } example = nil } else { println("Non-Brauer analysis suppressed") } } func isAdditionChain(a []int) bool { for i := 2; i < len(a); i++ { if a[i] > a[i-1]*2 { return false } ok := false jloop: for j := i - 1; j >= 0; j-- { for k := j; k >= 0; k-- { if a[j]+a[k] == a[i] { ok = true break jloop } } } if !ok { return false } } if example == nil && !isBrauer(a) { example = make([]int, len(a)) copy(example, a) } return true } func isBrauer(a []int) bool { for i := 2; i < len(a); i++ { ok := false for j := i - 1; j >= 0; j-- { if a[i-1]+a[j] == a[i] { ok = true break } } if !ok { return false } } return true } func nextChains(index, le int, seq []int, pcount *int) { for { if index < le-1 { nextChains(index+1, le, seq, pcount) } if seq[index]+le-1-index >= seq[le-1] { return } seq[index]++ for i := index + 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } if isAdditionChain(seq) { (*pcount)++ } } } func findNonBrauer(num, le, brauer int) int { seq := make([]int, le) seq[0] = 1 seq[le-1] = num for i := 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } count := 0 if isAdditionChain(seq) { count = 1 } nextChains(2, le, seq, &count) return count - brauer } func main() { nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} fmt.Println("Searching for Brauer chains up to a minimum length of 12:") for _, num := range nums { findBrauer(num, 12, 79) } }
using System; namespace AdditionChains { class Program { static int[] Prepend(int n, int[] seq) { int[] result = new int[seq.Length + 1]; Array.Copy(seq, 0, result, 1, seq.Length); result[0] = n; return result; } static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0); if (seq[0] == n) return new Tuple<int, int>(pos, 1); if (pos < min_len) return TryPerm(0, pos, seq, n, min_len); return new Tuple<int, int>(min_len, 0); } static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Tuple<int, int>(min_len, 0); Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len); Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1); if (res2.Item1 < res1.Item1) return res2; if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2); throw new Exception("TryPerm exception"); } static Tuple<int, int> InitTryPerm(int x) { return TryPerm(0, 0, new int[] { 1 }, x, 12); } static void FindBrauer(int num) { Tuple<int, int> res = InitTryPerm(num); Console.WriteLine(); Console.WriteLine("N = {0}", num); Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1); Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2); } static void Main(string[] args) { int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; Array.ForEach(nums, n => FindBrauer(n)); } } }
Translate the given Go code snippet into C# without altering its behavior.
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
using System; namespace Repeat { class Program { static void Repeat(int count, Action<int> fn) { if (null == fn) { throw new ArgumentNullException("fn"); } for (int i = 0; i < count; i++) { fn.Invoke(i + 1); } } static void Main(string[] args) { Repeat(3, x => Console.WriteLine("Example {0}", x)); } } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
using System; namespace Repeat { class Program { static void Repeat(int count, Action<int> fn) { if (null == fn) { throw new ArgumentNullException("fn"); } for (int i = 0; i < count; i++) { fn.Invoke(i + 1); } } static void Main(string[] args) { Repeat(3, x => Console.WriteLine("Example {0}", x)); } } }
Convert this Go snippet to C# and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
public class Program { static void Main() { System.Console.WriteLine(42.ModInverse(2017)); } } public static class IntExtensions { public static int ModInverse(this int a, int m) { if (m == 1) return 0; int m0 = m; (int x, int y) = (1, 0); while (a > 1) { int q = a / m; (a, m) = (m, a % m); (x, y) = (y, x - q * y); } return x < 0 ? x + m0 : x; } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Goodbye, World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
using System.Text; using System.Net.Sockets; using System.Net; namespace WebServer { class GoodByeWorld { static void Main(string[] args) { const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n"; const int port = 8080; bool serverRunning = true; TcpListener tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); while (serverRunning) { Socket socketConnection = tcpListener.AcceptSocket(); byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length); socketConnection.Send(bMsg); socketConnection.Disconnect(true); } } } }
Rewrite the snippet below in C# so it works the same as the original Go code.
package main import ( "fmt" "math" "rcu" "time" ) func sos(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k) limit := (int(math.Sqrt(float64(n)))-3)/2 + 1 for i := 0; i < limit; i++ { p := 2*i + 3 s := (p*p - 3) / 2 for j := s; j < k; j += p { marked[j] = true } } for i := 0; i < k; i++ { if !marked[i] { primes = append(primes, 2*i+3) } } return primes } func soe(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k) limit := (int(math.Sqrt(float64(n)))-3)/2 + 1 for i := 0; i < limit; i++ { if !marked[i] { p := 2*i + 3 s := (p*p - 3) / 2 for j := s; j < k; j += p { marked[j] = true } } } for i := 0; i < k; i++ { if !marked[i] { primes = append(primes, 2*i+3) } } return primes } func main() { const limit = int(16e6) start := time.Now() primes := sos(limit) elapsed := int(time.Since(start).Milliseconds()) climit := rcu.Commatize(limit) celapsed := rcu.Commatize(elapsed) million := rcu.Commatize(1e6) millionth := rcu.Commatize(primes[1e6-1]) fmt.Printf("Using the Sieve of Sundaram generated primes up to %s in %s ms.\n\n", climit, celapsed) fmt.Println("First 100 odd primes generated by the Sieve of Sundaram:") for i, p := range primes[0:100] { fmt.Printf("%3d ", p) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\nThe %s Sundaram prime is %s\n", million, millionth) start = time.Now() primes = soe(limit) elapsed = int(time.Since(start).Milliseconds()) celapsed = rcu.Commatize(elapsed) millionth = rcu.Commatize(primes[1e6-1]) fmt.Printf("\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\n", celapsed) fmt.Printf("\nAs a check, the %s Sundaram prime would again have been %s\n", million, millionth) }
using System; using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static string fmt(int[] a) { var sb = new System.Text.StringBuilder(); for (int i = 0; i < a.Length; i++) sb.Append(string.Format("{0,5}{1}", a[i], i % 10 == 9 ? "\n" : " ")); return sb.ToString(); } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray(); sw.Stop(); Write("The first 100 odd prime numbers:\n{0}\n", fmt(pr.Take(100).ToArray())); Write("The millionth odd prime number: {0}", pr.Last()); Write("\n{0} ms", sw.Elapsed.TotalMilliseconds); } } class PG { public static IEnumerable<int> Sundaram(int n) { int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1; var comps = new bool[k + 1]; for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2) while ((t += d + 2) < k) comps[t] = true; for (; v < k; v++) if (!comps[v]) yield return (v << 1) + 1; } }
Translate this program into C# but keep the logic exactly as in Go.
package main import ( "fmt" "strconv" "strings" ) var atomicMass = map[string]float64{ "H": 1.008, "He": 4.002602, "Li": 6.94, "Be": 9.0121831, "B": 10.81, "C": 12.011, "N": 14.007, "O": 15.999, "F": 18.998403163, "Ne": 20.1797, "Na": 22.98976928, "Mg": 24.305, "Al": 26.9815385, "Si": 28.085, "P": 30.973761998, "S": 32.06, "Cl": 35.45, "Ar": 39.948, "K": 39.0983, "Ca": 40.078, "Sc": 44.955908, "Ti": 47.867, "V": 50.9415, "Cr": 51.9961, "Mn": 54.938044, "Fe": 55.845, "Co": 58.933194, "Ni": 58.6934, "Cu": 63.546, "Zn": 65.38, "Ga": 69.723, "Ge": 72.630, "As": 74.921595, "Se": 78.971, "Br": 79.904, "Kr": 83.798, "Rb": 85.4678, "Sr": 87.62, "Y": 88.90584, "Zr": 91.224, "Nb": 92.90637, "Mo": 95.95, "Ru": 101.07, "Rh": 102.90550, "Pd": 106.42, "Ag": 107.8682, "Cd": 112.414, "In": 114.818, "Sn": 118.710, "Sb": 121.760, "Te": 127.60, "I": 126.90447, "Xe": 131.293, "Cs": 132.90545196, "Ba": 137.327, "La": 138.90547, "Ce": 140.116, "Pr": 140.90766, "Nd": 144.242, "Pm": 145, "Sm": 150.36, "Eu": 151.964, "Gd": 157.25, "Tb": 158.92535, "Dy": 162.500, "Ho": 164.93033, "Er": 167.259, "Tm": 168.93422, "Yb": 173.054, "Lu": 174.9668, "Hf": 178.49, "Ta": 180.94788, "W": 183.84, "Re": 186.207, "Os": 190.23, "Ir": 192.217, "Pt": 195.084, "Au": 196.966569, "Hg": 200.592, "Tl": 204.38, "Pb": 207.2, "Bi": 208.98040, "Po": 209, "At": 210, "Rn": 222, "Fr": 223, "Ra": 226, "Ac": 227, "Th": 232.0377, "Pa": 231.03588, "U": 238.02891, "Np": 237, "Pu": 244, "Am": 243, "Cm": 247, "Bk": 247, "Cf": 251, "Es": 252, "Fm": 257, "Uue": 315, "Ubn": 299, } func replaceParens(s string) string { var letter byte = 'a' for { start := strings.IndexByte(s, '(') if start == -1 { break } restart: for i := start + 1; i < len(s); i++ { if s[i] == ')' { expr := s[start+1 : i] symbol := fmt.Sprintf("@%c", letter) s = strings.Replace(s, s[start:i+1], symbol, 1) atomicMass[symbol] = evaluate(expr) letter++ break } if s[i] == '(' { start = i goto restart } } } return s } func evaluate(s string) float64 { s += string('[') var symbol, number string sum := 0.0 for i := 0; i < len(s); i++ { c := s[i] switch { case c >= '@' && c <= '[': n := 1 if number != "" { n, _ = strconv.Atoi(number) } if symbol != "" { sum += atomicMass[symbol] * float64(n) } if c == '[' { break } symbol = string(c) number = "" case c >= 'a' && c <= 'z': symbol += string(c) case c >= '0' && c <= '9': number += string(c) default: panic(fmt.Sprintf("Unexpected symbol %c in molecule", c)) } } return sum } func main() { molecules := []string{ "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue", } for _, molecule := range molecules { mass := evaluate(replaceParens(molecule)) fmt.Printf("%17s -> %7.3f\n", molecule, mass) } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChemicalCalculator { class Program { static Dictionary<string, double> atomicMass = new Dictionary<string, double>() { {"H", 1.008 }, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; static double Evaluate(string s) { s += "["; double sum = 0.0; string symbol = ""; string number = ""; for (int i = 0; i < s.Length; ++i) { var c = s[i]; if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = int.Parse(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c.ToString(); number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { throw new Exception(string.Format("Unexpected symbol {0} in molecule", c)); } } return sum; } static string ReplaceFirst(string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } static string ReplaceParens(string s) { char letter = 's'; while (true) { var start = s.IndexOf('('); if (start == -1) { break; } for (int i = start + 1; i < s.Length; ++i) { if (s[i] == ')') { var expr = s.Substring(start + 1, i - start - 1); var symbol = string.Format("@{0}", letter); s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol); atomicMass[symbol] = Evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } static void Main() { var molecules = new string[]{ "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; foreach (var molecule in molecules) { var mass = Evaluate(ReplaceParens(molecule)); Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass); } } } }
Write the same code in C# as shown below in Go.
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com", BindPassword: "readonlypassword", UserFilter: "(uid=%s)", GroupFilter: "(memberUid=%s)", Attributes: []string{"givenName", "sn", "mail", "uid"}, } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } }
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
Rewrite this program in C# while keeping its functionality equivalent to the Go version.
package main import "fmt" const ( N = 2200 N2 = N * N * 2 ) func main() { s := 3 var s1, s2 int var r [N + 1]bool var ab [N2 + 1]bool for a := 1; a <= N; a++ { a2 := a * a for b := a; b <= N; b++ { ab[a2 + b * b] = true } } for c := 1; c <= N; c++ { s1 = s s += 2 s2 = s for d := c + 1; d <= N; d++ { if ab[s1] { r[d] = true } s1 += s2 s2 += 2 } } for d := 1; d <= N; d++ { if !r[d] { fmt.Printf("%d ", d) } } fmt.Println() }
using System; namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2; static void Main(string[] args) { bool[] found = new bool[MAX + 1]; bool[] a2b2 = new bool[MAX2 + 1]; int s = 3; for(int a = 1; a <= MAX; a++) { int a2 = a * a; for (int b=a; b<=MAX; b++) { a2b2[a2 + b * b] = true; } } for (int c = 1; c <= MAX; c++) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= MAX; d++) { if (a2b2[s1]) found[d] = true; s1 += s2; s2 += 2; } } Console.WriteLine("The values of d <= {0} which can't be represented:", MAX); for (int d = 1; d < MAX; d++) { if (!found[d]) Console.Write("{0} ", d); } Console.WriteLine(); } } }
Change the programming language of this snippet from Go to C# without modifying what it does.
package main import ( "fmt" "log" "strings" ) type HouseSet [5]*House type House struct { n Nationality c Colour a Animal d Drink s Smoke } type Nationality int8 type Colour int8 type Animal int8 type Drink int8 type Smoke int8 const ( English Nationality = iota Swede Dane Norwegian German ) const ( Red Colour = iota Green White Yellow Blue ) const ( Dog Animal = iota Birds Cats Horse Zebra ) const ( Tea Drink = iota Coffee Milk Beer Water ) const ( PallMall Smoke = iota Dunhill Blend BlueMaster Prince ) var nationalities = [...]string{"English", "Swede", "Dane", "Norwegian", "German"} var colours = [...]string{"red", "green", "white", "yellow", "blue"} var animals = [...]string{"dog", "birds", "cats", "horse", "zebra"} var drinks = [...]string{"tea", "coffee", "milk", "beer", "water"} var smokes = [...]string{"Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince"} func (n Nationality) String() string { return nationalities[n] } func (c Colour) String() string { return colours[c] } func (a Animal) String() string { return animals[a] } func (d Drink) String() string { return drinks[d] } func (s Smoke) String() string { return smokes[s] } func (h House) String() string { return fmt.Sprintf("%-9s  %-6s  %-5s  %-6s %s", h.n, h.c, h.a, h.d, h.s) } func (hs HouseSet) String() string { lines := make([]string, 0, len(hs)) for i, h := range hs { s := fmt.Sprintf("%d %s", i, h) lines = append(lines, s) } return strings.Join(lines, "\n") } func simpleBruteForce() (int, HouseSet) { var v []House for n := range nationalities { for c := range colours { for a := range animals { for d := range drinks { for s := range smokes { h := House{ n: Nationality(n), c: Colour(c), a: Animal(a), d: Drink(d), s: Smoke(s), } if !h.Valid() { continue } v = append(v, h) } } } } } n := len(v) log.Println("Generated", n, "valid houses") combos := 0 first := 0 valid := 0 var validSet HouseSet for a := 0; a < n; a++ { if v[a].n != Norwegian { continue } for b := 0; b < n; b++ { if b == a { continue } if v[b].anyDups(&v[a]) { continue } for c := 0; c < n; c++ { if c == b || c == a { continue } if v[c].d != Milk { continue } if v[c].anyDups(&v[b], &v[a]) { continue } for d := 0; d < n; d++ { if d == c || d == b || d == a { continue } if v[d].anyDups(&v[c], &v[b], &v[a]) { continue } for e := 0; e < n; e++ { if e == d || e == c || e == b || e == a { continue } if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) { continue } combos++ set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]} if set.Valid() { valid++ if valid == 1 { first = combos } validSet = set } } } } } } log.Println("Tested", first, "different combinations of valid houses before finding solution") log.Println("Tested", combos, "different combinations of valid houses in total") return valid, validSet } func (h *House) anyDups(list ...*House) bool { for _, b := range list { if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s { return true } } return false } func (h *House) Valid() bool { if h.n == English && h.c != Red || h.n != English && h.c == Red { return false } if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog { return false } if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea { return false } if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee { return false } if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall { return false } if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill { return false } if h.a == Cats && h.s == Blend { return false } if h.a == Horse && h.s == Dunhill { return false } if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster { return false } if h.n == German && h.s != Prince || h.n != German && h.s == Prince { return false } if h.n == Norwegian && h.c == Blue { return false } if h.d == Water && h.s == Blend { return false } return true } func (hs *HouseSet) Valid() bool { ni := make(map[Nationality]int, 5) ci := make(map[Colour]int, 5) ai := make(map[Animal]int, 5) di := make(map[Drink]int, 5) si := make(map[Smoke]int, 5) for i, h := range hs { ni[h.n] = i ci[h.c] = i ai[h.a] = i di[h.d] = i si[h.s] = i } if ci[Green]+1 != ci[White] { return false } if dist(ai[Cats], si[Blend]) != 1 { return false } if dist(ai[Horse], si[Dunhill]) != 1 { return false } if dist(ni[Norwegian], ci[Blue]) != 1 { return false } if dist(di[Water], si[Blend]) != 1 { return false } if hs[2].d != Milk { return false } if hs[0].n != Norwegian { return false } return true } func dist(a, b int) int { if a > b { return a - b } return b - a } func main() { log.SetFlags(0) n, sol := simpleBruteForce() fmt.Println(n, "solution found") fmt.Println(sol) }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; public enum Colour { Red, Green, White, Yellow, Blue } public enum Nationality { Englishman, Swede, Dane, Norwegian,German } public enum Pet { Dog, Birds, Cats, Horse, Zebra } public enum Drink { Coffee, Tea, Milk, Beer, Water } public enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince} public static class ZebraPuzzle { private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved; static ZebraPuzzle() { var solve = from colours in Permute<Colour>() where (colours,Colour.White).IsRightOf(colours, Colour.Green) from nations in Permute<Nationality>() where nations[0] == Nationality.Norwegian where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) from drinks in Permute<Drink>() where drinks[2] == Drink.Milk where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) from pets in Permute<Pet>() where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) from smokes in Permute<Smoke>() where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) select (colours, drinks, smokes, pets, nations); _solved = solve.First(); } private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj); private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1; private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v); private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a, U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v); public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values) { if (values.Count() == 1) return values.ToSingleton(); return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v)); } public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray()); private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; } private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>(); public static new String ToString() { var sb = new StringBuilder(); sb.AppendLine("House Colour Drink Nationality Smokes Pet"); sb.AppendLine("───── ────── ──────── ─────────── ────────── ─────"); var (colours, drinks, smokes, pets, nations) = _solved; for (var i = 0; i < 5; i++) sb.AppendLine($"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}"); return sb.ToString(); } public static void Main(string[] arguments) { var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)]; WriteLine($"The zebra owner is {owner}"); Write(ToString()); Read(); } }
Ensure the translated C# code behaves exactly like the original Go snippet.
package main import ( "encoding/xml" "fmt" "io" "net/http" "net/url" ) const language = "Go" var baseQuery = "http: "&format=xml&list=categorymembers&cmlimit=100" func req(u string, foundCm func(string)) string { resp, err := http.Get(u) if err != nil { fmt.Println(err) return "" } defer resp.Body.Close() for p := xml.NewDecoder(resp.Body); ; { t, err := p.RawToken() switch s, ok := t.(xml.StartElement); { case err == io.EOF: return "" case err != nil: fmt.Println(err) return "" case !ok: continue case s.Name.Local == "cm": for _, a := range s.Attr { if a.Name.Local == "title" { foundCm(a.Value) } } case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && s.Attr[0].Name.Local == "cmcontinue": return url.QueryEscape(s.Attr[0].Value) } } return "" } func main() { langMap := make(map[string]bool) storeLang := func(cm string) { langMap[cm] = true } languageQuery := baseQuery + "&cmtitle=Category:" + language continueAt := req(languageQuery, storeLang) for continueAt > "" { continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang) } if len(langMap) == 0 { fmt.Println("no tasks implemented for", language) return } printUnImp := func(cm string) { if !langMap[cm] { fmt.Println(cm) } } taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks" continueAt = req(taskQuery, printUnImp) for continueAt > "" { continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp) } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Net; class Program { static List<string> GetTitlesFromCategory(string category) { string searchQueryFormat = "http: List<string> results = new List<string>(); string cmcontinue = string.Empty; do { string cmContinueKeyValue; if (cmcontinue.Length > 0) cmContinueKeyValue = String.Format("&cmcontinue={0}", cmcontinue); else cmContinueKeyValue = String.Empty; string query = String.Format(searchQueryFormat, category, cmContinueKeyValue); string content = new WebClient().DownloadString(query); results.AddRange(new Regex("\"title\":\"(.+?)\"").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value)); cmcontinue = Regex.Match(content, @"{""cmcontinue"":""([^""]+)""}", RegexOptions.IgnoreCase).Groups["1"].Value; } while (cmcontinue.Length > 0); return results; } static string[] GetUnimplementedTasksFromLanguage(string language) { List<string> alltasks = GetTitlesFromCategory("Programming_Tasks"); List<string> lang = GetTitlesFromCategory(language); return alltasks.Where(x => !lang.Contains(x)).ToArray(); } static void Main(string[] args) { string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]); foreach (string i in unimpl) Console.WriteLine(i); } }
Produce a functionally identical C# code for the snippet given in Go.
package main import "fmt" func main() { x := 2. xi := .5 y := 4. yi := .25 z := x + y zi := 1 / (x + y) numbers := []float64{x, y, z} inverses := []float64{xi, yi, zi} mfs := make([]func(float64) float64, len(numbers)) for i := range mfs { mfs[i] = multiplier(numbers[i], inverses[i]) } for _, mf := range mfs { fmt.Println(mf(1)) } } func multiplier(n1, n2 float64) func(float64) float64 { n1n2 := n1 * n2 return func(m float64) float64 { return n1n2 * m } }
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
Transform the following Go implementation into C#, maintaining the same output and logic.
package main import "fmt" func main() { x := 2. xi := .5 y := 4. yi := .25 z := x + y zi := 1 / (x + y) numbers := []float64{x, y, z} inverses := []float64{xi, yi, zi} mfs := make([]func(float64) float64, len(numbers)) for i := range mfs { mfs[i] = multiplier(numbers[i], inverses[i]) } for _, mf := range mfs { fmt.Println(mf(1)) } } func multiplier(n1, n2 float64) func(float64) float64 { n1n2 := n1 * n2 return func(m float64) float64 { return n1n2 * m } }
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
Ensure the translated C# code behaves exactly like the original Go snippet.
package main import "fmt" func main() { x := 2. xi := .5 y := 4. yi := .25 z := x + y zi := 1 / (x + y) numbers := []float64{x, y, z} inverses := []float64{xi, yi, zi} mfs := make([]func(float64) float64, len(numbers)) for i := range mfs { mfs[i] = multiplier(numbers[i], inverses[i]) } for _, mf := range mfs { fmt.Println(mf(1)) } } func multiplier(n1, n2 float64) func(float64) float64 { n1n2 := n1 * n2 return func(m float64) float64 { return n1n2 * m } }
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
Translate this program into C# but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) } func solve(board string) string { buffer = make([]byte, len(board)) width := strings.Index(board[1:], "\n") + 1 dirs := []struct { move, push string dPos int }{ {"u", "U", -width}, {"r", "R", 1}, {"d", "D", width}, {"l", "L", -1}, } visited := map[string]bool{board: true} open := []state{state{board, "", strings.Index(board, "@")}} for len(open) > 0 { s1 := &open[0] open = open[1:] for _, dir := range dirs { var newBoard, newSol string newPos := s1.pos + dir.dPos switch s1.board[newPos] { case '$', '*': newBoard = s1.push(dir.dPos) if newBoard == "" || visited[newBoard] { continue } newSol = s1.cSol + dir.push if strings.IndexAny(newBoard, ".+") < 0 { return newSol } case ' ', '.': newBoard = s1.move(dir.dPos) if visited[newBoard] { continue } newSol = s1.cSol + dir.move default: continue } open = append(open, state{newBoard, newSol, newPos}) visited[newBoard] = true } } return "No solution" } type state struct { board string cSol string pos int } var buffer []byte func (s *state) move(dPos int) string { copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } newPos := s.pos + dPos if buffer[newPos] == ' ' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } return string(buffer) } func (s *state) push(dPos int) string { newPos := s.pos + dPos boxPos := newPos + dPos switch s.board[boxPos] { case ' ', '.': default: return "" } copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } if buffer[newPos] == '$' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } if buffer[boxPos] == ' ' { buffer[boxPos] = '$' } else { buffer[boxPos] = '*' } return string(buffer) }
using System.Collections.Generic; using System.Linq; using System.Text; namespace SokobanSolver { public class SokobanSolver { private class Board { public string Cur { get; internal set; } public string Sol { get; internal set; } public int X { get; internal set; } public int Y { get; internal set; } public Board(string cur, string sol, int x, int y) { Cur = cur; Sol = sol; X = x; Y = y; } } private string destBoard, currBoard; private int playerX, playerY, nCols; SokobanSolver(string[] board) { nCols = board[0].Length; StringBuilder destBuf = new StringBuilder(); StringBuilder currBuf = new StringBuilder(); for (int r = 0; r < board.Length; r++) { for (int c = 0; c < nCols; c++) { char ch = board[r][c]; destBuf.Append(ch != '$' && ch != '@' ? ch : ' '); currBuf.Append(ch != '.' ? ch : ' '); if (ch == '@') { this.playerX = c; this.playerY = r; } } } destBoard = destBuf.ToString(); currBoard = currBuf.ToString(); } private string Move(int x, int y, int dx, int dy, string trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard[newPlayerPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[newPlayerPos] = '@'; return new string(trial); } private string Push(int x, int y, int dx, int dy, string trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard[newBoxPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = '$'; return new string(trial); } private bool IsSolved(string trialBoard) { for (int i = 0; i < trialBoard.Length; i++) if ((destBoard[i] == '.') != (trialBoard[i] == '$')) return false; return true; } private string Solve() { char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } }; int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } }; ISet<string> history = new HashSet<string>(); LinkedList<Board> open = new LinkedList<Board>(); history.Add(currBoard); open.AddLast(new Board(currBoard, string.Empty, playerX, playerY)); while (!open.Count.Equals(0)) { Board item = open.First(); open.RemoveFirst(); string cur = item.Cur; string sol = item.Sol; int x = item.X; int y = item.Y; for (int i = 0; i < dirs.GetLength(0); i++) { string trial = cur; int dx = dirs[i, 0]; int dy = dirs[i, 1]; if (trial[(y + dy) * nCols + x + dx] == '$') { if ((trial = Push(x, y, dx, dy, trial)) != null) { if (!history.Contains(trial)) { string newSol = sol + dirLabels[i, 1]; if (IsSolved(trial)) return newSol; open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } else if ((trial = Move(x, y, dx, dy, trial)) != null) { if (!history.Contains(trial)) { string newSol = sol + dirLabels[i, 0]; open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } } return "No solution"; } public static void Main(string[] a) { string level = "#######," + "# #," + "# #," + "#. # #," + "#. $$ #," + "#.$$ #," + "#.# @#," + "#######"; System.Console.WriteLine("Level:\n"); foreach (string line in level.Split(',')) { System.Console.WriteLine(line); } System.Console.WriteLine("\nSolution:\n"); System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve()); } } }
Write the same code in C# as shown below in Go.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool) *big.Rat { t1 := big.NewInt(32) t1.Mul(factorial(6*n), t1) t2 := big.NewInt(532*n*n + 126*n + 9) t3 := new(big.Int) t3.Exp(factorial(n), six, nil) t3.Mul(t3, three) ip := new(big.Int) ip.Mul(t1, t2) ip.Quo(ip, t3) pw := 6*n + 3 t1.SetInt64(pw) tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil)) if print { fmt.Printf("%d %44d %3d  %-35s\n", n, ip, -pw, tm.FloatString(33)) } return tm } func main() { fmt.Println("N Integer Portion Pow Nth Term (33 dp)") fmt.Println(strings.Repeat("-", 89)) for n := int64(0); n < 10; n++ { almkvistGiullera(n, true) } sum := new(big.Rat) prev := new(big.Rat) pow70 := new(big.Int).Exp(ten, seventy, nil) prec := new(big.Rat).SetFrac(one, pow70) n := int64(0) for { term := almkvistGiullera(n, false) sum.Add(sum, term) z := new(big.Rat).Sub(sum, prev) z.Abs(z) if z.Cmp(prec) < 0 { break } prev.Set(sum) n++ } sum.Inv(sum) pi := new(big.Float).SetPrec(256).SetRat(sum) pi.Sqrt(pi) fmt.Println("\nPi to 70 decimal places is:") fmt.Println(pi.Text('f', 70)) }
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
Convert the following code from Go to C#, ensuring the logic remains intact.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool) *big.Rat { t1 := big.NewInt(32) t1.Mul(factorial(6*n), t1) t2 := big.NewInt(532*n*n + 126*n + 9) t3 := new(big.Int) t3.Exp(factorial(n), six, nil) t3.Mul(t3, three) ip := new(big.Int) ip.Mul(t1, t2) ip.Quo(ip, t3) pw := 6*n + 3 t1.SetInt64(pw) tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil)) if print { fmt.Printf("%d %44d %3d  %-35s\n", n, ip, -pw, tm.FloatString(33)) } return tm } func main() { fmt.Println("N Integer Portion Pow Nth Term (33 dp)") fmt.Println(strings.Repeat("-", 89)) for n := int64(0); n < 10; n++ { almkvistGiullera(n, true) } sum := new(big.Rat) prev := new(big.Rat) pow70 := new(big.Int).Exp(ten, seventy, nil) prec := new(big.Rat).SetFrac(one, pow70) n := int64(0) for { term := almkvistGiullera(n, false) sum.Add(sum, term) z := new(big.Rat).Sub(sum, prev) z.Abs(z) if z.Cmp(prec) < 0 { break } prev.Set(sum) n++ } sum.Inv(sum) pi := new(big.Float).SetPrec(256).SetRat(sum) pi.Sqrt(pi) fmt.Println("\nPi to 70 decimal places is:") fmt.Println(pi.Text('f', 70)) }
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
Rewrite the snippet below in C# so it works the same as the original Go code.
package main import ( "fmt" "rcu" ) func powerset(set []int) [][]int { if len(set) == 0 { return [][]int{{}} } head := set[0] tail := set[1:] p1 := powerset(tail) var p2 [][]int for _, s := range powerset(tail) { h := []int{head} h = append(h, s...) p2 = append(p2, h) } return append(p1, p2...) } func isPractical(n int) bool { if n == 1 { return true } divs := rcu.ProperDivisors(n) subsets := powerset(divs) found := make([]bool, n) count := 0 for _, subset := range subsets { sum := rcu.SumInts(subset) if sum > 0 && sum < n && !found[sum] { found[sum] = true count++ if count == n-1 { return true } } } return false } func main() { fmt.Println("In the range 1..333, there are:") var practical []int for i := 1; i <= 333; i++ { if isPractical(i) { practical = append(practical, i) } } fmt.Println(" ", len(practical), "practical numbers") fmt.Println(" The first ten are", practical[0:10]) fmt.Println(" The final ten are", practical[len(practical)-10:]) fmt.Println("\n666 is practical:", isPractical(666)) }
using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static bool soas(int n, IEnumerable<int> f) { if (n <= 0) return false; if (f.Contains(n)) return true; switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true; case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0); return soas(d, rf) || soas(n, rf); } return true; } static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList(); return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f)); } static void Main() { int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2) if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : ""); Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m); do Write("\n{0,5} is a{1}practical number.", m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
Can you help me rewrite this code in C# instead of Go, keeping it the same logically?
package main import ( "fmt" "rcu" ) const LIMIT = 999999 var primes = rcu.Primes(LIMIT) func longestSeq(dir string) { pd := 0 longSeqs := [][]int{{2}} currSeq := []int{2} for i := 1; i < len(primes); i++ { d := primes[i] - primes[i-1] if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) { if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } currSeq = []int{primes[i-1], primes[i]} } else { currSeq = append(currSeq, primes[i]) } pd = d } if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":") for _, ls := range longSeqs { var diffs []int for i := 1; i < len(ls); i++ { diffs = append(diffs, ls[i]-ls[i-1]) } for i := 0; i < len(ls)-1; i++ { fmt.Print(ls[i], " (", diffs[i], ") ") } fmt.Println(ls[len(ls)-1]) } fmt.Println() } func main() { fmt.Println("For primes < 1 million:\n") for _, dir := range []string{"ascending", "descending"} { longestSeq(dir) } }
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console; class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0, ng, d, ld = 0; var desc = new string[] { "A", "", "De" }; int[] mx = new int[] { 0, 0, 0 }, bi = new int[] { 0, 0, 0 }, c = new int[] { 2, 2, 2 }; WriteLine("For primes up to {0:n0}:", lmt); var pr = PG.Primes(lmt).ToArray(); for (int i = 0; i < pr.Length; i++) { ng = pr[i].Item2; d = ng.CompareTo(lg) + 1; if (ld == d) c[2 - d]++; else { if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; } c[d] = 2; } ld = d; lg = ng; } for (int r = 0; r <= 2; r += 2) { Write("{0}scending, found run of {1} consecutive primes:\n {2} ", desc[r], mx[r] + 1, pr[bi[r]++].Item1); foreach (var itm in pr.Skip(bi[r]).Take(mx[r])) Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n"); } } } } class PG { public static IEnumerable<TG> Primes(int lim) { bool[] flags = new bool[lim + 1]; int j = 3, lj = 2; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return new TG(j, j - lj); lj = 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 new TG(j, j - lj); lj = j; } } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 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 } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { limit := int(1e6) c := sieve(limit - 1) var erdos []int for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { if !c[i-fact] { found = false break } j++ fact = fact * j } if found { erdos = append(erdos, i) } } if i > 2 { i += 2 } else { i += 1 } } lowerLimit := 2500 var erdosLower []int for _, e := range erdos { if e < lowerLimit { erdosLower = append(erdosLower, e) } else { break } } fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit)) for i, e := range erdosLower { fmt.Printf("%6d", e) if (i+1)%10 == 0 { fmt.Println() } } show := 7875 fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1])) }
using System; using static System.Console; class Program { const int lmt = (int)1e6, first = 2500; static int[] f = new int[10]; static void Main(string[] args) { f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++) f[b] = f[a] * (b + 1); int pc = 0, nth = 0, lv = 0; for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) { if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " "); nth++; lv = i; } Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); } static string ord(int n) { return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; } static bool is_erdos_prime(int p) { if (!is_pr(p)) return false; int m = 0, t; while ((t = p - f[m++]) > 0) if (is_pr(t)) return false; return true; bool is_pr(int x) { if (x < 4) return x > 1; if ((x & 1) == 0) return false; for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 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 } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { limit := int(1e6) c := sieve(limit - 1) var erdos []int for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { if !c[i-fact] { found = false break } j++ fact = fact * j } if found { erdos = append(erdos, i) } } if i > 2 { i += 2 } else { i += 1 } } lowerLimit := 2500 var erdosLower []int for _, e := range erdos { if e < lowerLimit { erdosLower = append(erdosLower, e) } else { break } } fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit)) for i, e := range erdosLower { fmt.Printf("%6d", e) if (i+1)%10 == 0 { fmt.Println() } } show := 7875 fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1])) }
using System; using static System.Console; class Program { const int lmt = (int)1e6, first = 2500; static int[] f = new int[10]; static void Main(string[] args) { f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++) f[b] = f[a] * (b + 1); int pc = 0, nth = 0, lv = 0; for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) { if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " "); nth++; lv = i; } Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); } static string ord(int n) { return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; } static bool is_erdos_prime(int p) { if (!is_pr(p)) return false; int m = 0, t; while ((t = p - f[m++]) > 0) if (is_pr(t)) return false; return true; bool is_pr(int x) { if (x < 4) return x > 1; if ((x & 1) == 0) return false; for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } } }
Write the same code in C# as shown below in Go.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00", } var example2 = []string{ "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00", } var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} var ( grid [][]int clues []int totalToFill = 0 ) func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true } back := grid[r][c] if back != 0 && back != count { return false } if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false } if back == count { nextClue++ } grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false } func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } } func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } } sort.Ints(lst) clues = lst if solve(startRow, startCol, 1, 0) { printResult(n + 1) } } }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Maintain the same structure and functionality when rewriting this code in C#.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00", } var example2 = []string{ "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00", } var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} var ( grid [][]int clues []int totalToFill = 0 ) func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true } back := grid[r][c] if back != 0 && back != count { return false } if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false } if back == count { nextClue++ } grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false } func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } } func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } } sort.Ints(lst) clues = lst if solve(startRow, startCol, 1, 0) { printResult(n + 1) } } }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Write the same algorithm in C# as shown in this Go implementation.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
Rewrite the snippet below in C# so it works the same as the original Go code.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
Convert this Go snippet to C# and keep its semantics consistent.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Write a version of this Go function in C# with identical behavior.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Convert this Go block to C#, preserving its control flow and logic.
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if bs[i] || other[i] { bs[i] = true } else { bs[i] = false } } } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func newPuzzle(data [2]string) { rowData := strings.Fields(data[0]) colData := strings.Fields(data[1]) rows := getCandidates(rowData, len(colData)) cols := getCandidates(colData, len(rowData)) for { numChanged := reduceMutual(cols, rows) if numChanged == -1 { fmt.Println("No solution") return } if numChanged == 0 { break } } for _, row := range rows { for i := 0; i < len(cols); i++ { fmt.Printf(iff(row[0][i], "# ", ". ")) } fmt.Println() } fmt.Println() } func getCandidates(data []string, le int) [][]BitSet { var result [][]BitSet for _, s := range data { var lst []BitSet a := []byte(s) sumBytes := 0 for _, b := range a { sumBytes += int(b - 'A' + 1) } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-'A'+1)) } for _, r := range genSequence(prep, le-sumBytes+1) { bits := []byte(r[1:]) bitset := make(BitSet, len(bits)) for i, b := range bits { bitset[i] = b == '1' } lst = append(lst, bitset) } result = append(result, lst) } return result } func genSequence(ones []string, numZeros int) []string { le := len(ones) if le == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-le+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } func reduceMutual(cols, rows [][]BitSet) int { countRemoved1 := reduce(cols, rows) if countRemoved1 == -1 { return -1 } countRemoved2 := reduce(rows, cols) if countRemoved2 == -1 { return -1 } return countRemoved1 + countRemoved2 } func reduce(a, b [][]BitSet) int { countRemoved := 0 for i := 0; i < len(a); i++ { commonOn := make(BitSet, len(b)) for j := 0; j < len(b); j++ { commonOn[j] = true } commonOff := make(BitSet, len(b)) for _, candidate := range a[i] { commonOn.and(candidate) commonOff.or(candidate) } for j := 0; j < len(b); j++ { fi, fj := i, j for k := len(b[j]) - 1; k >= 0; k-- { cnd := b[j][k] if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) { lb := len(b[j]) copy(b[j][k:], b[j][k+1:]) b[j][lb-1] = nil b[j] = b[j][:lb-1] countRemoved++ } } if len(b[j]) == 0 { return -1 } } } return countRemoved } func main() { p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"} p2 := [2]string{ "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA", } p3 := [2]string{ "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC", } p4 := [2]string{ "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM", } for _, puzzleData := range [][2]string{p1, p2, p3, p4} { newPuzzle(puzzleData) } }
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
Write a version of this Go function in C# with identical behavior.
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if bs[i] || other[i] { bs[i] = true } else { bs[i] = false } } } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func newPuzzle(data [2]string) { rowData := strings.Fields(data[0]) colData := strings.Fields(data[1]) rows := getCandidates(rowData, len(colData)) cols := getCandidates(colData, len(rowData)) for { numChanged := reduceMutual(cols, rows) if numChanged == -1 { fmt.Println("No solution") return } if numChanged == 0 { break } } for _, row := range rows { for i := 0; i < len(cols); i++ { fmt.Printf(iff(row[0][i], "# ", ". ")) } fmt.Println() } fmt.Println() } func getCandidates(data []string, le int) [][]BitSet { var result [][]BitSet for _, s := range data { var lst []BitSet a := []byte(s) sumBytes := 0 for _, b := range a { sumBytes += int(b - 'A' + 1) } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-'A'+1)) } for _, r := range genSequence(prep, le-sumBytes+1) { bits := []byte(r[1:]) bitset := make(BitSet, len(bits)) for i, b := range bits { bitset[i] = b == '1' } lst = append(lst, bitset) } result = append(result, lst) } return result } func genSequence(ones []string, numZeros int) []string { le := len(ones) if le == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-le+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } func reduceMutual(cols, rows [][]BitSet) int { countRemoved1 := reduce(cols, rows) if countRemoved1 == -1 { return -1 } countRemoved2 := reduce(rows, cols) if countRemoved2 == -1 { return -1 } return countRemoved1 + countRemoved2 } func reduce(a, b [][]BitSet) int { countRemoved := 0 for i := 0; i < len(a); i++ { commonOn := make(BitSet, len(b)) for j := 0; j < len(b); j++ { commonOn[j] = true } commonOff := make(BitSet, len(b)) for _, candidate := range a[i] { commonOn.and(candidate) commonOff.or(candidate) } for j := 0; j < len(b); j++ { fi, fj := i, j for k := len(b[j]) - 1; k >= 0; k-- { cnd := b[j][k] if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) { lb := len(b[j]) copy(b[j][k:], b[j][k+1:]) b[j][lb-1] = nil b[j] = b[j][:lb-1] countRemoved++ } } if len(b[j]) == 0 { return -1 } } } return countRemoved } func main() { p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"} p2 := [2]string{ "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA", } p3 := [2]string{ "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC", } p4 := [2]string{ "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM", } for _, puzzleData := range [][2]string{p1, p2, p3, p4} { newPuzzle(puzzleData) } }
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import ( "bufio" "fmt" "log" "math/rand" "os" "regexp" "strings" "time" ) var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}} const ( nRows = 10 nCols = nRows gridSize = nRows * nCols minWords = 25 ) var ( re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows)) re2 = regexp.MustCompile("[^A-Z]") ) type grid struct { numAttempts int cells [nRows][nCols]byte solutions []string } func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if re1.MatchString(word) { words = append(words, word) } } check(scanner.Err()) return words } func createWordSearch(words []string) *grid { var gr *grid outer: for i := 1; i < 100; i++ { gr = new(grid) messageLen := gr.placeMessage("Rosetta Code") target := gridSize - messageLen cellsFilled := 0 rand.Shuffle(len(words), func(i, j int) { words[i], words[j] = words[j], words[i] }) for _, word := range words { cellsFilled += gr.tryPlaceWord(word) if cellsFilled == target { if len(gr.solutions) >= minWords { gr.numAttempts = i break outer } else { break } } } } return gr } func (gr *grid) placeMessage(msg string) int { msg = strings.ToUpper(msg) msg = re2.ReplaceAllLiteralString(msg, "") messageLen := len(msg) if messageLen > 0 && messageLen < gridSize { gapSize := gridSize / messageLen for i := 0; i < messageLen; i++ { pos := i*gapSize + rand.Intn(gapSize) gr.cells[pos/nCols][pos%nCols] = msg[i] } return messageLen } return 0 } func (gr *grid) tryPlaceWord(word string) int { randDir := rand.Intn(len(dirs)) randPos := rand.Intn(gridSize) for dir := 0; dir < len(dirs); dir++ { dir = (dir + randDir) % len(dirs) for pos := 0; pos < gridSize; pos++ { pos = (pos + randPos) % gridSize lettersPlaced := gr.tryLocation(word, dir, pos) if lettersPlaced > 0 { return lettersPlaced } } } return 0 } func (gr *grid) tryLocation(word string, dir, pos int) int { r := pos / nCols c := pos % nCols le := len(word) if (dirs[dir][0] == 1 && (le+c) > nCols) || (dirs[dir][0] == -1 && (le-1) > c) || (dirs[dir][1] == 1 && (le+r) > nRows) || (dirs[dir][1] == -1 && (le-1) > r) { return 0 } overlaps := 0 rr := r cc := c for i := 0; i < le; i++ { if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] { return 0 } cc += dirs[dir][0] rr += dirs[dir][1] } rr = r cc = c for i := 0; i < le; i++ { if gr.cells[rr][cc] == word[i] { overlaps++ } else { gr.cells[rr][cc] = word[i] } if i < le-1 { cc += dirs[dir][0] rr += dirs[dir][1] } } lettersPlaced := le - overlaps if lettersPlaced > 0 { sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr) gr.solutions = append(gr.solutions, sol) } return lettersPlaced } func printResult(gr *grid) { if gr.numAttempts == 0 { fmt.Println("No grid to display") return } size := len(gr.solutions) fmt.Println("Attempts:", gr.numAttempts) fmt.Println("Number of words:", size) fmt.Println("\n 0 1 2 3 4 5 6 7 8 9") for r := 0; r < nRows; r++ { fmt.Printf("\n%d ", r) for c := 0; c < nCols; c++ { fmt.Printf(" %c ", gr.cells[r][c]) } } fmt.Println("\n") for i := 0; i < size-1; i += 2 { fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1]) } if size%2 == 1 { fmt.Println(gr.solutions[size-1]) } } func main() { rand.Seed(time.Now().UnixNano()) unixDictPath := "/usr/share/dict/words" printResult(createWordSearch(readWords(unixDictPath))) }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Wordseach { static class Program { readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; class Grid { public char[,] Cells = new char[nRows, nCols]; public List<string> Solutions = new List<string>(); public int NumAttempts; } readonly static int nRows = 10; readonly static int nCols = 10; readonly static int gridSize = nRows * nCols; readonly static int minWords = 25; readonly static Random rand = new Random(); static void Main(string[] args) { PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))); } private static List<string> ReadWords(string filename) { int maxLen = Math.Max(nRows, nCols); return System.IO.File.ReadAllLines(filename) .Select(s => s.Trim().ToLower()) .Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$")) .ToList(); } private static Grid CreateWordSearch(List<string> words) { int numAttempts = 0; while (++numAttempts < 100) { words.Shuffle(); var grid = new Grid(); int messageLen = PlaceMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; foreach (var word in words) { cellsFilled += TryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.Solutions.Count >= minWords) { grid.NumAttempts = numAttempts; return grid; } else break; } } } return null; } private static int TryPlaceWord(Grid grid, string word) { int randDir = rand.Next(dirs.GetLength(0)); int randPos = rand.Next(gridSize); for (int dir = 0; dir < dirs.GetLength(0); dir++) { dir = (dir + randDir) % dirs.GetLength(0); for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize; int lettersPlaced = TryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; } private static int TryLocation(Grid grid, string word, int dir, int pos) { int r = pos / nCols; int c = pos % nCols; int len = word.Length; if ((dirs[dir, 0] == 1 && (len + c) > nCols) || (dirs[dir, 0] == -1 && (len - 1) > c) || (dirs[dir, 1] == 1 && (len + r) > nRows) || (dirs[dir, 1] == -1 && (len - 1) > r)) return 0; int rr, cc, i, overlaps = 0; for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i]) { return 0; } cc += dirs[dir, 0]; rr += dirs[dir, 1]; } for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] == word[i]) overlaps++; else grid.Cells[rr, cc] = word[i]; if (i < len - 1) { cc += dirs[dir, 0]; rr += dirs[dir, 1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})"); } return lettersPlaced; } private static int PlaceMessage(Grid grid, string msg) { msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", ""); int messageLen = msg.Length; if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen; for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.Next(gapSize); grid.Cells[pos / nCols, pos % nCols] = msg[i]; } return messageLen; } return 0; } public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rand.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } private static void PrintResult(Grid grid) { if (grid == null || grid.NumAttempts == 0) { Console.WriteLine("No grid to display"); return; } int size = grid.Solutions.Count; Console.WriteLine("Attempts: " + grid.NumAttempts); Console.WriteLine("Number of words: " + size); Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { Console.Write("\n{0} ", r); for (int c = 0; c < nCols; c++) Console.Write(" {0} ", grid.Cells[r, c]); } Console.WriteLine("\n"); for (int i = 0; i < size - 1; i += 2) { Console.WriteLine("{0} {1}", grid.Solutions[i], grid.Solutions[i + 1]); } if (size % 2 == 1) Console.WriteLine(grid.Solutions[size - 1]); Console.ReadLine(); } } }
Maintain the same structure and functionality when rewriting this code in C#.
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
Keep all operations the same but rewrite the snippet in C#.
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() { animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Collie{Dog: Dog{ Animal: Animal{Alive: true}, ObedienceTrained: true, }}, } fmt.Println("created:") for _, a := range animals { a.print() } f, err := os.Create("objects.dat") if err != nil { fmt.Println(err) return } for _, a := range animals { gob.Register(a) } err = gob.NewEncoder(f).Encode(animals) if err != nil { fmt.Println(err) return } f.Close() f, err = os.Open("objects.dat") if err != nil { fmt.Println(err) return } var clones []printable gob.NewDecoder(f).Decode(&clones) if err != nil { fmt.Println(err) return } fmt.Println("\nloaded from objects.dat:") for _, c := range clones { c.print() } } type Animal struct { Alive bool } func (a *Animal) print() { if a.Alive { fmt.Println(" live animal, unspecified type") } else { fmt.Println(" dead animal, unspecified type") } } type Dog struct { Animal ObedienceTrained bool } func (d *Dog) print() { switch { case !d.Alive: fmt.Println(" dead dog") case d.ObedienceTrained: fmt.Println(" trained dog") default: fmt.Println(" dog, not trained") } } type Cat struct { Animal LitterBoxTrained bool } func (c *Cat) print() { switch { case !c.Alive: fmt.Println(" dead cat") case c.LitterBoxTrained: fmt.Println(" litter box trained cat") default: fmt.Println(" cat, not litter box trained") } } type Lab struct { Dog Color string } func (l *Lab) print() { var r string if l.Color == "" { r = "lab, color unspecified" } else { r = l.Color + " lab" } switch { case !l.Alive: fmt.Println(" dead", r) case l.ObedienceTrained: fmt.Println(" trained", r) default: fmt.Printf(" %s, not trained\n", r) } } type Collie struct { Dog CatchesFrisbee bool } func (c *Collie) print() { switch { case !c.Alive: fmt.Println(" dead collie") case c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" trained collie, catches frisbee") case c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" trained collie, but doesn't catch frisbee") case !c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" collie, not trained, but catches frisbee") case !c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" collie, not trained, doesn't catch frisbee") } }
using System; using System.IO; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace Object_serialization { [Serializable] public class Being { public bool Alive { get; set; } } [Serializable] public class Animal: Being { public Animal() { } public Animal(long id, string name, bool alive = true) { Id = id; Name = name; Alive = alive; } public long Id { get; set; } public string Name { get; set; } public void Print() { Console.WriteLine("{0}, id={1} is {2}", Name, Id, Alive ? "alive" : "dead"); } } internal class Program { private static void Main() { string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\objects.dat"; var n = new List<Animal> { new Animal(1, "Fido"), new Animal(2, "Lupo"), new Animal(7, "Wanda"), new Animal(3, "Kiki", alive: false) }; foreach(Animal animal in n) animal.Print(); using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write)) new BinaryFormatter().Serialize(stream, n); n.Clear(); Console.WriteLine("---------------"); List<Animal> m; using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) m = (List<Animal>) new BinaryFormatter().Deserialize(stream); foreach(Animal animal in m) animal.Print(); } } }
Change the programming language of this snippet from Go to C# without modifying what it does.
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {length: 0, suffix: oddRoot, edges: edges{}}, oddRoot: {length: -1, suffix: oddRoot, edges: edges{}}, } suffix := oddRoot var n, k int for i, c := range s { for n = suffix; ; n = tree[n].suffix { k = tree[n].length if b := i - k - 1; b >= 0 && s[b] == c { break } } if e, ok := tree[n].edges[c]; ok { suffix = e continue } suffix = len(tree) tree = append(tree, node{length: k + 2, edges: edges{}}) tree[n].edges[c] = suffix if tree[suffix].length == 1 { tree[suffix].suffix = 0 continue } for { n = tree[n].suffix if b := i - tree[n].length - 1; b >= 0 && s[b] == c { break } } tree[suffix].suffix = tree[n].edges[c] } return tree } func subPalindromes(tree []node) (s []string) { var children func(int, string) children = func(n int, p string) { for c, n := range tree[n].edges { c := string(c) p := c + p + c s = append(s, p) children(n, p) } } children(0, "") for c, n := range tree[1].edges { c := string(c) s = append(s, c) children(n, c) } return }
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {length: 0, suffix: oddRoot, edges: edges{}}, oddRoot: {length: -1, suffix: oddRoot, edges: edges{}}, } suffix := oddRoot var n, k int for i, c := range s { for n = suffix; ; n = tree[n].suffix { k = tree[n].length if b := i - k - 1; b >= 0 && s[b] == c { break } } if e, ok := tree[n].edges[c]; ok { suffix = e continue } suffix = len(tree) tree = append(tree, node{length: k + 2, edges: edges{}}) tree[n].edges[c] = suffix if tree[suffix].length == 1 { tree[suffix].suffix = 0 continue } for { n = tree[n].suffix if b := i - tree[n].length - 1; b >= 0 && s[b] == c { break } } tree[suffix].suffix = tree[n].edges[c] } return tree } func subPalindromes(tree []node) (s []string) { var children func(int, string) children = func(n int, p string) { for c, n := range tree[n].edges { c := string(c) p := c + p + c s = append(s, p) children(n, p) } } children(0, "") for c, n := range tree[1].edges { c := string(c) s = append(s, c) children(n, c) } return }
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
Produce a language-to-language conversion: from Go to C#, same semantics.
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
using static System.Console; using System.Collections.Generic; using System.Linq; using System.Globalization; public static class Program { public static void Main() { WriteLine("Long years in the 21st century:"); WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53))); } public static IEnumerable<int> To(this int start, int end) { for (int i = start; i < end; i++) yield return i; } }
Keep all operations the same but rewrite the snippet in C#.
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
using static System.Console; using System.Collections.Generic; using System.Linq; using System.Globalization; public static class Program { public static void Main() { WriteLine("Long years in the 21st century:"); WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53))); } public static IEnumerable<int> To(this int start, int end) { for (int i = start; i < end; i++) yield return i; } }
Translate this program into C# but keep the logic exactly as in Go.
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(divs []int) int { sum := 0 for _, div := range divs { sum += div } return sum } func isPartSum(divs []int, sum int) bool { if sum == 0 { return true } le := len(divs) if le == 0 { return false } last := divs[le-1] divs = divs[0 : le-1] if last > sum { return isPartSum(divs, sum) } return isPartSum(divs, sum) || isPartSum(divs, sum-last) } func isZumkeller(n int) bool { divs := getDivisors(n) sum := sum(divs) if sum%2 == 1 { return false } if n%2 == 1 { abundance := sum - 2*n return abundance > 0 && abundance%2 == 0 } return isPartSum(divs, sum/2) } func main() { fmt.Println("The first 220 Zumkeller numbers are:") for i, count := 2, 0; count < 220; i++ { if isZumkeller(i) { fmt.Printf("%3d ", i) count++ if count%20 == 0 { fmt.Println() } } } fmt.Println("\nThe first 40 odd Zumkeller numbers are:") for i, count := 3, 0; count < 40; i += 2 { if isZumkeller(i) { fmt.Printf("%5d ", i) count++ if count%10 == 0 { fmt.Println() } } } fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:") for i, count := 3, 0; count < 40; i += 2 { if (i % 10 != 5) && isZumkeller(i) { fmt.Printf("%7d ", i) count++ if count%8 == 0 { fmt.Println() } } } fmt.Println() }
using System; using System.Collections.Generic; using System.Linq; namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.Add(i); if (i != j) { divs.Add(j); } } } return divs; } static bool IsPartSum(List<int> divs, int sum) { if (sum == 0) { return true; } var le = divs.Count; if (le == 0) { return false; } var last = divs[le - 1]; List<int> newDivs = new List<int>(); for (int i = 0; i < le - 1; i++) { newDivs.Add(divs[i]); } if (last > sum) { return IsPartSum(newDivs, sum); } return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last); } static bool IsZumkeller(int n) { var divs = GetDivisors(n); var sum = divs.Sum(); if (sum % 2 == 1) { return false; } if (n % 2 == 1) { var abundance = sum - 2 * n; return abundance > 0 && abundance % 2 == 0; } return IsPartSum(divs, sum / 2); } static void Main() { Console.WriteLine("The first 220 Zumkeller numbers are:"); int i = 2; for (int count = 0; count < 220; i++) { if (IsZumkeller(i)) { Console.Write("{0,3} ", i); count++; if (count % 20 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (IsZumkeller(i)) { Console.Write("{0,5} ", i); count++; if (count % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (i % 10 != 5 && IsZumkeller(i)) { Console.Write("{0,7} ", i); count++; if (count % 8 == 0) { Console.WriteLine(); } } } } } }
Produce a language-to-language conversion: from Go to C#, same semantics.
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
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); } } }
Produce a functionally identical C# code for the snippet given in Go.
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
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 Go to C# without modifying what it does.
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
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); } } }
Write the same code in C# as shown below in Go.
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() } func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } } func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
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)); } }
Change the following Go code into C# without altering its purpose.
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() } func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } } func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
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)); } }
Write a version of this Go function in C# with identical behavior.
package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
int a=0,b=1/a;
Convert the following code from Go to C#, ensuring the logic remains intact.
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MarkovChainTextGenerator { class Program { static string Join(string a, string b) { return a + " " + b; } static string Markov(string filePath, int keySize, int outputSize) { if (keySize < 1) throw new ArgumentException("Key size can't be less than 1"); string body; using (StreamReader sr = new StreamReader(filePath)) { body = sr.ReadToEnd(); } var words = body.Split(); if (outputSize < keySize || words.Length < outputSize) { throw new ArgumentException("Output size is out of range"); } Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); for (int i = 0; i < words.Length - keySize; i++) { var key = words.Skip(i).Take(keySize).Aggregate(Join); string value; if (i + keySize < words.Length) { value = words[i + keySize]; } else { value = ""; } if (dict.ContainsKey(key)) { dict[key].Add(value); } else { dict.Add(key, new List<string>() { value }); } } Random rand = new Random(); List<string> output = new List<string>(); int n = 0; int rn = rand.Next(dict.Count); string prefix = dict.Keys.Skip(rn).Take(1).Single(); output.AddRange(prefix.Split()); while (true) { var suffix = dict[prefix]; if (suffix.Count == 1) { if (suffix[0] == "") { return output.Aggregate(Join); } output.Add(suffix[0]); } else { rn = rand.Next(suffix.Count); output.Add(suffix[rn]); } if (output.Count >= outputSize) { return output.Take(outputSize).Aggregate(Join); } n++; prefix = output.Skip(n).Take(keySize).Aggregate(Join); } } static void Main(string[] args) { Console.WriteLine(Markov("alice_oz.txt", 3, 200)); } } }
Write a version of this Go function in C# with identical behavior.
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MarkovChainTextGenerator { class Program { static string Join(string a, string b) { return a + " " + b; } static string Markov(string filePath, int keySize, int outputSize) { if (keySize < 1) throw new ArgumentException("Key size can't be less than 1"); string body; using (StreamReader sr = new StreamReader(filePath)) { body = sr.ReadToEnd(); } var words = body.Split(); if (outputSize < keySize || words.Length < outputSize) { throw new ArgumentException("Output size is out of range"); } Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); for (int i = 0; i < words.Length - keySize; i++) { var key = words.Skip(i).Take(keySize).Aggregate(Join); string value; if (i + keySize < words.Length) { value = words[i + keySize]; } else { value = ""; } if (dict.ContainsKey(key)) { dict[key].Add(value); } else { dict.Add(key, new List<string>() { value }); } } Random rand = new Random(); List<string> output = new List<string>(); int n = 0; int rn = rand.Next(dict.Count); string prefix = dict.Keys.Skip(rn).Take(1).Single(); output.AddRange(prefix.Split()); while (true) { var suffix = dict[prefix]; if (suffix.Count == 1) { if (suffix[0] == "") { return output.Aggregate(Join); } output.Add(suffix[0]); } else { rn = rand.Next(suffix.Count); output.Add(suffix[rn]); } if (output.Count >= outputSize) { return output.Take(outputSize).Aggregate(Join); } n++; prefix = output.Skip(n).Take(keySize).Aggregate(Join); } } static void Main(string[] args) { Console.WriteLine(Markov("alice_oz.txt", 3, 200)); } } }
Write a version of this Go function in C# with identical behavior.
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq *PriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.m[pq.items[i]] = i pq.m[pq.items[j]] = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(pq.items) item := x.(Vertex) pq.m[item] = n pq.items = append(pq.items, item) } func (pq *PriorityQueue) Pop() interface{} { old := pq.items n := len(old) item := old[n-1] pq.m[item] = -1 pq.items = old[0 : n-1] return item } func (pq *PriorityQueue) update(item Vertex, priority int) { pq.pr[item] = priority heap.Fix(pq, pq.m[item]) } func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) { heap.Push(pq, item) pq.update(item, priority) } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) { vs := g.Vertices() dist = make(map[Vertex]int, len(vs)) prev = make(map[Vertex]Vertex, len(vs)) sid := source dist[sid] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vs)), m: make(map[Vertex]int, len(vs)), pr: make(map[Vertex]int, len(vs)), } for _, v := range vs { if v != sid { dist[v] = Infinity } prev[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt prev[v] = u q.update(v, alt) } } } return dist, prev } type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int } type Vertex int type sg struct { ids map[string]Vertex names map[Vertex]string edges map[Vertex]map[Vertex]int } func newsg(ids map[string]Vertex) sg { g := sg{ids: ids} g.names = make(map[Vertex]string, len(ids)) for k, v := range ids { g.names[v] = k } g.edges = make(map[Vertex]map[Vertex]int) return g } func (g sg) edge(u, v string, w int) { if _, ok := g.edges[g.ids[u]]; !ok { g.edges[g.ids[u]] = make(map[Vertex]int) } g.edges[g.ids[u]][g.ids[v]] = w } func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) { s = g.names[v] for prev[v] >= 0 { v = prev[v] s = g.names[v] + s } return s } func (g sg) Vertices() []Vertex { vs := make([]Vertex, 0, len(g.ids)) for _, v := range g.ids { vs = append(vs, v) } return vs } func (g sg) Neighbors(u Vertex) []Vertex { vs := make([]Vertex, 0, len(g.edges[u])) for v := range g.edges[u] { vs = append(vs, v) } return vs } func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] } func main() { g := newsg(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 7) g.edge("a", "c", 9) g.edge("a", "f", 14) g.edge("b", "c", 10) g.edge("b", "d", 15) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 6) g.edge("e", "f", 9) dist, prev := Dijkstra(g, g.ids["a"]) fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev)) }
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; } } }
Generate an equivalent C# version of this Go code.
package main import ( "fmt" "math/rand" "time" ) type vector []float64 func e(n uint) vector { if n > 4 { panic("n must be less than 5") } result := make(vector, 32) result[1<<n] = 1.0 return result } func cdot(a, b vector) vector { return mul(vector{0.5}, add(mul(a, b), mul(b, a))) } func neg(x vector) vector { return mul(vector{-1}, x) } func bitCount(i int) int { i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) i = (i + (i >> 4)) & 0x0F0F0F0F i = i + (i >> 8) i = i + (i >> 16) return i & 0x0000003F } func reorderingSign(i, j int) float64 { i >>= 1 sum := 0 for i != 0 { sum += bitCount(i & j) i >>= 1 } cond := (sum & 1) == 0 if cond { return 1.0 } return -1.0 } func add(a, b vector) vector { result := make(vector, 32) copy(result, a) for i, _ := range b { result[i] += b[i] } return result } func mul(a, b vector) vector { result := make(vector, 32) for i, _ := range a { if a[i] != 0 { for j, _ := range b { if b[j] != 0 { s := reorderingSign(i, j) * a[i] * b[j] k := i ^ j result[k] += s } } } } return result } func randomVector() vector { result := make(vector, 32) for i := uint(0); i < 5; i++ { result = add(result, mul(vector{rand.Float64()}, e(i))) } return result } func randomMultiVector() vector { result := make(vector, 32) for i := 0; i < 32; i++ { result[i] = rand.Float64() } return result } func main() { rand.Seed(time.Now().UnixNano()) for i := uint(0); i < 5; i++ { for j := uint(0); j < 5; j++ { if i < j { if cdot(e(i), e(j))[0] != 0 { fmt.Println("Unexpected non-null scalar product.") return } } else if i == j { if cdot(e(i), e(j))[0] == 0 { fmt.Println("Unexpected null scalar product.") } } } } a := randomMultiVector() b := randomMultiVector() c := randomMultiVector() x := randomVector() fmt.Println(mul(mul(a, b), c)) fmt.Println(mul(a, mul(b, c))) fmt.Println(mul(a, add(b, c))) fmt.Println(add(mul(a, b), mul(a, c))) fmt.Println(mul(add(a, b), c)) fmt.Println(add(mul(a, c), mul(b, c))) fmt.Println(mul(x, x)) }
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); } } }
Translate the given Go code snippet into C# without altering its behavior.
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree { n := 0 for i := 0; i < len(suf); { b := suf[i] ch := t[n].ch var x2, n2 int for ; ; x2++ { if x2 == len(ch) { n2 = len(t) t = append(t, node{sub: suf[i:]}) t[n].ch = append(t[n].ch, n2) return t } n2 = ch[x2] if t[n2].sub[0] == b { break } } sub2 := t[n2].sub j := 0 for ; j < len(sub2); j++ { if suf[i+j] != sub2[j] { n3 := n2 n2 = len(t) t = append(t, node{sub2[:j], []int{n3}}) t[n3].sub = sub2[j:] t[n].ch[x2] = n2 break } } i += j n = n2 } return t } func vis(t tree) { if len(t) == 0 { fmt.Println("<empty>") return } var f func(int, string) f = func(n int, pre string) { children := t[n].ch if len(children) == 0 { fmt.Println("╴", t[n].sub) return } fmt.Println("┐", t[n].sub) last := len(children) - 1 for _, ch := range children[:last] { fmt.Print(pre, "├─") f(ch, pre+"│ ") } fmt.Print(pre, "└─") f(children[last], pre+" ") } f(0, "") }
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
Translate the given Go code snippet into C# without altering its behavior.
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree { n := 0 for i := 0; i < len(suf); { b := suf[i] ch := t[n].ch var x2, n2 int for ; ; x2++ { if x2 == len(ch) { n2 = len(t) t = append(t, node{sub: suf[i:]}) t[n].ch = append(t[n].ch, n2) return t } n2 = ch[x2] if t[n2].sub[0] == b { break } } sub2 := t[n2].sub j := 0 for ; j < len(sub2); j++ { if suf[i+j] != sub2[j] { n3 := n2 n2 = len(t) t = append(t, node{sub2[:j], []int{n3}}) t[n3].sub = sub2[j:] t[n].ch[x2] = n2 break } } i += j n = n2 } return t } func vis(t tree) { if len(t) == 0 { fmt.Println("<empty>") return } var f func(int, string) f = func(n int, pre string) { children := t[n].ch if len(children) == 0 { fmt.Println("╴", t[n].sub) return } fmt.Println("┐", t[n].sub) last := len(children) - 1 for _, ch := range children[:last] { fmt.Print(pre, "├─") f(ch, pre+"│ ") } fmt.Print(pre, "└─") f(children[last], pre+" ") } f(0, "") }
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
Convert the following code from Go to C#, ensuring the logic remains intact.
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
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()); } } } }
Write the same algorithm in C# as shown in this Go implementation.
package main import "fmt" type TinyInt int func NewTinyInt(i int) TinyInt { if i < 1 { i = 1 } else if i > 10 { i = 10 } return TinyInt(i) } func (t1 TinyInt) Add(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) + int(t2)) } func (t1 TinyInt) Sub(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) - int(t2)) } func (t1 TinyInt) Mul(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) * int(t2)) } func (t1 TinyInt) Div(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) / int(t2)) } func (t1 TinyInt) Rem(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) % int(t2)) } func (t TinyInt) Inc() TinyInt { return t.Add(TinyInt(1)) } func (t TinyInt) Dec() TinyInt { return t.Sub(TinyInt(1)) } func main() { t1 := NewTinyInt(6) t2 := NewTinyInt(3) fmt.Println("t1 =", t1) fmt.Println("t2 =", t2) fmt.Println("t1 + t2 =", t1.Add(t2)) fmt.Println("t1 - t2 =", t1.Sub(t2)) fmt.Println("t1 * t2 =", t1.Mul(t2)) fmt.Println("t1 / t2 =", t1.Div(t2)) fmt.Println("t1 % t2 =", t1.Rem(t2)) fmt.Println("t1 + 1 =", t1.Inc()) fmt.Println("t1 - 1 =", t1.Dec()) }
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 }