Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given Go code snippet into Java without altering its behavior.
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{ {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10}, {1, 2}, {2, 1}, } func main() { for _, pg := range tpg { fmt.Printf("%s:\n", pg.name) for _, pt := range tpt { fmt.Println(pt, inside(pt, pg)) } } }
import static java.lang.Math.*; public class RayCasting { static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P); if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
Port the following code from Go to Java with equivalent syntax and logic.
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{ {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10}, {1, 2}, {2, 1}, } func main() { for _, pg := range tpg { fmt.Printf("%s:\n", pg.name) for _, pt := range tpt { fmt.Println(pt, inside(pt, pg)) } } }
import static java.lang.Math.*; public class RayCasting { static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P); if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
Generate a Java translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
import static java.lang.Math.*; import java.util.Locale; public class Test { public static void main(String[] args) { Pt a = Pt.fromY(1); Pt b = Pt.fromY(2); System.out.printf("a = %s%n", a); System.out.printf("b = %s%n", b); Pt c = a.plus(b); System.out.printf("c = a + b = %s%n", c); Pt d = c.neg(); System.out.printf("d = -c = %s%n", d); System.out.printf("c + d = %s%n", c.plus(d)); System.out.printf("a + b + d = %s%n", a.plus(b).plus(d)); System.out.printf("a * 12345 = %s%n", a.mult(12345)); } } class Pt { final static int bCoeff = 7; double x, y; Pt(double x, double y) { this.x = x; this.y = y; } static Pt zero() { return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); } boolean isZero() { return this.x > 1e20 || this.x < -1e20; } static Pt fromY(double y) { return new Pt(cbrt(pow(y, 2) - bCoeff), y); } Pt dbl() { if (isZero()) return this; double L = (3 * this.x * this.x) / (2 * this.y); double x2 = pow(L, 2) - 2 * this.x; return new Pt(x2, L * (this.x - x2) - this.y); } Pt neg() { return new Pt(this.x, -this.y); } Pt plus(Pt q) { if (this.x == q.x && this.y == q.y) return dbl(); if (isZero()) return q; if (q.isZero()) return this; double L = (q.y - this.y) / (q.x - this.x); double xx = pow(L, 2) - this.x - q.x; return new Pt(xx, L * (this.x - xx) - this.y); } Pt mult(int n) { Pt r = Pt.zero(); Pt p = this; for (int i = 1; i <= n; i <<= 1) { if ((i & n) != 0) r = r.plus(p); p = p.dbl(); } return r; } @Override public String toString() { if (isZero()) return "Zero"; return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y); } }
Write the same algorithm in Java as shown in this Go implementation.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
import static java.lang.Math.*; import java.util.Locale; public class Test { public static void main(String[] args) { Pt a = Pt.fromY(1); Pt b = Pt.fromY(2); System.out.printf("a = %s%n", a); System.out.printf("b = %s%n", b); Pt c = a.plus(b); System.out.printf("c = a + b = %s%n", c); Pt d = c.neg(); System.out.printf("d = -c = %s%n", d); System.out.printf("c + d = %s%n", c.plus(d)); System.out.printf("a + b + d = %s%n", a.plus(b).plus(d)); System.out.printf("a * 12345 = %s%n", a.mult(12345)); } } class Pt { final static int bCoeff = 7; double x, y; Pt(double x, double y) { this.x = x; this.y = y; } static Pt zero() { return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); } boolean isZero() { return this.x > 1e20 || this.x < -1e20; } static Pt fromY(double y) { return new Pt(cbrt(pow(y, 2) - bCoeff), y); } Pt dbl() { if (isZero()) return this; double L = (3 * this.x * this.x) / (2 * this.y); double x2 = pow(L, 2) - 2 * this.x; return new Pt(x2, L * (this.x - x2) - this.y); } Pt neg() { return new Pt(this.x, -this.y); } Pt plus(Pt q) { if (this.x == q.x && this.y == q.y) return dbl(); if (isZero()) return q; if (q.isZero()) return this; double L = (q.y - this.y) / (q.x - this.x); double xx = pow(L, 2) - this.x - q.x; return new Pt(xx, L * (this.x - xx) - this.y); } Pt mult(int n) { Pt r = Pt.zero(); Pt p = this; for (int i = 1; i <= n; i <<= 1) { if ((i & n) != 0) r = r.plus(p); p = p.dbl(); } return r; } @Override public String toString() { if (isZero()) return "Zero"; return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y); } }
Can you help me rewrite this code in Java instead of Go, keeping it the same logically?
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Count("the three truths", "th")) fmt.Println(strings.Count("ababababab", "abab")) }
public class CountSubstring { public static int countSubstring(String subStr, String str){ return (str.length() - str.replace(subStr, "").length()) / subStr.length(); } public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("abab", "ababababab")); System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); } }
Maintain the same structure and functionality when rewriting this code in Java.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
Rewrite this program in Java while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
Translate this program into Java but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) func main() { c := "cat" d := "dog" if c == d { fmt.Println(c, "is bytewise identical to", d) } if c != d { fmt.Println(c, "is bytewise different from", d) } if c > d { fmt.Println(c, "is lexically bytewise greater than", d) } if c < d { fmt.Println(c, "is lexically bytewise less than", d) } if c >= d { fmt.Println(c, "is lexically bytewise greater than or equal to", d) } if c <= d { fmt.Println(c, "is lexically bytewise less than or equal to", d) } eqf := `when interpreted as UTF-8 and compared under Unicode simple case folding rules.` if strings.EqualFold(c, d) { fmt.Println(c, "equal to", d, eqf) } else { fmt.Println(c, "not equal to", d, eqf) } }
public class Compare { public static void compare (String A, String B) { if (A.equals(B)) System.debug(A + ' and ' + B + ' are lexically equal.'); else System.debug(A + ' and ' + B + ' are not lexically equal.'); if (A.equalsIgnoreCase(B)) System.debug(A + ' and ' + B + ' are case-insensitive lexically equal.'); else System.debug(A + ' and ' + B + ' are not case-insensitive lexically equal.'); if (A.compareTo(B) < 0) System.debug(A + ' is lexically before ' + B); else if (A.compareTo(B) > 0) System.debug(A + ' is lexically after ' + B); if (A.compareTo(B) >= 0) System.debug(A + ' is not lexically before ' + B); if (A.compareTo(B) <= 0) System.debug(A + ' is not lexically after ' + B); System.debug('The lexical relationship is: ' + A.compareTo(B)); } }
Port the following code from Go to Java with equivalent syntax and logic.
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
Can you help me rewrite this code in Java instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) func main() { const nn = 32 const step = .05 xVal := make([]float64, nn) tSin := make([]float64, nn) tCos := make([]float64, nn) tTan := make([]float64, nn) for i := range xVal { xVal[i] = float64(i) * step tSin[i], tCos[i] = math.Sincos(xVal[i]) tTan[i] = tSin[i] / tCos[i] } iSin := thieleInterpolator(tSin, xVal) iCos := thieleInterpolator(tCos, xVal) iTan := thieleInterpolator(tTan, xVal) fmt.Printf("%16.14f\n", 6*iSin(.5)) fmt.Printf("%16.14f\n", 3*iCos(.5)) fmt.Printf("%16.14f\n", 4*iTan(1)) } func thieleInterpolator(x, y []float64) func(float64) float64 { n := len(x) ρ := make([][]float64, n) for i := range ρ { ρ[i] = make([]float64, n-i) ρ[i][0] = y[i] } for i := 0; i < n-1; i++ { ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) } for i := 2; i < n; i++ { for j := 0; j < n-i; j++ { ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] } } ρ0 := ρ[0] return func(xin float64) float64 { var a float64 for i := n - 1; i > 1; i-- { a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) } return y[0] + (xin-x[0])/(ρ0[1]+a) } }
import static java.lang.Math.*; public class Test { final static int N = 32; final static int N2 = (N * (N - 1) / 2); final static double STEP = 0.05; static double[] xval = new double[N]; static double[] t_sin = new double[N]; static double[] t_cos = new double[N]; static double[] t_tan = new double[N]; static double[] r_sin = new double[N2]; static double[] r_cos = new double[N2]; static double[] r_tan = new double[N2]; static double rho(double[] x, double[] y, double[] r, int i, int n) { if (n < 0) return 0; if (n == 0) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } static double thiele(double[] x, double[] y, double[] r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } public static void main(String[] args) { for (int i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (int i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN; System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0)); System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0)); System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0)); } }
Port the following code from Go to Java with equivalent syntax and logic.
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
import java.util.*; public class FWord { private String fWord0 = ""; private String fWord1 = ""; private String nextFWord () { final String result; if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
Change the following Go code into Java without altering its purpose.
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
import java.util.*; public class FWord { private String fWord0 = ""; private String fWord1 = ""; private String nextFWord () { final String result; if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
Rewrite this program in Java while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d float64) float64 { return d2d(d) * 400 / 360 } func d2m(d float64) float64 { return d2d(d) * 6400 / 360 } func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 } func g2d(g float64) float64 { return g2g(g) * 360 / 400 } func g2m(g float64) float64 { return g2g(g) * 6400 / 400 } func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 } func m2d(m float64) float64 { return m2m(m) * 360 / 6400 } func m2g(m float64) float64 { return m2m(m) * 400 / 6400 } func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 } func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi } func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi } func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi } func s(f float64) string { wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".") if len(wf) == 1 { return fmt.Sprintf("%7s ", wf[0]) } le := len(wf[1]) if le > 7 { le = 7 } return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le]) } func main() { angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ft := "%s %s %s %s %s\n" fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a))) } fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a))) } fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a))) } fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ") for _, a := range angles { fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))) } }
import java.text.DecimalFormat; public class AnglesNormalizationAndConversion { public static void main(String[] args) { DecimalFormat formatAngle = new DecimalFormat("######0.000000"); DecimalFormat formatConv = new DecimalFormat("###0.0000"); System.out.printf(" degrees gradiens mils radians%n"); for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) { for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) { double d = 0, g = 0, m = 0, r = 0; switch (units) { case "degrees": d = d2d(angle); g = d2g(d); m = d2m(d); r = d2r(d); break; case "gradiens": g = g2g(angle); d = g2d(g); m = g2m(g); r = g2r(g); break; case "mils": m = m2m(angle); d = m2d(m); g = m2g(m); r = m2r(m); break; case "radians": r = r2r(angle); d = r2d(r); g = r2g(r); m = r2m(r); break; } System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r)); } } } private static final double DEGREE = 360D; private static final double GRADIAN = 400D; private static final double MIL = 6400D; private static final double RADIAN = (2 * Math.PI); private static double d2d(double a) { return a % DEGREE; } private static double d2g(double a) { return a * (GRADIAN / DEGREE); } private static double d2m(double a) { return a * (MIL / DEGREE); } private static double d2r(double a) { return a * (RADIAN / 360); } private static double g2d(double a) { return a * (DEGREE / GRADIAN); } private static double g2g(double a) { return a % GRADIAN; } private static double g2m(double a) { return a * (MIL / GRADIAN); } private static double g2r(double a) { return a * (RADIAN / GRADIAN); } private static double m2d(double a) { return a * (DEGREE / MIL); } private static double m2g(double a) { return a * (GRADIAN / MIL); } private static double m2m(double a) { return a % MIL; } private static double m2r(double a) { return a * (RADIAN / MIL); } private static double r2d(double a) { return a * (DEGREE / RADIAN); } private static double r2g(double a) { return a * (GRADIAN / RADIAN); } private static double r2m(double a) { return a * (MIL / RADIAN); } private static double r2r(double a) { return a % RADIAN; } }
Rewrite the snippet below in Java so it works the same as the original Go code.
package main import ( "fmt" "os" "path" ) func CommonPrefix(sep byte, paths ...string) string { switch len(paths) { case 0: return "" case 1: return path.Clean(paths[0]) } c := []byte(path.Clean(paths[0])) c = append(c, sep) for _, v := range paths[1:] { v = path.Clean(v) + string(sep) if len(v) < len(c) { c = c[:len(v)] } for i := 0; i < len(c); i++ { if v[i] != c[i] { c = c[:i] break } } } for i := len(c) - 1; i >= 0; i-- { if c[i] == sep { c = c[:i] break } } return string(c) } func main() { c := CommonPrefix(os.PathSeparator, "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", "/home "/home/user1/././tmp/covertly/foo", "/home/bob/../user1/tmp/coved/bar", ) if c == "" { fmt.Println("No common path") } else { fmt.Println("Common path:", c) } }
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
Write a version of this Go function in Java with identical behavior.
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
import static java.lang.Math.abs; import java.util.*; import java.util.function.IntSupplier; public class Test { static void distCheck(IntSupplier f, int nRepeats, double delta) { Map<Integer, Integer> counts = new HashMap<>(); for (int i = 0; i < nRepeats; i++) counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1); double target = nRepeats / (double) counts.size(); int deltaCount = (int) (delta / 100.0 * target); counts.forEach((k, v) -> { if (abs(target - v) >= deltaCount) System.out.printf("distribution potentially skewed " + "for '%s': '%d'%n", k, v); }); counts.keySet().stream().sorted().forEach(k -> System.out.printf("%d %d%n", k, counts.get(k))); } public static void main(String[] a) { distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1); } }
Port the following code from Go to Java with equivalent syntax and logic.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Port the following code from Go to Java with equivalent syntax and logic.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Produce a language-to-language conversion: from Go to Java, same semantics.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Maintain the same structure and functionality when rewriting this code in Java.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Change the programming language of this snippet from Go to Java without modifying what it does.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Keep all operations the same but rewrite the snippet in Java.
func inc(n int) { x := n + 1 println(x) }
Object foo = new Object(); int[] fooArray = new int[size]; int x = 0;
Change the following Go code into Java without altering its purpose.
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
Translate the given Go code snippet into Java without altering its behavior.
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
Convert this Go snippet to Java and keep its semantics consistent.
package main import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" ) func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) } func entropy(file string) float64 { d, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } var f [256]float64 for _, b := range d { f[b]++ } hm := 0. for _, c := range f { if c > 0 { hm += c * math.Log2(c) } } l := float64(len(d)) return math.Log2(l) - hm/l }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Generate a Java translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" ) func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) } func entropy(file string) float64 { d, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } var f [256]float64 for _, b := range d { f[b]++ } hm := 0. for _, c := range f { if c > 0 { hm += c * math.Log2(c) } } l := float64(len(d)) return math.Log2(l) - hm/l }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Port the provided Go code into Java while preserving the original functionality.
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Port the provided Go code into Java while preserving the original functionality.
package main import "github.com/fogleman/gg" var points []gg.Point const width = 81 func peano(x, y, lg, i1, i2 int) { if lg == 1 { px := float64(width-x) * 10 py := float64(width-y) * 10 points = append(points, gg.Point{px, py}) return } lg /= 3 peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2) peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2) peano(x+lg, y+lg, lg, i1, 1-i2) peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2) peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2) peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2) peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2) peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2) peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2) } func main() { peano(0, 0, width, 0, 0) dc := gg.NewContext(820, 820) dc.SetRGB(1, 1, 1) dc.Clear() for _, p := range points { dc.LineTo(p.X, p.Y) } dc.SetRGB(1, 0, 1) dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("peano.png") }
import java.io.*; public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.currentX = length; s.currentY = length; s.lineLength = length; s.begin(656); s.execute(rewrite(4)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private PeanoCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = "L"; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'L') sb.append("LFRFL-F-RFLFR+F+LFRFL"); else if (ch == 'R') sb.append("RFLFR+F+LFRFL-F-RFLFR"); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final int ANGLE = 90; }
Convert this Go snippet to Java and keep its semantics consistent.
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
import java.util.Random; public class SevenSidedDice { private static final Random rnd = new Random(); public static void main(String[] args) { SevenSidedDice now=new SevenSidedDice(); System.out.println("Random number from 1 to 7: "+now.seven()); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1+rnd.nextInt(5); } }
Produce a functionally identical Java code for the snippet given in Go.
package main import ( "fmt" "strings" ) func main() { p, tests, swaps := Solution() fmt.Println(p) fmt.Println("Tested", tests, "positions and did", swaps, "swaps.") } const conn = ` A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H` var connections = []struct{ a, b int }{ {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, } type pegs [8]int func (p *pegs) Valid() bool { for _, c := range connections { if absdiff(p[c.a], p[c.b]) <= 1 { return false } } return true } func Solution() (p *pegs, tests, swaps int) { var recurse func(int) bool recurse = func(i int) bool { if i >= len(p)-1 { tests++ return p.Valid() } for j := i; j < len(p); j++ { swaps++ p[i], p[j] = p[j], p[i] if recurse(i + 1) { return true } p[i], p[j] = p[j], p[i] } return false } p = &pegs{1, 2, 3, 4, 5, 6, 7, 8} recurse(0) return } func (p *pegs) String() string { return strings.Map(func(r rune) rune { if 'A' <= r && r <= 'H' { return rune(p[r-'A'] + '0') } return r }, conn) } func absdiff(a, b int) int { if a > b { return a - b } return b - a }
import static java.lang.Math.abs; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public class NoConnection { static int[][] links = { {2, 3, 4}, {3, 4, 5}, {2, 4}, {5}, {2, 3, 4}, {3, 4, 5}, }; static int[] pegs = new int[8]; public static void main(String[] args) { List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList()); do { Collections.shuffle(vals); for (int i = 0; i < pegs.length; i++) pegs[i] = vals.get(i); } while (!solved()); printResult(); } static boolean solved() { for (int i = 0; i < links.length; i++) for (int peg : links[i]) if (abs(pegs[i] - peg) == 1) return false; return true; } static void printResult() { System.out.printf(" %s %s%n", pegs[0], pegs[1]); System.out.printf("%s %s %s %s%n", pegs[2], pegs[3], pegs[4], pegs[5]); System.out.printf(" %s %s%n", pegs[6], pegs[7]); } }
Port the provided Go code into Java while preserving the original functionality.
package main import "fmt" func isPrime(n uint64) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := uint64(5) for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func ord(n int) string { m := n % 100 if m >= 4 && m <= 20 { return fmt.Sprintf("%dth", n) } m %= 10 suffix := "th" if m < 4 { switch m { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" } } return fmt.Sprintf("%d%s", n, suffix) } func isMagnanimous(n uint64) bool { if n < 10 { return true } for p := uint64(10); ; p *= 10 { q := n / p r := n % p if !isPrime(q + r) { return false } if q < 10 { break } } return true } func listMags(from, thru, digs, perLine int) { if from < 2 { fmt.Println("\nFirst", thru, "magnanimous numbers:") } else { fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru)) } for i, c := uint64(0), 0; c < thru; i++ { if isMagnanimous(i) { c++ if c >= from { fmt.Printf("%*d ", digs, i) if c%perLine == 0 { fmt.Println() } } } } } func main() { listMags(1, 45, 3, 15) listMags(241, 250, 1, 10) listMags(391, 400, 1, 10) }
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
Generate a Java translation of this Go snippet without changing its computational steps.
package main import "fmt" func isPrime(n uint64) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := uint64(5) for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func ord(n int) string { m := n % 100 if m >= 4 && m <= 20 { return fmt.Sprintf("%dth", n) } m %= 10 suffix := "th" if m < 4 { switch m { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" } } return fmt.Sprintf("%d%s", n, suffix) } func isMagnanimous(n uint64) bool { if n < 10 { return true } for p := uint64(10); ; p *= 10 { q := n / p r := n % p if !isPrime(q + r) { return false } if q < 10 { break } } return true } func listMags(from, thru, digs, perLine int) { if from < 2 { fmt.Println("\nFirst", thru, "magnanimous numbers:") } else { fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru)) } for i, c := uint64(0), 0; c < thru; i++ { if isMagnanimous(i) { c++ if c >= from { fmt.Printf("%*d ", digs, i) if c%perLine == 0 { fmt.Println() } } } } } func main() { listMags(1, 45, 3, 15) listMags(241, 250, 1, 10) listMags(391, 400, 1, 10) }
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
Write the same code in Java as shown below in Go.
package main import ( "container/heap" "fmt" ) func main() { p := newP() fmt.Print("First twenty: ") for i := 0; i < 20; i++ { fmt.Print(p(), " ") } fmt.Print("\nBetween 100 and 150: ") n := p() for n <= 100 { n = p() } for ; n < 150; n = p() { fmt.Print(n, " ") } for n <= 7700 { n = p() } c := 0 for ; n < 8000; n = p() { c++ } fmt.Println("\nNumber beween 7,700 and 8,000:", c) p = newP() for i := 1; i < 10000; i++ { p() } fmt.Println("10,000th prime:", p()) } func newP() func() int { n := 1 var pq pQueue top := &pMult{2, 4, 0} return func() int { for { n++ if n < top.pMult { heap.Push(&pq, &pMult{prime: n, pMult: n * n}) top = pq[0] return n } for top.pMult == n { top.pMult += top.prime heap.Fix(&pq, 0) top = pq[0] } } } } type pMult struct { prime int pMult int index int } type pQueue []*pMult func (q pQueue) Len() int { return len(q) } func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult } func (q pQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] q[i].index = i q[j].index = j } func (p *pQueue) Push(x interface{}) { q := *p e := x.(*pMult) e.index = len(q) *p = append(q, e) } func (p *pQueue) Pop() interface{} { q := *p last := len(q) - 1 e := q[last] *p = q[:last] return e }
import java.util.*; public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0; public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); } public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); } public int count() { return count_; } private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } } private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); } private static int nextOddNumber(int n) { return 1 + 2 * (n/2); } public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
Port the following code from Go to Java with equivalent syntax and logic.
package main import ( "fmt" "math/rand" "strings" "time" ) const rps = "rps" var msg = []string{ "Rock breaks scissors", "Paper covers rock", "Scissors cut paper", } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println("Rock Paper Scissors") fmt.Println("Enter r, p, or s as your play. Anything else ends the game.") fmt.Println("Running score shown as <your wins>:<my wins>") var pi string var aScore, pScore int sl := 3 pcf := make([]int, 3) var plays int aChoice := rand.Intn(3) for { fmt.Print("Play: ") _, err := fmt.Scanln(&pi) if err != nil || len(pi) != 1 { break } pChoice := strings.Index(rps, pi) if pChoice < 0 { break } pcf[pChoice]++ plays++ fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice]) switch (aChoice - pChoice + 3) % 3 { case 0: fmt.Println("Tie.") case 1: fmt.Printf("%s. My point.\n", msg[aChoice]) aScore++ case 2: fmt.Printf("%s. Your point.\n", msg[pChoice]) pScore++ } sl, _ = fmt.Printf("%d:%d ", pScore, aScore) switch rn := rand.Intn(plays); { case rn < pcf[0]: aChoice = 1 case rn < pcf[0]+pcf[1]: aChoice = 2 default: aChoice = 0 } } }
import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Random; public class RPS { public enum Item{ ROCK, PAPER, SCISSORS, ; public List<Item> losesToList; public boolean losesTo(Item other) { return losesToList.contains(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK); ROCK.losesToList = Arrays.asList(PAPER); PAPER.losesToList = Arrays.asList(SCISSORS); } } public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{ for(Item item:Item.values()) put(item, 1); }}; private int totalThrows = Item.values().length; public static void main(String[] args){ RPS rps = new RPS(); rps.run(); } public void run() { Scanner in = new Scanner(System.in); System.out.print("Make your choice: "); while(in.hasNextLine()){ Item aiChoice = getAIChoice(); String input = in.nextLine(); Item choice; try{ choice = Item.valueOf(input.toUpperCase()); }catch (IllegalArgumentException ex){ System.out.println("Invalid choice"); continue; } counts.put(choice, counts.get(choice) + 1); totalThrows++; System.out.println("Computer chose: " + aiChoice); if(aiChoice == choice){ System.out.println("Tie!"); }else if(aiChoice.losesTo(choice)){ System.out.println("You chose...wisely. You win!"); }else{ System.out.println("You chose...poorly. You lose!"); } System.out.print("Make your choice: "); } } private static final Random rng = new Random(); private Item getAIChoice() { int rand = rng.nextInt(totalThrows); for(Map.Entry<Item, Integer> entry:counts.entrySet()){ Item item = entry.getKey(); int count = entry.getValue(); if(rand < count){ List<Item> losesTo = item.losesToList; return losesTo.get(rng.nextInt(losesTo.size())); } rand -= count; } return null; } }
Generate a Java translation of this Go snippet without changing its computational steps.
package main import "fmt" func main() { var row, col int fmt.Print("enter rows cols: ") fmt.Scan(&row, &col) a := make([][]int, row) for i := range a { a[i] = make([]int, col) } fmt.Println("a[0][0] =", a[0][0]) a[row-1][col-1] = 7 fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1]) a = nil }
import java.util.Scanner; public class twoDimArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nbr1 = in.nextInt(); int nbr2 = in.nextInt(); double[][] array = new double[nbr1][nbr2]; array[0][0] = 42.0; System.out.println("The number at place [0 0] is " + array[0][0]); } }
Convert this Go block to Java, preserving its control flow and logic.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Please provide an equivalent version of this Go code in Java.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Produce a functionally identical Java code for the snippet given in Go.
package main import ( "fmt" "strings" ) var encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK" var freq = [26]float64{ 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074, } func sum(a []float64) (sum float64) { for _, f := range a { sum += f } return } func bestMatch(a []float64) int { sum := sum(a) bestFit, bestRotate := 1e100, 0 for rotate := 0; rotate < 26; rotate++ { fit := 0.0 for i := 0; i < 26; i++ { d := a[(i+rotate)%26]/sum - freq[i] fit += d * d / freq[i] } if fit < bestFit { bestFit, bestRotate = fit, rotate } } return bestRotate } func freqEveryNth(msg []int, key []byte) float64 { l := len(msg) interval := len(key) out := make([]float64, 26) accu := make([]float64, 26) for j := 0; j < interval; j++ { for k := 0; k < 26; k++ { out[k] = 0.0 } for i := j; i < l; i += interval { out[msg[i]]++ } rot := bestMatch(out) key[j] = byte(rot + 65) for i := 0; i < 26; i++ { accu[i] += out[(i+rot)%26] } } sum := sum(accu) ret := 0.0 for i := 0; i < 26; i++ { d := accu[i]/sum - freq[i] ret += d * d / freq[i] } return ret } func decrypt(text, key string) string { var sb strings.Builder ki := 0 for _, c := range text { if c < 'A' || c > 'Z' { continue } ci := (c - rune(key[ki]) + 26) % 26 sb.WriteRune(ci + 65) ki = (ki + 1) % len(key) } return sb.String() } func main() { enc := strings.Replace(encoded, " ", "", -1) txt := make([]int, len(enc)) for i := 0; i < len(txt); i++ { txt[i] = int(enc[i] - 'A') } bestFit, bestKey := 1e100, "" fmt.Println(" Fit Length Key") for j := 1; j <= 26; j++ { key := make([]byte, j) fit := freqEveryNth(txt, key) sKey := string(key) fmt.Printf("%f %2d %s", fit, j, sKey) if fit < bestFit { bestFit, bestKey = fit, sKey fmt.Print(" <--- best so far") } fmt.Println() } fmt.Println("\nBest key :", bestKey) fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey)) }
public class Vig{ static String encodedMessage = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; final static double freq[] = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; public static void main(String[] args) { int lenghtOfEncodedMessage = encodedMessage.length(); char[] encoded = new char [lenghtOfEncodedMessage] ; char[] key = new char [lenghtOfEncodedMessage] ; encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0); int txt[] = new int[lenghtOfEncodedMessage]; int len = 0, j; double fit, best_fit = 1e100; for (j = 0; j < lenghtOfEncodedMessage; j++) if (Character.isUpperCase(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); System.out.printf("%f, key length: %2d ", fit, j); System.out.print(key); if (fit < best_fit) { best_fit = fit; System.out.print(" <--- best so far"); } System.out.print("\n"); } } static String decrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length(); } return res; } static int best_match(final double []a, final double []b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } static double freq_every_nth(final int []msg, int len, int interval, char[] key) { double sum, d, ret; double [] accu = new double [26]; double [] out = new double [26]; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; rot = best_match(out, freq); try{ key[j] = (char)(rot + 'A'); } catch (Exception e) { System.out.print(e.getMessage()); } for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } }
Write the same code in Java as shown below in Go.
package main import ( "fmt" "math/big" ) type lft struct { q,r,s,t big.Int } func (t *lft) extr(x *big.Int) *big.Rat { var n, d big.Int var r big.Rat return r.SetFrac( n.Add(n.Mul(&t.q, x), &t.r), d.Add(d.Mul(&t.s, x), &t.t)) } var three = big.NewInt(3) var four = big.NewInt(4) func (t *lft) next() *big.Int { r := t.extr(three) var f big.Int return f.Div(r.Num(), r.Denom()) } func (t *lft) safe(n *big.Int) bool { r := t.extr(four) var f big.Int if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 { return true } return false } func (t *lft) comp(u *lft) *lft { var r lft var a, b big.Int r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s)) r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t)) r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s)) r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t)) return &r } func (t *lft) prod(n *big.Int) *lft { var r lft r.q.SetInt64(10) r.r.Mul(r.r.SetInt64(-10), n) r.t.SetInt64(1) return r.comp(t) } func main() { z := new(lft) z.q.SetInt64(1) z.t.SetInt64(1) var k int64 lfts := func() *lft { k++ r := new(lft) r.q.SetInt64(k) r.r.SetInt64(4*k+2) r.t.SetInt64(2*k+1) return r } for { y := z.next() if z.safe(y) { fmt.Print(y) z = z.prod(y) } else { z = z.comp(lfts()) } } }
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
Keep all operations the same but rewrite the snippet in Java.
package main import "fmt" var m map[int]int func initMap() { m = make(map[int]int) m[1] = 1 m[2] = 1 } func q(n int) (r int) { if r = m[n]; r == 0 { r = q(n-q(n-1)) + q(n-q(n-2)) m[n] = r } return } func main() { initMap() for n := 1; n <= 10; n++ { showQ(n) } showQ(1000) count, p := 0, 1 for n := 2; n <= 1e5; n++ { qn := q(n) if qn < p { count++ } p = qn } fmt.Println("count:", count) initMap() showQ(1e6) } func showQ(n int) { fmt.Printf("Q(%d) = %d\n", n, q(n)) }
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Rewrite the snippet below in Java so it works the same as the original Go code.
package main import "fmt" var m map[int]int func initMap() { m = make(map[int]int) m[1] = 1 m[2] = 1 } func q(n int) (r int) { if r = m[n]; r == 0 { r = q(n-q(n-1)) + q(n-q(n-2)) m[n] = r } return } func main() { initMap() for n := 1; n <= 10; n++ { showQ(n) } showQ(1000) count, p := 0, 1 for n := 2; n <= 1e5; n++ { qn := q(n) if qn < p { count++ } p = qn } fmt.Println("count:", count) initMap() showQ(1e6) } func showQ(n int) { fmt.Printf("Q(%d) = %d\n", n, q(n)) }
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Write the same algorithm in Java as shown in this Go implementation.
package main import "fmt" type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) } func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func { return f(func(x int) int { return r(r)(x) }) } return g(g) } func almost_fac(f Func) Func { return func(x int) int { if x <= 1 { return 1 } return x * f(x-1) } } func almost_fib(f Func) Func { return func(x int) int { if x <= 2 { return 1 } return f(x-1)+f(x-2) } }
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Can you help me rewrite this code in Java instead of Go, keeping it the same logically?
package main import "fmt" type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) } func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func { return f(func(x int) int { return r(r)(x) }) } return g(g) } func almost_fac(f Func) Func { return func(x int) int { if x <= 1 { return 1 } return x * f(x-1) } } func almost_fib(f Func) Func { return func(x int) int { if x <= 2 { return 1 } return f(x-1)+f(x-2) } }
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Transform the following Go implementation into Java, maintaining the same output and logic.
func addsub(x, y int) (int, int) { return x + y, x - y }
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
Write the same code in Java as shown below in Go.
package main import "fmt" func main() { const max = 1000 a := make([]int, max) for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("The first ten terms of the Van Eck sequence are:") fmt.Println(a[:10]) fmt.Println("\nTerms 991 to 1000 of the sequence are:") fmt.Println(a[990:]) }
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
Keep all operations the same but rewrite the snippet in Java.
package main import "fmt" func main() { const max = 1000 a := make([]int, max) for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("The first ten terms of the Van Eck sequence are:") fmt.Println(a[:10]) fmt.Println("\nTerms 991 to 1000 of the sequence are:") fmt.Println(a[990:]) }
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
Port the provided Go code into Java while preserving the original functionality.
package main import ( "fmt" "io" "log" "os" "github.com/stacktic/ftp" ) func main() { const ( hostport = "localhost:21" username = "anonymous" password = "anonymous" dir = "pub" file = "somefile.bin" ) conn, err := ftp.Connect(hostport) if err != nil { log.Fatal(err) } defer conn.Quit() fmt.Println(conn) if err = conn.Login(username, password); err != nil { log.Fatal(err) } if err = conn.ChangeDir(dir); err != nil { log.Fatal(err) } fmt.Println(conn.CurrentDir()) files, err := conn.List(".") if err != nil { log.Fatal(err) } for _, f := range files { fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name) } r, err := conn.Retr(file) if err != nil { log.Fatal(err) } defer r.Close() f, err := os.Create(file) if err != nil { log.Fatal(err) } defer f.Close() n, err := io.Copy(f, r) if err != nil { log.Fatal(err) } fmt.Println("Wrote", n, "bytes to", file) }
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "ftptest@example.com"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
Translate the given Go code snippet into Java without altering its behavior.
package main import ( "fmt" "io" "log" "os" "github.com/stacktic/ftp" ) func main() { const ( hostport = "localhost:21" username = "anonymous" password = "anonymous" dir = "pub" file = "somefile.bin" ) conn, err := ftp.Connect(hostport) if err != nil { log.Fatal(err) } defer conn.Quit() fmt.Println(conn) if err = conn.Login(username, password); err != nil { log.Fatal(err) } if err = conn.ChangeDir(dir); err != nil { log.Fatal(err) } fmt.Println(conn.CurrentDir()) files, err := conn.List(".") if err != nil { log.Fatal(err) } for _, f := range files { fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name) } r, err := conn.Retr(file) if err != nil { log.Fatal(err) } defer r.Close() f, err := os.Create(file) if err != nil { log.Fatal(err) } defer f.Close() n, err := io.Copy(f, r) if err != nil { log.Fatal(err) } fmt.Println("Wrote", n, "bytes to", file) }
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "ftptest@example.com"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
Write the same algorithm in Java as shown in this Go implementation.
package main import ( "fmt" "math" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&expr) if len(expr) != 7 { fmt.Println("invalid. expression length must be 7." + " (4 numbers, 3 operators, no spaces)") return } stack := make([]float64, 0, 4) for _, r := range expr { if r >= '0' && r <= '9' { if len(n) == 0 { fmt.Println("too many numbers.") return } i := 0 for n[i] != r { i++ if i == len(n) { fmt.Println("wrong numbers.") return } } n = append(n[:i], n[i+1:]...) stack = append(stack, float64(r-'0')) continue } if len(stack) < 2 { fmt.Println("invalid expression syntax.") return } switch r { case '+': stack[len(stack)-2] += stack[len(stack)-1] case '-': stack[len(stack)-2] -= stack[len(stack)-1] case '*': stack[len(stack)-2] *= stack[len(stack)-1] case '/': stack[len(stack)-2] /= stack[len(stack)-1] default: fmt.Printf("%c invalid.\n", r) return } stack = stack[:len(stack)-1] } if math.Abs(stack[0]-24) > 1e-6 { fmt.Println("incorrect.", stack[0], "!= 24") } else { fmt.Println("correct.") } }
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Rewrite this program in Java while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&expr) if len(expr) != 7 { fmt.Println("invalid. expression length must be 7." + " (4 numbers, 3 operators, no spaces)") return } stack := make([]float64, 0, 4) for _, r := range expr { if r >= '0' && r <= '9' { if len(n) == 0 { fmt.Println("too many numbers.") return } i := 0 for n[i] != r { i++ if i == len(n) { fmt.Println("wrong numbers.") return } } n = append(n[:i], n[i+1:]...) stack = append(stack, float64(r-'0')) continue } if len(stack) < 2 { fmt.Println("invalid expression syntax.") return } switch r { case '+': stack[len(stack)-2] += stack[len(stack)-1] case '-': stack[len(stack)-2] -= stack[len(stack)-1] case '*': stack[len(stack)-2] *= stack[len(stack)-1] case '/': stack[len(stack)-2] /= stack[len(stack)-1] default: fmt.Printf("%c invalid.\n", r) return } stack = stack[:len(stack)-1] } if math.Abs(stack[0]-24) > 1e-6 { fmt.Println("incorrect.", stack[0], "!= 24") } else { fmt.Println("correct.") } }
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Rewrite the snippet below in Java so it works the same as the original Go code.
package main import "fmt" func main() { for i := 1; i <= 10; i++ { fmt.Printf("%d", i) if i%5 == 0 { fmt.Printf("\n") continue } fmt.Printf(", ") } }
for(int i = 1;i <= 10; i++){ System.out.print(i); if(i % 5 == 0){ System.out.println(); continue; } System.out.print(", "); }
Produce a language-to-language conversion: from Go to Java, same semantics.
package main import "github.com/fogleman/gg" var colors = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func drawBars(dc *gg.Context) { w := float64(dc.Width() / len(colors)) h := float64(dc.Height()) for i := range colors { dc.SetHexColor(colors[i]) dc.DrawRectangle(w*float64(i), 0, w, h) dc.Fill() } } func main() { dc := gg.NewContext(400, 400) drawBars(dc) dc.SavePNG("color_bars.png") }
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
Translate this program into Java but keep the logic exactly as in Go.
package main import "github.com/fogleman/gg" var colors = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func drawBars(dc *gg.Context) { w := float64(dc.Width() / len(colors)) h := float64(dc.Height()) for i := range colors { dc.SetHexColor(colors[i]) dc.DrawRectangle(w*float64(i), 0, w, h) dc.Fill() } } func main() { dc := gg.NewContext(400, 400) drawBars(dc) dc.SavePNG("color_bars.png") }
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
Preserve the algorithm and functionality while converting the code from Go to Java.
package main import "fmt" type matrix [][]float64 func zero(n int) matrix { r := make([][]float64, n) a := make([]float64, n*n) for i := range r { r[i] = a[n*i : n*(i+1)] } return r } func eye(n int) matrix { r := zero(n) for i := range r { r[i][i] = 1 } return r } func (m matrix) print(label string) { if label > "" { fmt.Printf("%s:\n", label) } for _, r := range m { for _, e := range r { fmt.Printf(" %9.5f", e) } fmt.Println() } } func (a matrix) pivotize() matrix { p := eye(len(a)) for j, r := range a { max := r[j] row := j for i := j; i < len(a); i++ { if a[i][j] > max { max = a[i][j] row = i } } if j != row { p[j], p[row] = p[row], p[j] } } return p } func (m1 matrix) mul(m2 matrix) matrix { r := zero(len(m1)) for i, r1 := range m1 { for j := range m2 { for k := range m1 { r[i][j] += r1[k] * m2[k][j] } } } return r } func (a matrix) lu() (l, u, p matrix) { l = zero(len(a)) u = zero(len(a)) p = a.pivotize() a = p.mul(a) for j := range a { l[j][j] = 1 for i := 0; i <= j; i++ { sum := 0. for k := 0; k < i; k++ { sum += u[k][j] * l[i][k] } u[i][j] = a[i][j] - sum } for i := j; i < len(a); i++ { sum := 0. for k := 0; k < j; k++ { sum += u[k][j] * l[i][k] } l[i][j] = (a[i][j] - sum) / u[j][j] } } return } func main() { showLU(matrix{ {1, 3, 5}, {2, 4, 7}, {1, 1, 0}}) showLU(matrix{ {11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}) } func showLU(a matrix) { a.print("\na") l, u, p := a.lu() l.print("l") u.print("u") p.print("p") }
import static java.util.Arrays.stream; import java.util.Locale; import static java.util.stream.IntStream.range; public class Test { static double dotProduct(double[] a, double[] b) { return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum(); } static double[][] matrixMul(double[][] A, double[][] B) { double[][] result = new double[A.length][B[0].length]; double[] aux = new double[B.length]; for (int j = 0; j < B[0].length; j++) { for (int k = 0; k < B.length; k++) aux[k] = B[k][j]; for (int i = 0; i < A.length; i++) result[i][j] = dotProduct(A[i], aux); } return result; } static double[][] pivotize(double[][] m) { int n = m.length; double[][] id = range(0, n).mapToObj(j -> range(0, n) .mapToDouble(i -> i == j ? 1 : 0).toArray()) .toArray(double[][]::new); for (int i = 0; i < n; i++) { double maxm = m[i][i]; int row = i; for (int j = i; j < n; j++) if (m[j][i] > maxm) { maxm = m[j][i]; row = j; } if (i != row) { double[] tmp = id[i]; id[i] = id[row]; id[row] = tmp; } } return id; } static double[][][] lu(double[][] A) { int n = A.length; double[][] L = new double[n][n]; double[][] U = new double[n][n]; double[][] P = pivotize(A); double[][] A2 = matrixMul(P, A); for (int j = 0; j < n; j++) { L[j][j] = 1; for (int i = 0; i < j + 1; i++) { double s1 = 0; for (int k = 0; k < i; k++) s1 += U[k][j] * L[i][k]; U[i][j] = A2[i][j] - s1; } for (int i = j; i < n; i++) { double s2 = 0; for (int k = 0; k < j; k++) s2 += U[k][j] * L[i][k]; L[i][j] = (A2[i][j] - s2) / U[j][j]; } } return new double[][][]{L, U, P}; } static void print(double[][] m) { stream(m).forEach(a -> { stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n)); System.out.println(); }); System.out.println(); } public static void main(String[] args) { double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}}; double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1}, {2.0, 5, 7, 1}}; for (double[][] m : lu(a)) print(m); System.out.println(); for (double[][] m : lu(b)) print(m); } }
Rewrite this program in Java while keeping its functionality equivalent to the Go version.
package main import ( "fmt" ) const numbers = 3 func main() { max := 20 words := map[int]string{ 3: "Fizz", 5: "Buzz", 7: "Baxx", } keys := []int{3, 5, 7} divisible := false for i := 1; i <= max; i++ { for _, n := range keys { if i % n == 0 { fmt.Print(words[n]) divisible = true } } if !divisible { fmt.Print(i) } fmt.Println() divisible = false } }
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
Translate the given Python code snippet into C# without altering its behavior.
def bitwise_built_ins(width, a, b): mask = (1 << width) - 1 print(f) def rotr(width, a, n): "Rotate a, n times to the right" if n < 0: return rotl(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return ((a >> n) | ((a & ((1 << n) - 1)) << (width - n))) def rotl(width, a, n): "Rotate a, n times to the left" if n < 0: return rotr(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return (((a << n) & mask) | (a >> (width - n))) def asr(width, a, n): "Arithmetic shift a, n times to the right. (sign preserving)." mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) if n < 0: return (a << -n) & mask elif n == 0: return a elif n >= width: return mask if a & top_bit_mask else 0 else: a = a & mask if a & top_bit_mask: signs = (1 << n) - 1 return a >> n | (signs << width - n) else: return a >> n def helper_funcs(width, a): mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) aa = a | top_bit_mask print(f) if __name__ == '__main__': bitwise_built_ins(8, 27, 125) helper_funcs(8, 27)
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); }
Write a version of this Python function in C# with identical behavior.
l = 3 ints = 13 def setup(): size(700, 600) background(0, 0, 255) translate(150, 100) stroke(255) turn_left(l, ints) turn_right(l, ints) def turn_right(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(90)) turn_right(l, ints - 1) def turn_left(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(-90)) turn_right(l, ints - 1)
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; public class DragonCurve : Form { private List<int> turns; private double startingAngle, side; public DragonCurve(int iter) { Size = new Size(800, 600); StartPosition = FormStartPosition.CenterScreen; DoubleBuffered = true; BackColor = Color.White; startingAngle = -iter * (Math.PI / 4); side = 400 / Math.Pow(2, iter / 2.0); turns = getSequence(iter); } private List<int> getSequence(int iter) { var turnSequence = new List<int>(); for (int i = 0; i < iter; i++) { var copy = new List<int>(turnSequence); copy.Reverse(); turnSequence.Add(1); foreach (int turn in copy) { turnSequence.Add(-turn); } } return turnSequence; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int)(Math.Cos(angle) * side); int y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; foreach (int turn in turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int)(Math.Cos(angle) * side); y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; } } [STAThread] static void Main() { Application.Run(new DragonCurve(14)); } }
Write the same code in C# as shown below in Python.
def insert(anchor, new): new.next = anchor.next new.prev = anchor anchor.next.prev = new anchor.next = new
static void InsertAfter(Link prev, int i) { if (prev.next != null) { prev.next.prev = new Link() { item = i, prev = prev, next = prev.next }; prev.next = prev.next.prev; } else prev.next = new Link() { item = i, prev = prev }; }
Maintain the same structure and functionality when rewriting this code in C#.
import random def partition(vector, left, right, pivotIndex): pivotValue = vector[pivotIndex] vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] storeIndex = left for i in range(left, right): if vector[i] < pivotValue: vector[storeIndex], vector[i] = vector[i], vector[storeIndex] storeIndex += 1 vector[right], vector[storeIndex] = vector[storeIndex], vector[right] return storeIndex def _select(vector, left, right, k): "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive." while True: pivotIndex = random.randint(left, right) pivotNewIndex = partition(vector, left, right, pivotIndex) pivotDist = pivotNewIndex - left if pivotDist == k: return vector[pivotNewIndex] elif k < pivotDist: right = pivotNewIndex - 1 else: k -= pivotDist + 1 left = pivotNewIndex + 1 def select(vector, k, left=None, right=None): if left is None: left = 0 lv1 = len(vector) - 1 if right is None: right = lv1 assert vector and k >= 0, "Either null vector or k < 0 " assert 0 <= left <= lv1, "left is out of range" assert left <= right <= lv1, "right is out of range" return _select(vector, left, right, k) if __name__ == '__main__': v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] print([select(v, i) for i in range(10)])
using System; using System.Collections.Generic; using System.Linq; namespace QuickSelect { internal static class Program { #region Static Members private static void Main() { var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; Console.WriteLine( "Loop quick select 10 times." ); for( var i = 0 ; i < 10 ; i++ ) { Console.Write( inputArray.NthSmallestElement( i ) ); if( i < 9 ) Console.Write( ", " ); } Console.WriteLine(); Console.WriteLine( "Just sort 10 elements." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "Get 4 smallest and sort them." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } internal static class ArrayExtension { #region Static Members public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T> { if( count < 0 ) throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." ); if( count == 0 ) return new T[0]; if( array.Length <= count ) return array; return QuickSelectSmallest( array, count - 1 ).Take( count ); } public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T> { if( n < 0 || n > array.Length - 1 ) throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) ); if( array.Length == 0 ) throw new ArgumentException( "Array is empty.", "array" ); if( array.Length == 1 ) return array[ 0 ]; return QuickSelectSmallest( array, n )[ n ]; } private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T> { var partiallySortedArray = (T[]) input.Clone(); var startIndex = 0; var endIndex = input.Length - 1; var pivotIndex = n; var r = new Random(); while( endIndex > startIndex ) { pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex ); if( pivotIndex == n ) break; if( pivotIndex > n ) endIndex = pivotIndex - 1; else startIndex = pivotIndex + 1; pivotIndex = r.Next( startIndex, endIndex ); } return partiallySortedArray; } private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T> { var pivotValue = array[ pivotIndex ]; array.Swap( pivotIndex, endIndex ); for( var i = startIndex ; i < endIndex ; i++ ) { if( array[ i ].CompareTo( pivotValue ) > 0 ) continue; array.Swap( i, startIndex ); startIndex++; } array.Swap( endIndex, startIndex ); return startIndex; } private static void Swap<T>( this T[] array, int index1, int index2 ) { if( index1 == index2 ) return; var temp = array[ index1 ]; array[ index1 ] = array[ index2 ]; array[ index2 ] = temp; } #endregion } }
Convert this Python block to C#, preserving its control flow and logic.
i = int('1a',16)
public static class BaseConverter { public static long stringToLong(string s, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); checked { int slen = s.Length; long result = 0; bool isNegative = false; for ( int i = 0; i < slen; i++ ) { char c = s[i]; int num; if ( c == '-' ) { if ( i != 0 ) throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s"); isNegative = true; continue; } if ( c > 0x2F && c < 0x3A ) num = c - 0x30; else if ( c > 0x40 && c < 0x5B ) num = c - 0x37; else if ( c > 0x60 && c < 0x7B ) num = c - 0x57; else throw new ArgumentException("The string contains an invalid character '" + c + "'", "s"); if ( num >= b ) throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s"); result *= b; result += num; } if ( isNegative ) result = -result; return result; } } public static string longToString(long n, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); if ( b == 10 ) return n.ToString(); checked { long longBase = b; StringBuilder sb = new StringBuilder(); if ( n < 0 ) { n = -n; sb.Append('-'); } long div = 1; while ( n / div >= b ) div *= b; while ( true ) { byte digit = (byte) (n / div); if ( digit < 10 ) sb.Append((char) (digit + 0x30)); else sb.Append((char) (digit + 0x57)); if ( div == 1 ) break; n %= div; div /= b; } return sb.ToString(); } } }
Keep all operations the same but rewrite the snippet in C#.
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Preserve the algorithm and functionality while converting the code from Python to C#.
>>> s = 'The quick brown fox jumps over the lazy dog' >>> import zlib >>> hex(zlib.crc32(s)) '0x414fa339' >>> import binascii >>> hex(binascii.crc32(s)) '0x414fa339'
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
Produce a functionally identical C# code for the snippet given in Python.
class MyClass: name2 = 2 def __init__(self): self.name1 = 0 def someMethod(self): self.name1 = 1 MyClass.name2 = 3 myclass = MyClass() class MyOtherClass: count = 0 def __init__(self, name, gender="Male", age=None): MyOtherClass.count += 1 self.name = name self.gender = gender if age is not None: self.age = age def __del__(self): MyOtherClass.count -= 1 person1 = MyOtherClass("John") print person1.name, person1.gender print person1.age person2 = MyOtherClass("Jane", "Female", 23) print person2.name, person2.gender, person2.age
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { MyClass instance = new MyClass(); instance.SomeMethod(); instance.Variable = 99; System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
Preserve the algorithm and functionality while converting the code from Python to C#.
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Ensure the translated C# code behaves exactly like the original Python snippet.
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Ensure the translated C# code behaves exactly like the original Python snippet.
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Produce a language-to-language conversion: from Python to C#, same semantics.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Write the same code in C# as shown below in Python.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Generate a C# translation of this Python snippet without changing its computational steps.
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
static int Fib(int n) { if (n < 0) throw new ArgumentException("Must be non negativ", "n"); Func<int, int> fib = null; fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p; return fib(n); }
Rewrite this program in C# while keeping its functionality equivalent to the Python version.
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
Generate a C# translation of this Python snippet without changing its computational steps.
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
Please provide an equivalent version of this Python code in C#.
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
Produce a language-to-language conversion: from Python to C#, same semantics.
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
using System; using System.IO; class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt"); Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\docs"); } }
Convert the following code from Python to C#, ensuring the logic remains intact.
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation' class Delegate: def thing(self): return 'delegate implementation' if __name__ == '__main__': a = Delegator() assert a.operation() == 'default implementation' a.delegate = 'A delegate may be any object' assert a.operation() == 'default implementation' a.delegate = Delegate() assert a.operation() == 'delegate implementation'
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
Convert this Python snippet to C# and keep its semantics consistent.
>>> s = "Hello" >>> s[0] = "h" Traceback (most recent call last): File "<pyshell s[0] = "h" TypeError: 'str' object does not support item assignment
readonly DateTime now = DateTime.Now;
Write the same code in C# as shown below in Python.
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
Produce a functionally identical C# code for the snippet given in Python.
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
Write a version of this Python function in C# with identical behavior.
def spiral(n): dx,dy = 1,0 x,y = 0,0 myarray = [[None]* n for j in range(n)] for i in xrange(n**2): myarray[x][y] = i nx,ny = x+dx, y+dy if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None: x,y = nx,ny else: dx,dy = -dy,dx x,y = x+dx, y+dy return myarray def printspiral(myarray): n = range(len(myarray)) for y in n: for x in n: print "%2i" % myarray[x][y], print printspiral(spiral(5))
public int[,] Spiral(int n) { int[,] result = new int[n, n]; int pos = 0; int count = n; int value = -n; int sum = -1; do { value = -1 * value / n; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } value *= n; count--; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } } while (count > 0); return result; } public void PrintArray(int[,] array) { int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1; for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { Console.Write(array[i, j].ToString().PadLeft(n, ' ')); } Console.WriteLine(); } }
Rewrite this program in C# while keeping its functionality equivalent to the Python version.
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:] def faulhaberSum(p, n): def go(x, y): return y * (n ** x) return sum( map(go, count(1), faulhaberTriangle(p)[-1]) ) def main(): fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) ) def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox def compose(g): return lambda f: lambda x: g(f(x)) def concat(xs): def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] def fmap(f): def go(xs): return list(map(f, xs)) return go def index(xs): return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) def showRatio(m): def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go if __name__ == '__main__': main()
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static Frac[] FaulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; for (int i = 0; i < p + 1; i++) { coeffs[i] = Frac.ZERO; } Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); } return coeffs; } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Frac[] coeffs = FaulhaberTriangle(i); foreach (Frac coeff in coeffs) { Console.Write("{0,5} ", coeff); } Console.WriteLine(); } } } }
Ensure the translated C# code behaves exactly like the original Python snippet.
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:] def faulhaberSum(p, n): def go(x, y): return y * (n ** x) return sum( map(go, count(1), faulhaberTriangle(p)[-1]) ) def main(): fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) ) def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox def compose(g): return lambda f: lambda x: g(f(x)) def concat(xs): def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] def fmap(f): def go(xs): return list(map(f, xs)) return go def index(xs): return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) def showRatio(m): def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go if __name__ == '__main__': main()
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static Frac[] FaulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; for (int i = 0; i < p + 1; i++) { coeffs[i] = Frac.ZERO; } Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); } return coeffs; } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Frac[] coeffs = FaulhaberTriangle(i); foreach (Frac coeff in coeffs) { Console.Write("{0,5} ", coeff); } Console.WriteLine(); } } } }
Produce a functionally identical C# code for the snippet given in Python.
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Rewrite this program in C# while keeping its functionality equivalent to the Python version.
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Generate a C# translation of this Python snippet without changing its computational steps.
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
Write the same code in C# as shown below in Python.
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
Keep all operations the same but rewrite the snippet in C#.
string = raw_input("Input a string: ")
using System; namespace C_Sharp_Console { class example { static void Main() { string word; int num; Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.ReadLine(); } } }
Ensure the translated C# code behaves exactly like the original Python snippet.
from itertools import combinations def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) ) def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), ) bagged = max( anycomb(items), key=totalvalue) print("Bagged the following items\n " + '\n '.join(sorted(item for item,_,_ in bagged))) val, wt = totalvalue(bagged) print("for a total value of %i and a total weight of %i" % (val, -wt))
using System; using System.Collections.Generic; namespace Tests_With_Framework_4 { class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400; public Bag() { items = new List<Item>(); } void AddItem(Item i) { if ((TotalWeight + i.Weight) <= MaxWeightAllowed) items.Add(i); } public void Calculate(List<Item> items) { foreach (Item i in Sorte(items)) { AddItem(i); } } List<Item> Sorte(List<Item> inputItems) { List<Item> choosenItems = new List<Item>(); for (int i = 0; i < inputItems.Count; i++) { int j = -1; if (i == 0) { choosenItems.Add(inputItems[i]); } if (i > 0) { if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j)) { choosenItems.Add(inputItems[i]); } } } return choosenItems; } bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd) { if (!(lastBound < 0)) { if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV ) { indxToAdd = lastBound; } return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd); } if (indxToAdd > -1) { choosenItems.Insert(indxToAdd, knapsackItems[i]); return true; } return false; } #region IEnumerable<Item> Members IEnumerator<Item> IEnumerable<Item>.GetEnumerator() { foreach (Item i in items) yield return i; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return items.GetEnumerator(); } #endregion public int TotalWeight { get { var sum = 0; foreach (Item i in this) { sum += i.Weight; } return sum; } } public class Item { public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } } public override string ToString() { return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV; } } } class Program { static void Main(string[] args) {List<Bag.Item> knapsackItems = new List<Bag.Item>(); knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 }); knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 }); knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 }); knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 }); knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 }); knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 }); knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 }); knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 }); knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 }); knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 }); knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 }); Bag b = new Bag(); b.Calculate(knapsackItems); b.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine(b.Sum(x => x.Weight)); Console.ReadKey(); } } }
Write the same code in C# as shown below in Python.
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Produce a language-to-language conversion: from Python to C#, same semantics.
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Ensure the translated C# code behaves exactly like the original Python snippet.
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Generate an equivalent C# version of this Python code.
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
using System; class Program { static void Main(string[] args) { var cube = new Func<double, double>(x => Math.Pow(x, 3.0)); var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0)); var functionTuples = new[] { (forward: Math.Sin, backward: Math.Asin), (forward: Math.Cos, backward: Math.Acos), (forward: cube, backward: croot) }; foreach (var ft in functionTuples) { Console.WriteLine(ft.backward(ft.forward(0.5))); } } }
Produce a language-to-language conversion: from Python to C#, same semantics.
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
Change the following Python code into C# without altering its purpose.
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
Write the same code in C# as shown below in Python.
>>> from xml.etree import ElementTree as ET >>> from itertools import izip >>> def characterstoxml(names, remarks): root = ET.Element("CharacterRemarks") for name, remark in izip(names, remarks): c = ET.SubElement(root, "Character", {'name': name}) c.text = remark return ET.tostring(root) >>> print characterstoxml( names = ["April", "Tam O'Shanter", "Emily"], remarks = [ "Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', 'Short & shrift' ] ).replace('><','>\n<')
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Program { static string CreateXML(Dictionary<string, string> characterRemarks) { var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key))); var xml = new XElement("CharacterRemarks", remarks); return xml.ToString(); } static void Main(string[] args) { var characterRemarks = new Dictionary<string, string> { { "April", "Bubbly: I'm > Tam and <= Emily" }, { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" }, { "Emily", "Short & shrift" } }; string xml = CreateXML(characterRemarks); Console.WriteLine(xml); } }
Write the same code in C# as shown below in Python.
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string str = "I am a string"; if (new Regex("string$").IsMatch(str)) { Console.WriteLine("Ends with string."); } str = new Regex(" a ").Replace(str, " another "); Console.WriteLine(str); } }
Please provide an equivalent version of this Python code in C#.
inclusive_range = mn, mx = (1, 10) print( % inclusive_range) i = 0 while True: i += 1 guess = (mn+mx)//2 txt = input("Guess %2i is: %2i. The score for which is (h,l,=): " % (i, guess)).strip().lower()[0] if txt not in 'hl=': print(" I don't understand your input of '%s' ?" % txt) continue if txt == 'h': mx = guess-1 if txt == 'l': mn = guess+1 if txt == '=': print(" Ye-Haw!!") break if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]): print("Please check your scoring as I cannot find the value") break print("\nThanks for keeping score.")
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class RealisticGuess { private int max; private int min; private int guess; public void Start() { Console.Clear(); string input; try { Console.WriteLine("Please enter the lower boundary"); input = Console.ReadLine(); min = Convert.ToInt32(input); Console.WriteLine("Please enter the upper boundary"); input = Console.ReadLine(); max = Convert.ToInt32(input); } catch (FormatException) { Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again."); Console.ReadKey(true); Start(); } Console.WriteLine("Think of a number between {0} and {1}.", min, max); Thread.Sleep(2500); Console.WriteLine("Ready?"); Console.WriteLine("Press any key to begin."); Console.ReadKey(true); Guess(min, max); } public void Guess(int min, int max) { int counter = 1; string userAnswer; bool correct = false; Random rand = new Random(); while (correct == false) { guess = rand.Next(min, max); Console.Clear(); Console.WriteLine("{0}", guess); Console.WriteLine("Is this number correct? {Y/N}"); userAnswer = Console.ReadLine(); if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N") { Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'"); Console.WriteLine("Is the number correct? {Y/N}"); userAnswer = Console.ReadLine(); } if (userAnswer == "y" || userAnswer == "Y") { correct = true; } if (userAnswer == "n" || userAnswer == "N") { counter++; if (max == min) { Console.WriteLine("Error: Range Intersect. Press enter to restart the game."); Console.ReadKey(true); Guess(1, 101); } Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H") { Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'"); Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); } if (userAnswer == "l" || userAnswer == "L") { max = guess; } if (userAnswer == "h" || userAnswer == "H") { min = guess; } } } if (correct == true) { EndAndLoop(counter); } } public void EndAndLoop(int iterations) { string userChoice; bool loop = false; Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations); while (loop == false) { Console.WriteLine("Would you like to play again? {Y/N}"); userChoice = Console.ReadLine(); if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n") { Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit."); } if (userChoice == "Y" || userChoice == "y") { Start(); } if (userChoice == "N" || userChoice == "n") { Environment.Exit(1); } } } } class Program { static void Main(string[] args) { Console.Title = "Random Number"; RealisticGuess game = new RealisticGuess(); game.Start(); } } }
Convert the following code from Python to C#, ensuring the logic remains intact.
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
static class Program { static void Main() { System.Collections.Hashtable h = new System.Collections.Hashtable(); string[] keys = { "foo", "bar", "val" }; string[] values = { "little", "miss", "muffet" }; System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); for (int i = 0; i < keys.Length; i++) { h.Add(keys[i], values[i]); } } }
Maintain the same structure and functionality when rewriting this code in C#.
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
Rewrite the snippet below in C# so it works the same as the original Python code.
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
Port the following code from Python to C# with equivalent syntax and logic.
import pygame, sys from pygame.locals import * from math import sin, cos, radians pygame.init() WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15 window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum") screen = pygame.display.get_surface() screen.fill((255,255,255)) PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4 class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw() def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2) firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0 midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2 midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1) def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw() bob = BobMass() TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK) def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update() while True: input(pygame.event.get()) pygame.display.flip()
using System; using System.Drawing; using System.Windows.Forms; class CSharpPendulum { Form _form; Timer _timer; double _angle = Math.PI / 2, _angleAccel, _angleVelocity = 0, _dt = 0.1; int _length = 50; [STAThread] static void Main() { var p = new CSharpPendulum(); } public CSharpPendulum() { _form = new Form() { Text = "Pendulum", Width = 200, Height = 200 }; _timer = new Timer() { Interval = 30 }; _timer.Tick += delegate(object sender, EventArgs e) { int anchorX = (_form.Width / 2) - 12, anchorY = _form.Height / 4, ballX = anchorX + (int)(Math.Sin(_angle) * _length), ballY = anchorY + (int)(Math.Cos(_angle) * _length); _angleAccel = -9.81 / _length * Math.Sin(_angle); _angleVelocity += _angleAccel * _dt; _angle += _angleVelocity * _dt; Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height); Graphics g = Graphics.FromImage(dblBuffer); Graphics f = Graphics.FromHwnd(_form.Handle); g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY)); g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7); g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14); f.Clear(Color.White); f.DrawImage(dblBuffer, new Point(0, 0)); }; _timer.Start(); Application.Run(_form); } }
Port the provided Python code into C# while preserving the original functionality.
def heapsort(lst): for start in range((len(lst)-2)/2, -1, -1): siftdown(lst, start, len(lst)-1) for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] siftdown(lst, 0, end - 1) return lst def siftdown(lst, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] root = child else: break
using System; using System.Collections.Generic; using System.Text; public class HeapSortClass { public static void HeapSort<T>(T[] array) { HeapSort<T>(array, 0, array.Length, Comparer<T>.Default); } public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer) { HeapSort<T>(array, offset, length, comparer.Compare); } public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison) { for (int i = 0; i < length; i++) { int index = i; T item = array[offset + i]; while (index > 0 && comparison(array[offset + (index - 1) / 2], item) < 0) { int top = (index - 1) / 2; array[offset + index] = array[offset + top]; index = top; } array[offset + index] = item; } for (int i = length - 1; i > 0; i--) { T last = array[offset + i]; array[offset + i] = array[offset]; int index = 0; while (index * 2 + 1 < i) { int left = index * 2 + 1, right = left + 1; if (right < i && comparison(array[offset + left], array[offset + right]) < 0) { if (comparison(last, array[offset + right]) > 0) break; array[offset + index] = array[offset + right]; index = right; } else { if (comparison(last, array[offset + left]) > 0) break; array[offset + index] = array[offset + left]; index = left; } } array[offset + index] = last; } } static void Main() { byte[] r = {5, 4, 1, 2}; HeapSort(r); string[] s = { "-", "D", "a", "33" }; HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase); } }
Please provide an equivalent version of this Python code in C#.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"; } public class Deck : IEnumerable<Card> { static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; readonly List<Card> cards; public Deck() { cards = (from suit in suits from rank in ranks select new Card(rank, suit)).ToList(); } public int Count => cards.Count; public void Shuffle() { var random = new Random(); for (int i = 0; i < cards.Count; i++) { int r = random.Next(i, cards.Count); var temp = cards[i]; cards[i] = cards[r]; cards[r] = temp; } } public Card Deal() { int last = cards.Count - 1; Card card = cards[last]; cards.RemoveAt(last); return card; } public IEnumerator<Card> GetEnumerator() { for (int i = cards.Count - 1; i >= 0; i--) yield return cards[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); }