Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in C# as shown below in Go.
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
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)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....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 a version of this Go function in C# with identical behavior.
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
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)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....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(); } }
Change the programming language of this snippet from Go to C# without modifying what it does.
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; private set; } } public class NameNemesis { public NameNemesis(string name, string nemesis) { Name = name; Nemesis = nemesis; } public string Name { get; private set; } public string Nemesis { get; private set; } } public class DataContext { public DataContext() { AgeName = new List<AgeName>(); NameNemesis = new List<NameNemesis>(); } public List<AgeName> AgeName { get; set; } public List<NameNemesis> NameNemesis { get; set; } } public class AgeNameNemesis { public AgeNameNemesis(byte age, string name, string nemesis) { Age = age; Name = name; Nemesis = nemesis; } public byte Age { get; private set; } public string Name { get; private set; } public string Nemesis { get; private set; } } class Program { public static void Main() { var data = GetData(); var result = ExecuteHashJoin(data); WriteResultToConsole(result); } private static void WriteResultToConsole(List<AgeNameNemesis> result) { result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); } private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data) { return (data.AgeName.Join(data.NameNemesis, ageName => ageName.Name, nameNemesis => nameNemesis.Name, (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) .ToList(); } private static DataContext GetData() { var context = new DataContext(); context.AgeName.AddRange(new [] { new AgeName(27, "Jonah"), new AgeName(18, "Alan"), new AgeName(28, "Glory"), new AgeName(18, "Popeye"), new AgeName(28, "Alan") }); context.NameNemesis.AddRange(new[] { new NameNemesis("Jonah", "Whales"), new NameNemesis("Jonah", "Spiders"), new NameNemesis("Alan", "Ghosts"), new NameNemesis("Alan", "Zombies"), new NameNemesis("Glory", "Buffy") }); return context; } } }
Transform the following Go implementation into C#, maintaining the same output and logic.
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } oss = append(oss, n) } } sort.Ints(oss) fmt.Println("Odd squarefree semiprimes under 1,000:") for i, n := range oss { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found.\n", len(oss)) }
using System; using static System.Console; using System.Collections; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>(); var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First(); lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++) res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt)) Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : ""); Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Produce a language-to-language conversion: from Go to C#, same semantics.
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } oss = append(oss, n) } } sort.Ints(oss) fmt.Println("Odd squarefree semiprimes under 1,000:") for i, n := range oss { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found.\n", len(oss)) }
using System; using static System.Console; using System.Collections; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>(); var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First(); lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++) res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt)) Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : ""); Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
Rewrite this program in C# while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
Write the same algorithm in C# as shown in this Go implementation.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", n) return 0 } func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
using System; using System.Dynamic; class Example : DynamicObject { public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = null; Console.WriteLine("This is {0}.", binder.Name); return true; } } class Program { static void Main(string[] args) { dynamic ex = new Example(); ex.Foo(); ex.Bar(); } }
Port the provided Go code into C# while preserving the original functionality.
package main import ( "fmt" "sort" ) type matrix [][]int func dList(n, start int) (r matrix) { start-- a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] sort.Ints(a[1:]) first := a[1] var recurse func(last int) recurse = func(last int) { if last == first { for j, v := range a[1:] { if j+1 == v { return } } b := make([]int, n) copy(b, a) for i := range b { b[i]++ } r = append(r, b) return } for i := last; i >= 1; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func reducedLatinSquare(n int, echo bool) uint64 { if n <= 0 { if echo { fmt.Println("[]\n") } return 0 } else if n == 1 { if echo { fmt.Println("[1]\n") } return 1 } rlatin := make(matrix, n) for i := 0; i < n; i++ { rlatin[i] = make([]int, n) } for j := 0; j < n; j++ { rlatin[0][j] = j + 1 } count := uint64(0) var recurse func(i int) recurse = func(i int) { rows := dList(n, i) outer: for r := 0; r < len(rows); r++ { copy(rlatin[i-1], rows[r]) for k := 0; k < i-1; k++ { for j := 1; j < n; j++ { if rlatin[k][j] == rlatin[i-1][j] { if r < len(rows)-1 { continue outer } else if i > 2 { return } } } } if i < n { recurse(i + 1) } else { count++ if echo { printSquare(rlatin, n) } } } return } recurse(2) return count } func printSquare(latin matrix, n int) { for i := 0; i < n; i++ { fmt.Println(latin[i]) } fmt.Println() } func factorial(n uint64) uint64 { if n == 0 { return 1 } prod := uint64(1) for i := uint64(2); i <= n; i++ { prod *= i } return prod } func main() { fmt.Println("The four reduced latin squares of order 4 are:\n") reducedLatinSquare(4, true) fmt.Println("The size of the set of reduced latin squares for the following orders") fmt.Println("and hence the total number of latin squares of these orders are:\n") for n := uint64(1); n <= 6; n++ { size := reducedLatinSquare(int(n), false) f := factorial(n - 1) f *= f * n * size fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f) } }
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; matrix r = new matrix(); void recurse(int last) { if (last == first) { for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; } } var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f); } } } }
Please provide an equivalent version of this Go code in C#.
package main import ( "fmt" "math" "math/rand" "time" ) type xy struct { x, y float64 } const n = 1000 const scale = 100. func d(p1, p2 xy) float64 { return math.Hypot(p2.x-p1.x, p2.y-p1.y) } func main() { rand.Seed(time.Now().Unix()) points := make([]xy, n) for i := range points { points[i] = xy{rand.Float64() * scale, rand.Float64() * scale} } p1, p2 := closestPair(points) fmt.Println(p1, p2) fmt.Println("distance:", d(p1, p2)) } func closestPair(points []xy) (p1, p2 xy) { if len(points) < 2 { panic("at least two points expected") } min := 2 * scale for i, q1 := range points[:len(points)-1] { for _, q2 := range points[i+1:] { if dq := d(q1, q2); dq < min { p1, p2 = q1, q2 min = dq } } } return }
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; } public readonly PointF P1; public readonly PointF P2; public float Length() { return (float)Math.Sqrt(LengthSquared()); } public float LengthSquared() { return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y); } }
Produce a language-to-language conversion: from Go to C#, same semantics.
package main import ( "fmt" "unsafe" ) func main() { myVar := 3.14 myPointer := &myVar fmt.Println("Address:", myPointer, &myVar) fmt.Printf("Address: %p %p\n", myPointer, &myVar) var addr64 int64 var addr32 int32 ptr := unsafe.Pointer(myPointer) if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) { addr64 = int64(uintptr(ptr)) fmt.Printf("Pointer stored in int64: %#016x\n", addr64) } if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) { addr32 = int32(uintptr(ptr)) fmt.Printf("Pointer stored in int32: %#08x\n", addr32) } addr := uintptr(ptr) fmt.Printf("Pointer stored in uintptr: %#08x\n", addr) fmt.Println("value as float:", myVar) i := (*int32)(unsafe.Pointer(&myVar)) fmt.Printf("value as int32: %#08x\n", *i) }
int i = 5; int* p = &i;
Generate a C# translation of this Go snippet without changing its computational steps.
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
class Animal { } class Dog : Animal { } class Lab : Dog { } class Collie : Dog { } class Cat : Animal { }
Translate the given Go code snippet into C# without altering its behavior.
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
System.Collections.HashTable map = new System.Collections.HashTable(); map["key1"] = "foo";
Rewrite the snippet below in C# so it works the same as the original Go code.
package main import ( "github.com/fogleman/gg" "math" ) const tau = 2 * math.Pi func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func colorWheel(dc *gg.Context) { width, height := dc.Width(), dc.Height() centerX, centerY := width/2, height/2 radius := centerX if centerY < radius { radius = centerY } for y := 0; y < height; y++ { dy := float64(y - centerY) for x := 0; x < width; x++ { dx := float64(x - centerX) dist := math.Sqrt(dx*dx + dy*dy) if dist <= float64(radius) { theta := math.Atan2(dy, dx) hue := (theta + math.Pi) / tau r, g, b := hsb2rgb(hue, 1, 1) dc.SetRGB255(r, g, b) dc.SetPixel(x, y) } } } } func main() { const width, height = 480, 480 dc := gg.NewContext(width, height) dc.SetRGB(1, 1, 1) dc.Clear() colorWheel(dc) dc.SavePNG("color_wheel.png") }
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality); imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null); DrawHue(100); } void DrawHue(int saturation) { var bmp = (WriteableBitmap)imgMain.Source; int centerX = (int)bmp.Width / 2; int centerY = (int)bmp.Height / 2; int radius = Math.Min(centerX, centerY); int radius2 = radius - 40; bmp.Lock(); unsafe{ var buf = bmp.BackBuffer; IntPtr pixLineStart; for(int y=0; y < bmp.Height; y++){ pixLineStart = buf + bmp.BackBufferStride * y; double dy = (y - centerY); for(int x=0; x < bmp.Width; x++){ double dx = (x - centerX); double dist = Math.Sqrt(dx * dx + dy * dy); if (radius2 <= dist && dist <= radius) { double theta = Math.Atan2(dy, dx); double hue = (theta + Math.PI) / (2.0 * Math.PI); *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100); } } } } bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480)); bmp.Unlock(); } static int HSB_to_RGB(int h, int s, int v) { var rgb = new int[3]; var baseColor = (h + 60) % 360 / 120; var shift = (h + 60) % 360 - (120 * baseColor + 60 ); var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3; rgb[baseColor] = 255; rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f); for (var i = 0; i < 3; i++) rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f)); for (var i = 0; i < 3; i++) rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f); return RGB2int(rgb[0], rgb[1], rgb[2]); } public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
Change the following Go code into C# without altering its purpose.
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
Produce a functionally identical C# code for the snippet given in Go.
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
Preserve the algorithm and functionality while converting the code from Go to C#.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) var ten = big.NewInt(10) var twenty = big.NewInt(20) var hundred = big.NewInt(100) func sqrt(n float64, limit int) { if n < 0 { log.Fatal("Number cannot be negative") } count := 0 for n != math.Trunc(n) { n *= 100 count-- } i := big.NewInt(int64(n)) j := new(big.Int).Sqrt(i) count += len(j.String()) k := new(big.Int).Set(j) d := new(big.Int).Set(j) t := new(big.Int) digits := 0 var sb strings.Builder for digits < limit { sb.WriteString(d.String()) t.Mul(k, d) i.Sub(i, t) i.Mul(i, hundred) k.Mul(j, twenty) d.Set(one) for d.Cmp(ten) <= 0 { t.Add(k, d) t.Mul(t, d) if t.Cmp(i) > 0 { d.Sub(d, one) break } d.Add(d, one) } j.Mul(j, ten) j.Add(j, d) k.Add(k, d) digits = digits + 1 } root := strings.TrimRight(sb.String(), "0") if len(root) == 0 { root = "0" } if count > 0 { root = root[0:count] + "." + root[count:] } else if count == 0 { root = "0." + root } else { root = "0." + strings.Repeat("0", -count) + root } root = strings.TrimSuffix(root, ".") fmt.Println(root) } func main() { numbers := []float64{2, 0.2, 10.89, 625, 0.0001} digits := []int{500, 80, 8, 8, 8} for i, n := range numbers { fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n) sqrt(n, digits[i]) fmt.Println() } }
using System; using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { BI i, j, k, d; i = 2; int n = -1; int n0 = -1; j = (BI)Floor(Sqrt((double)i)); k = j; d = j; DateTime st = DateTime.Now; if (args.Length > 0) int.TryParse(args[0], out n); if (n > 0) n0 = n; else n = 1; do { Write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d++) if ((k + d) * d > i) { d -= 1; break; } j = j * 10 + d; k += d; if (n0 > 0) n--; } while (n > 0); if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); } }
Convert this Go snippet to C# and keep its semantics consistent.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) var ten = big.NewInt(10) var twenty = big.NewInt(20) var hundred = big.NewInt(100) func sqrt(n float64, limit int) { if n < 0 { log.Fatal("Number cannot be negative") } count := 0 for n != math.Trunc(n) { n *= 100 count-- } i := big.NewInt(int64(n)) j := new(big.Int).Sqrt(i) count += len(j.String()) k := new(big.Int).Set(j) d := new(big.Int).Set(j) t := new(big.Int) digits := 0 var sb strings.Builder for digits < limit { sb.WriteString(d.String()) t.Mul(k, d) i.Sub(i, t) i.Mul(i, hundred) k.Mul(j, twenty) d.Set(one) for d.Cmp(ten) <= 0 { t.Add(k, d) t.Mul(t, d) if t.Cmp(i) > 0 { d.Sub(d, one) break } d.Add(d, one) } j.Mul(j, ten) j.Add(j, d) k.Add(k, d) digits = digits + 1 } root := strings.TrimRight(sb.String(), "0") if len(root) == 0 { root = "0" } if count > 0 { root = root[0:count] + "." + root[count:] } else if count == 0 { root = "0." + root } else { root = "0." + strings.Repeat("0", -count) + root } root = strings.TrimSuffix(root, ".") fmt.Println(root) } func main() { numbers := []float64{2, 0.2, 10.89, 625, 0.0001} digits := []int{500, 80, 8, 8, 8} for i, n := range numbers { fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n) sqrt(n, digits[i]) fmt.Println() } }
using System; using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { BI i, j, k, d; i = 2; int n = -1; int n0 = -1; j = (BI)Floor(Sqrt((double)i)); k = j; d = j; DateTime st = DateTime.Now; if (args.Length > 0) int.TryParse(args[0], out n); if (n > 0) n0 = n; else n = 1; do { Write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d++) if ((k + d) * d > i) { d -= 1; break; } j = j * 10 + d; k += d; if (n0 > 0) n--; } while (n > 0); if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); } }
Change the programming language of this snippet from Go to C# without modifying what it does.
package main import ( "fmt" "rcu" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func permutations(input []int) [][]int { perms := [][]int{input} a := make([]int, len(input)) copy(a, input) var n = len(input) - 1 for c := 1; c < factorial(n+1); c++ { i := n - 1 j := n for a[i] > a[i+1] { i-- } for a[j] < a[i] { j-- } a[i], a[j] = a[j], a[i] j = n i += 1 for i < j { a[i], a[j] = a[j], a[i] i++ j-- } b := make([]int, len(input)) copy(b, a) perms = append(perms, b) } return perms } func main() { outer: for _, start := range []int{1, 0} { fmt.Printf("The largest pandigital decimal prime which uses all the digits %d..n once is:\n", start) for _, n := range []int{7, 4} { m := n + 1 - start list := make([]int, m) for i := 0; i < m; i++ { list[i] = i + start } perms := permutations(list) for i := len(perms) - 1; i >= 0; i-- { le := len(perms[i]) if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) { continue } p := 0 pow := 1 for j := le - 1; j >= 0; j-- { p += perms[i][j] * pow pow *= 10 } if rcu.IsPrime(p) { fmt.Println(rcu.Commatize(p) + "\n") continue outer } } } } }
using System; class Program { static void fun(char sp) { var sw = System.Diagnostics.Stopwatch.StartNew(); for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) { var s = x.ToString(); for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt; if (x % 3 == 0) continue; for (int i = 1; i * i < x; ) { if (x % (i += 4) == 0) goto nxt; if (x % (i += 2) == 0) goto nxt; } sw.Stop(); Console.WriteLine("{0}..7: {1,10:n0} {2} μs", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break; nxt: ; } } static void Main(string[] args) { fun('1'); fun('0'); } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import ( "fmt" "rcu" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func permutations(input []int) [][]int { perms := [][]int{input} a := make([]int, len(input)) copy(a, input) var n = len(input) - 1 for c := 1; c < factorial(n+1); c++ { i := n - 1 j := n for a[i] > a[i+1] { i-- } for a[j] < a[i] { j-- } a[i], a[j] = a[j], a[i] j = n i += 1 for i < j { a[i], a[j] = a[j], a[i] i++ j-- } b := make([]int, len(input)) copy(b, a) perms = append(perms, b) } return perms } func main() { outer: for _, start := range []int{1, 0} { fmt.Printf("The largest pandigital decimal prime which uses all the digits %d..n once is:\n", start) for _, n := range []int{7, 4} { m := n + 1 - start list := make([]int, m) for i := 0; i < m; i++ { list[i] = i + start } perms := permutations(list) for i := len(perms) - 1; i >= 0; i-- { le := len(perms[i]) if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) { continue } p := 0 pow := 1 for j := le - 1; j >= 0; j-- { p += perms[i][j] * pow pow *= 10 } if rcu.IsPrime(p) { fmt.Println(rcu.Commatize(p) + "\n") continue outer } } } } }
using System; class Program { static void fun(char sp) { var sw = System.Diagnostics.Stopwatch.StartNew(); for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) { var s = x.ToString(); for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt; if (x % 3 == 0) continue; for (int i = 1; i * i < x; ) { if (x % (i += 4) == 0) goto nxt; if (x % (i += 2) == 0) goto nxt; } sw.Stop(); Console.WriteLine("{0}..7: {1,10:n0} {2} μs", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break; nxt: ; } } static void Main(string[] args) { fun('1'); fun('0'); } }
Change the following Go code into C# without altering its purpose.
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } func main() { primes := rcu.Primes(999) var nonDesc []int for _, p := range primes { if nonDescending(p) { nonDesc = append(nonDesc, p) } } fmt.Println("Primes below 1,000 with digits in non-decreasing order:") for i, n := range nonDesc { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n%d such primes found.\n", len(nonDesc)) }
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; } static int to10(string s) { int res = 0; foreach (char i in s) res = res * ba + chars.IndexOf(i); return res; } static bool nd(string s) { if (s.Length < 2) return true; char l = s[0]; for (int i = 1; i < s.Length; i++) if (chars.IndexOf(l) > chars.IndexOf(s[i])) return false; else l = s[i] ; return true; } static void Main(string[] args) { int c, lim = 1000; string s; foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) { ba = b; c = 0; foreach (var a in PG.Primes(lim)) if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : ""); WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j; yield return 2; for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Maintain the same structure and functionality when rewriting this code in C#.
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } func main() { primes := rcu.Primes(999) var nonDesc []int for _, p := range primes { if nonDescending(p) { nonDesc = append(nonDesc, p) } } fmt.Println("Primes below 1,000 with digits in non-decreasing order:") for i, n := range nonDesc { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n%d such primes found.\n", len(nonDesc)) }
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; } static int to10(string s) { int res = 0; foreach (char i in s) res = res * ba + chars.IndexOf(i); return res; } static bool nd(string s) { if (s.Length < 2) return true; char l = s[0]; for (int i = 1; i < s.Length; i++) if (chars.IndexOf(l) > chars.IndexOf(s[i])) return false; else l = s[i] ; return true; } static void Main(string[] args) { int c, lim = 1000; string s; foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) { ba = b; c = 0; foreach (var a in PG.Primes(lim)) if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : ""); WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j; yield return 2; for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Translate the given Go code snippet into C# without altering its behavior.
package main import ( "fmt" "math" "rcu" ) func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false } func soms(n int, f []int) bool { if n <= 0 { return false } if contains(f, n) { return true } sum := rcu.SumInts(f) if n > sum { return false } if n == sum { return true } rf := make([]int, len(f)) copy(rf, f) for i, j := 0, len(rf)-1; i < j; i, j = i+1, j-1 { rf[i], rf[j] = rf[j], rf[i] } rf = rf[1:] return soms(n-f[len(f)-1], rf) || soms(n, rf) } func main() { var s, a []int sf := "\nStopped checking after finding %d sequential non-gaps after the final gap of %d\n" i, g := 1, 1 for g >= (i >> 1) { r := int(math.Sqrt(float64(i))) if r*r == i { s = append(s, i) } if !soms(i, s) { g = i a = append(a, g) } i++ } fmt.Println("Numbers which are not the sum of distinct squares:") fmt.Println(a) fmt.Printf(sf, i-g, g) fmt.Printf("Found %d in total\n", len(a)) } var r int
using System; using System.Collections.Generic; using System.Linq; class Program { static bool soms(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().Skip(1).ToList(); return soms(n - f.Last(), rf) || soms(n, rf); } return false; } static void Main() { var sw = System.Diagnostics.Stopwatch.StartNew(); int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>(); var sf = "stopped checking after finding {0} sequential non-gaps after the final gap of {1}"; for (i = 1, g = 1; g >= (i >> 1); i++) { if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i); if (!soms(i, s)) a.Add(g = i); } sw.Stop(); Console.WriteLine("Numbers which are not the sum of distinct squares:"); Console.WriteLine(string.Join(", ", a)); Console.WriteLine(sf, i - g, g); Console.Write("found {0} total in {1} ms", a.Count, sw.Elapsed.TotalMilliseconds); } }
Change the following Go code into C# without altering its purpose.
package main import ( "fmt" "rcu" ) func allButOneEven(prime int) bool { digits := rcu.Digits(prime, 10) digits = digits[:len(digits)-1] allEven := true for _, d := range digits { if d&1 == 1 { allEven = false break } } return allEven } func main() { const ( LIMIT = 999 LIMIT2 = 9999999999 MAX_DIGITS = 3 ) primes := rcu.Primes(LIMIT) var results []int for _, prime := range primes[1:] { if allButOneEven(prime) { results = append(results, prime) } } fmt.Println("Primes under", rcu.Commatize(LIMIT+1), "which contain only one odd digit:") for i, p := range results { fmt.Printf("%*s ", MAX_DIGITS, rcu.Commatize(p)) if (i+1)%9 == 0 { fmt.Println() } } fmt.Println("\nFound", len(results), "such primes.\n") primes = rcu.Primes(LIMIT2) count := 0 pow := 10 for _, prime := range primes[1:] { if allButOneEven(prime) { count++ } if prime > pow { fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow)) pow *= 10 } } fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow)) }
using System; using System.Collections.Generic; class Program { static List<uint> sieve(uint max, bool ordinary = false) { uint k = ((max - 3) >> 1) + 1, lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1; var pl = new List<uint> { }; var ic = new bool[k]; for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i]) for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true; if (ordinary) { pl.Add(2); for (uint i = 0, j = 3; i < k; i++, j += 2) if (!ic[i]) pl.Add(j); } else for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2) if (!ic[i]) { while ((t /= 10) > 0) if (((t % 10) & 1) == 1) goto skip; pl.Add(j); skip:; } return pl; } static void Main(string[] args) { var pl = sieve((uint)1e9); uint c = 0, l = 10, p = 1; Console.WriteLine("List of one-odd-digit primes < 1,000:"); for (int i = 0; pl[i] < 1000; i++) Console.Write("{0,3}{1}", pl[i], i % 9 == 8 ? "\n" : " "); string fmt = "\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})"; foreach (var itm in pl) if (itm < l) c++; else Console.Write(fmt, c++, p++, l, l *= 10); Console.Write(fmt, c++, p++, l); } }
Rewrite this program in C# while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "rcu" ) func allButOneEven(prime int) bool { digits := rcu.Digits(prime, 10) digits = digits[:len(digits)-1] allEven := true for _, d := range digits { if d&1 == 1 { allEven = false break } } return allEven } func main() { const ( LIMIT = 999 LIMIT2 = 9999999999 MAX_DIGITS = 3 ) primes := rcu.Primes(LIMIT) var results []int for _, prime := range primes[1:] { if allButOneEven(prime) { results = append(results, prime) } } fmt.Println("Primes under", rcu.Commatize(LIMIT+1), "which contain only one odd digit:") for i, p := range results { fmt.Printf("%*s ", MAX_DIGITS, rcu.Commatize(p)) if (i+1)%9 == 0 { fmt.Println() } } fmt.Println("\nFound", len(results), "such primes.\n") primes = rcu.Primes(LIMIT2) count := 0 pow := 10 for _, prime := range primes[1:] { if allButOneEven(prime) { count++ } if prime > pow { fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow)) pow *= 10 } } fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow)) }
using System; using System.Collections.Generic; class Program { static List<uint> sieve(uint max, bool ordinary = false) { uint k = ((max - 3) >> 1) + 1, lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1; var pl = new List<uint> { }; var ic = new bool[k]; for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i]) for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true; if (ordinary) { pl.Add(2); for (uint i = 0, j = 3; i < k; i++, j += 2) if (!ic[i]) pl.Add(j); } else for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2) if (!ic[i]) { while ((t /= 10) > 0) if (((t % 10) & 1) == 1) goto skip; pl.Add(j); skip:; } return pl; } static void Main(string[] args) { var pl = sieve((uint)1e9); uint c = 0, l = 10, p = 1; Console.WriteLine("List of one-odd-digit primes < 1,000:"); for (int i = 0; pl[i] < 1000; i++) Console.Write("{0,3}{1}", pl[i], i % 9 == 8 ? "\n" : " "); string fmt = "\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})"; foreach (var itm in pl) if (itm < l) c++; else Console.Write(fmt, c++, p++, l, l *= 10); Console.Write(fmt, c++, p++, l); } }
Translate this program into C# but keep the logic exactly as in Go.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i < n; i++ { f := t.Field(i) fmt.Printf("%-8s %-8v %-8t\n", f.Name, f.Type, f.PkgPath == "", ) } fmt.Println() }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetPropertyValues(t, flags)) { Console.WriteLine(prop); } foreach (var field in GetFieldValues(t, flags)) { Console.WriteLine(field); } } public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) => from p in typeof(T).GetProperties(flags) where p.GetIndexParameters().Length == 0 select (p.Name, p.GetValue(obj, null)); public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) => typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj))); class TestClass { private int privateField = 7; public int PublicNumber { get; } = 4; private int PrivateNumber { get; } = 2; } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import ( "fmt" "strings" ) const limit = 50000 var ( divs, subs []int mins [][]string ) func minsteps(n int) { if n == 1 { mins[1] = []string{} return } min := limit var p, q int var op byte for _, div := range divs { if n%div == 0 { d := n / div steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, div, '/' } } } for _, sub := range subs { if d := n - sub; d >= 1 { steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, sub, '-' } } } mins[n] = append(mins[n], fmt.Sprintf("%c%d -> %d", op, q, p)) mins[n] = append(mins[n], mins[p]...) } func main() { for r := 0; r < 2; r++ { divs = []int{2, 3} if r == 0 { subs = []int{1} } else { subs = []int{2} } mins = make([][]string, limit+1) fmt.Printf("With: Divisors: %v, Subtractors: %v =>\n", divs, subs) fmt.Println(" Minimum number of steps to diminish the following numbers down to 1 is:") for i := 1; i <= limit; i++ { minsteps(i) if i <= 10 { steps := len(mins[i]) plural := "s" if steps == 1 { plural = " " } fmt.Printf(" %2d: %d step%s: %s\n", i, steps, plural, strings.Join(mins[i], ", ")) } } for _, lim := range []int{2000, 20000, 50000} { max := 0 for _, min := range mins[0 : lim+1] { m := len(min) if m > max { max = m } } var maxs []int for i, min := range mins[0 : lim+1] { if len(min) == max { maxs = append(maxs, i) } } nums := len(maxs) verb, verb2, plural := "are", "have", "s" if nums == 1 { verb, verb2, plural = "is", "has", "" } fmt.Printf(" There %s %d number%s in the range 1-%d ", verb, nums, plural, lim) fmt.Printf("that %s maximum 'minimal steps' of %d:\n", verb2, max) fmt.Println(" ", maxs) } fmt.Println() } }
using System; using System.Collections.Generic; using System.Linq; public static class MinimalSteps { public static void Main() { var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 }); var lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); Console.WriteLine(); subtractors = new [] { 2 }; lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); } private static void PrintRange((char op, int param, int steps)[] lookup, int limit) { for (int goal = 1; goal <= limit; goal++) { var x = lookup[goal]; if (x.param == 0) { Console.WriteLine($"{goal} cannot be reached with these numbers."); continue; } Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: "); for (int n = goal; n > 1; ) { Console.Write($"{n},{x.op}{x.param}=> "); n = x.op == '/' ? n / x.param : n - x.param; x = lookup[n]; } Console.WriteLine("1"); } } private static void PrintMaxMins((char op, int param, int steps)[] lookup) { var maxSteps = lookup.Max(x => x.steps); var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList(); Console.WriteLine(items.Count == 1 ? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}" : $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}" ); } private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors) { var lookup = new (char op, int param, int steps)[goal+1]; lookup[1] = ('/', 1, 0); for (int n = 1; n < lookup.Length; n++) { var ln = lookup[n]; if (ln.param == 0) continue; for (int d = 0; d < divisors.Length; d++) { int target = n * divisors[d]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1); } for (int s = 0; s < subtractors.Length; s++) { int target = n + subtractors[s]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1); } } return lookup; } private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source); }
Write the same code in C# as shown below in Go.
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width); static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; string[][] table = new string[lines.Length][]; int columns = 0; for (int i = 0; i < lines.Length; i++) { string[] row = lines[i].TrimEnd(Separator).Split(Separator); if (columns < row.Length) columns = row.Length; table[i] = row; } string[][] formattedTable = new string[table.Length][]; for (int i = 0; i < formattedTable.Length; i++) { formattedTable[i] = new string[columns]; } for (int j = 0; j < columns; j++) { int columnWidth = 0; for (int i = 0; i < table.Length; i++) { if (j < table[i].Length && columnWidth < table[i][j].Length) columnWidth = table[i][j].Length; } for (int i = 0; i < formattedTable.Length; i++) { if (j < table[i].Length) formattedTable[i][j] = justification(table[i][j], columnWidth); else formattedTable[i][j] = new String(' ', columnWidth); } } string[] result = new string[formattedTable.Length]; for (int i = 0; i < result.Length; i++) { result[i] = String.Join(" ", formattedTable[i]); } return result; } static string JustifyLeft(string s, int width) { return s.PadRight(width); } static string JustifyRight(string s, int width) { return s.PadLeft(width); } static string JustifyCenter(string s, int width) { return s.PadLeft((width + s.Length) / 2).PadRight(width); } static void Main() { string[] input = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column.", }; foreach (string line in AlignColumns(input, JustifyCenter)) { Console.WriteLine(line); } } }
Change the following Go code into C# without altering its purpose.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Convert this Go snippet to C# and keep its semantics consistent.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Ensure the translated C# code behaves exactly like the original Go snippet.
package main import "rcu" func isIdoneal(n int) bool { for a := 1; a < n; a++ { for b := a + 1; b < n; b++ { if a*b+a+b > n { break } for c := b + 1; c < n; c++ { sum := a*b + b*c + a*c if sum == n { return false } if sum > n { break } } } } return true } func main() { var idoneals []int for n := 1; n <= 1850; n++ { if isIdoneal(n) { idoneals = append(idoneals, n) } } rcu.PrintTable(idoneals, 13, 4, false) }
using System; class Program { static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); int a, b, c, i, n, s3, ab; var res = new int[65]; for (n = 1, i = 0; n < 1850; n++) { bool found = true; for (a = 1; a < n; a++) for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) { if (ab > n) break; for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) { if (s3 == n) found = false; if (s3 >= n) break; } } if (found) res[i++] = n; } sw.Stop(); Console.WriteLine("The 65 known Idoneal numbers:"); for (i = 0; i < res.Length; i++) Console.Write("{0,5}{1}", res[i], i % 13 == 12 ? "\n" : ""); Console.Write("Calculations took {0} ms", sw.Elapsed.TotalMilliseconds); } }
Write the same algorithm in C# as shown in this Go implementation.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func convertToBase58(hash string, base int) (string, error) { var x, ok = new(big.Int).SetString(hash, base) if !ok { return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base) } var sb strings.Builder var rem = new(big.Int) for x.Cmp(big0) == 1 { x.QuoRem(x, big58, rem) r := rem.Int64() sb.WriteByte(alphabet[r]) } return reverse(sb.String()), nil } func main() { s := "25420294593250030202636073700053352635053786165627414518" b, err := convertToBase58(s, 10) if err != nil { log.Fatal(err) } fmt.Println(s, "->", b) hashes := [...]string{ "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", } for _, hash := range hashes { b58, err := convertToBase58(hash, 0) if err != nil { log.Fatal(err) } fmt.Printf("%-56s -> %s\n", hash, b58) } }
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
Generate a C# translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func convertToBase58(hash string, base int) (string, error) { var x, ok = new(big.Int).SetString(hash, base) if !ok { return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base) } var sb strings.Builder var rem = new(big.Int) for x.Cmp(big0) == 1 { x.QuoRem(x, big58, rem) r := rem.Int64() sb.WriteByte(alphabet[r]) } return reverse(sb.String()), nil } func main() { s := "25420294593250030202636073700053352635053786165627414518" b, err := convertToBase58(s, 10) if err != nil { log.Fatal(err) } fmt.Println(s, "->", b) hashes := [...]string{ "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", } for _, hash := range hashes { b58, err := convertToBase58(hash, 0) if err != nil { log.Fatal(err) } fmt.Printf("%-56s -> %s\n", hash, b58) } }
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
Convert this Go block to C#, preserving its control flow and logic.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) n := 0 for n < 1 || n > 5 { fmt.Print("How many integer variables do you want to create (max 5) : ") scanner.Scan() n, _ = strconv.Atoi(scanner.Text()) check(scanner.Err()) } vars := make(map[string]int) fmt.Println("OK, enter the variable names and their values, below") for i := 1; i <= n; { fmt.Println("\n Variable", i) fmt.Print(" Name  : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if _, ok := vars[name]; ok { fmt.Println(" Sorry, you've already created a variable of that name, try again") continue } var value int var err error for { fmt.Print(" Value : ") scanner.Scan() value, err = strconv.Atoi(scanner.Text()) check(scanner.Err()) if err != nil { fmt.Println(" Not a valid integer, try again") } else { break } } vars[name] = value i++ } fmt.Println("\nEnter q to quit") for { fmt.Print("\nWhich variable do you want to inspect : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if s := strings.ToLower(name); s == "q" { return } v, ok := vars[name] if !ok { fmt.Println("Sorry there's no variable of that name, try again") } else { fmt.Println("It's value is", v) } } }
using System; using System.Dynamic; using System.Collections.Generic; public class Program { public static void Main() { string varname = Console.ReadLine(); dynamic expando = new ExpandoObject(); var map = expando as IDictionary<string, object>; map.Add(varname, "Hello world!"); Console.WriteLine(expando.foo); } }
Generate an equivalent C# version of this Go code.
package main import ( "crypto/des" "encoding/hex" "fmt" "log" ) func main() { key, err := hex.DecodeString("0e329232ea6d0d73") if err != nil { log.Fatal(err) } c, err := des.NewCipher(key) if err != nil { log.Fatal(err) } src, err := hex.DecodeString("8787878787878787") if err != nil { log.Fatal(err) } dst := make([]byte, des.BlockSize) c.Encrypt(dst, src) fmt.Printf("%x\n", dst) }
using System; using System.IO; using System.Security.Cryptography; namespace DES { class Program { static string ByteArrayToString(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); } static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) { byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv); CryptoStreamMode mode = CryptoStreamMode.Write; MemoryStream memStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode); cryptoStream.Write(messageBytes, 0, messageBytes.Length); cryptoStream.FlushFinalBlock(); byte[] encryptedMessageBytes = new byte[memStream.Length]; memStream.Position = 0; memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length); return encryptedMessageBytes; } static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) { byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv); CryptoStreamMode mode = CryptoStreamMode.Write; MemoryStream memStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode); cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length); cryptoStream.FlushFinalBlock(); byte[] decryptedMessageBytes = new byte[memStream.Length]; memStream.Position = 0; memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length); return decryptedMessageBytes; } static void Main(string[] args) { byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 }; byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 }; byte[] encStr = Encrypt(plainBytes, keyBytes); Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr)); byte[] decBytes = Decrypt(encStr, keyBytes); Console.WriteLine("Decoded: {0}", ByteArrayToString(decBytes)); } } }
Port the provided Go code into C# while preserving the original functionality.
package main import ( "fmt" "math" ) type vector = []float64 type matrix []vector type fun = func(vector) float64 type funs = []fun type jacobian = []funs func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func (m1 matrix) sub(m2 matrix) matrix { rows, cols := len(m1), len(m1[0]) if rows != len(m2) || cols != len(m2[0]) { panic("Matrices cannot be subtracted.") } result := make(matrix, rows) for i := 0; i < rows; i++ { result[i] = make(vector, cols) for j := 0; j < cols; j++ { result[i][j] = m1[i][j] - m2[i][j] } } return result } func (m matrix) transpose() matrix { rows, cols := len(m), len(m[0]) trans := make(matrix, cols) for i := 0; i < cols; i++ { trans[i] = make(vector, rows) for j := 0; j < rows; j++ { trans[i][j] = m[j][i] } } return trans } func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(vector, 2*le) copy(aug[i], m[i]) aug[i][i+le] = 1 } aug.toReducedRowEchelonForm() inv := make(matrix, le) for i := 0; i < le; i++ { inv[i] = make(vector, le) copy(inv[i], aug[i][le:]) } return inv } func (m matrix) toReducedRowEchelonForm() { lead := 0 rowCount, colCount := len(m), len(m[0]) for r := 0; r < rowCount; r++ { if colCount <= lead { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if colCount == lead { return } } } m[i], m[r] = m[r], m[i] if div := m[r][lead]; div != 0 { for j := 0; j < colCount; j++ { m[r][j] /= div } } for k := 0; k < rowCount; k++ { if k != r { mult := m[k][lead] for j := 0; j < colCount; j++ { m[k][j] -= m[r][j] * mult } } } lead++ } } func solve(fs funs, jacob jacobian, guesses vector) vector { size := len(fs) var gu1 vector gu2 := make(vector, len(guesses)) copy(gu2, guesses) jac := make(matrix, size) for i := 0; i < size; i++ { jac[i] = make(vector, size) } tol := 1e-8 maxIter := 12 iter := 0 for { gu1 = gu2 g := matrix{gu1}.transpose() t := make(vector, size) for i := 0; i < size; i++ { t[i] = fs[i](gu1) } f := matrix{t}.transpose() for i := 0; i < size; i++ { for j := 0; j < size; j++ { jac[i][j] = jacob[i][j](gu1) } } g1 := g.sub(jac.inverse().mul(f)) gu2 = make(vector, size) for i := 0; i < size; i++ { gu2[i] = g1[i][0] } iter++ any := false for i, v := range gu2 { if math.Abs(v)-gu1[i] > tol { any = true break } } if !any || iter >= maxIter { break } } return gu2 } func main() { f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] } f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] } fs := funs{f1, f2} jacob := jacobian{ funs{ func(x vector) float64 { return -2*x[0] + 1 }, func(x vector) float64 { return -1 }, }, funs{ func(x vector) float64 { return 5*x[1] - 2*x[0] }, func(x vector) float64 { return 1 + 5*x[0] }, }, } guesses := vector{1.2, 1.2} sol := solve(fs, jacob, guesses) fmt.Printf("Approximate solutions are x = %.7f, y = %.7f\n", sol[0], sol[1]) fmt.Println() f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 } f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] } f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] } fs = funs{f3, f4, f5} jacob = jacobian{ funs{ func(x vector) float64 { return 18 * x[0] }, func(x vector) float64 { return 72 * x[1] }, func(x vector) float64 { return 8 * x[2] }, }, funs{ func(x vector) float64 { return 2 * x[0] }, func(x vector) float64 { return -4 * x[1] }, func(x vector) float64 { return -20 }, }, funs{ func(x vector) float64 { return 2 * x[0] }, func(x vector) float64 { return -2 * x[1] }, func(x vector) float64 { return 2 * x[2] }, }, } guesses = vector{1, 1, 0} sol = solve(fs, jacob, guesses) fmt.Printf("Approximate solutions are x = %.7f, y = %.7f, z = %.7f\n", sol[0], sol[1], sol[2]) }
using System; namespace Rosetta { internal interface IFun { double F(int index, Vector x); double df(int index, int derivative, Vector x); double[] weights(); } class Newton { internal Vector Do(int size, IFun fun, Vector start) { Vector X = start.Clone(); Vector F = new Vector(size); Matrix J = new Matrix(size, size); Vector D; do { for (int i = 0; i < size; i++) F[i] = fun.F(i, X); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) J[i, j] = fun.df(i, j, X); J.ElimPartial(F); X -= F; } while (F.norm(fun.weights()) > 1e-12); return X; } } }
Port the following code from Go to C# with equivalent syntax and logic.
package main import ( "fmt" "math" ) type vector = []float64 type matrix []vector type fun = func(vector) float64 type funs = []fun type jacobian = []funs func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func (m1 matrix) sub(m2 matrix) matrix { rows, cols := len(m1), len(m1[0]) if rows != len(m2) || cols != len(m2[0]) { panic("Matrices cannot be subtracted.") } result := make(matrix, rows) for i := 0; i < rows; i++ { result[i] = make(vector, cols) for j := 0; j < cols; j++ { result[i][j] = m1[i][j] - m2[i][j] } } return result } func (m matrix) transpose() matrix { rows, cols := len(m), len(m[0]) trans := make(matrix, cols) for i := 0; i < cols; i++ { trans[i] = make(vector, rows) for j := 0; j < rows; j++ { trans[i][j] = m[j][i] } } return trans } func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(vector, 2*le) copy(aug[i], m[i]) aug[i][i+le] = 1 } aug.toReducedRowEchelonForm() inv := make(matrix, le) for i := 0; i < le; i++ { inv[i] = make(vector, le) copy(inv[i], aug[i][le:]) } return inv } func (m matrix) toReducedRowEchelonForm() { lead := 0 rowCount, colCount := len(m), len(m[0]) for r := 0; r < rowCount; r++ { if colCount <= lead { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if colCount == lead { return } } } m[i], m[r] = m[r], m[i] if div := m[r][lead]; div != 0 { for j := 0; j < colCount; j++ { m[r][j] /= div } } for k := 0; k < rowCount; k++ { if k != r { mult := m[k][lead] for j := 0; j < colCount; j++ { m[k][j] -= m[r][j] * mult } } } lead++ } } func solve(fs funs, jacob jacobian, guesses vector) vector { size := len(fs) var gu1 vector gu2 := make(vector, len(guesses)) copy(gu2, guesses) jac := make(matrix, size) for i := 0; i < size; i++ { jac[i] = make(vector, size) } tol := 1e-8 maxIter := 12 iter := 0 for { gu1 = gu2 g := matrix{gu1}.transpose() t := make(vector, size) for i := 0; i < size; i++ { t[i] = fs[i](gu1) } f := matrix{t}.transpose() for i := 0; i < size; i++ { for j := 0; j < size; j++ { jac[i][j] = jacob[i][j](gu1) } } g1 := g.sub(jac.inverse().mul(f)) gu2 = make(vector, size) for i := 0; i < size; i++ { gu2[i] = g1[i][0] } iter++ any := false for i, v := range gu2 { if math.Abs(v)-gu1[i] > tol { any = true break } } if !any || iter >= maxIter { break } } return gu2 } func main() { f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] } f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] } fs := funs{f1, f2} jacob := jacobian{ funs{ func(x vector) float64 { return -2*x[0] + 1 }, func(x vector) float64 { return -1 }, }, funs{ func(x vector) float64 { return 5*x[1] - 2*x[0] }, func(x vector) float64 { return 1 + 5*x[0] }, }, } guesses := vector{1.2, 1.2} sol := solve(fs, jacob, guesses) fmt.Printf("Approximate solutions are x = %.7f, y = %.7f\n", sol[0], sol[1]) fmt.Println() f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 } f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] } f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] } fs = funs{f3, f4, f5} jacob = jacobian{ funs{ func(x vector) float64 { return 18 * x[0] }, func(x vector) float64 { return 72 * x[1] }, func(x vector) float64 { return 8 * x[2] }, }, funs{ func(x vector) float64 { return 2 * x[0] }, func(x vector) float64 { return -4 * x[1] }, func(x vector) float64 { return -20 }, }, funs{ func(x vector) float64 { return 2 * x[0] }, func(x vector) float64 { return -2 * x[1] }, func(x vector) float64 { return 2 * x[2] }, }, } guesses = vector{1, 1, 0} sol = solve(fs, jacob, guesses) fmt.Printf("Approximate solutions are x = %.7f, y = %.7f, z = %.7f\n", sol[0], sol[1], sol[2]) }
using System; namespace Rosetta { internal interface IFun { double F(int index, Vector x); double df(int index, int derivative, Vector x); double[] weights(); } class Newton { internal Vector Do(int size, IFun fun, Vector start) { Vector X = start.Clone(); Vector F = new Vector(size); Matrix J = new Matrix(size, size); Vector D; do { for (int i = 0; i < size; i++) F[i] = fun.F(i, X); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) J[i, j] = fun.df(i, j, X); J.ElimPartial(F); X -= F; } while (F.norm(fun.weights()) > 1e-12); return X; } } }
Transform the following Go implementation into C#, maintaining the same output and logic.
package main import ( "fmt" "math" ) type vector = []float64 type matrix []vector type fun = func(vector) float64 type funs = []fun type jacobian = []funs func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func (m1 matrix) sub(m2 matrix) matrix { rows, cols := len(m1), len(m1[0]) if rows != len(m2) || cols != len(m2[0]) { panic("Matrices cannot be subtracted.") } result := make(matrix, rows) for i := 0; i < rows; i++ { result[i] = make(vector, cols) for j := 0; j < cols; j++ { result[i][j] = m1[i][j] - m2[i][j] } } return result } func (m matrix) transpose() matrix { rows, cols := len(m), len(m[0]) trans := make(matrix, cols) for i := 0; i < cols; i++ { trans[i] = make(vector, rows) for j := 0; j < rows; j++ { trans[i][j] = m[j][i] } } return trans } func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(vector, 2*le) copy(aug[i], m[i]) aug[i][i+le] = 1 } aug.toReducedRowEchelonForm() inv := make(matrix, le) for i := 0; i < le; i++ { inv[i] = make(vector, le) copy(inv[i], aug[i][le:]) } return inv } func (m matrix) toReducedRowEchelonForm() { lead := 0 rowCount, colCount := len(m), len(m[0]) for r := 0; r < rowCount; r++ { if colCount <= lead { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if colCount == lead { return } } } m[i], m[r] = m[r], m[i] if div := m[r][lead]; div != 0 { for j := 0; j < colCount; j++ { m[r][j] /= div } } for k := 0; k < rowCount; k++ { if k != r { mult := m[k][lead] for j := 0; j < colCount; j++ { m[k][j] -= m[r][j] * mult } } } lead++ } } func solve(fs funs, jacob jacobian, guesses vector) vector { size := len(fs) var gu1 vector gu2 := make(vector, len(guesses)) copy(gu2, guesses) jac := make(matrix, size) for i := 0; i < size; i++ { jac[i] = make(vector, size) } tol := 1e-8 maxIter := 12 iter := 0 for { gu1 = gu2 g := matrix{gu1}.transpose() t := make(vector, size) for i := 0; i < size; i++ { t[i] = fs[i](gu1) } f := matrix{t}.transpose() for i := 0; i < size; i++ { for j := 0; j < size; j++ { jac[i][j] = jacob[i][j](gu1) } } g1 := g.sub(jac.inverse().mul(f)) gu2 = make(vector, size) for i := 0; i < size; i++ { gu2[i] = g1[i][0] } iter++ any := false for i, v := range gu2 { if math.Abs(v)-gu1[i] > tol { any = true break } } if !any || iter >= maxIter { break } } return gu2 } func main() { f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] } f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] } fs := funs{f1, f2} jacob := jacobian{ funs{ func(x vector) float64 { return -2*x[0] + 1 }, func(x vector) float64 { return -1 }, }, funs{ func(x vector) float64 { return 5*x[1] - 2*x[0] }, func(x vector) float64 { return 1 + 5*x[0] }, }, } guesses := vector{1.2, 1.2} sol := solve(fs, jacob, guesses) fmt.Printf("Approximate solutions are x = %.7f, y = %.7f\n", sol[0], sol[1]) fmt.Println() f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 } f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] } f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] } fs = funs{f3, f4, f5} jacob = jacobian{ funs{ func(x vector) float64 { return 18 * x[0] }, func(x vector) float64 { return 72 * x[1] }, func(x vector) float64 { return 8 * x[2] }, }, funs{ func(x vector) float64 { return 2 * x[0] }, func(x vector) float64 { return -4 * x[1] }, func(x vector) float64 { return -20 }, }, funs{ func(x vector) float64 { return 2 * x[0] }, func(x vector) float64 { return -2 * x[1] }, func(x vector) float64 { return 2 * x[2] }, }, } guesses = vector{1, 1, 0} sol = solve(fs, jacob, guesses) fmt.Printf("Approximate solutions are x = %.7f, y = %.7f, z = %.7f\n", sol[0], sol[1], sol[2]) }
using System; namespace Rosetta { internal interface IFun { double F(int index, Vector x); double df(int index, int derivative, Vector x); double[] weights(); } class Newton { internal Vector Do(int size, IFun fun, Vector start) { Vector X = start.Clone(); Vector F = new Vector(size); Matrix J = new Matrix(size, size); Vector D; do { for (int i = 0; i < size; i++) F[i] = fun.F(i, X); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) J[i, j] = fun.df(i, j, X); J.ElimPartial(F); X -= F; } while (F.norm(fun.weights()) > 1e-12); return X; } } }
Keep all operations the same but rewrite the snippet in C#.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) type vector = []*big.Int type matrix []vector var ( zero = new(big.Int) one = big.NewInt(1) ) func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) temp := new(big.Int) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { result[i][j] = new(big.Int) for k := 0; k < rows2; k++ { temp.Mul(m1[i][k], m2[k][j]) result[i][j].Add(result[i][j], temp) } } } return result } func identityMatrix(n uint64) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := uint64(0); i < n; i++ { ident[i] = make(vector, n) for j := uint64(0); j < n; j++ { ident[i][j] = new(big.Int) if i == j { ident[i][j].Set(one) } } } return ident } func (m matrix) pow(n *big.Int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n.Cmp(zero) == -1: panic("Negative exponents not supported") case n.Cmp(zero) == 0: return identityMatrix(uint64(le)) case n.Cmp(one) == 0: return m } pow := identityMatrix(uint64(le)) base := m e := new(big.Int).Set(n) temp := new(big.Int) for e.Cmp(zero) > 0 { temp.And(e, one) if temp.Cmp(one) == 0 { pow = pow.mul(base) } e.Rsh(e, 1) base = base.mul(base) } return pow } func fibonacci(n *big.Int) *big.Int { if n.Cmp(zero) == 0 { return zero } m := matrix{{one, one}, {one, zero}} m = m.pow(n.Sub(n, one)) return m[0][0] } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() n := new(big.Int) for i := uint64(10); i <= 1e7; i *= 10 { n.SetUint64(i) s := fibonacci(n).String() fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n", commatize(i), commatize(uint64(len(s)))) if len(s) > 20 { fmt.Printf(" First 20 : %s\n", s[0:20]) if len(s) < 40 { fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:]) } else { fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) } } else { fmt.Printf(" All %-2d  : %s\n", len(s), s) } fmt.Println() } sfxs := []string{"nd", "th"} for i, e := range []uint{16, 32} { n.Lsh(one, e) s := fibonacci(n).String() fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i], commatize(uint64(len(s)))) fmt.Printf(" First 20 : %s\n", s[0:20]) fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) fmt.Println() } fmt.Printf("Took %s\n\n", time.Since(start)) }
using System; using System.IO; using System.Numerics; using System.Threading; using System.Diagnostics; using System.Globalization; namespace Fibonacci { class Program { private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } }; private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" }; private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B) { if (A.GetLength(1) != B.GetLength(0)) { throw new ArgumentException("Illegal matrix dimensions for multiplication."); } var C = new BigInteger[A.GetLength(0), B.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < B.GetLength(1); ++j) { for (int k = 0; k < A.GetLength(1); ++k) { C[i, j] += A[i, k] * B[k, j]; } } } return C; } private static BigInteger[,] Power(in BigInteger[,] A, ulong n) { if (A.GetLength(1) != A.GetLength(0)) { throw new ArgumentException("Not a square matrix."); } var C = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { C[i, i] = BigInteger.One; } if (0 == n) return C; var S = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < A.GetLength(1); ++j) { S[i, j] = A[i, j]; } } while (0 < n) { if (1 == n % 2) C = Multiply(C, S); S = Multiply(S,S); n /= 2; } return C; } public static BigInteger Fib(in ulong n) { var C = Power(F, n); return C[0, 1]; } public static void Task(in ulong p) { var ans = Fib(p).ToString(); var sp = p.ToString("N0", nfi); if (ans.Length <= 40) { Console.WriteLine("Fibonacci({0}) = {1}", sp, ans); } else { Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]); } } public static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (ulong p = 10; p <= 10_000_000; p *= 10) { Task(p); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Took " + elapsedTime); } } }
Can you help me rewrite this code in C# instead of Go, keeping it the same logically?
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) type vector = []*big.Int type matrix []vector var ( zero = new(big.Int) one = big.NewInt(1) ) func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) temp := new(big.Int) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { result[i][j] = new(big.Int) for k := 0; k < rows2; k++ { temp.Mul(m1[i][k], m2[k][j]) result[i][j].Add(result[i][j], temp) } } } return result } func identityMatrix(n uint64) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := uint64(0); i < n; i++ { ident[i] = make(vector, n) for j := uint64(0); j < n; j++ { ident[i][j] = new(big.Int) if i == j { ident[i][j].Set(one) } } } return ident } func (m matrix) pow(n *big.Int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n.Cmp(zero) == -1: panic("Negative exponents not supported") case n.Cmp(zero) == 0: return identityMatrix(uint64(le)) case n.Cmp(one) == 0: return m } pow := identityMatrix(uint64(le)) base := m e := new(big.Int).Set(n) temp := new(big.Int) for e.Cmp(zero) > 0 { temp.And(e, one) if temp.Cmp(one) == 0 { pow = pow.mul(base) } e.Rsh(e, 1) base = base.mul(base) } return pow } func fibonacci(n *big.Int) *big.Int { if n.Cmp(zero) == 0 { return zero } m := matrix{{one, one}, {one, zero}} m = m.pow(n.Sub(n, one)) return m[0][0] } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() n := new(big.Int) for i := uint64(10); i <= 1e7; i *= 10 { n.SetUint64(i) s := fibonacci(n).String() fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n", commatize(i), commatize(uint64(len(s)))) if len(s) > 20 { fmt.Printf(" First 20 : %s\n", s[0:20]) if len(s) < 40 { fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:]) } else { fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) } } else { fmt.Printf(" All %-2d  : %s\n", len(s), s) } fmt.Println() } sfxs := []string{"nd", "th"} for i, e := range []uint{16, 32} { n.Lsh(one, e) s := fibonacci(n).String() fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i], commatize(uint64(len(s)))) fmt.Printf(" First 20 : %s\n", s[0:20]) fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) fmt.Println() } fmt.Printf("Took %s\n\n", time.Since(start)) }
using System; using System.IO; using System.Numerics; using System.Threading; using System.Diagnostics; using System.Globalization; namespace Fibonacci { class Program { private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } }; private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" }; private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B) { if (A.GetLength(1) != B.GetLength(0)) { throw new ArgumentException("Illegal matrix dimensions for multiplication."); } var C = new BigInteger[A.GetLength(0), B.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < B.GetLength(1); ++j) { for (int k = 0; k < A.GetLength(1); ++k) { C[i, j] += A[i, k] * B[k, j]; } } } return C; } private static BigInteger[,] Power(in BigInteger[,] A, ulong n) { if (A.GetLength(1) != A.GetLength(0)) { throw new ArgumentException("Not a square matrix."); } var C = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { C[i, i] = BigInteger.One; } if (0 == n) return C; var S = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < A.GetLength(1); ++j) { S[i, j] = A[i, j]; } } while (0 < n) { if (1 == n % 2) C = Multiply(C, S); S = Multiply(S,S); n /= 2; } return C; } public static BigInteger Fib(in ulong n) { var C = Power(F, n); return C[0, 1]; } public static void Task(in ulong p) { var ans = Fib(p).ToString(); var sp = p.ToString("N0", nfi); if (ans.Length <= 40) { Console.WriteLine("Fibonacci({0}) = {1}", sp, ans); } else { Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]); } } public static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (ulong p = 10; p <= 10_000_000; p *= 10) { Task(p); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Took " + elapsedTime); } } }
Write the same algorithm in C# as shown in this Go implementation.
package main import "fmt" func reverse(n uint64) uint64 { r := uint64(0) for n > 0 { r = n%10 + r*10 n /= 10 } return r } func main() { pow := uint64(10) nextN: for n := 2; n < 10; n++ { low := pow * 9 pow *= 10 high := pow - 1 fmt.Printf("Largest palindromic product of two %d-digit integers: ", n) for i := high; i >= low; i-- { j := reverse(i) p := i*pow + j for k := high; k > low; k -= 2 { if k % 10 == 5 { continue } l := p / k if l > high { break } if p%k == 0 { fmt.Printf("%d x %d = %d\n", k, l, p) continue nextN } } } } }
using System; class Program { static bool isPal(int n) { int rev = 0, lr = -1, rem; while (n > rev) { n = Math.DivRem(n, 10, out rem); if (lr < 0 && rem == 0) return false; lr = rev; rev = 10 * rev + rem; if (n == rev || n == lr) return true; } return false; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c; var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = ""; y /= 11; if ((y & 1) == 0) y--; if (y % 5 == 0) y -= 2; y *= 11; while (y <= max) { c = 0; y10 = y * 10; z = max9 + a[ld = y % 10]; p = y * z; while (p >= bp) { if (isPal(p)) { if (p > bp) bp = p; bs = string.Format("{0} x {1} = {2}", y, z - c, bp); } p -= y10; c += 10; } y += ld == 3 ? 44 : 22; } sw.Stop(); Console.Write("{0} {1} μs", bs, sw.Elapsed.TotalMilliseconds * 1000.0); } }
Write the same code in C# as shown below in Go.
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatize(s string, startIndex, period int, sep string) string { if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" { return s } m := reg.FindString(s[startIndex:]) if m == "" { return s } splits := strings.Split(m, ".") ip := splits[0] if len(ip) > period { pi := reverse(ip) for i := (len(ip) - 1) / period * period; i >= period; i -= period { pi = pi[:i] + sep + pi[i:] } ip = reverse(pi) } if strings.Contains(m, ".") { dp := splits[1] if len(dp) > period { for i := (len(dp) - 1) / period * period; i >= period; i -= period { dp = dp[:i] + sep + dp[i:] } } ip += "." + dp } return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1) } func main() { tests := [...]string{ "123456789.123456789", ".123456789", "57256.1D-4", "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "-in Aus$+1411.8millions", "===US$0017440 millions=== (in 2000 dollars)", "123.e8000 is pretty big.", "The land area of the earth is 57268900(29% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are " + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + " protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some.", } fmt.Println(commatize(tests[0], 0, 2, "*")) fmt.Println(commatize(tests[1], 0, 3, "-")) fmt.Println(commatize(tests[2], 0, 4, "__")) fmt.Println(commatize(tests[3], 0, 5, " ")) fmt.Println(commatize(tests[4], 0, 3, ".")) for _, test := range tests[5:] { fmt.Println(commatize(test, 0, 3, ",")) } }
static string[] inputs = { "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "\"-in Aus$+1411.8millions\"", "===US$0017440 millions=== (in 2000 dollars)" }; void Main() { inputs.Select(s => Commatize(s, 0, 3, ",")) .ToList() .ForEach(Console.WriteLine); } string Commatize(string text, int startPosition, int interval, string separator) { var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*"); var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList(); return string.Join("", x); } string Commatize(Match match, int interval, string separator, string original) { if (match.Length <= interval) return original.Substring(match.Index, match.Index == original.Length ? 0 : Math.Max(match.Length, 1)); return string.Join(separator, match.Value.Split(interval)); } public static class Extension { public static string[] Split(this string source, int interval) { return SplitImpl(source, interval).ToArray(); } static IEnumerable<string>SplitImpl(string source, int interval) { for (int i = 1; i < source.Length; i++) { if (i % interval != 0) continue; yield return source.Substring(i - interval, interval); } } }
Port the provided Go code into C# while preserving the original functionality.
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } return cf } func arithmethic_coding(str string, radix int64) (*big.Int, *big.Int, map[byte]int64) { chars := []byte(str) freq := make(map[byte]int64) for _, c := range chars { freq[c] += 1 } cf := cumulative_freq(freq) base := len(chars) L := big.NewInt(0) pf := big.NewInt(1) bigBase := big.NewInt(int64(base)) for _, c := range chars { x := big.NewInt(cf[c]) L.Mul(L, bigBase) L.Add(L, x.Mul(x, pf)) pf.Mul(pf, big.NewInt(freq[c])) } U := big.NewInt(0) U.Set(L) U.Add(U, pf) bigOne := big.NewInt(1) bigZero := big.NewInt(0) bigRadix := big.NewInt(radix) tmp := big.NewInt(0).Set(pf) powr := big.NewInt(0) for { tmp.Div(tmp, bigRadix) if tmp.Cmp(bigZero) == 0 { break } powr.Add(powr, bigOne) } diff := big.NewInt(0) diff.Sub(U, bigOne) diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil)) return diff, powr, freq } func arithmethic_decoding(num *big.Int, radix int64, pow *big.Int, freq map[byte]int64) string { powr := big.NewInt(radix) enc := big.NewInt(0).Set(num) enc.Mul(enc, powr.Exp(powr, pow, nil)) base := int64(0) for _, v := range freq { base += v } cf := cumulative_freq(freq) dict := make(map[int64]byte) for k, v := range cf { dict[v] = k } lchar := -1 for i := int64(0); i < base; i++ { if v, ok := dict[i]; ok { lchar = int(v) } else if lchar != -1 { dict[i] = byte(lchar) } } decoded := make([]byte, base) bigBase := big.NewInt(base) for i := base - 1; i >= 0; i-- { pow := big.NewInt(0) pow.Exp(bigBase, big.NewInt(i), nil) div := big.NewInt(0) div.Div(enc, pow) c := dict[div.Int64()] fv := freq[c] cv := cf[c] prod := big.NewInt(0).Mul(pow, big.NewInt(cv)) diff := big.NewInt(0).Sub(enc, prod) enc.Div(diff, big.NewInt(fv)) decoded[base-i-1] = c } return string(decoded) } func main() { var radix = int64(10) strSlice := []string{ `DABDDB`, `DABDDBBDDBA`, `ABRACADABRA`, `TOBEORNOTTOBEORTOBEORNOT`, } for _, str := range strSlice { enc, pow, freq := arithmethic_coding(str, radix) dec := arithmethic_decoding(enc, radix, pow, freq) fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow) if str != dec { panic("\tHowever that is incorrect!") } } }
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; namespace AruthmeticCoding { using Freq = Dictionary<char, long>; using Triple = Tuple<BigInteger, int, Dictionary<char, long>>; class Program { static Freq CumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; i++) { char c = (char)i; if (freq.ContainsKey(c)) { long v = freq[c]; cf[c] = total; total += v; } } return cf; } static Triple ArithmeticCoding(string str, long radix) { Freq freq = new Freq(); foreach (char c in str) { if (freq.ContainsKey(c)) { freq[c] += 1; } else { freq[c] = 1; } } Freq cf = CumulativeFreq(freq); BigInteger @base = str.Length; BigInteger lower = 0; BigInteger pf = 1; foreach (char c in str) { BigInteger x = cf[c]; lower = lower * @base + x * pf; pf = pf * freq[c]; } BigInteger upper = lower + pf; int powr = 0; BigInteger bigRadix = radix; while (true) { pf = pf / bigRadix; if (pf == 0) break; powr++; } BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)); return new Triple(diff, powr, freq); } static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = radix; BigInteger enc = num * BigInteger.Pow(powr, pwr); long @base = freq.Values.Sum(); Freq cf = CumulativeFreq(freq); Dictionary<long, char> dict = new Dictionary<long, char>(); foreach (char key in cf.Keys) { long value = cf[key]; dict[value] = key; } long lchar = -1; for (long i = 0; i < @base; i++) { if (dict.ContainsKey(i)) { lchar = dict[i]; } else if (lchar != -1) { dict[i] = (char)lchar; } } StringBuilder decoded = new StringBuilder((int)@base); BigInteger bigBase = @base; for (long i = @base - 1; i >= 0; --i) { BigInteger pow = BigInteger.Pow(bigBase, (int)i); BigInteger div = enc / pow; char c = dict[(long)div]; BigInteger fv = freq[c]; BigInteger cv = cf[c]; BigInteger diff = enc - pow * cv; enc = diff / fv; decoded.Append(c); } return decoded.ToString(); } static void Main(string[] args) { long radix = 10; string[] strings = { "DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT" }; foreach (string str in strings) { Triple encoded = ArithmeticCoding(str, radix); string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3); Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", str, encoded.Item1, radix, encoded.Item2); if (str != dec) { throw new Exception("\tHowever that is incorrect!"); } } } } }
Translate the given Go code snippet into C# without altering its behavior.
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(L) t := make([][]int, len(g)) var Visit func(int) Visit = func(u int) { if !vis[u] { vis[u] = true for _, v := range g[u] { Visit(v) t[v] = append(t[v], u) } x-- L[x] = u } } for u := range g { Visit(u) } c := make([]int, len(g)) var Assign func(int, int) Assign = func(u, root int) { if vis[u] { vis[u] = false c[u] = root for _, v := range t[u] { Assign(v, root) } } } for _, u := range L { Assign(u, u) } return c }
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
Translate this program into C# but keep the logic exactly as in Go.
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(L) t := make([][]int, len(g)) var Visit func(int) Visit = func(u int) { if !vis[u] { vis[u] = true for _, v := range g[u] { Visit(v) t[v] = append(t[v], u) } x-- L[x] = u } } for u := range g { Visit(u) } c := make([]int, len(g)) var Assign func(int, int) Assign = func(u, root int) { if vis[u] { vis[u] = false c[u] = root for _, v := range t[u] { Assign(v, root) } } } for _, u := range L { Assign(u, u) } return c }
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
Transform the following Go implementation into C#, maintaining the same output and logic.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := reflect.ValueOf(x) t := reflect.TypeOf(x) n := t.NumMethod() fmt.Printf("Type %v has %d exported methods:\n", t, n) const format = "%-6s %-46s %s\n" fmt.Printf(format, "Name", "Method expression", "Method value") for i := 0; i < n; i++ { fmt.Printf(format, t.Method(i).Name, t.Method(i).Func.Type(), v.Method(i).Type(), ) } fmt.Println() }
using System; using System.Reflection; public class Rosetta { public static void Main() { BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; foreach (var method in typeof(TestForMethodReflection).GetMethods(flags)) Console.WriteLine(method); } class TestForMethodReflection { public void MyPublicMethod() {} private void MyPrivateMethod() {} public static void MyPublicStaticMethod() {} private static void MyPrivateStaticMethod() {} } }
Translate this program into C# but keep the logic exactly as in Go.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
using System; class Example { public int foo(int x) { return 42 + x; } } class Program { static void Main(string[] args) { var example = new Example(); var method = "foo"; var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 }); Console.WriteLine("{0}(5) = {1}", method, result); } }
Transform the following Go implementation into C#, maintaining the same output and logic.
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := <-solution: print12("solution", s) case m := <-nearMiss: ms = append(ms, m) } } for _, m := range ms { print12("near miss", m) } } func print12(label string, bits int) { fmt.Print(label, ":") for i := 1; i <= 12; i++ { if bits&1 == 1 { fmt.Print(" ", i) } bits >>= 1 } fmt.Println() } func checkPerm(tz int) { ts := func(n uint) bool { return tz>>(n-1)&1 == 1 } ntrue := func(xs ...uint) int { nt := 0 for _, x := range xs { if ts(x) { nt++ } } return nt } var con bool test := func(statement uint, b bool) { switch { case ts(statement) == b: case con: panic("bail") default: con = true } } defer func() { if x := recover(); x != nil { if msg, ok := x.(string); !ok && msg != "bail" { panic(x) } } done <- true }() test(1, true) test(2, ntrue(7, 8, 9, 10, 11, 12) == 3) test(3, ntrue(2, 4, 6, 8, 10, 12) == 2) test(4, !ts(5) || ts(6) && ts(7)) test(5, !ts(4) && !ts(3) && !ts(2)) test(6, ntrue(1, 3, 5, 7, 9, 11) == 4) test(7, ts(2) != ts(3)) test(8, !ts(7) || ts(5) && ts(6)) test(9, ntrue(1, 2, 3, 4, 5, 6) == 3) test(10, ts(11) && ts(12)) test(11, ntrue(7, 8, 9) == 1) test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4) if con { nearMiss <- tz } else { solution <- tz } }
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
Change the programming language of this snippet from Go to C# without modifying what it does.
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := <-solution: print12("solution", s) case m := <-nearMiss: ms = append(ms, m) } } for _, m := range ms { print12("near miss", m) } } func print12(label string, bits int) { fmt.Print(label, ":") for i := 1; i <= 12; i++ { if bits&1 == 1 { fmt.Print(" ", i) } bits >>= 1 } fmt.Println() } func checkPerm(tz int) { ts := func(n uint) bool { return tz>>(n-1)&1 == 1 } ntrue := func(xs ...uint) int { nt := 0 for _, x := range xs { if ts(x) { nt++ } } return nt } var con bool test := func(statement uint, b bool) { switch { case ts(statement) == b: case con: panic("bail") default: con = true } } defer func() { if x := recover(); x != nil { if msg, ok := x.(string); !ok && msg != "bail" { panic(x) } } done <- true }() test(1, true) test(2, ntrue(7, 8, 9, 10, 11, 12) == 3) test(3, ntrue(2, 4, 6, 8, 10, 12) == 2) test(4, !ts(5) || ts(6) && ts(7)) test(5, !ts(4) && !ts(3) && !ts(2)) test(6, ntrue(1, 3, 5, 7, 9, 11) == 4) test(7, ts(2) != ts(3)) test(8, !ts(7) || ts(5) && ts(6)) test(9, ntrue(1, 2, 3, 4, 5, 6) == 3) test(10, ts(11) && ts(12)) test(11, ntrue(7, 8, 9) == 1) test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4) if con { nearMiss <- tz } else { solution <- tz } }
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
Translate this program into C# but keep the logic exactly as in Go.
package main import ( "bufio" "fmt" "log" "os" ) type SomeStruct struct { runtimeFields map[string]string } func check(err error) { if err != nil { log.Fatal(err) } } func main() { ss := SomeStruct{make(map[string]string)} scanner := bufio.NewScanner(os.Stdin) fmt.Println("Create two fields at runtime: ") for i := 1; i <= 2; i++ { fmt.Printf(" Field #%d:\n", i) fmt.Print(" Enter name  : ") scanner.Scan() name := scanner.Text() fmt.Print(" Enter value : ") scanner.Scan() value := scanner.Text() check(scanner.Err()) ss.runtimeFields[name] = value fmt.Println() } for { fmt.Print("Which field do you want to inspect ? ") scanner.Scan() name := scanner.Text() check(scanner.Err()) value, ok := ss.runtimeFields[name] if !ok { fmt.Println("There is no field of that name, try again") } else { fmt.Printf("Its value is '%s'\n", value) return } } }
using System; using System.Dynamic; namespace DynamicClassVariable { internal static class Program { #region Static Members private static void Main() { dynamic sampleObj = new ExpandoObject(); sampleObj.bar = 1; Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } }
Maintain the same structure and functionality when rewriting this code in C#.
package onetime import ( "crypto/hmac" "crypto/sha1" "encoding/binary" "errors" "hash" "math" "time" ) type OneTimePassword struct { Digit int TimeStep time.Duration BaseTime time.Time Hash func() hash.Hash } func (otp *OneTimePassword) HOTP(secret []byte, count uint64) uint { hs := otp.hmacSum(secret, count) return otp.truncate(hs) } func (otp *OneTimePassword) hmacSum(secret []byte, count uint64) []byte { mac := hmac.New(otp.Hash, secret) binary.Write(mac, binary.BigEndian, count) return mac.Sum(nil) } func (otp *OneTimePassword) truncate(hs []byte) uint { sbits := dt(hs) snum := uint(sbits[3]) | uint(sbits[2])<<8 snum |= uint(sbits[1])<<16 | uint(sbits[0])<<24 return snum % uint(math.Pow(10, float64(otp.Digit))) } func Simple(digit int) (otp OneTimePassword, err error) { if digit < 6 { err = errors.New("minimum of 6 digits is required for a valid HTOP code") return } else if digit > 9 { err = errors.New("HTOP code cannot be longer than 9 digits") return } const step = 30 * time.Second otp = OneTimePassword{digit, step, time.Unix(0, 0), sha1.New} return } func (otp *OneTimePassword) TOTP(secret []byte) uint { return otp.HOTP(secret, otp.steps(time.Now())) } func (otp *OneTimePassword) steps(now time.Time) uint64 { elapsed := now.Unix() - otp.BaseTime.Unix() return uint64(float64(elapsed) / otp.TimeStep.Seconds()) } func dt(hs []byte) []byte { offset := int(hs[len(hs)-1] & 0xf) p := hs[offset : offset+4] p[0] &= 0x7f return p }
using System; using System.Security.Cryptography; namespace RosettaTOTP { public class TOTP_SHA1 { private byte[] K; public TOTP_SHA1() { GenerateKey(); } public void GenerateKey() { using (RandomNumberGenerator rng = new RNGCryptoServiceProvider()) { K = new byte[HMACSHA1.Create().HashSize / 8]; rng.GetBytes(K); } } public int HOTP(UInt64 C, int digits = 6) { var hmac = HMACSHA1.Create(); hmac.Key = K; hmac.ComputeHash(BitConverter.GetBytes(C)); return Truncate(hmac.Hash, digits); } public UInt64 CounterNow(int T1 = 30) { var secondsSinceEpoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; return (UInt64)Math.Floor(secondsSinceEpoch / T1); } private int DT(byte[] hmac_result) { int offset = hmac_result[19] & 0xf; int bin_code = (hmac_result[offset] & 0x7f) << 24 | (hmac_result[offset + 1] & 0xff) << 16 | (hmac_result[offset + 2] & 0xff) << 8 | (hmac_result[offset + 3] & 0xff); return bin_code; } private int Truncate(byte[] hmac_result, int digits) { var Snum = DT(hmac_result); return Snum % (int)Math.Pow(10, digits); } } class Program { static void Main(string[] args) { var totp = new TOTP_SHA1(); Console.WriteLine(totp.HOTP(totp.CounterNow())); } } }
Write the same algorithm in C as shown in this Python implementation.
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) >>> [ Y(fac)(i) for i in range(10) ] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) >>> [ Y(fib)(i) for i in range(10) ] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#include <stdio.h> #include <stdlib.h> typedef struct func_t *func; typedef struct func_t { func (*fn) (func, func); func _; int num; } func_t; func new(func(*f)(func, func), func _) { func x = malloc(sizeof(func_t)); x->fn = f; x->_ = _; x->num = 0; return x; } func call(func f, func n) { return f->fn(f, n); } func Y(func(*f)(func, func)) { func g = new(f, 0); g->_ = g; return g; } func num(int n) { func x = new(0, 0); x->num = n; return x; } func fac(func self, func n) { int nn = n->num; return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num) : num(1); } func fib(func self, func n) { int nn = n->num; return nn > 1 ? num( call(self->_, num(nn - 1))->num + call(self->_, num(nn - 2))->num ) : num(1); } void show(func n) { printf(" %d", n->num); } int main() { int i; func f = Y(fac); printf("fac: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); f = Y(fib); printf("fib: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); return 0; }
Generate a C translation of this Python snippet without changing its computational steps.
def addsub(x, y): return x + y, x - y
#include<stdio.h> typedef struct{ int integer; float decimal; char letter; char string[100]; double bigDecimal; }Composite; Composite example() { Composite C = {1, 2.3, 'a', "Hello World", 45.678}; return C; } int main() { Composite C = example(); printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal); return 0; }
Convert this Python snippet to C and keep its semantics consistent.
def van_eck(): n, seen, val = 0, {}, 0 while True: yield val last = {val: n} val = n - seen.get(val, n) seen.update(last) n += 1 if __name__ == '__main__': print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10))) print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
#include <stdlib.h> #include <stdio.h> int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } } printf("The first ten terms of the Van Eck sequence are:\n"); for (int i = 0; i < 10; i ++) printf("%d ", a[i]); printf("\n\nTerms 991 to 1000 of the sequence are:\n"); for (int i = 990; i < 1000; i ++) printf("%d ", a[i]); putchar('\n'); return 0; }
Transform the following Python implementation into C, maintaining the same output and logic.
def van_eck(): n, seen, val = 0, {}, 0 while True: yield val last = {val: n} val = n - seen.get(val, n) seen.update(last) n += 1 if __name__ == '__main__': print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10))) print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
#include <stdlib.h> #include <stdio.h> int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } } printf("The first ten terms of the Van Eck sequence are:\n"); for (int i = 0; i < 10; i ++) printf("%d ", a[i]); printf("\n\nTerms 991 to 1000 of the sequence are:\n"); for (int i = 990; i < 1000; i ++) printf("%d ", a[i]); putchar('\n'); return 0; }
Change the programming language of this snippet from Python to C without modifying what it does.
from ftplib import FTP ftp = FTP('kernel.org') ftp.login() ftp.cwd('/pub/linux/kernel') ftp.set_pasv(True) print ftp.retrlines('LIST') print ftp.retrbinary('RETR README', open('README', 'wb').write) ftp.quit()
#include <ftplib.h> int main(void) { netbuf *nbuf; FtpInit(); FtpConnect("kernel.org", &nbuf); FtpLogin("anonymous", "", nbuf); FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf); FtpChdir("pub/linux/kernel", nbuf); FtpDir((void*)0, ".", nbuf); FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf); FtpQuit(nbuf); return 0; }
Convert this Python block to C, preserving its control flow and logic.
from __future__ import division, print_function import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer.lower() == 'q': break if answer == '!': digits = choose4() print ("New digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") if __name__ == '__main__': main()
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
from __future__ import division, print_function import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer.lower() == 'q': break if answer == '!': digits = choose4() print ("New digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") if __name__ == '__main__': main()
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Write a version of this Python function in C with identical behavior.
for i in range(1, 11): if i % 5 == 0: print(i) continue print(i, end=', ')
for(int i = 1;i <= 10; i++){ printf("%d", i); if(i % 5 == 0){ printf("\n"); continue; } printf(", "); }
Transform the following Python implementation into C, maintaining the same output and logic.
from livewires import * horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors) for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")" exec ExcStrng box(index*stepik,0,(index+1)*stepik,vert,filled=1) while keys_pressed() != ['x']: pass end_graphics()
#include<conio.h> #define COLOURS 8 int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); clrscr(); for(colour=0;colour<COLOURS;colour++) { getch(); gotoxy(1+colour*MAXCOL/COLOURS,1); textbackground(colour); for(j=0;j<MAXROW;j++){ for(i=0;i<MAXCOL/COLOURS;i++){ cprintf(" "); } gotoxy(1+colour*MAXCOL/COLOURS,1+j); } } getch(); textbackground(BLACK); return 0; }
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
from livewires import * horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors) for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")" exec ExcStrng box(index*stepik,0,(index+1)*stepik,vert,filled=1) while keys_pressed() != ['x']: pass end_graphics()
#include<conio.h> #define COLOURS 8 int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); clrscr(); for(colour=0;colour<COLOURS;colour++) { getch(); gotoxy(1+colour*MAXCOL/COLOURS,1); textbackground(colour); for(j=0;j<MAXROW;j++){ for(i=0;i<MAXCOL/COLOURS;i++){ cprintf(" "); } gotoxy(1+colour*MAXCOL/COLOURS,1+j); } } getch(); textbackground(BLACK); return 0; }
Change the programming language of this snippet from Python to C without modifying what it does.
from pprint import pprint def matrixMul(A, B): TB = zip(*B) return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A] def pivotize(m): n = len(m) ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)] for j in xrange(n): row = max(xrange(j, n), key=lambda i: abs(m[i][j])) if j != row: ID[j], ID[row] = ID[row], ID[j] return ID def lu(A): n = len(A) L = [[0.0] * n for i in xrange(n)] U = [[0.0] * n for i in xrange(n)] P = pivotize(A) A2 = matrixMul(P, A) for j in xrange(n): L[j][j] = 1.0 for i in xrange(j+1): s1 = sum(U[k][j] * L[i][k] for k in xrange(i)) U[i][j] = A2[i][j] - s1 for i in xrange(j, n): s2 = sum(U[k][j] * L[i][k] for k in xrange(j)) L[i][j] = (A2[i][j] - s2) / U[j][j] return (L, U, P) a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]] for part in lu(a): pprint(part, width=19) print print b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]] for part in lu(b): pprint(part) print
#include <stdio.h> #include <stdlib.h> #include <math.h> #define foreach(a, b, c) for (int a = b; a < c; a++) #define for_i foreach(i, 0, n) #define for_j foreach(j, 0, n) #define for_k foreach(k, 0, n) #define for_ij for_i for_j #define for_ijk for_ij for_k #define _dim int n #define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; } #define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; } typedef double **mat; #define _zero(a) mat_zero(a, n) void mat_zero(mat x, int n) { for_ij x[i][j] = 0; } #define _new(a) a = mat_new(n) mat mat_new(_dim) { mat x = malloc(sizeof(double*) * n); x[0] = malloc(sizeof(double) * n * n); for_i x[i] = x[0] + n * i; _zero(x); return x; } #define _copy(a) mat_copy(a, n) mat mat_copy(void *s, _dim) { mat x = mat_new(n); for_ij x[i][j] = ((double (*)[n])s)[i][j]; return x; } #define _del(x) mat_del(x) void mat_del(mat x) { free(x[0]); free(x); } #define _QUOT(x) #x #define QUOTE(x) _QUOT(x) #define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n) void mat_show(mat x, char *fmt, _dim) { if (!fmt) fmt = "%8.4g"; for_i { printf(i ? " " : " [ "); for_j { printf(fmt, x[i][j]); printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n"); } } } #define _mul(a, b) mat_mul(a, b, n) mat mat_mul(mat a, mat b, _dim) { mat c = _new(c); for_ijk c[i][j] += a[i][k] * b[k][j]; return c; } #define _pivot(a, b) mat_pivot(a, b, n) void mat_pivot(mat a, mat p, _dim) { for_ij { p[i][j] = (i == j); } for_i { int max_j = i; foreach(j, i, n) if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j; if (max_j != i) for_k { _swap(p[i][k], p[max_j][k]); } } } #define _LU(a, l, u, p) mat_LU(a, l, u, p, n) void mat_LU(mat A, mat L, mat U, mat P, _dim) { _zero(L); _zero(U); _pivot(A, P); mat Aprime = _mul(P, A); for_i { L[i][i] = 1; } for_ij { double s; if (j <= i) { _sum_k(0, j, L[j][k] * U[k][i], s) U[j][i] = Aprime[j][i] - s; } if (j >= i) { _sum_k(0, i, L[j][k] * U[k][i], s); L[j][i] = (Aprime[j][i] - s) / U[i][i]; } } _del(Aprime); } double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }}; double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}; int main() { int n = 3; mat A, L, P, U; _new(L); _new(P); _new(U); A = _copy(A3); _LU(A, L, U, P); _show(A); _show(L); _show(U); _show(P); _del(A); _del(L); _del(U); _del(P); printf("\n"); n = 4; _new(L); _new(P); _new(U); A = _copy(A4); _LU(A, L, U, P); _show(A); _show(L); _show(U); _show(P); _del(A); _del(L); _del(U); _del(P); return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
def genfizzbuzz(factorwords, numbers): factorwords.sort(key=lambda factor_and_word: factor_and_word[0]) lines = [] for num in numbers: words = ''.join(word for factor, word in factorwords if (num % factor) == 0) lines.append(words if words else str(num)) return '\n'.join(lines) if __name__ == '__main__': print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
#include <stdio.h> #include <stdlib.h> struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf("%s", info[it].text); found_word = 1; } } if (0 == found_word) printf("%d", i); printf("\n"); } } int main(void) { struct replace_info info[3] = { {5, "Buzz"}, {7, "Baxx"}, {3, "Fizz"} }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
Translate the given Python code snippet into C without altering its behavior.
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Generate a C translation of this Python snippet without changing its computational steps.
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Maintain the same structure and functionality when rewriting this code in C.
def isExt(fileName, extensions): return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Translate the given Python code snippet into C without altering its behavior.
def isExt(fileName, extensions): return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Produce a language-to-language conversion: from Python to C, same semantics.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from itertools import izip_longest as zip_longest else: from itertools import zip_longest def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def ask4(): 'get four random digits >0 from the player' digits = '' while len(digits) != 4 or not all(d in '123456789' for d in digits): digits = input('Enter the digits to solve for: ') digits = ''.join(digits.strip().split()) return list(digits) def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def solve(digits): digilen = len(digits) exprlen = 2 * digilen - 1 digiperm = sorted(set(permutations(digits))) opcomb = list(product('+-*/', repeat=digilen-1)) brackets = ( [()] + [(x,y) for x in range(0, exprlen, 2) for y in range(x+4, exprlen+2, 2) if (x,y) != (0,exprlen+1)] + [(0, 3+1, 4+2, 7+3)] ) for d in digiperm: for ops in opcomb: if '/' in ops: d2 = [('F(%s)' % i) for i in d] else: d2 = d ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue=''))) for b in brackets: exp = ex[::] for insertpoint, bracket in zip(b, '()'*(len(b)//2)): exp.insert(insertpoint, bracket) txt = ''.join(exp) try: num = eval(txt) except ZeroDivisionError: continue if num == 24: if '/' in ops: exp = [ (term if not term.startswith('F(') else term[2]) for term in exp ] ans = ' '.join(exp).rstrip() print ("Solution found:",ans) return ans print ("No solution found for:", ' '.join(digits)) return '!' def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer == '?': solve(digits) answer = '!' if answer.lower() == 'q': break if answer == '!': digits = choose4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if answer == '!!': digits = ask4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: if '/' in answer: answer = ''.join( (('F(%s)' % char) if char in '123456789' else char) for char in answer ) ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") main()
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Change the programming language of this snippet from Python to C without modifying what it does.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from itertools import izip_longest as zip_longest else: from itertools import zip_longest def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def ask4(): 'get four random digits >0 from the player' digits = '' while len(digits) != 4 or not all(d in '123456789' for d in digits): digits = input('Enter the digits to solve for: ') digits = ''.join(digits.strip().split()) return list(digits) def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def solve(digits): digilen = len(digits) exprlen = 2 * digilen - 1 digiperm = sorted(set(permutations(digits))) opcomb = list(product('+-*/', repeat=digilen-1)) brackets = ( [()] + [(x,y) for x in range(0, exprlen, 2) for y in range(x+4, exprlen+2, 2) if (x,y) != (0,exprlen+1)] + [(0, 3+1, 4+2, 7+3)] ) for d in digiperm: for ops in opcomb: if '/' in ops: d2 = [('F(%s)' % i) for i in d] else: d2 = d ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue=''))) for b in brackets: exp = ex[::] for insertpoint, bracket in zip(b, '()'*(len(b)//2)): exp.insert(insertpoint, bracket) txt = ''.join(exp) try: num = eval(txt) except ZeroDivisionError: continue if num == 24: if '/' in ops: exp = [ (term if not term.startswith('F(') else term[2]) for term in exp ] ans = ' '.join(exp).rstrip() print ("Solution found:",ans) return ans print ("No solution found for:", ' '.join(digits)) return '!' def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer == '?': solve(digits) answer = '!' if answer.lower() == 'q': break if answer == '!': digits = choose4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if answer == '!!': digits = ask4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: if '/' in answer: answer = ''.join( (('F(%s)' % char) if char in '123456789' else char) for char in answer ) ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") main()
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
import threading import time import random def worker(workernum, barrier): sleeptime = random.random() print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier.wait() sleeptime = random.random() print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier = threading.Barrier(3) w1 = threading.Thread(target=worker, args=((1,barrier))) w2 = threading.Thread(target=worker, args=((2,barrier))) w3 = threading.Thread(target=worker, args=((3,barrier))) w1.start() w2.start() w3.start()
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> int main() { int jobs = 41, tid; omp_set_num_threads(5); #pragma omp parallel shared(jobs) private(tid) { tid = omp_get_thread_num(); while (jobs > 0) { #pragma omp barrier if (!jobs) break; printf("%d: taking job %d\n", tid, jobs--); usleep(100000 + rand() / (double) RAND_MAX * 3000000); printf("%d: done job\n", tid); } printf("[%d] leaving\n", tid); #pragma omp barrier } return 0; }
Write the same code in C as shown below in Python.
def tobits(n, _group=8, _sep='_', _pad=False): 'Express n as binary bits with separator' bits = '{0:b}'.format(n)[::-1] if _pad: bits = '{0:0{1}b}'.format(n, ((_group+len(bits)-1)//_group)*_group)[::-1] answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] answer = '0'*(len(_sep)-1) + answer else: answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] return answer def tovlq(n): return tobits(n, _group=7, _sep='1_', _pad=True) def toint(vlq): return int(''.join(vlq.split('_1')), 2) def vlqsend(vlq): for i, byte in enumerate(vlq.split('_')[::-1]): print('Sent byte {0:3}: {1:
#include <stdio.h> #include <stdint.h> void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; } uint64_t from_seq(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++ & 128); return r; } int main() { uint8_t s[10]; uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; int i, j; for (j = 0; j < sizeof(x)/8; j++) { to_seq(x[j], s); printf("seq from %llx: [ ", x[j]); i = 0; do { printf("%02x ", s[i]); } while ((s[i++] & 128)); printf("] back: %llx\n", from_seq(s)); } return 0; }
Generate an equivalent C version of this Python code.
import pyaudio chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) data = stream.read(chunk) print [ord(i) for i in data]
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> void * record(size_t bytes) { int fd; if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0; void *a = malloc(bytes); read(fd, a, bytes); close(fd); return a; } int play(void *buf, size_t len) { int fd; if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0; write(fd, buf, len); close(fd); return 1; } int main() { void *p = record(65536); play(p, 65536); return 0; }
Produce a language-to-language conversion: from Python to C, same semantics.
import argh import hashlib import sys @argh.arg('filename', nargs='?', default=None) def main(filename, block_size=1024*1024): if filename: fin = open(filename, 'rb') else: fin = sys.stdin stack = [] block = fin.read(block_size) while block: node = (0, hashlib.sha256(block).digest()) stack.append(node) while len(stack) >= 2 and stack[-2][0] == stack[-1][0]: a = stack[-2] b = stack[-1] l = a[0] stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())] block = fin.read(block_size) while len(stack) > 1: a = stack[-2] b = stack[-1] al = a[0] bl = b[0] stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())] print(stack[0][1].hex()) argh.dispatch_command(main)
#include <glib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> guchar* sha256_merkle_tree(FILE* in, size_t block_size) { gchar* buffer = g_malloc(block_size); GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free); gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256); GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256); size_t bytes; while ((bytes = fread(buffer, 1, block_size, in)) > 0) { g_checksum_reset(checksum); g_checksum_update(checksum, (guchar*)buffer, bytes); gsize len = digest_length; guchar* digest = g_malloc(len); g_checksum_get_digest(checksum, digest, &len); g_ptr_array_add(hashes, digest); } g_free(buffer); guint hashes_length = hashes->len; if (hashes_length == 0) { g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return NULL; } while (hashes_length > 1) { guint j = 0; for (guint i = 0; i < hashes_length; i += 2, ++j) { guchar* digest1 = g_ptr_array_index(hashes, i); guchar* digest_out = g_ptr_array_index(hashes, j); if (i + 1 < hashes_length) { guchar* digest2 = g_ptr_array_index(hashes, i + 1); g_checksum_reset(checksum); g_checksum_update(checksum, digest1, digest_length); g_checksum_update(checksum, digest2, digest_length); gsize len = digest_length; g_checksum_get_digest(checksum, digest_out, &len); } else { memcpy(digest_out, digest1, digest_length); } } hashes_length = j; } guchar* result = g_ptr_array_steal_index(hashes, 0); g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return result; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s filename\n", argv[0]); return EXIT_FAILURE; } FILE* in = fopen(argv[1], "rb"); if (in) { guchar* digest = sha256_merkle_tree(in, 1024); fclose(in); if (digest) { gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256); for (gssize i = 0; i < length; ++i) printf("%02x", digest[i]); printf("\n"); g_free(digest); } } else { perror(argv[1]); return EXIT_FAILURE; } return EXIT_SUCCESS; }
Please provide an equivalent version of this Python code in C.
s = "alphaBETA" print s.upper() print s.lower() print s.swapcase() print "fOo bAR".capitalize() print "fOo bAR".title() import string print string.capwords("fOo bAR")
#include <ctype.h> #include <stdio.h> void str_toupper(char *s) { while(*s) { *s=toupper(*s); s++; } } void str_tolower(char *s) { while(*s) { *s=tolower(*s); s++; } } int main(int argc, char *argv[]) { char t[255]="alphaBETA"; str_toupper(t); printf("uppercase: %s\n", t); str_tolower(t); printf("lowercase: %s\n", t); return 0; }
Generate an equivalent C version of this Python code.
from javax.swing import JOptionPane def to_int(n, default=0): try: return int(n) except ValueError: return default number = to_int(JOptionPane.showInputDialog ("Enter an Integer")) println(number) a_string = JOptionPane.showInputDialog ("Enter a String") println(a_string)
#include <gtk/gtk.h> void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg; gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]); msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "You wrote '%s' and selected the number %d%s", c, (gint)v, (v==75000) ? "" : " which is wrong (75000 expected)!"); gtk_widget_show_all(GTK_WIDGET(msg)); (void)gtk_dialog_run(GTK_DIALOG(msg)); gtk_widget_destroy(GTK_WIDGET(msg)); if ( v==75000 ) gtk_main_quit(); } int main(int argc, char **argv) { GtkWindow *win; GtkEntry *entry; GtkSpinButton *spin; GtkButton *okbutton; GtkLabel *entry_l, *spin_l; GtkHBox *hbox[2]; GtkVBox *vbox; GtkWidget *widgs[2]; gtk_init(&argc, &argv); win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, "Insert values"); entry_l = (GtkLabel *)gtk_label_new("Insert a string"); spin_l = (GtkLabel *)gtk_label_new("Insert 75000"); entry = (GtkEntry *)gtk_entry_new(); spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1); widgs[0] = GTK_WIDGET(entry); widgs[1] = GTK_WIDGET(spin); okbutton = (GtkButton *)gtk_button_new_with_label("Ok"); hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1); vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin)); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
t = { 'x': 20, 'y': 30, 'a': 60 } def setup(): size(450, 400) background(0, 0, 200) stroke(-1) sc(7, 400, -60) def sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5): if o: o -= 1 l *= HALF sc(o, l, -a)[A] += a sc(o, l, a)[A] += a sc(o, l, -a) else: x, y = s[X], s[Y] s[X] += cos(radians(s[A])) * l s[Y] += sin(radians(s[A])) * l line(x, y, s[X], s[Y]) return s
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct cursor_tag { double x; double y; int angle; } cursor_t; void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; } void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, "L%g,%g\n", cursor->x, cursor->y); } void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } } void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, "<svg xmlns='http: size, size); fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n"); fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='"); fprintf(out, "M%g,%g\n", cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, "'/>\n</svg>\n"); } int main(int argc, char** argv) { const char* filename = "sierpinski_arrowhead.svg"; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, "w"); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
Translate this program into C but keep the logic exactly as in Python.
import fileinput import sys nodata = 0; nodata_max=-1; nodata_maxline=[]; tot_file = 0 num_file = 0 infiles = sys.argv[1:] for line in fileinput.input(): tot_line=0; num_line=0; field = line.split() date = field[0] data = [float(f) for f in field[1::2]] flags = [int(f) for f in field[2::2]] for datum, flag in zip(data, flags): if flag<1: nodata += 1 else: if nodata_max==nodata and nodata>0: nodata_maxline.append(date) if nodata_max<nodata and nodata>0: nodata_max=nodata nodata_maxline=[date] nodata=0; tot_line += datum num_line += 1 tot_file += tot_line num_file += num_line print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % ( date, len(data) -num_line, num_line, tot_line, tot_line/num_line if (num_line>0) else 0) print "" print "File(s) = %s" % (", ".join(infiles),) print "Total = %10.3f" % (tot_file,) print "Readings = %6i" % (num_file,) print "Average = %10.3f" % (tot_file / num_file,) print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % ( nodata_max, ", ".join(nodata_maxline))
#include <stdio.h> #include <stdlib.h> #include <string.h> static int badHrs, maxBadHrs; static double hrsTot = 0.0; static int rdgsTot = 0; char bhEndDate[40]; int mungeLine( char *line, int lno, FILE *fout ) { char date[40], *tkn; int dHrs, flag, hrs2, hrs; double hrsSum; int hrsCnt = 0; double avg; tkn = strtok(line, "."); if (tkn) { int n = sscanf(tkn, "%s %d", &date, &hrs2); if (n<2) { printf("badly formated line - %d %s\n", lno, tkn); return 0; } hrsSum = 0.0; while( tkn= strtok(NULL, ".")) { n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs); if (n>=2) { if (flag > 0) { hrsSum += 1.0*hrs2 + .001*dHrs; hrsCnt += 1; if (maxBadHrs < badHrs) { maxBadHrs = badHrs; strcpy(bhEndDate, date); } badHrs = 0; } else { badHrs += 1; } hrs2 = hrs; } else { printf("bad file syntax line %d: %s\n",lno, tkn); } } avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0; fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n", date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt); hrsTot += hrsSum; rdgsTot += hrsCnt; } return 1; } int main() { FILE *infile, *outfile; int lineNo = 0; char line[512]; const char *ifilename = "readings.txt"; outfile = fopen("V0.txt", "w"); infile = fopen(ifilename, "rb"); if (!infile) { printf("Can't open %s\n", ifilename); exit(1); } while (NULL != fgets(line, 512, infile)) { lineNo += 1; if (0 == mungeLine(line, lineNo, outfile)) printf("Bad line at %d",lineNo); } fclose(infile); fprintf(outfile, "File: %s\n", ifilename); fprintf(outfile, "Total:  %.3f\n", hrsTot); fprintf(outfile, "Readings: %d\n", rdgsTot); fprintf(outfile, "Average:  %.3f\n", hrsTot/rdgsTot); fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs); fprintf(outfile, "Ends on date %s\n", bhEndDate); fclose(outfile); return 0; }
Transform the following Python implementation into C, maintaining the same output and logic.
>>> import hashlib >>> >>> tests = ( (b"", 'd41d8cd98f00b204e9800998ecf8427e'), (b"a", '0cc175b9c0f1b6a831c399e269772661'), (b"abc", '900150983cd24fb0d6963f7d28e17f72'), (b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'), (b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'), (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'), (b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') ) >>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden >>>
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> const char *string = "The quick brown fox jumped over the lazy dog's back"; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", result[i]); printf("\n"); return EXIT_SUCCESS; }
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Port the following code from Python to C with equivalent syntax and logic.
import datetime def mt(): datime1="March 7 2009 7:30pm EST" formatting = "%B %d %Y %I:%M%p " datime2 = datime1[:-3] tdelta = datetime.timedelta(hours=12) s3 = datetime.datetime.strptime(datime2, formatting) datime2 = s3+tdelta print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:] mt()
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST"; strptime(d, "%B %d %Y %I:%M%p %Z", &ts); t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); return EXIT_SUCCESS; }
Transform the following Python implementation into C, maintaining the same output and logic.
from time import sleep from threading import Timer def sleepsort(values): sleepsort.result = [] def add1(x): sleepsort.result.append(x) mx = values[0] for v in values: if mx < v: mx = v Timer(v, add1, [v]).start() sleep(mx+1) return sleepsort.result if __name__ == '__main__': x = [3,2,4,7,3,6,9,1] if sleepsort(x) == sorted(x): print('sleep sort worked for:',x) else: print('sleep sort FAILED for:',x)
>>>>>,----------[++++++++ ++[->+>+<<]>+>[-<<+>>]+++ +++++[-<------>]>>+>,---- ------<<+[->>>>>+<<<<<]>> ]>>>[<<<<[<<<[->>+<<[->+> [-]<<]]>[-<+>]>[-<<<.>>>> ->>>>>[>>>>>]<-<<<<[<<<<< ]+<]<<<<]>>>>>[>>>>>]<]
Translate the given Python code snippet into C without altering its behavior.
from random import randint def do_scan(mat): for row in mat: for item in row: print item, if item == 20: print return print print mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)] do_scan(mat)
#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int a[10][10], i, j; srand(time(NULL)); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) a[i][j] = rand() % 20 + 1; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf(" %d", a[i][j]); if (a[i][j] == 20) goto Done; } printf("\n"); } Done: printf("\n"); return 0; }
Write the same code in C as shown below in Python.
from fractions import gcd def pt1(maxperimeter=100): trips = [] for a in range(1, maxperimeter): aa = a*a for b in range(a, maxperimeter-a+1): bb = b*b for c in range(b, maxperimeter-b-a+1): cc = c*c if a+b+c > maxperimeter or cc > aa + bb: break if aa + bb == cc: trips.append((a,b,c, gcd(a, b) == 1)) return trips def pytrip(trip=(3,4,5),perim=100, prim=1): a0, b0, c0 = a, b, c = sorted(trip) t, firstprim = set(), prim>0 while a + b + c <= perim: t.add((a, b, c, firstprim>0)) a, b, c, firstprim = a+a0, b+b0, c+c0, False t2 = set() for a, b, c, firstprim in t: a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7 if a5 - b5 + c7 <= perim: t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim) if a5 + b5 + c7 <= perim: t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim) if -a5 + b5 + c7 <= perim: t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim) return t | t2 def pt2(maxperimeter=100): trips = pytrip((3,4,5), maxperimeter, 1) return trips def printit(maxperimeter=100, pt=pt1): trips = pt(maxperimeter) print(" Up to a perimeter of %i there are %i triples, of which %i are primitive" % (maxperimeter, len(trips), len([prim for a,b,c,prim in trips if prim]))) for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)): print(algo.__doc__) for maxperimeter in range(mn, mx+1, mn): printit(maxperimeter, algo)
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Generate a C translation of this Python snippet without changing its computational steps.
from fractions import gcd def pt1(maxperimeter=100): trips = [] for a in range(1, maxperimeter): aa = a*a for b in range(a, maxperimeter-a+1): bb = b*b for c in range(b, maxperimeter-b-a+1): cc = c*c if a+b+c > maxperimeter or cc > aa + bb: break if aa + bb == cc: trips.append((a,b,c, gcd(a, b) == 1)) return trips def pytrip(trip=(3,4,5),perim=100, prim=1): a0, b0, c0 = a, b, c = sorted(trip) t, firstprim = set(), prim>0 while a + b + c <= perim: t.add((a, b, c, firstprim>0)) a, b, c, firstprim = a+a0, b+b0, c+c0, False t2 = set() for a, b, c, firstprim in t: a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7 if a5 - b5 + c7 <= perim: t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim) if a5 + b5 + c7 <= perim: t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim) if -a5 + b5 + c7 <= perim: t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim) return t | t2 def pt2(maxperimeter=100): trips = pytrip((3,4,5), maxperimeter, 1) return trips def printit(maxperimeter=100, pt=pt1): trips = pt(maxperimeter) print(" Up to a perimeter of %i there are %i triples, of which %i are primitive" % (maxperimeter, len(trips), len([prim for a,b,c,prim in trips if prim]))) for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)): print(algo.__doc__) for maxperimeter in range(mn, mx+1, mn): printit(maxperimeter, algo)
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Preserve the algorithm and functionality while converting the code from Python to C.
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] unique = list(set(items))
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
Preserve the algorithm and functionality while converting the code from Python to C.
def lookandsay(number): result = "" repeat = number[0] number = number[1:]+" " times = 1 for actual in number: if actual != repeat: result += str(times)+repeat times = 1 repeat = actual else: times += 1 return result num = "1" for i in range(10): print num num = lookandsay(num)
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
Maintain the same structure and functionality when rewriting this code in C.
from collections import deque stack = deque() stack.append(value) value = stack.pop() not stack
#include <stdio.h> #include <stdlib.h> #define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ stk_##name stk_##name##_create(size_t init_size) { \ stk_##name s; if (!init_size) init_size = 4; \ s = malloc(sizeof(struct stk_##name##_t)); \ if (!s) return 0; \ s->buf = malloc(sizeof(type) * init_size); \ if (!s->buf) { free(s); return 0; } \ s->len = 0, s->alloc = init_size; \ return s; } \ int stk_##name##_push(stk_##name s, type item) { \ type *tmp; \ if (s->len >= s->alloc) { \ tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ if (!tmp) return -1; s->buf = tmp; \ s->alloc *= 2; } \ s->buf[s->len++] = item; \ return s->len; } \ type stk_##name##_pop(stk_##name s) { \ type tmp; \ if (!s->len) abort(); \ tmp = s->buf[--s->len]; \ if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ s->alloc /= 2; \ s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ return tmp; } \ void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) #define stk_size(s) ((s)->len) DECL_STACK_TYPE(int, int) int main(void) { int i; stk_int stk = stk_int_create(0); printf("pushing: "); for (i = 'a'; i <= 'z'; i++) { printf(" %c", i); stk_int_push(stk, i); } printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); printf("\npoppoing:"); while (stk_size(stk)) printf(" %c", stk_int_pop(stk)); printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); stk_int_delete(stk); return 0; }
Preserve the algorithm and functionality while converting the code from Python to C.
from math import gcd def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) if __name__ == '__main__': def is_prime(n): return φ(n) == n - 1 for n in range(1, 26): print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}") count = 0 for n in range(1, 10_000 + 1): count += is_prime(n) if n in {100, 1000, 10_000}: print(f"Primes up to {n}: {count}")
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
Transform the following Python implementation into C, maintaining the same output and logic.
if x == 0: foo() elif x == 1: bar() elif x == 2: baz() else: qux() match x: 0 => foo() 1 => bar() 2 => baz() _ => qux() (a) ? b : c
int a = 3; if (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } unless (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } switch (a) { case 2: puts ("a is 2"); break; case 3: puts ("a is 3"); break; case 4: puts ("a is 4"); break; default: puts("is neither"); }
Translate this program into C but keep the logic exactly as in Python.
from fractions import Fraction def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,' '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,' '13 / 11, 15 / 14, 15 / 2, 55 / 1'): flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')] n = Fraction(n) while True: yield n.numerator for f in flist: if (n * f).denominator == 1: break else: break n *= f if __name__ == '__main__': n, m = 2, 15 print('First %i members of fractran(%i):\n ' % (m, n) + ', '.join(str(f) for f,i in zip(fractran(n), range(m))))
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); else gmp_printf(" %Zd", val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf("\nhalt: %Zd has no divisors\n", val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); return 0; }
Convert this Python snippet to C and keep its semantics consistent.
from fractions import Fraction def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,' '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,' '13 / 11, 15 / 14, 15 / 2, 55 / 1'): flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')] n = Fraction(n) while True: yield n.numerator for f in flist: if (n * f).denominator == 1: break else: break n *= f if __name__ == '__main__': n, m = 2, 15 print('First %i members of fractran(%i):\n ' % (m, n) + ', '.join(str(f) for f,i in zip(fractran(n), range(m))))
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); else gmp_printf(" %Zd", val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf("\nhalt: %Zd has no divisors\n", val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); return 0; }
Write a version of this Python function in C with identical behavior.
>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] >>> def stoogesort(L, i=0, j=None): if j is None: j = len(L) - 1 if L[j] < L[i]: L[i], L[j] = L[j], L[i] if j - i > 1: t = (j - i + 1) // 3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L >>> stoogesort(data) [-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
#include <stdio.h> #define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } int main(int argc, char *argv[]) { int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; int i, n; n = sizeof(nums)/sizeof(int); StoogeSort(nums, 0, n-1); for(i = 0; i <= n-1; i++) printf("%5d", nums[i]); return 0; }
Produce a functionally identical C code for the snippet given in Python.
import sys, os import random import time def print_there(x, y, text): sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) sys.stdout.flush() class Ball(): def __init__(self): self.x = 0 self.y = 0 def update(self): self.x += random.randint(0,1) self.y += 1 def fall(self): self.y +=1 class Board(): def __init__(self, width, well_depth, N): self.balls = [] self.fallen = [0] * (width + 1) self.width = width self.well_depth = well_depth self.N = N self.shift = 4 def update(self): for ball in self.balls: if ball.y < self.width: ball.update() elif ball.y < self.width + self.well_depth - self.fallen[ball.x]: ball.fall() elif ball.y == self.width + self.well_depth - self.fallen[ball.x]: self.fallen[ball.x] += 1 else: pass def balls_on_board(self): return len(self.balls) - sum(self.fallen) def add_ball(self): if(len(self.balls) <= self.N): self.balls.append(Ball()) def print_board(self): for y in range(self.width + 1): for x in range(y): print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, " def print_ball(self, ball): if ball.y <= self.width: x = self.width - ball.y + 2*ball.x + self.shift else: x = 2*ball.x + self.shift y = ball.y + 1 print_there(y, x, "*") def print_all(self): print(chr(27) + "[2J") self.print_board(); for ball in self.balls: self.print_ball(ball) def main(): board = Board(width = 15, well_depth = 5, N = 10) board.add_ball() while(board.balls_on_board() > 0): board.print_all() time.sleep(0.25) board.update() board.print_all() time.sleep(0.25) board.update() board.add_ball() if __name__=="__main__": main()
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b; #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts("\033[H"), i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++, putchar(' ')) printf(B(i, j) == '*' ? C(i - 1, j) ? "\033[32m%c\033[m" : "\033[31m%c\033[m" : "%c", B(i, j)); } void init() { int i, j; puts("\033[H\033[J"); b = malloc(w * h); memset(b, ' ', w * h); x = malloc(sizeof(int) * BALLS * 2); y = x + BALLS; for (i = 0; i < n; i++) for (j = -i; j <= i; j += 2) B(2 * i+2, j + w/2) = '*'; srand(time(0)); } void move(int idx) { int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0; if (yy < 0) return; if (yy == h - 1) { y[idx] = -1; return; } switch(c = B(yy + 1, xx)) { case ' ': yy++; break; case '*': sl = 1; default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1)) if (!rnd(sl++)) o = 1; if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1)) if (!rnd(sl++)) o = -1; if (!o) kill = 1; xx += o; } c = V(idx); V(idx) = ' '; idx[y] = yy, idx[x] = xx; B(yy, xx) = c; if (kill) idx[y] = -1; } int run(void) { static int step = 0; int i; for (i = 0; i < cnt; i++) move(i); if (2 == ++step && cnt < BALLS) { step = 0; x[cnt] = w/2; y[cnt] = 0; if (V(cnt) != ' ') return 0; V(cnt) = rnd(80) + 43; cnt++; } return 1; } int main(int c, char **v) { if (c < 2 || (n = atoi(v[1])) <= 3) n = 5; if (n >= 20) n = 20; w = n * 2 + 1; init(); do { show_board(), usleep(60000); } while (run()); return 0; }
Translate this program into C but keep the logic exactly as in Python.
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps': n = R-L if n < 2: return 0 swaps = 0 m = n//2 for i in range(m): if A[R-(i+1)] < A[L+i]: (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],) swaps += 1 if (n & 1) and (A[L+m] < A[L+m-1]): (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],) swaps += 1 return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R) def circle_sort(L:list)->'sort A in place, returning the number of swaps': swaps = 0 s = 1 while s: s = circle_sort_backend(L, 0, len(L)) swaps += s return swaps if __name__ == '__main__': from random import shuffle for i in range(309): L = list(range(i)) M = L[:] shuffle(L) N = L[:] circle_sort(L) if L != M: print(len(L)) print(N) print(L)
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf("%d ", x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); } int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x)); return 0; }
Translate this program into C but keep the logic exactly as in Python.
import os from PIL import Image def imgsave(path, arr): w, h = len(arr), len(arr[0]) img = Image.new('1', (w, h)) for x in range(w): for y in range(h): img.putpixel((x, y), arr[x][y]) img.save(path) def get_shape(mat): return len(mat), len(mat[0]) def kron(matrix1, matrix2): final_list = [] count = len(matrix2) for elem1 in matrix1: for i in range(count): sub_list = [] for num1 in elem1: for num2 in matrix2[i]: sub_list.append(num1 * num2) final_list.append(sub_list) return final_list def kronpow(mat): matrix = mat while True: yield matrix matrix = kron(mat, matrix) def fractal(name, mat, order=6): path = os.path.join('fractals', name) os.makedirs(path, exist_ok=True) fgen = kronpow(mat) print(name) for i in range(order): p = os.path.join(path, f'{i}.jpg') print('Calculating n =', i, end='\t', flush=True) mat = next(fgen) imgsave(p, mat) x, y = get_shape(mat) print('Saved as', x, 'x', y, 'image', p) test1 = [ [0, 1, 0], [1, 1, 1], [0, 1, 0] ] test2 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ] test3 = [ [1, 0, 1], [0, 1, 0], [1, 0, 1] ] fractal('test1', test1) fractal('test2', test2) fractal('test3', test3)
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = fopen(inputFile,"r"); int i,j,k,l; unsigned long prod; int** matrix; cell *coreList,*tempList,*resultList; fscanf(fp,"%d%d",&ROW,&COL); matrix = (int**)malloc(ROW*sizeof(int*)); for(i=0;i<ROW;i++){ matrix[i] = (int*)malloc(COL*sizeof(int)); for(j=0;j<COL;j++){ fscanf(fp,"%d",&matrix[i][j]); if(matrix[i][j]==1) SUM++; } } coreList = (cell*)malloc(SUM*sizeof(cell)); resultList = (cell*)malloc(SUM*sizeof(cell)); k = 0; for(i=0;i<ROW;i++){ for(j=0;j<COL;j++){ if(matrix[i][j]==1){ coreList[k].row = i+1; coreList[k].col = j+1; resultList[k].row = i+1; resultList[k].col = j+1; k++; } } } prod = k; for(i=2;i<=power;i++){ tempList = (cell*)malloc(prod*k*sizeof(cell)); l = 0; for(j=0;j<prod;j++){ for(k=0;k<SUM;k++){ tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row; tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col; l++; } } free(resultList); prod *= k; resultList = (cell*)malloc(prod*sizeof(cell)); for(j=0;j<prod;j++){ resultList[j].row = tempList[j].row; resultList[j].col = tempList[j].col; } free(tempList); } return resultList; } int main(){ char fileName[100]; int power,i,length; cell* resultList; printf("Enter input file name : "); scanf("%s",fileName); printf("Enter power : "); scanf("%d",&power); resultList = kroneckerProduct(fileName,power); initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal"); length = raiseTo(SUM,power); for(i=0;i<length;i++){ putpixel(resultList[i].row,resultList[i].col,15); } getch(); closegraph(); return 0; }
Convert this Python block to C, preserving its control flow and logic.
import os from PIL import Image def imgsave(path, arr): w, h = len(arr), len(arr[0]) img = Image.new('1', (w, h)) for x in range(w): for y in range(h): img.putpixel((x, y), arr[x][y]) img.save(path) def get_shape(mat): return len(mat), len(mat[0]) def kron(matrix1, matrix2): final_list = [] count = len(matrix2) for elem1 in matrix1: for i in range(count): sub_list = [] for num1 in elem1: for num2 in matrix2[i]: sub_list.append(num1 * num2) final_list.append(sub_list) return final_list def kronpow(mat): matrix = mat while True: yield matrix matrix = kron(mat, matrix) def fractal(name, mat, order=6): path = os.path.join('fractals', name) os.makedirs(path, exist_ok=True) fgen = kronpow(mat) print(name) for i in range(order): p = os.path.join(path, f'{i}.jpg') print('Calculating n =', i, end='\t', flush=True) mat = next(fgen) imgsave(p, mat) x, y = get_shape(mat) print('Saved as', x, 'x', y, 'image', p) test1 = [ [0, 1, 0], [1, 1, 1], [0, 1, 0] ] test2 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ] test3 = [ [1, 0, 1], [0, 1, 0], [1, 0, 1] ] fractal('test1', test1) fractal('test2', test2) fractal('test3', test3)
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = fopen(inputFile,"r"); int i,j,k,l; unsigned long prod; int** matrix; cell *coreList,*tempList,*resultList; fscanf(fp,"%d%d",&ROW,&COL); matrix = (int**)malloc(ROW*sizeof(int*)); for(i=0;i<ROW;i++){ matrix[i] = (int*)malloc(COL*sizeof(int)); for(j=0;j<COL;j++){ fscanf(fp,"%d",&matrix[i][j]); if(matrix[i][j]==1) SUM++; } } coreList = (cell*)malloc(SUM*sizeof(cell)); resultList = (cell*)malloc(SUM*sizeof(cell)); k = 0; for(i=0;i<ROW;i++){ for(j=0;j<COL;j++){ if(matrix[i][j]==1){ coreList[k].row = i+1; coreList[k].col = j+1; resultList[k].row = i+1; resultList[k].col = j+1; k++; } } } prod = k; for(i=2;i<=power;i++){ tempList = (cell*)malloc(prod*k*sizeof(cell)); l = 0; for(j=0;j<prod;j++){ for(k=0;k<SUM;k++){ tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row; tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col; l++; } } free(resultList); prod *= k; resultList = (cell*)malloc(prod*sizeof(cell)); for(j=0;j<prod;j++){ resultList[j].row = tempList[j].row; resultList[j].col = tempList[j].col; } free(tempList); } return resultList; } int main(){ char fileName[100]; int power,i,length; cell* resultList; printf("Enter input file name : "); scanf("%s",fileName); printf("Enter power : "); scanf("%d",&power); resultList = kroneckerProduct(fileName,power); initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal"); length = raiseTo(SUM,power); for(i=0;i<length;i++){ putpixel(resultList[i].row,resultList[i].col,15); } getch(); closegraph(); return 0; }
Produce a language-to-language conversion: from Python to C, same semantics.
def readconf(fn): ret = {} with file(fn) as fp: for line in fp: line = line.strip() if not line or line.startswith(' boolval = True if line.startswith(';'): line = line.lstrip(';') if len(line.split()) != 1: continue boolval = False bits = line.split(None, 1) if len(bits) == 1: k = bits[0] v = boolval else: k, v = bits ret[k.lower()] = v return ret if __name__ == '__main__': import sys conf = readconf(sys.argv[1]) for k, v in sorted(conf.items()): print k, '=', v
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si("FULLNAME", this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, "Sorry, something went wrong :-(\n"); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value("YES", 0); if (populate_configs(&confs)) { return 1; } printf( "Full name: %s\n" "Favorite fruit: %s\n" "Need spelling: %s\n" "Seeds removed: %s\n", confs.fullname, confs.favouritefruit, confs.needspeeling ? "True" : "False", confs.seedsremoved ? "True" : "False" ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); } #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }
Convert this Python snippet to C and keep its semantics consistent.
def readconf(fn): ret = {} with file(fn) as fp: for line in fp: line = line.strip() if not line or line.startswith(' boolval = True if line.startswith(';'): line = line.lstrip(';') if len(line.split()) != 1: continue boolval = False bits = line.split(None, 1) if len(bits) == 1: k = bits[0] v = boolval else: k, v = bits ret[k.lower()] = v return ret if __name__ == '__main__': import sys conf = readconf(sys.argv[1]) for k, v in sorted(conf.items()): print k, '=', v
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si("FULLNAME", this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, "Sorry, something went wrong :-(\n"); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value("YES", 0); if (populate_configs(&confs)) { return 1; } printf( "Full name: %s\n" "Favorite fruit: %s\n" "Need spelling: %s\n" "Seeds removed: %s\n", confs.fullname, confs.favouritefruit, confs.needspeeling ? "True" : "False", confs.seedsremoved ? "True" : "False" ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); } #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }