Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated Go code behaves exactly like the original Java snippet.
public class AirMass { public static void main(String[] args) { System.out.println("Angle 0 m 13700 m"); System.out.println("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { System.out.printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } } private static double rho(double a) { return Math.exp(-a / 8500.0); } private static double height(double a, double z, double d) { double aa = RE + a; double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z))); return hh - RE; } private static double columnDensity(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = Math.max(DD * d, DD); sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } private static double airmass(double a, double z) { return columnDensity(a, z) / columnDensity(a, 0.0); } private static final double RE = 6371000.0; private static final double DD = 0.001; private static final double FIN = 10000000.0; }
package main import ( "fmt" "math" ) const ( RE = 6371000 DD = 0.001 FIN = 1e7 ) func rho(a float64) float64 { return math.Exp(-a / 8500) } func radians(degrees float64) float64 { return degrees * math.Pi / 180 } func height(a, z, d float64) float64 { aa := RE + a hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z))) return hh - RE } func columnDensity(a, z float64) float64 { sum := 0.0 d := 0.0 for d < FIN { delta := math.Max(DD, DD*d) sum += rho(height(a, z, d+0.5*delta)) * delta d += delta } return sum } func airmass(a, z float64) float64 { return columnDensity(a, z) / columnDensity(a, 0) } func main() { fmt.Println("Angle 0 m 13700 m") fmt.Println("------------------------------------") for z := 0; z <= 90; z += 5 { fz := float64(z) fmt.Printf("%2d %11.8f %11.8f\n", z, airmass(0, fz), airmass(13700, fz)) } }
Change the following Java code into Go without altering its purpose.
public class PancakeSort { int[] heap; public String toString() { String info = ""; for (int x: heap) info += x + " "; return info; } public void flip(int n) { for (int i = 0; i < (n+1) / 2; ++i) { int tmp = heap[i]; heap[i] = heap[n-i]; heap[n-i] = tmp; } System.out.println("flip(0.." + n + "): " + toString()); } public int[] minmax(int n) { int xm, xM; xm = xM = heap[0]; int posm = 0, posM = 0; for (int i = 1; i < n; ++i) { if (heap[i] < xm) { xm = heap[i]; posm = i; } else if (heap[i] > xM) { xM = heap[i]; posM = i; } } return new int[] {posm, posM}; } public void sort(int n, int dir) { if (n == 0) return; int[] mM = minmax(n); int bestXPos = mM[dir]; int altXPos = mM[1-dir]; boolean flipped = false; if (bestXPos == n-1) { --n; } else if (bestXPos == 0) { flip(n-1); --n; } else if (altXPos == n-1) { dir = 1-dir; --n; flipped = true; } else { flip(bestXPos); } sort(n, dir); if (flipped) { flip(n); } } PancakeSort(int[] numbers) { heap = numbers; sort(numbers.length, 1); } public static void main(String[] args) { int[] numbers = new int[args.length]; for (int i = 0; i < args.length; ++i) numbers[i] = Integer.valueOf(args[i]); PancakeSort pancakes = new PancakeSort(numbers); System.out.println(pancakes); } }
package main import "fmt" func main() { list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) list.sort() fmt.Println("sorted! ", list) } type pancake []int func (a pancake) sort() { for uns := len(a) - 1; uns > 0; uns-- { lx, lg := 0, a[0] for i := 1; i <= uns; i++ { if a[i] > lg { lx, lg = i, a[i] } } a.flip(lx) a.flip(uns) } } func (a pancake) flip(r int) { for l := 0; l < r; l, r = l+1, r-1 { a[l], a[r] = a[r], a[l] } }
Keep all operations the same but rewrite the snippet in Go.
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; public class ChemicalCalculator { private static final Map<String, Double> atomicMass = new HashMap<>(); static { atomicMass.put("H", 1.008); atomicMass.put("He", 4.002602); atomicMass.put("Li", 6.94); atomicMass.put("Be", 9.0121831); atomicMass.put("B", 10.81); atomicMass.put("C", 12.011); atomicMass.put("N", 14.007); atomicMass.put("O", 15.999); atomicMass.put("F", 18.998403163); atomicMass.put("Ne", 20.1797); atomicMass.put("Na", 22.98976928); atomicMass.put("Mg", 24.305); atomicMass.put("Al", 26.9815385); atomicMass.put("Si", 28.085); atomicMass.put("P", 30.973761998); atomicMass.put("S", 32.06); atomicMass.put("Cl", 35.45); atomicMass.put("Ar", 39.948); atomicMass.put("K", 39.0983); atomicMass.put("Ca", 40.078); atomicMass.put("Sc", 44.955908); atomicMass.put("Ti", 47.867); atomicMass.put("V", 50.9415); atomicMass.put("Cr", 51.9961); atomicMass.put("Mn", 54.938044); atomicMass.put("Fe", 55.845); atomicMass.put("Co", 58.933194); atomicMass.put("Ni", 58.6934); atomicMass.put("Cu", 63.546); atomicMass.put("Zn", 65.38); atomicMass.put("Ga", 69.723); atomicMass.put("Ge", 72.630); atomicMass.put("As", 74.921595); atomicMass.put("Se", 78.971); atomicMass.put("Br", 79.904); atomicMass.put("Kr", 83.798); atomicMass.put("Rb", 85.4678); atomicMass.put("Sr", 87.62); atomicMass.put("Y", 88.90584); atomicMass.put("Zr", 91.224); atomicMass.put("Nb", 92.90637); atomicMass.put("Mo", 95.95); atomicMass.put("Ru", 101.07); atomicMass.put("Rh", 102.90550); atomicMass.put("Pd", 106.42); atomicMass.put("Ag", 107.8682); atomicMass.put("Cd", 112.414); atomicMass.put("In", 114.818); atomicMass.put("Sn", 118.710); atomicMass.put("Sb", 121.760); atomicMass.put("Te", 127.60); atomicMass.put("I", 126.90447); atomicMass.put("Xe", 131.293); atomicMass.put("Cs", 132.90545196); atomicMass.put("Ba", 137.327); atomicMass.put("La", 138.90547); atomicMass.put("Ce", 140.116); atomicMass.put("Pr", 140.90766); atomicMass.put("Nd", 144.242); atomicMass.put("Pm", 145.0); atomicMass.put("Sm", 150.36); atomicMass.put("Eu", 151.964); atomicMass.put("Gd", 157.25); atomicMass.put("Tb", 158.92535); atomicMass.put("Dy", 162.500); atomicMass.put("Ho", 164.93033); atomicMass.put("Er", 167.259); atomicMass.put("Tm", 168.93422); atomicMass.put("Yb", 173.054); atomicMass.put("Lu", 174.9668); atomicMass.put("Hf", 178.49); atomicMass.put("Ta", 180.94788); atomicMass.put("W", 183.84); atomicMass.put("Re", 186.207); atomicMass.put("Os", 190.23); atomicMass.put("Ir", 192.217); atomicMass.put("Pt", 195.084); atomicMass.put("Au", 196.966569); atomicMass.put("Hg", 200.592); atomicMass.put("Tl", 204.38); atomicMass.put("Pb", 207.2); atomicMass.put("Bi", 208.98040); atomicMass.put("Po", 209.0); atomicMass.put("At", 210.0); atomicMass.put("Rn", 222.0); atomicMass.put("Fr", 223.0); atomicMass.put("Ra", 226.0); atomicMass.put("Ac", 227.0); atomicMass.put("Th", 232.0377); atomicMass.put("Pa", 231.03588); atomicMass.put("U", 238.02891); atomicMass.put("Np", 237.0); atomicMass.put("Pu", 244.0); atomicMass.put("Am", 243.0); atomicMass.put("Cm", 247.0); atomicMass.put("Bk", 247.0); atomicMass.put("Cf", 251.0); atomicMass.put("Es", 252.0); atomicMass.put("Fm", 257.0); atomicMass.put("Uue", 315.0); atomicMass.put("Ubn", 299.0); } private static double evaluate(String s) { String sym = s + "["; double sum = 0.0; StringBuilder symbol = new StringBuilder(); String number = ""; for (int i = 0; i < sym.length(); ++i) { char c = sym.charAt(i); if ('@' <= c && c <= '[') { int n = 1; if (!number.isEmpty()) { n = Integer.parseInt(number); } if (symbol.length() > 0) { sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n; } if (c == '[') { break; } symbol = new StringBuilder(String.valueOf(c)); number = ""; } else if ('a' <= c && c <= 'z') { symbol.append(c); } else if ('0' <= c && c <= '9') { number += c; } else { throw new RuntimeException("Unexpected symbol " + c + " in molecule"); } } return sum; } private static String replaceParens(String s) { char letter = 'a'; String si = s; while (true) { int start = si.indexOf('('); if (start == -1) { break; } for (int i = start + 1; i < si.length(); ++i) { if (si.charAt(i) == ')') { String expr = si.substring(start + 1, i); String symbol = "@" + letter; String pattern = Pattern.quote(si.substring(start, i + 1)); si = si.replaceFirst(pattern, symbol); atomicMass.put(symbol, evaluate(expr)); letter++; break; } if (si.charAt(i) == '(') { start = i; } } } return si; } public static void main(String[] args) { List<String> molecules = List.of( "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" ); for (String molecule : molecules) { double mass = evaluate(replaceParens(molecule)); System.out.printf("%17s -> %7.3f\n", molecule, mass); } } }
package main import ( "fmt" "strconv" "strings" ) var atomicMass = map[string]float64{ "H": 1.008, "He": 4.002602, "Li": 6.94, "Be": 9.0121831, "B": 10.81, "C": 12.011, "N": 14.007, "O": 15.999, "F": 18.998403163, "Ne": 20.1797, "Na": 22.98976928, "Mg": 24.305, "Al": 26.9815385, "Si": 28.085, "P": 30.973761998, "S": 32.06, "Cl": 35.45, "Ar": 39.948, "K": 39.0983, "Ca": 40.078, "Sc": 44.955908, "Ti": 47.867, "V": 50.9415, "Cr": 51.9961, "Mn": 54.938044, "Fe": 55.845, "Co": 58.933194, "Ni": 58.6934, "Cu": 63.546, "Zn": 65.38, "Ga": 69.723, "Ge": 72.630, "As": 74.921595, "Se": 78.971, "Br": 79.904, "Kr": 83.798, "Rb": 85.4678, "Sr": 87.62, "Y": 88.90584, "Zr": 91.224, "Nb": 92.90637, "Mo": 95.95, "Ru": 101.07, "Rh": 102.90550, "Pd": 106.42, "Ag": 107.8682, "Cd": 112.414, "In": 114.818, "Sn": 118.710, "Sb": 121.760, "Te": 127.60, "I": 126.90447, "Xe": 131.293, "Cs": 132.90545196, "Ba": 137.327, "La": 138.90547, "Ce": 140.116, "Pr": 140.90766, "Nd": 144.242, "Pm": 145, "Sm": 150.36, "Eu": 151.964, "Gd": 157.25, "Tb": 158.92535, "Dy": 162.500, "Ho": 164.93033, "Er": 167.259, "Tm": 168.93422, "Yb": 173.054, "Lu": 174.9668, "Hf": 178.49, "Ta": 180.94788, "W": 183.84, "Re": 186.207, "Os": 190.23, "Ir": 192.217, "Pt": 195.084, "Au": 196.966569, "Hg": 200.592, "Tl": 204.38, "Pb": 207.2, "Bi": 208.98040, "Po": 209, "At": 210, "Rn": 222, "Fr": 223, "Ra": 226, "Ac": 227, "Th": 232.0377, "Pa": 231.03588, "U": 238.02891, "Np": 237, "Pu": 244, "Am": 243, "Cm": 247, "Bk": 247, "Cf": 251, "Es": 252, "Fm": 257, "Uue": 315, "Ubn": 299, } func replaceParens(s string) string { var letter byte = 'a' for { start := strings.IndexByte(s, '(') if start == -1 { break } restart: for i := start + 1; i < len(s); i++ { if s[i] == ')' { expr := s[start+1 : i] symbol := fmt.Sprintf("@%c", letter) s = strings.Replace(s, s[start:i+1], symbol, 1) atomicMass[symbol] = evaluate(expr) letter++ break } if s[i] == '(' { start = i goto restart } } } return s } func evaluate(s string) float64 { s += string('[') var symbol, number string sum := 0.0 for i := 0; i < len(s); i++ { c := s[i] switch { case c >= '@' && c <= '[': n := 1 if number != "" { n, _ = strconv.Atoi(number) } if symbol != "" { sum += atomicMass[symbol] * float64(n) } if c == '[' { break } symbol = string(c) number = "" case c >= 'a' && c <= 'z': symbol += string(c) case c >= '0' && c <= '9': number += string(c) default: panic(fmt.Sprintf("Unexpected symbol %c in molecule", c)) } } return sum } func main() { molecules := []string{ "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue", } for _, molecule := range molecules { mass := evaluate(replaceParens(molecule)) fmt.Printf("%17s -> %7.3f\n", molecule, mass) } }
Ensure the translated Go code behaves exactly like the original Java snippet.
import java.io.IOException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapConnectionDemo { public static void main(String[] args) throws LdapException, IOException { try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) { connection.bind(); connection.unBind(); } } }
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com", BindPassword: "readonlypassword", UserFilter: "(uid=%s)", GroupFilter: "(memberUid=%s)", Attributes: []string{"givenName", "sn", "mail", "uid"}, } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } }
Keep all operations the same but rewrite the snippet in Go.
package org.rosettacode.java; import java.util.Arrays; import java.util.stream.IntStream; public class HeapsAlgorithm { public static void main(String[] args) { Object[] array = IntStream.range(0, 4) .boxed() .toArray(); HeapsAlgorithm algorithm = new HeapsAlgorithm(); algorithm.recursive(array); System.out.println(); algorithm.loop(array); } void recursive(Object[] array) { recursive(array, array.length, true); } void recursive(Object[] array, int n, boolean plus) { if (n == 1) { output(array, plus); } else { for (int i = 0; i < n; i++) { recursive(array, n - 1, i == 0); swap(array, n % 2 == 0 ? i : 0, n - 1); } } } void output(Object[] array, boolean plus) { System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1")); } void swap(Object[] array, int a, int b) { Object o = array[a]; array[a] = array[b]; array[b] = o; } void loop(Object[] array) { loop(array, array.length); } void loop(Object[] array, int n) { int[] c = new int[n]; output(array, true); boolean plus = false; for (int i = 0; i < n; ) { if (c[i] < i) { if (i % 2 == 0) { swap(array, 0, i); } else { swap(array, c[i], i); } output(array, plus); plus = !plus; c[i]++; i = 0; } else { c[i] = 0; i++; } } } }
package permute func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } } func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } default: p0 := pf(n - 1) i := n var d int return func(p []int) int { switch { case sign == 0: case i == n: i-- sign = p0(p[:i]) d = -1 case i == 0: i++ sign *= p0(p[1:]) d = 1 if sign == 0 { p[0], p[1] = p[1], p[0] } default: p[i], p[i-1] = p[i-1], p[i] sign = -sign i += d } return sign } } }
Please provide an equivalent version of this Java code in Go.
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); } private static List<Long> getPythagoreanQuadruples(long max) { List<Long> list = new ArrayList<>(); long n = -1; long m = -1; while ( true ) { long nTest = (long) Math.pow(2, n+1); long mTest = (long) (5L * Math.pow(2, m+1)); long test = 0; if ( nTest > mTest ) { test = mTest; m++; } else { test = nTest; n++; } if ( test < max ) { list.add(test); } else { break; } } return list; } }
package main import "fmt" const ( N = 2200 N2 = N * N * 2 ) func main() { s := 3 var s1, s2 int var r [N + 1]bool var ab [N2 + 1]bool for a := 1; a <= N; a++ { a2 := a * a for b := a; b <= N; b++ { ab[a2 + b * b] = true } } for c := 1; c <= N; c++ { s1 = s s += 2 s2 = s for d := c + 1; d <= N; d++ { if ab[s1] { r[d] = true } s1 += s2 s2 += 2 } } for d := 1; d <= N; d++ { if !r[d] { fmt.Printf("%d ", d) } } fmt.Println() }
Change the following Java code into Go without altering its purpose.
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); disableOption("needspeeling"); setOption("numberofbananas", "1024"); addOption("numberofstrawberries", "62000"); store(); } } private enum EntryType { EMPTY, ENABLED, DISABLED, COMMENT } private static class Entry { EntryType type; String name, value; Entry(EntryType t, String n, String v) { type = t; name = n; value = v; } } private static Map<String, Entry> entries = new LinkedHashMap<>(); private static String path; private static boolean readConfig(String p) { path = p; File f = new File(path); if (!f.exists() || f.isDirectory()) return false; String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)"; Pattern regex = Pattern.compile(regexString); try (Scanner sc = new Scanner(new FileReader(f))){ int emptyLines = 0; String line; while (sc.hasNext()) { line = sc.nextLine().trim(); if (line.isEmpty()) { addOption("" + emptyLines++, null, EntryType.EMPTY); } else if (line.charAt(0) == '#') { entries.put(line, new Entry(EntryType.COMMENT, line, null)); } else { line = line.replaceAll("[^a-zA-Z0-9\\x20;]", ""); Matcher m = regex.matcher(line); if (m.find() && !m.group(2).isEmpty()) { EntryType t = EntryType.ENABLED; if (!m.group(1).isEmpty()) t = EntryType.DISABLED; addOption(m.group(2), m.group(3), t); } } } } catch (IOException e) { System.out.println(e); } return true; } private static void addOption(String name, String value) { addOption(name, value, EntryType.ENABLED); } private static void addOption(String name, String value, EntryType t) { name = name.toUpperCase(); entries.put(name, new Entry(t, name, value)); } private static void enableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.ENABLED; } private static void disableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.DISABLED; } private static void setOption(String name, String value) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.value = value; } private static void store() { try (PrintWriter pw = new PrintWriter(path)) { for (Entry e : entries.values()) { switch (e.type) { case EMPTY: pw.println(); break; case ENABLED: pw.format("%s %s%n", e.name, e.value); break; case DISABLED: pw.format("; %s %s%n", e.name, e.value); break; case COMMENT: pw.println(e.name); break; default: break; } } if (pw.checkError()) { throw new IOException("writing to file failed"); } } catch (IOException e) { System.out.println(e); } } }
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { case ignore, parseError, comment, blank: return l.value case value: s := l.option if l.disabled { s = "; " + s } if l.value != "" { s += " " + l.value } return s } panic("unexpected line kind") } func removeDross(s string) string { return strings.Map(func(r rune) rune { if r < 32 || r > 0x7f || unicode.IsControl(r) { return -1 } return r }, s) } func parseLine(s string) line { if s == "" { return line{kind: blank} } if s[0] == '#' { return line{kind: comment, value: s} } s = removeDross(s) fields := strings.Fields(s) if len(fields) == 0 { return line{kind: blank} } semi := false for len(fields[0]) > 0 && fields[0][0] == ';' { semi = true fields[0] = fields[0][1:] } if fields[0] == "" { fields = fields[1:] } switch len(fields) { case 0: return line{kind: ignore} case 1: return line{ kind: value, option: strings.ToUpper(fields[0]), disabled: semi, } case 2: return line{ kind: value, option: strings.ToUpper(fields[0]), value: fields[1], disabled: semi, } } return line{kind: parseError, value: s} } type Config struct { options map[string]int lines []line } func (c *Config) index(option string) int { if i, ok := c.options[option]; ok { return i } return -1 } func (c *Config) addLine(l line) { switch l.kind { case ignore: return case value: if c.index(l.option) >= 0 { return } c.options[l.option] = len(c.lines) c.lines = append(c.lines, l) default: c.lines = append(c.lines, l) } } func ReadConfig(path string) (*Config, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() r := bufio.NewReader(f) c := &Config{options: make(map[string]int)} for { s, err := r.ReadString('\n') if s != "" { if err == nil { s = s[:len(s)-1] } c.addLine(parseLine(s)) } if err == io.EOF { break } if err != nil { return nil, err } } return c, nil } func (c *Config) Set(option string, val string) { if i := c.index(option); i >= 0 { line := &c.lines[i] line.disabled = false line.value = val return } c.addLine(line{ kind: value, option: option, value: val, }) } func (c *Config) Enable(option string, enabled bool) { if i := c.index(option); i >= 0 { c.lines[i].disabled = !enabled } } func (c *Config) Write(w io.Writer) { for _, line := range c.lines { fmt.Println(line) } } func main() { c, err := ReadConfig("/tmp/cfg") if err != nil { log.Fatalln(err) } c.Enable("NEEDSPEELING", false) c.Set("SEEDSREMOVED", "") c.Set("NUMBEROFBANANAS", "1024") c.Set("NUMBEROFSTRAWBERRIES", "62000") c.Write(os.Stdout) }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class ImageConvolution { public static class ArrayData { public final int[] dataArray; public final int width; public final int height; public ArrayData(int width, int height) { this(new int[width * height], width, height); } public ArrayData(int[] dataArray, int width, int height) { this.dataArray = dataArray; this.width = width; this.height = height; } public int get(int x, int y) { return dataArray[y * width + x]; } public void set(int x, int y, int value) { dataArray[y * width + x] = value; } } private static int bound(int value, int endIndex) { if (value < 0) return 0; if (value < endIndex) return value; return endIndex - 1; } public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor) { int inputWidth = inputData.width; int inputHeight = inputData.height; int kernelWidth = kernel.width; int kernelHeight = kernel.height; if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd width"); if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd height"); int kernelWidthRadius = kernelWidth >>> 1; int kernelHeightRadius = kernelHeight >>> 1; ArrayData outputData = new ArrayData(inputWidth, inputHeight); for (int i = inputWidth - 1; i >= 0; i--) { for (int j = inputHeight - 1; j >= 0; j--) { double newValue = 0.0; for (int kw = kernelWidth - 1; kw >= 0; kw--) for (int kh = kernelHeight - 1; kh >= 0; kh--) newValue += kernel.get(kw, kh) * inputData.get( bound(i + kw - kernelWidthRadius, inputWidth), bound(j + kh - kernelHeightRadius, inputHeight)); outputData.set(i, j, (int)Math.round(newValue / kernelDivisor)); } } return outputData; } public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException { BufferedImage inputImage = ImageIO.read(new File(filename)); int width = inputImage.getWidth(); int height = inputImage.getHeight(); int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width); ArrayData reds = new ArrayData(width, height); ArrayData greens = new ArrayData(width, height); ArrayData blues = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; reds.set(x, y, (rgbValue >>> 16) & 0xFF); greens.set(x, y, (rgbValue >>> 8) & 0xFF); blues.set(x, y, rgbValue & 0xFF); } } return new ArrayData[] { reds, greens, blues }; } public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException { ArrayData reds = redGreenBlue[0]; ArrayData greens = redGreenBlue[1]; ArrayData blues = redGreenBlue[2]; BufferedImage outputImage = new BufferedImage(reds.width, reds.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < reds.height; y++) { for (int x = 0; x < reds.width; x++) { int red = bound(reds.get(x, y), 256); int green = bound(greens.get(x, y), 256); int blue = bound(blues.get(x, y), 256); outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { int kernelWidth = Integer.parseInt(args[2]); int kernelHeight = Integer.parseInt(args[3]); int kernelDivisor = Integer.parseInt(args[4]); System.out.println("Kernel size: " + kernelWidth + "x" + kernelHeight + ", divisor=" + kernelDivisor); int y = 5; ArrayData kernel = new ArrayData(kernelWidth, kernelHeight); for (int i = 0; i < kernelHeight; i++) { System.out.print("["); for (int j = 0; j < kernelWidth; j++) { kernel.set(j, i, Integer.parseInt(args[y++])); System.out.print(" " + kernel.get(j, i) + " "); } System.out.println("]"); } ArrayData[] dataArrays = getArrayDatasFromImage(args[0]); for (int i = 0; i < dataArrays.length; i++) dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor); writeOutputImage(args[1], dataArrays); return; } }
package main import ( "fmt" "image" "image/color" "image/jpeg" "math" "os" ) func kf3(k *[9]float64, src, dst *image.Gray) { for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ { for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ { var sum float64 var i int for yo := y - 1; yo <= y+1; yo++ { for xo := x - 1; xo <= x+1; xo++ { if (image.Point{xo, yo}).In(src.Rect) { sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y) } else { sum += k[i] * float64(src.At(x, y).(color.Gray).Y) } i++ } } dst.SetGray(x, y, color.Gray{uint8(math.Min(255, math.Max(0, sum)))}) } } } var blur = [9]float64{ 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9} func blurY(src *image.YCbCr) *image.YCbCr { dst := *src if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y { return &dst } srcGray := image.Gray{src.Y, src.YStride, src.Rect} dstGray := srcGray dstGray.Pix = make([]uint8, len(src.Y)) kf3(&blur, &srcGray, &dstGray) dst.Y = dstGray.Pix dst.Cb = append([]uint8{}, src.Cb...) dst.Cr = append([]uint8{}, src.Cr...) return &dst } func main() { f, err := os.Open("Lenna100.jpg") if err != nil { fmt.Println(err) return } img, err := jpeg.Decode(f) if err != nil { fmt.Println(err) return } f.Close() y, ok := img.(*image.YCbCr) if !ok { fmt.Println("expected color jpeg") return } f, err = os.Create("blur.jpg") if err != nil { fmt.Println(err) return } err = jpeg.Encode(f, blurY(y), &jpeg.Options{90}) if err != nil { fmt.Println(err) } }
Keep all operations the same but rewrite the snippet in Go.
import java.util.Random; public class Dice{ private static int roll(int nDice, int nSides){ int sum = 0; Random rand = new Random(); for(int i = 0; i < nDice; i++){ sum += rand.nextInt(nSides) + 1; } return sum; } private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){ int p1Wins = 0; for(int i = 0; i < rolls; i++){ int p1Roll = roll(p1Dice, p1Sides); int p2Roll = roll(p2Dice, p2Sides); if(p1Roll > p2Roll) p1Wins++; } return p1Wins; } public static void main(String[] args){ int p1Dice = 9; int p1Sides = 4; int p2Dice = 6; int p2Sides = 6; int rolls = 10000; int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 5; p1Sides = 10; p2Dice = 6; p2Sides = 7; rolls = 10000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 9; p1Sides = 4; p2Dice = 6; p2Sides = 6; rolls = 1000000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 5; p1Sides = 10; p2Dice = 6; p2Sides = 7; rolls = 1000000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); } }
package main import( "math" "fmt" ) func minOf(x, y uint) uint { if x < y { return x } return y } func throwDie(nSides, nDice, s uint, counts []uint) { if nDice == 0 { counts[s]++ return } for i := uint(1); i <= nSides; i++ { throwDie(nSides, nDice - 1, s + i, counts) } } func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 { len1 := (nSides1 + 1) * nDice1 c1 := make([]uint, len1) throwDie(nSides1, nDice1, 0, c1) len2 := (nSides2 + 1) * nDice2 c2 := make([]uint, len2) throwDie(nSides2, nDice2, 0, c2) p12 := math.Pow(float64(nSides1), float64(nDice1)) * math.Pow(float64(nSides2), float64(nDice2)) tot := 0.0 for i := uint(0); i < len1; i++ { for j := uint(0); j < minOf(i, len2); j++ { tot += float64(c1[i] * c2[j]) / p12 } } return tot } func main() { fmt.Println(beatingProbability(4, 9, 6, 6)) fmt.Println(beatingProbability(10, 5, 7, 6)) }
Preserve the algorithm and functionality while converting the code from Java to Go.
import java.util.*; public class Sokoban { String destBoard, currBoard; int playerX, playerY, nCols; Sokoban(String[] board) { nCols = board[0].length(); StringBuilder destBuf = new StringBuilder(); StringBuilder currBuf = new StringBuilder(); for (int r = 0; r < board.length; r++) { for (int c = 0; c < nCols; c++) { char ch = board[r].charAt(c); destBuf.append(ch != '$' && ch != '@' ? ch : ' '); currBuf.append(ch != '.' ? ch : ' '); if (ch == '@') { this.playerX = c; this.playerY = r; } } } destBoard = destBuf.toString(); currBoard = currBuf.toString(); } String move(int x, int y, int dx, int dy, String trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard.charAt(newPlayerPos) != ' ') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = ' '; trial[newPlayerPos] = '@'; return new String(trial); } String push(int x, int y, int dx, int dy, String trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard.charAt(newBoxPos) != ' ') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = ' '; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = '$'; return new String(trial); } boolean isSolved(String trialBoard) { for (int i = 0; i < trialBoard.length(); i++) if ((destBoard.charAt(i) == '.') != (trialBoard.charAt(i) == '$')) return false; return true; } String solve() { class Board { String cur, sol; int x, y; Board(String s1, String s2, int px, int py) { cur = s1; sol = s2; x = px; y = py; } } char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}}; int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1]; if (trial.charAt((y + dy) * nCols + x + dx) == '$') { if ((trial = push(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][1]; if (isSolved(trial)) return newSol; open.add(new Board(trial, newSol, x + dx, y + dy)); history.add(trial); } } } else if ((trial = move(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][0]; open.add(new Board(trial, newSol, x + dx, y + dy)); history.add(trial); } } } } return "No solution"; } public static void main(String[] a) { String level = "#######,# #,# #,#. # #,#. $$ #," + "#.$$ #,#.# @#,#######"; System.out.println(new Sokoban(level.split(",")).solve()); } }
package main import ( "fmt" "strings" ) func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) } func solve(board string) string { buffer = make([]byte, len(board)) width := strings.Index(board[1:], "\n") + 1 dirs := []struct { move, push string dPos int }{ {"u", "U", -width}, {"r", "R", 1}, {"d", "D", width}, {"l", "L", -1}, } visited := map[string]bool{board: true} open := []state{state{board, "", strings.Index(board, "@")}} for len(open) > 0 { s1 := &open[0] open = open[1:] for _, dir := range dirs { var newBoard, newSol string newPos := s1.pos + dir.dPos switch s1.board[newPos] { case '$', '*': newBoard = s1.push(dir.dPos) if newBoard == "" || visited[newBoard] { continue } newSol = s1.cSol + dir.push if strings.IndexAny(newBoard, ".+") < 0 { return newSol } case ' ', '.': newBoard = s1.move(dir.dPos) if visited[newBoard] { continue } newSol = s1.cSol + dir.move default: continue } open = append(open, state{newBoard, newSol, newPos}) visited[newBoard] = true } } return "No solution" } type state struct { board string cSol string pos int } var buffer []byte func (s *state) move(dPos int) string { copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } newPos := s.pos + dPos if buffer[newPos] == ' ' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } return string(buffer) } func (s *state) push(dPos int) string { newPos := s.pos + dPos boxPos := newPos + dPos switch s.board[boxPos] { case ' ', '.': default: return "" } copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } if buffer[newPos] == '$' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } if buffer[boxPos] == ' ' { buffer[boxPos] = '$' } else { buffer[boxPos] = '*' } return string(buffer) }
Please provide an equivalent version of this Java code in Go.
import java.util.*; public class PracticalNumbers { public static void main(String[] args) { final int from = 1; final int to = 333; List<Integer> practical = new ArrayList<>(); for (int i = from; i <= to; ++i) { if (isPractical(i)) practical.add(i); } System.out.printf("Found %d practical numbers between %d and %d:\n%s\n", practical.size(), from, to, shorten(practical, 10)); printPractical(666); printPractical(6666); printPractical(66666); printPractical(672); printPractical(720); printPractical(222222); } private static void printPractical(int n) { if (isPractical(n)) System.out.printf("%d is a practical number.\n", n); else System.out.printf("%d is not a practical number.\n", n); } private static boolean isPractical(int n) { int[] divisors = properDivisors(n); for (int i = 1; i < n; ++i) { if (!sumOfAnySubset(i, divisors, divisors.length)) return false; } return true; } private static boolean sumOfAnySubset(int n, int[] f, int len) { if (len == 0) return false; int total = 0; for (int i = 0; i < len; ++i) { if (n == f[i]) return true; total += f[i]; } if (n == total) return true; if (n > total) return false; --len; int d = n - f[len]; return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len); } private static int[] properDivisors(int n) { List<Integer> divisors = new ArrayList<>(); divisors.add(1); for (int i = 2;; ++i) { int i2 = i * i; if (i2 > n) break; if (n % i == 0) { divisors.add(i); if (i2 != n) divisors.add(n / i); } } int[] result = new int[divisors.size()]; for (int i = 0; i < result.length; ++i) result[i] = divisors.get(i); Arrays.sort(result); return result; } private static String shorten(List<Integer> list, int n) { StringBuilder str = new StringBuilder(); int len = list.size(), i = 0; if (n > 0 && len > 0) str.append(list.get(i++)); for (; i < n && i < len; ++i) { str.append(", "); str.append(list.get(i)); } if (len > i + n) { if (n > 0) str.append(", ..."); i = len - n; } for (; i < len; ++i) { str.append(", "); str.append(list.get(i)); } return str.toString(); } }
package main import ( "fmt" "rcu" ) func powerset(set []int) [][]int { if len(set) == 0 { return [][]int{{}} } head := set[0] tail := set[1:] p1 := powerset(tail) var p2 [][]int for _, s := range powerset(tail) { h := []int{head} h = append(h, s...) p2 = append(p2, h) } return append(p1, p2...) } func isPractical(n int) bool { if n == 1 { return true } divs := rcu.ProperDivisors(n) subsets := powerset(divs) found := make([]bool, n) count := 0 for _, subset := range subsets { sum := rcu.SumInts(subset) if sum > 0 && sum < n && !found[sum] { found[sum] = true count++ if count == n-1 { return true } } } return false } func main() { fmt.Println("In the range 1..333, there are:") var practical []int for i := 1; i <= 333; i++ { if isPractical(i) { practical = append(practical, i) } } fmt.Println(" ", len(practical), "practical numbers") fmt.Println(" The first ten are", practical[0:10]) fmt.Println(" The final ten are", practical[len(practical)-10:]) fmt.Println("\n666 is practical:", isPractical(666)) }
Maintain the same structure and functionality when rewriting this code in Go.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { limit := int(1e6) c := sieve(limit - 1) var erdos []int for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { if !c[i-fact] { found = false break } j++ fact = fact * j } if found { erdos = append(erdos, i) } } if i > 2 { i += 2 } else { i += 1 } } lowerLimit := 2500 var erdosLower []int for _, e := range erdos { if e < lowerLimit { erdosLower = append(erdosLower, e) } else { break } } fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit)) for i, e := range erdosLower { fmt.Printf("%6d", e) if (i+1)%10 == 0 { fmt.Println() } } show := 7875 fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1])) }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { limit := int(1e6) c := sieve(limit - 1) var erdos []int for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { if !c[i-fact] { found = false break } j++ fact = fact * j } if found { erdos = append(erdos, i) } } if i > 2 { i += 2 } else { i += 1 } } lowerLimit := 2500 var erdosLower []int for _, e := range erdos { if e < lowerLimit { erdosLower = append(erdosLower, e) } else { break } } fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit)) for i, e := range erdosLower { fmt.Printf("%6d", e) if (i+1)%10 == 0 { fmt.Println() } } show := 7875 fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1])) }
Generate a Go translation of this Java snippet without changing its computational steps.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { limit := int(1e6) c := sieve(limit - 1) var erdos []int for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { if !c[i-fact] { found = false break } j++ fact = fact * j } if found { erdos = append(erdos, i) } } if i > 2 { i += 2 } else { i += 1 } } lowerLimit := 2500 var erdosLower []int for _, e := range erdos { if e < lowerLimit { erdosLower = append(erdosLower, e) } else { break } } fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit)) for i, e := range erdosLower { fmt.Printf("%6d", e) if (i+1)%10 == 0 { fmt.Println() } } show := 7875 fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1])) }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.util.*; public class Numbrix { final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00"}; final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static int[][] grid; static int[] clues; static int totalToFill; public static void main(String[] args) { int nRows = board.length + 2; int nCols = board[0].split(",").length + 2; int startRow = 0, startCol = 0; grid = new int[nRows][nCols]; totalToFill = (nRows - 2) * (nCols - 2); List<Integer> lst = new ArrayList<>(); for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); if (r >= 1 && r < nRows - 1) { String[] row = board[r - 1].split(","); for (int c = 1; c < nCols - 1; c++) { int val = Integer.parseInt(row[c - 1]); if (val > 0) lst.add(val); if (val == 1) { startRow = r; startCol = c; } grid[r][c] = val; } } } clues = lst.stream().sorted().mapToInt(i -> i).toArray(); if (solve(startRow, startCol, 1, 0)) printResult(); } static boolean solve(int r, int c, int count, int nextClue) { if (count > totalToFill) return true; if (grid[r][c] != 0 && grid[r][c] != count) return false; if (grid[r][c] == 0 && nextClue < clues.length) if (clues[nextClue] == count) return false; int back = grid[r][c]; if (back == count) nextClue++; grid[r][c] = count; for (int[] move : moves) if (solve(r + move[1], c + move[0], count + 1, nextClue)) return true; grid[r][c] = back; return false; } static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) continue; System.out.printf("%2d ", i); } System.out.println(); } } }
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00", } var example2 = []string{ "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00", } var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} var ( grid [][]int clues []int totalToFill = 0 ) func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true } back := grid[r][c] if back != 0 && back != count { return false } if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false } if back == count { nextClue++ } grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false } func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } } func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } } sort.Ints(lst) clues = lst if solve(startRow, startCol, 1, 0) { printResult(n + 1) } } }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.*; public class Numbrix { final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00"}; final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static int[][] grid; static int[] clues; static int totalToFill; public static void main(String[] args) { int nRows = board.length + 2; int nCols = board[0].split(",").length + 2; int startRow = 0, startCol = 0; grid = new int[nRows][nCols]; totalToFill = (nRows - 2) * (nCols - 2); List<Integer> lst = new ArrayList<>(); for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); if (r >= 1 && r < nRows - 1) { String[] row = board[r - 1].split(","); for (int c = 1; c < nCols - 1; c++) { int val = Integer.parseInt(row[c - 1]); if (val > 0) lst.add(val); if (val == 1) { startRow = r; startCol = c; } grid[r][c] = val; } } } clues = lst.stream().sorted().mapToInt(i -> i).toArray(); if (solve(startRow, startCol, 1, 0)) printResult(); } static boolean solve(int r, int c, int count, int nextClue) { if (count > totalToFill) return true; if (grid[r][c] != 0 && grid[r][c] != count) return false; if (grid[r][c] == 0 && nextClue < clues.length) if (clues[nextClue] == count) return false; int back = grid[r][c]; if (back == count) nextClue++; grid[r][c] = count; for (int[] move : moves) if (solve(r + move[1], c + move[0], count + 1, nextClue)) return true; grid[r][c] = back; return false; } static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) continue; System.out.printf("%2d ", i); } System.out.println(); } } }
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00", } var example2 = []string{ "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00", } var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} var ( grid [][]int clues []int totalToFill = 0 ) func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true } back := grid[r][c] if back != 0 && back != count { return false } if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false } if back == count { nextClue++ } grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false } func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } } func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } } sort.Ints(lst) clues = lst if solve(startRow, startCol, 1, 0) { printResult(n + 1) } } }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.*; public class Numbrix { final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00"}; final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static int[][] grid; static int[] clues; static int totalToFill; public static void main(String[] args) { int nRows = board.length + 2; int nCols = board[0].split(",").length + 2; int startRow = 0, startCol = 0; grid = new int[nRows][nCols]; totalToFill = (nRows - 2) * (nCols - 2); List<Integer> lst = new ArrayList<>(); for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); if (r >= 1 && r < nRows - 1) { String[] row = board[r - 1].split(","); for (int c = 1; c < nCols - 1; c++) { int val = Integer.parseInt(row[c - 1]); if (val > 0) lst.add(val); if (val == 1) { startRow = r; startCol = c; } grid[r][c] = val; } } } clues = lst.stream().sorted().mapToInt(i -> i).toArray(); if (solve(startRow, startCol, 1, 0)) printResult(); } static boolean solve(int r, int c, int count, int nextClue) { if (count > totalToFill) return true; if (grid[r][c] != 0 && grid[r][c] != count) return false; if (grid[r][c] == 0 && nextClue < clues.length) if (clues[nextClue] == count) return false; int back = grid[r][c]; if (back == count) nextClue++; grid[r][c] = count; for (int[] move : moves) if (solve(r + move[1], c + move[0], count + 1, nextClue)) return true; grid[r][c] = back; return false; } static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) continue; System.out.printf("%2d ", i); } System.out.println(); } } }
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00", } var example2 = []string{ "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00", } var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} var ( grid [][]int clues []int totalToFill = 0 ) func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true } back := grid[r][c] if back != 0 && back != count { return false } if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false } if back == count { nextClue++ } grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false } func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } } func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } } sort.Ints(lst) clues = lst if solve(startRow, startCol, 1, 0) { printResult(n + 1) } } }
Write a version of this Java function in Go with identical behavior.
package lvijay; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class Church { public static interface ChurchNum extends Function<ChurchNum, ChurchNum> { } public static ChurchNum zero() { return f -> x -> x; } public static ChurchNum next(ChurchNum n) { return f -> x -> f.apply(n.apply(f).apply(x)); } public static ChurchNum plus(ChurchNum a) { return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x)); } public static ChurchNum pow(ChurchNum m) { return n -> m.apply(n); } public static ChurchNum mult(ChurchNum a) { return b -> f -> x -> b.apply(a.apply(f)).apply(x); } public static ChurchNum toChurchNum(int n) { if (n <= 0) { return zero(); } return next(toChurchNum(n - 1)); } public static int toInt(ChurchNum c) { AtomicInteger counter = new AtomicInteger(0); ChurchNum funCounter = f -> { counter.incrementAndGet(); return f; }; plus(zero()).apply(c).apply(funCounter).apply(x -> x); return counter.get(); } public static void main(String[] args) { ChurchNum zero = zero(); ChurchNum three = next(next(next(zero))); ChurchNum four = next(next(next(next(zero)))); System.out.println("3+4=" + toInt(plus(three).apply(four))); System.out.println("4+3=" + toInt(plus(four).apply(three))); System.out.println("3*4=" + toInt(mult(three).apply(four))); System.out.println("4*3=" + toInt(mult(four).apply(three))); System.out.println("3^4=" + toInt(pow(four).apply(three))); System.out.println("4^3=" + toInt(pow(three).apply(four))); System.out.println(" 8=" + toInt(toChurchNum(8))); } }
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
Translate this program into Go but keep the logic exactly as in Java.
package lvijay; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class Church { public static interface ChurchNum extends Function<ChurchNum, ChurchNum> { } public static ChurchNum zero() { return f -> x -> x; } public static ChurchNum next(ChurchNum n) { return f -> x -> f.apply(n.apply(f).apply(x)); } public static ChurchNum plus(ChurchNum a) { return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x)); } public static ChurchNum pow(ChurchNum m) { return n -> m.apply(n); } public static ChurchNum mult(ChurchNum a) { return b -> f -> x -> b.apply(a.apply(f)).apply(x); } public static ChurchNum toChurchNum(int n) { if (n <= 0) { return zero(); } return next(toChurchNum(n - 1)); } public static int toInt(ChurchNum c) { AtomicInteger counter = new AtomicInteger(0); ChurchNum funCounter = f -> { counter.incrementAndGet(); return f; }; plus(zero()).apply(c).apply(funCounter).apply(x -> x); return counter.get(); } public static void main(String[] args) { ChurchNum zero = zero(); ChurchNum three = next(next(next(zero))); ChurchNum four = next(next(next(next(zero)))); System.out.println("3+4=" + toInt(plus(three).apply(four))); System.out.println("4+3=" + toInt(plus(four).apply(three))); System.out.println("3*4=" + toInt(mult(three).apply(four))); System.out.println("4*3=" + toInt(mult(four).apply(three))); System.out.println("3^4=" + toInt(pow(four).apply(three))); System.out.println("4^3=" + toInt(pow(three).apply(four))); System.out.println(" 8=" + toInt(toChurchNum(8))); } }
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
Write a version of this Java function in Go with identical behavior.
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[][] grid; static int totalToFill; public static void main(String[] args) { int nRows = board.length + 6; int nCols = board[0].length() + 6; grid = new int[nRows][nCols]; for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); for (int c = 3; c < nCols - 3; c++) if (r >= 3 && r < nRows - 3) { if (board[r - 3].charAt(c - 3) == '0') { grid[r][c] = 0; totalToFill++; } } } int pos = -1, r, c; do { do { pos++; r = pos / nCols; c = pos % nCols; } while (grid[r][c] == -1); grid[r][c] = 1; if (solve(r, c, 2)) break; grid[r][c] = 0; } while (pos < nRows * nCols); printResult(); } static boolean solve(int r, int c, int count) { if (count > totalToFill) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != totalToFill) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
Keep all operations the same but rewrite the snippet in Go.
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[][] grid; static int totalToFill; public static void main(String[] args) { int nRows = board.length + 6; int nCols = board[0].length() + 6; grid = new int[nRows][nCols]; for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); for (int c = 3; c < nCols - 3; c++) if (r >= 3 && r < nRows - 3) { if (board[r - 3].charAt(c - 3) == '0') { grid[r][c] = 0; totalToFill++; } } } int pos = -1, r, c; do { do { pos++; r = pos / nCols; c = pos % nCols; } while (grid[r][c] == -1); grid[r][c] = 1; if (solve(r, c, 2)) break; grid[r][c] = 0; } while (pos < nRows * nCols); printResult(); } static boolean solve(int r, int c, int count) { if (count > totalToFill) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != totalToFill) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[][] grid; static int totalToFill; public static void main(String[] args) { int nRows = board.length + 6; int nCols = board[0].length() + 6; grid = new int[nRows][nCols]; for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); for (int c = 3; c < nCols - 3; c++) if (r >= 3 && r < nRows - 3) { if (board[r - 3].charAt(c - 3) == '0') { grid[r][c] = 0; totalToFill++; } } } int pos = -1, r, c; do { do { pos++; r = pos / nCols; c = pos % nCols; } while (grid[r][c] == -1); grid[r][c] = 1; if (solve(r, c, 2)) break; grid[r][c] = 0; } while (pos < nRows * nCols); printResult(); } static boolean solve(int r, int c, int count) { if (count > totalToFill) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != totalToFill) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
Convert this Java snippet to Go and keep its semantics consistent.
import java.util.*; import static java.util.Arrays.*; import static java.util.stream.Collectors.toList; public class NonogramSolver { static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}; static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE " + "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"}; static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC"}; static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q " + "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"}; public static void main(String[] args) { for (String[] puzzleData : new String[][]{p1, p2, p3, p4}) newPuzzle(puzzleData); } static void newPuzzle(String[] data) { String[] rowData = data[0].split("\\s"); String[] colData = data[1].split("\\s"); List<List<BitSet>> cols, rows; rows = getCandidates(rowData, colData.length); cols = getCandidates(colData, rowData.length); int numChanged; do { numChanged = reduceMutual(cols, rows); if (numChanged == -1) { System.out.println("No solution"); return; } } while (numChanged > 0); for (List<BitSet> row : rows) { for (int i = 0; i < cols.size(); i++) System.out.print(row.get(0).get(i) ? "# " : ". "); System.out.println(); } System.out.println(); } static List<List<BitSet>> getCandidates(String[] data, int len) { List<List<BitSet>> result = new ArrayList<>(); for (String s : data) { List<BitSet> lst = new LinkedList<>(); int sumChars = s.chars().map(c -> c - 'A' + 1).sum(); List<String> prep = stream(s.split("")) .map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList()); for (String r : genSequence(prep, len - sumChars + 1)) { char[] bits = r.substring(1).toCharArray(); BitSet bitset = new BitSet(bits.length); for (int i = 0; i < bits.length; i++) bitset.set(i, bits[i] == '1'); lst.add(bitset); } result.add(lst); } return result; } static List<String> genSequence(List<String> ones, int numZeros) { if (ones.isEmpty()) return asList(repeat(numZeros, "0")); List<String> result = new ArrayList<>(); for (int x = 1; x < numZeros - ones.size() + 2; x++) { List<String> skipOne = ones.stream().skip(1).collect(toList()); for (String tail : genSequence(skipOne, numZeros - x)) result.add(repeat(x, "0") + ones.get(0) + tail); } return result; } static String repeat(int n, String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append(s); return sb.toString(); } static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) { int countRemoved1 = reduce(cols, rows); if (countRemoved1 == -1) return -1; int countRemoved2 = reduce(rows, cols); if (countRemoved2 == -1) return -1; return countRemoved1 + countRemoved2; } static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) { int countRemoved = 0; for (int i = 0; i < a.size(); i++) { BitSet commonOn = new BitSet(); commonOn.set(0, b.size()); BitSet commonOff = new BitSet(); for (BitSet candidate : a.get(i)) { commonOn.and(candidate); commonOff.or(candidate); } for (int j = 0; j < b.size(); j++) { final int fi = i, fj = j; if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi)) || (!commonOff.get(fj) && cnd.get(fi)))) countRemoved++; if (b.get(j).isEmpty()) return -1; } } return countRemoved; } }
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if bs[i] || other[i] { bs[i] = true } else { bs[i] = false } } } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func newPuzzle(data [2]string) { rowData := strings.Fields(data[0]) colData := strings.Fields(data[1]) rows := getCandidates(rowData, len(colData)) cols := getCandidates(colData, len(rowData)) for { numChanged := reduceMutual(cols, rows) if numChanged == -1 { fmt.Println("No solution") return } if numChanged == 0 { break } } for _, row := range rows { for i := 0; i < len(cols); i++ { fmt.Printf(iff(row[0][i], "# ", ". ")) } fmt.Println() } fmt.Println() } func getCandidates(data []string, le int) [][]BitSet { var result [][]BitSet for _, s := range data { var lst []BitSet a := []byte(s) sumBytes := 0 for _, b := range a { sumBytes += int(b - 'A' + 1) } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-'A'+1)) } for _, r := range genSequence(prep, le-sumBytes+1) { bits := []byte(r[1:]) bitset := make(BitSet, len(bits)) for i, b := range bits { bitset[i] = b == '1' } lst = append(lst, bitset) } result = append(result, lst) } return result } func genSequence(ones []string, numZeros int) []string { le := len(ones) if le == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-le+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } func reduceMutual(cols, rows [][]BitSet) int { countRemoved1 := reduce(cols, rows) if countRemoved1 == -1 { return -1 } countRemoved2 := reduce(rows, cols) if countRemoved2 == -1 { return -1 } return countRemoved1 + countRemoved2 } func reduce(a, b [][]BitSet) int { countRemoved := 0 for i := 0; i < len(a); i++ { commonOn := make(BitSet, len(b)) for j := 0; j < len(b); j++ { commonOn[j] = true } commonOff := make(BitSet, len(b)) for _, candidate := range a[i] { commonOn.and(candidate) commonOff.or(candidate) } for j := 0; j < len(b); j++ { fi, fj := i, j for k := len(b[j]) - 1; k >= 0; k-- { cnd := b[j][k] if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) { lb := len(b[j]) copy(b[j][k:], b[j][k+1:]) b[j][lb-1] = nil b[j] = b[j][:lb-1] countRemoved++ } } if len(b[j]) == 0 { return -1 } } } return countRemoved } func main() { p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"} p2 := [2]string{ "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA", } p3 := [2]string{ "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC", } p4 := [2]string{ "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM", } for _, puzzleData := range [][2]string{p1, p2, p3, p4} { newPuzzle(puzzleData) } }
Translate this program into Go but keep the logic exactly as in Java.
import java.util.*; import static java.util.Arrays.*; import static java.util.stream.Collectors.toList; public class NonogramSolver { static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}; static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE " + "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"}; static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC"}; static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q " + "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"}; public static void main(String[] args) { for (String[] puzzleData : new String[][]{p1, p2, p3, p4}) newPuzzle(puzzleData); } static void newPuzzle(String[] data) { String[] rowData = data[0].split("\\s"); String[] colData = data[1].split("\\s"); List<List<BitSet>> cols, rows; rows = getCandidates(rowData, colData.length); cols = getCandidates(colData, rowData.length); int numChanged; do { numChanged = reduceMutual(cols, rows); if (numChanged == -1) { System.out.println("No solution"); return; } } while (numChanged > 0); for (List<BitSet> row : rows) { for (int i = 0; i < cols.size(); i++) System.out.print(row.get(0).get(i) ? "# " : ". "); System.out.println(); } System.out.println(); } static List<List<BitSet>> getCandidates(String[] data, int len) { List<List<BitSet>> result = new ArrayList<>(); for (String s : data) { List<BitSet> lst = new LinkedList<>(); int sumChars = s.chars().map(c -> c - 'A' + 1).sum(); List<String> prep = stream(s.split("")) .map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList()); for (String r : genSequence(prep, len - sumChars + 1)) { char[] bits = r.substring(1).toCharArray(); BitSet bitset = new BitSet(bits.length); for (int i = 0; i < bits.length; i++) bitset.set(i, bits[i] == '1'); lst.add(bitset); } result.add(lst); } return result; } static List<String> genSequence(List<String> ones, int numZeros) { if (ones.isEmpty()) return asList(repeat(numZeros, "0")); List<String> result = new ArrayList<>(); for (int x = 1; x < numZeros - ones.size() + 2; x++) { List<String> skipOne = ones.stream().skip(1).collect(toList()); for (String tail : genSequence(skipOne, numZeros - x)) result.add(repeat(x, "0") + ones.get(0) + tail); } return result; } static String repeat(int n, String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append(s); return sb.toString(); } static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) { int countRemoved1 = reduce(cols, rows); if (countRemoved1 == -1) return -1; int countRemoved2 = reduce(rows, cols); if (countRemoved2 == -1) return -1; return countRemoved1 + countRemoved2; } static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) { int countRemoved = 0; for (int i = 0; i < a.size(); i++) { BitSet commonOn = new BitSet(); commonOn.set(0, b.size()); BitSet commonOff = new BitSet(); for (BitSet candidate : a.get(i)) { commonOn.and(candidate); commonOff.or(candidate); } for (int j = 0; j < b.size(); j++) { final int fi = i, fj = j; if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi)) || (!commonOff.get(fj) && cnd.get(fi)))) countRemoved++; if (b.get(j).isEmpty()) return -1; } } return countRemoved; } }
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if bs[i] || other[i] { bs[i] = true } else { bs[i] = false } } } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func newPuzzle(data [2]string) { rowData := strings.Fields(data[0]) colData := strings.Fields(data[1]) rows := getCandidates(rowData, len(colData)) cols := getCandidates(colData, len(rowData)) for { numChanged := reduceMutual(cols, rows) if numChanged == -1 { fmt.Println("No solution") return } if numChanged == 0 { break } } for _, row := range rows { for i := 0; i < len(cols); i++ { fmt.Printf(iff(row[0][i], "# ", ". ")) } fmt.Println() } fmt.Println() } func getCandidates(data []string, le int) [][]BitSet { var result [][]BitSet for _, s := range data { var lst []BitSet a := []byte(s) sumBytes := 0 for _, b := range a { sumBytes += int(b - 'A' + 1) } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-'A'+1)) } for _, r := range genSequence(prep, le-sumBytes+1) { bits := []byte(r[1:]) bitset := make(BitSet, len(bits)) for i, b := range bits { bitset[i] = b == '1' } lst = append(lst, bitset) } result = append(result, lst) } return result } func genSequence(ones []string, numZeros int) []string { le := len(ones) if le == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-le+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } func reduceMutual(cols, rows [][]BitSet) int { countRemoved1 := reduce(cols, rows) if countRemoved1 == -1 { return -1 } countRemoved2 := reduce(rows, cols) if countRemoved2 == -1 { return -1 } return countRemoved1 + countRemoved2 } func reduce(a, b [][]BitSet) int { countRemoved := 0 for i := 0; i < len(a); i++ { commonOn := make(BitSet, len(b)) for j := 0; j < len(b); j++ { commonOn[j] = true } commonOff := make(BitSet, len(b)) for _, candidate := range a[i] { commonOn.and(candidate) commonOff.or(candidate) } for j := 0; j < len(b); j++ { fi, fj := i, j for k := len(b[j]) - 1; k >= 0; k-- { cnd := b[j][k] if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) { lb := len(b[j]) copy(b[j][k:], b[j][k+1:]) b[j][lb-1] = nil b[j] = b[j][:lb-1] countRemoved++ } } if len(b[j]) == 0 { return -1 } } } return countRemoved } func main() { p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"} p2 := [2]string{ "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA", } p3 := [2]string{ "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC", } p4 := [2]string{ "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM", } for _, puzzleData := range [][2]string{p1, p2, p3, p4} { newPuzzle(puzzleData) } }
Write the same code in Go as shown below in Java.
import java.io.*; import static java.lang.String.format; import java.util.*; public class WordSearch { static class Grid { int numAttempts; char[][] cells = new char[nRows][nCols]; List<String> solutions = new ArrayList<>(); } final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; final static int nRows = 10; final static int nCols = 10; final static int gridSize = nRows * nCols; final static int minWords = 25; final static Random rand = new Random(); public static void main(String[] args) { printResult(createWordSearch(readWords("unixdict.txt"))); } static List<String> readWords(String filename) { int maxLen = Math.max(nRows, nCols); List<String> words = new ArrayList<>(); try (Scanner sc = new Scanner(new FileReader(filename))) { while (sc.hasNext()) { String s = sc.next().trim().toLowerCase(); if (s.matches("^[a-z]{3," + maxLen + "}$")) words.add(s); } } catch (FileNotFoundException e) { System.out.println(e); } return words; } static Grid createWordSearch(List<String> words) { Grid grid = null; int numAttempts = 0; outer: while (++numAttempts < 100) { Collections.shuffle(words); grid = new Grid(); int messageLen = placeMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; for (String word : words) { cellsFilled += tryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.solutions.size() >= minWords) { grid.numAttempts = numAttempts; break outer; } else break; } } } return grid; } static int placeMessage(Grid grid, String msg) { msg = msg.toUpperCase().replaceAll("[^A-Z]", ""); int messageLen = msg.length(); if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen; for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.nextInt(gapSize); grid.cells[pos / nCols][pos % nCols] = msg.charAt(i); } return messageLen; } return 0; } static int tryPlaceWord(Grid grid, String word) { int randDir = rand.nextInt(dirs.length); int randPos = rand.nextInt(gridSize); for (int dir = 0; dir < dirs.length; dir++) { dir = (dir + randDir) % dirs.length; for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize; int lettersPlaced = tryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; } static int tryLocation(Grid grid, String word, int dir, int pos) { int r = pos / nCols; int c = pos % nCols; int len = word.length(); if ((dirs[dir][0] == 1 && (len + c) > nCols) || (dirs[dir][0] == -1 && (len - 1) > c) || (dirs[dir][1] == 1 && (len + r) > nRows) || (dirs[dir][1] == -1 && (len - 1) > r)) return 0; int rr, cc, i, overlaps = 0; for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i)) return 0; cc += dirs[dir][0]; rr += dirs[dir][1]; } for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.cells[rr][cc] == word.charAt(i)) overlaps++; else grid.cells[rr][cc] = word.charAt(i); if (i < len - 1) { cc += dirs[dir][0]; rr += dirs[dir][1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.solutions.add(format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)); } return lettersPlaced; } static void printResult(Grid grid) { if (grid == null || grid.numAttempts == 0) { System.out.println("No grid to display"); return; } int size = grid.solutions.size(); System.out.println("Attempts: " + grid.numAttempts); System.out.println("Number of words: " + size); System.out.println("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { System.out.printf("%n%d ", r); for (int c = 0; c < nCols; c++) System.out.printf(" %c ", grid.cells[r][c]); } System.out.println("\n"); for (int i = 0; i < size - 1; i += 2) { System.out.printf("%s %s%n", grid.solutions.get(i), grid.solutions.get(i + 1)); } if (size % 2 == 1) System.out.println(grid.solutions.get(size - 1)); } }
package main import ( "bufio" "fmt" "log" "math/rand" "os" "regexp" "strings" "time" ) var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}} const ( nRows = 10 nCols = nRows gridSize = nRows * nCols minWords = 25 ) var ( re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows)) re2 = regexp.MustCompile("[^A-Z]") ) type grid struct { numAttempts int cells [nRows][nCols]byte solutions []string } func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if re1.MatchString(word) { words = append(words, word) } } check(scanner.Err()) return words } func createWordSearch(words []string) *grid { var gr *grid outer: for i := 1; i < 100; i++ { gr = new(grid) messageLen := gr.placeMessage("Rosetta Code") target := gridSize - messageLen cellsFilled := 0 rand.Shuffle(len(words), func(i, j int) { words[i], words[j] = words[j], words[i] }) for _, word := range words { cellsFilled += gr.tryPlaceWord(word) if cellsFilled == target { if len(gr.solutions) >= minWords { gr.numAttempts = i break outer } else { break } } } } return gr } func (gr *grid) placeMessage(msg string) int { msg = strings.ToUpper(msg) msg = re2.ReplaceAllLiteralString(msg, "") messageLen := len(msg) if messageLen > 0 && messageLen < gridSize { gapSize := gridSize / messageLen for i := 0; i < messageLen; i++ { pos := i*gapSize + rand.Intn(gapSize) gr.cells[pos/nCols][pos%nCols] = msg[i] } return messageLen } return 0 } func (gr *grid) tryPlaceWord(word string) int { randDir := rand.Intn(len(dirs)) randPos := rand.Intn(gridSize) for dir := 0; dir < len(dirs); dir++ { dir = (dir + randDir) % len(dirs) for pos := 0; pos < gridSize; pos++ { pos = (pos + randPos) % gridSize lettersPlaced := gr.tryLocation(word, dir, pos) if lettersPlaced > 0 { return lettersPlaced } } } return 0 } func (gr *grid) tryLocation(word string, dir, pos int) int { r := pos / nCols c := pos % nCols le := len(word) if (dirs[dir][0] == 1 && (le+c) > nCols) || (dirs[dir][0] == -1 && (le-1) > c) || (dirs[dir][1] == 1 && (le+r) > nRows) || (dirs[dir][1] == -1 && (le-1) > r) { return 0 } overlaps := 0 rr := r cc := c for i := 0; i < le; i++ { if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] { return 0 } cc += dirs[dir][0] rr += dirs[dir][1] } rr = r cc = c for i := 0; i < le; i++ { if gr.cells[rr][cc] == word[i] { overlaps++ } else { gr.cells[rr][cc] = word[i] } if i < le-1 { cc += dirs[dir][0] rr += dirs[dir][1] } } lettersPlaced := le - overlaps if lettersPlaced > 0 { sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr) gr.solutions = append(gr.solutions, sol) } return lettersPlaced } func printResult(gr *grid) { if gr.numAttempts == 0 { fmt.Println("No grid to display") return } size := len(gr.solutions) fmt.Println("Attempts:", gr.numAttempts) fmt.Println("Number of words:", size) fmt.Println("\n 0 1 2 3 4 5 6 7 8 9") for r := 0; r < nRows; r++ { fmt.Printf("\n%d ", r) for c := 0; c < nCols; c++ { fmt.Printf(" %c ", gr.cells[r][c]) } } fmt.Println("\n") for i := 0; i < size-1; i += 2 { fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1]) } if size%2 == 1 { fmt.Println(gr.solutions[size-1]) } } func main() { rand.Seed(time.Now().UnixNano()) unixDictPath := "/usr/share/dict/words" printResult(createWordSearch(readWords(unixDictPath))) }
Change the programming language of this snippet from Java to Go without modifying what it does.
module BreakOO { class Exposed { public String pub = "public"; protected String pro = "protected"; private String pri = "private"; @Override String toString() { return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}"; } } void run() { @Inject Console console; Exposed expo = new Exposed(); console.print($"before: {expo}"); expo.pub = $"this was {expo.pub}"; assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed)); expoPro.pro = $"this was {expoPro.pro}"; assert (private Exposed) expoPri := &expo.revealAs((private Exposed)); expoPri.pri = $"this was {expoPri.pri}"; assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed)); expoStr.pub = $"{expoStr.pub}!!!"; expoStr.pro = $"{expoStr.pro}!!!"; expoStr.pri = $"{expoStr.pri}!!!"; console.print($"after: {expo}"); } }
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
Write the same code in Go as shown below in Java.
module BreakOO { class Exposed { public String pub = "public"; protected String pro = "protected"; private String pri = "private"; @Override String toString() { return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}"; } } void run() { @Inject Console console; Exposed expo = new Exposed(); console.print($"before: {expo}"); expo.pub = $"this was {expo.pub}"; assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed)); expoPro.pro = $"this was {expoPro.pro}"; assert (private Exposed) expoPri := &expo.revealAs((private Exposed)); expoPri.pri = $"this was {expoPri.pri}"; assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed)); expoStr.pub = $"{expoStr.pub}!!!"; expoStr.pro = $"{expoStr.pro}!!!"; expoStr.pri = $"{expoStr.pri}!!!"; console.print($"after: {expo}"); } }
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.io.*; class Entity implements Serializable { static final long serialVersionUID = 3504465751164822571L; String name = "Entity"; public String toString() { return name; } } class Person extends Entity implements Serializable { static final long serialVersionUID = -9170445713373959735L; Person() { name = "Cletus"; } } public class SerializationTest { public static void main(String[] args) { Person instance1 = new Person(); System.out.println(instance1); Entity instance2 = new Entity(); System.out.println(instance2); try { ObjectOutput out = new ObjectOutputStream(new FileOutputStream("objects.dat")); out.writeObject(instance1); out.writeObject(instance2); out.close(); System.out.println("Serialized..."); } catch (IOException e) { System.err.println("Something screwed up while serializing"); e.printStackTrace(); System.exit(1); } try { ObjectInput in = new ObjectInputStream(new FileInputStream("objects.dat")); Object readObject1 = in.readObject(); Object readObject2 = in.readObject(); in.close(); System.out.println("Deserialized..."); System.out.println(readObject1); System.out.println(readObject2); } catch (IOException e) { System.err.println("Something screwed up while deserializing"); e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Unknown class for deserialized object"); e.printStackTrace(); System.exit(1); } } }
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() { animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Collie{Dog: Dog{ Animal: Animal{Alive: true}, ObedienceTrained: true, }}, } fmt.Println("created:") for _, a := range animals { a.print() } f, err := os.Create("objects.dat") if err != nil { fmt.Println(err) return } for _, a := range animals { gob.Register(a) } err = gob.NewEncoder(f).Encode(animals) if err != nil { fmt.Println(err) return } f.Close() f, err = os.Open("objects.dat") if err != nil { fmt.Println(err) return } var clones []printable gob.NewDecoder(f).Decode(&clones) if err != nil { fmt.Println(err) return } fmt.Println("\nloaded from objects.dat:") for _, c := range clones { c.print() } } type Animal struct { Alive bool } func (a *Animal) print() { if a.Alive { fmt.Println(" live animal, unspecified type") } else { fmt.Println(" dead animal, unspecified type") } } type Dog struct { Animal ObedienceTrained bool } func (d *Dog) print() { switch { case !d.Alive: fmt.Println(" dead dog") case d.ObedienceTrained: fmt.Println(" trained dog") default: fmt.Println(" dog, not trained") } } type Cat struct { Animal LitterBoxTrained bool } func (c *Cat) print() { switch { case !c.Alive: fmt.Println(" dead cat") case c.LitterBoxTrained: fmt.Println(" litter box trained cat") default: fmt.Println(" cat, not litter box trained") } } type Lab struct { Dog Color string } func (l *Lab) print() { var r string if l.Color == "" { r = "lab, color unspecified" } else { r = l.Color + " lab" } switch { case !l.Alive: fmt.Println(" dead", r) case l.ObedienceTrained: fmt.Println(" trained", r) default: fmt.Printf(" %s, not trained\n", r) } } type Collie struct { Dog CatchesFrisbee bool } func (c *Collie) print() { switch { case !c.Alive: fmt.Println(" dead collie") case c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" trained collie, catches frisbee") case c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" trained collie, but doesn't catch frisbee") case !c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" collie, not trained, but catches frisbee") case !c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" collie, not trained, doesn't catch frisbee") } }
Preserve the algorithm and functionality while converting the code from Java to Go.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Eertree { public static void main(String[] args) { List<Node> tree = eertree("eertree"); List<String> result = subPalindromes(tree); System.out.println(result); } private static class Node { int length; Map<Character, Integer> edges = new HashMap<>(); int suffix; public Node(int length) { this.length = length; } public Node(int length, Map<Character, Integer> edges, int suffix) { this.length = length; this.edges = edges != null ? edges : new HashMap<>(); this.suffix = suffix; } } private static final int EVEN_ROOT = 0; private static final int ODD_ROOT = 1; private static List<Node> eertree(String s) { List<Node> tree = new ArrayList<>(); tree.add(new Node(0, null, ODD_ROOT)); tree.add(new Node(-1, null, ODD_ROOT)); int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); for (n = suffix; ; n = tree.get(n).suffix) { k = tree.get(n).length; int b = i - k - 1; if (b >= 0 && s.charAt(b) == c) { break; } } if (tree.get(n).edges.containsKey(c)) { suffix = tree.get(n).edges.get(c); continue; } suffix = tree.size(); tree.add(new Node(k + 2)); tree.get(n).edges.put(c, suffix); if (tree.get(suffix).length == 1) { tree.get(suffix).suffix = 0; continue; } while (true) { n = tree.get(n).suffix; int b = i - tree.get(n).length - 1; if (b >= 0 && s.charAt(b) == c) { break; } } tree.get(suffix).suffix = tree.get(n).edges.get(c); } return tree; } private static List<String> subPalindromes(List<Node> tree) { List<String> s = new ArrayList<>(); subPalindromes_children(0, "", tree, s); for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) { String ct = String.valueOf(cm.getKey()); s.add(ct); subPalindromes_children(cm.getValue(), ct, tree, s); } return s; } private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) { for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) { Character c = cm.getKey(); Integer m = cm.getValue(); String pl = c + p + c; s.add(pl); subPalindromes_children(m, pl, tree, s); } } }
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {length: 0, suffix: oddRoot, edges: edges{}}, oddRoot: {length: -1, suffix: oddRoot, edges: edges{}}, } suffix := oddRoot var n, k int for i, c := range s { for n = suffix; ; n = tree[n].suffix { k = tree[n].length if b := i - k - 1; b >= 0 && s[b] == c { break } } if e, ok := tree[n].edges[c]; ok { suffix = e continue } suffix = len(tree) tree = append(tree, node{length: k + 2, edges: edges{}}) tree[n].edges[c] = suffix if tree[suffix].length == 1 { tree[suffix].suffix = 0 continue } for { n = tree[n].suffix if b := i - tree[n].length - 1; b >= 0 && s[b] == c { break } } tree[suffix].suffix = tree[n].edges[c] } return tree } func subPalindromes(tree []node) (s []string) { var children func(int, string) children = func(n int, p string) { for c, n := range tree[n].edges { c := string(c) p := c + p + c s = append(s, p) children(n, p) } } children(0, "") for c, n := range tree[1].edges { c := string(c) s = append(s, c) children(n, c) } return }
Translate the given Java code snippet into Go without altering its behavior.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Eertree { public static void main(String[] args) { List<Node> tree = eertree("eertree"); List<String> result = subPalindromes(tree); System.out.println(result); } private static class Node { int length; Map<Character, Integer> edges = new HashMap<>(); int suffix; public Node(int length) { this.length = length; } public Node(int length, Map<Character, Integer> edges, int suffix) { this.length = length; this.edges = edges != null ? edges : new HashMap<>(); this.suffix = suffix; } } private static final int EVEN_ROOT = 0; private static final int ODD_ROOT = 1; private static List<Node> eertree(String s) { List<Node> tree = new ArrayList<>(); tree.add(new Node(0, null, ODD_ROOT)); tree.add(new Node(-1, null, ODD_ROOT)); int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); for (n = suffix; ; n = tree.get(n).suffix) { k = tree.get(n).length; int b = i - k - 1; if (b >= 0 && s.charAt(b) == c) { break; } } if (tree.get(n).edges.containsKey(c)) { suffix = tree.get(n).edges.get(c); continue; } suffix = tree.size(); tree.add(new Node(k + 2)); tree.get(n).edges.put(c, suffix); if (tree.get(suffix).length == 1) { tree.get(suffix).suffix = 0; continue; } while (true) { n = tree.get(n).suffix; int b = i - tree.get(n).length - 1; if (b >= 0 && s.charAt(b) == c) { break; } } tree.get(suffix).suffix = tree.get(n).edges.get(c); } return tree; } private static List<String> subPalindromes(List<Node> tree) { List<String> s = new ArrayList<>(); subPalindromes_children(0, "", tree, s); for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) { String ct = String.valueOf(cm.getKey()); s.add(ct); subPalindromes_children(cm.getValue(), ct, tree, s); } return s; } private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) { for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) { Character c = cm.getKey(); Integer m = cm.getValue(); String pl = c + p + c; s.add(pl); subPalindromes_children(m, pl, tree, s); } } }
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {length: 0, suffix: oddRoot, edges: edges{}}, oddRoot: {length: -1, suffix: oddRoot, edges: edges{}}, } suffix := oddRoot var n, k int for i, c := range s { for n = suffix; ; n = tree[n].suffix { k = tree[n].length if b := i - k - 1; b >= 0 && s[b] == c { break } } if e, ok := tree[n].edges[c]; ok { suffix = e continue } suffix = len(tree) tree = append(tree, node{length: k + 2, edges: edges{}}) tree[n].edges[c] = suffix if tree[suffix].length == 1 { tree[suffix].suffix = 0 continue } for { n = tree[n].suffix if b := i - tree[n].length - 1; b >= 0 && s[b] == c { break } } tree[suffix].suffix = tree[n].edges[c] } return tree } func subPalindromes(tree []node) (s []string) { var children func(int, string) children = func(n int, p string) { for c, n := range tree[n].edges { c := string(c) p := c + p + c s = append(s, p) children(n, p) } } children(0, "") for c, n := range tree[1].edges { c := string(c) s = append(s, c) children(n, c) } return }
Write the same code in Go as shown below in Java.
import java.time.LocalDate; import java.time.temporal.WeekFields; public class LongYear { public static void main(String[] args) { System.out.printf("Long years this century:%n"); for (int year = 2000 ; year < 2100 ; year++ ) { if ( longYear(year) ) { System.out.print(year + " "); } } } private static boolean longYear(int year) { return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53; } }
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
Generate an equivalent Go version of this Java code.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ZumkellerNumbers { public static void main(String[] args) { int n = 1; System.out.printf("First 220 Zumkeller numbers:%n"); for ( int count = 1 ; count <= 220 ; n += 1 ) { if ( isZumkeller(n) ) { System.out.printf("%3d ", n); if ( count % 20 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( isZumkeller(n) ) { System.out.printf("%6d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( n % 5 != 0 && isZumkeller(n) ) { System.out.printf("%8d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } } private static boolean isZumkeller(int n) { if ( n % 18 == 6 || n % 18 == 12 ) { return true; } List<Integer> divisors = getDivisors(n); int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum(); if ( divisorSum % 2 == 1 ) { return false; } int abundance = divisorSum - 2 * n; if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) { return true; } Collections.sort(divisors); int j = divisors.size() - 1; int sum = divisorSum/2; if ( divisors.get(j) > sum ) { return false; } return canPartition(j, divisors, sum, new int[2]); } private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) { if ( j < 0 ) { return true; } for ( int i = 0 ; i < 2 ; i++ ) { if ( buckets[i] + divisors.get(j) <= sum ) { buckets[i] += divisors.get(j); if ( canPartition(j-1, divisors, sum, buckets) ) { return true; } buckets[i] -= divisors.get(j); } if( buckets[i] == 0 ) { break; } } return false; } private static final List<Integer> getDivisors(int number) { List<Integer> divisors = new ArrayList<Integer>(); long sqrt = (long) Math.sqrt(number); for ( int i = 1 ; i <= sqrt ; i++ ) { if ( number % i == 0 ) { divisors.add(i); int div = number / i; if ( div != i ) { divisors.add(div); } } } return divisors; } }
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(divs []int) int { sum := 0 for _, div := range divs { sum += div } return sum } func isPartSum(divs []int, sum int) bool { if sum == 0 { return true } le := len(divs) if le == 0 { return false } last := divs[le-1] divs = divs[0 : le-1] if last > sum { return isPartSum(divs, sum) } return isPartSum(divs, sum) || isPartSum(divs, sum-last) } func isZumkeller(n int) bool { divs := getDivisors(n) sum := sum(divs) if sum%2 == 1 { return false } if n%2 == 1 { abundance := sum - 2*n return abundance > 0 && abundance%2 == 0 } return isPartSum(divs, sum/2) } func main() { fmt.Println("The first 220 Zumkeller numbers are:") for i, count := 2, 0; count < 220; i++ { if isZumkeller(i) { fmt.Printf("%3d ", i) count++ if count%20 == 0 { fmt.Println() } } } fmt.Println("\nThe first 40 odd Zumkeller numbers are:") for i, count := 3, 0; count < 40; i += 2 { if isZumkeller(i) { fmt.Printf("%5d ", i) count++ if count%10 == 0 { fmt.Println() } } } fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:") for i, count := 3, 0; count < 40; i += 2 { if (i % 10 != 5) && isZumkeller(i) { fmt.Printf("%7d ", i) count++ if count%8 == 0 { fmt.Println() } } } fmt.Println() }
Write the same algorithm in Go as shown in this Java implementation.
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Port the following code from Java to Go with equivalent syntax and logic.
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Convert this Java block to Go, preserving its control flow and logic.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"}; public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); } private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; } private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; } }
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() } func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } } func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
Produce a functionally identical Go code for the snippet given in Java.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"}; public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); } private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; } private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; } }
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() } func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } } func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
Port the following code from Java to Go with equivalent syntax and logic.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; public class MarkovChain { private static Random r = new Random(); private static String markov(String filePath, int keySize, int outputSize) throws IOException { if (keySize < 1) throw new IllegalArgumentException("Key size can't be less than 1"); Path path = Paths.get(filePath); byte[] bytes = Files.readAllBytes(path); String[] words = new String(bytes).trim().split(" "); if (outputSize < keySize || outputSize >= words.length) { throw new IllegalArgumentException("Output size is out of range"); } Map<String, List<String>> dict = new HashMap<>(); for (int i = 0; i < (words.length - keySize); ++i) { StringBuilder key = new StringBuilder(words[i]); for (int j = i + 1; j < i + keySize; ++j) { key.append(' ').append(words[j]); } String value = (i + keySize < words.length) ? words[i + keySize] : ""; if (!dict.containsKey(key.toString())) { ArrayList<String> list = new ArrayList<>(); list.add(value); dict.put(key.toString(), list); } else { dict.get(key.toString()).add(value); } } int n = 0; int rn = r.nextInt(dict.size()); String prefix = (String) dict.keySet().toArray()[rn]; List<String> output = new ArrayList<>(Arrays.asList(prefix.split(" "))); while (true) { List<String> suffix = dict.get(prefix); if (suffix.size() == 1) { if (Objects.equals(suffix.get(0), "")) return output.stream().reduce("", (a, b) -> a + " " + b); output.add(suffix.get(0)); } else { rn = r.nextInt(suffix.size()); output.add(suffix.get(rn)); } if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce("", (a, b) -> a + " " + b); n++; prefix = output.stream().skip(n).limit(keySize).reduce("", (a, b) -> a + " " + b).trim(); } } public static void main(String[] args) throws IOException { System.out.println(markov("alice_oz.txt", 3, 200)); } }
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
Preserve the algorithm and functionality while converting the code from Java to Go.
import java.io.*; import java.util.*; public class Dijkstra { private static final Graph.Edge[] GRAPH = { new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d", 11), new Graph.Edge("c", "f", 2), new Graph.Edge("d", "e", 6), new Graph.Edge("e", "f", 9), }; private static final String START = "a"; private static final String END = "e"; public static void main(String[] args) { Graph g = new Graph(GRAPH); g.dijkstra(START); g.printPath(END); } } class Graph { private final Map<String, Vertex> graph; public static class Edge { public final String v1, v2; public final int dist; public Edge(String v1, String v2, int dist) { this.v1 = v1; this.v2 = v2; this.dist = dist; } } public static class Vertex implements Comparable<Vertex>{ public final String name; public int dist = Integer.MAX_VALUE; public Vertex previous = null; public final Map<Vertex, Integer> neighbours = new HashMap<>(); public Vertex(String name) { this.name = name; } private void printPath() { if (this == this.previous) { System.out.printf("%s", this.name); } else if (this.previous == null) { System.out.printf("%s(unreached)", this.name); } else { this.previous.printPath(); System.out.printf(" -> %s(%d)", this.name, this.dist); } } public int compareTo(Vertex other) { if (dist == other.dist) return name.compareTo(other.name); return Integer.compare(dist, other.dist); } @Override public String toString() { return "(" + name + ", " + dist + ")"; } } public Graph(Edge[] edges) { graph = new HashMap<>(edges.length); for (Edge e : edges) { if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); } for (Edge e : edges) { graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); } } public void dijkstra(String startName) { if (!graph.containsKey(startName)) { System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName); return; } final Vertex source = graph.get(startName); NavigableSet<Vertex> q = new TreeSet<>(); for (Vertex v : graph.values()) { v.previous = v == source ? source : null; v.dist = v == source ? 0 : Integer.MAX_VALUE; q.add(v); } dijkstra(q); } private void dijkstra(final NavigableSet<Vertex> q) { Vertex u, v; while (!q.isEmpty()) { u = q.pollFirst(); if (u.dist == Integer.MAX_VALUE) break; for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { v = a.getKey(); final int alternateDist = u.dist + a.getValue(); if (alternateDist < v.dist) { q.remove(v); v.dist = alternateDist; v.previous = u; q.add(v); } } } } public void printPath(String endName) { if (!graph.containsKey(endName)) { System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName); return; } graph.get(endName).printPath(); System.out.println(); } public void printAllPaths() { for (Vertex v : graph.values()) { v.printPath(); System.out.println(); } } }
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq *PriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.m[pq.items[i]] = i pq.m[pq.items[j]] = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(pq.items) item := x.(Vertex) pq.m[item] = n pq.items = append(pq.items, item) } func (pq *PriorityQueue) Pop() interface{} { old := pq.items n := len(old) item := old[n-1] pq.m[item] = -1 pq.items = old[0 : n-1] return item } func (pq *PriorityQueue) update(item Vertex, priority int) { pq.pr[item] = priority heap.Fix(pq, pq.m[item]) } func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) { heap.Push(pq, item) pq.update(item, priority) } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) { vs := g.Vertices() dist = make(map[Vertex]int, len(vs)) prev = make(map[Vertex]Vertex, len(vs)) sid := source dist[sid] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vs)), m: make(map[Vertex]int, len(vs)), pr: make(map[Vertex]int, len(vs)), } for _, v := range vs { if v != sid { dist[v] = Infinity } prev[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt prev[v] = u q.update(v, alt) } } } return dist, prev } type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int } type Vertex int type sg struct { ids map[string]Vertex names map[Vertex]string edges map[Vertex]map[Vertex]int } func newsg(ids map[string]Vertex) sg { g := sg{ids: ids} g.names = make(map[Vertex]string, len(ids)) for k, v := range ids { g.names[v] = k } g.edges = make(map[Vertex]map[Vertex]int) return g } func (g sg) edge(u, v string, w int) { if _, ok := g.edges[g.ids[u]]; !ok { g.edges[g.ids[u]] = make(map[Vertex]int) } g.edges[g.ids[u]][g.ids[v]] = w } func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) { s = g.names[v] for prev[v] >= 0 { v = prev[v] s = g.names[v] + s } return s } func (g sg) Vertices() []Vertex { vs := make([]Vertex, 0, len(g.ids)) for _, v := range g.ids { vs = append(vs, v) } return vs } func (g sg) Neighbors(u Vertex) []Vertex { vs := make([]Vertex, 0, len(g.edges[u])) for v := range g.edges[u] { vs = append(vs, v) } return vs } func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] } func main() { g := newsg(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 7) g.edge("a", "c", 9) g.edge("a", "f", 14) g.edge("b", "c", 10) g.edge("b", "d", 15) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 6) g.edge("e", "f", 9) dist, prev := Dijkstra(g, g.ids["a"]) fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev)) }
Ensure the translated Go code behaves exactly like the original Java snippet.
import java.util.Arrays; import java.util.Random; public class GeometricAlgebra { private static int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } private static double reorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += bitCount(k & j); k = k >> 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } static class Vector { private double[] dims; public Vector(double[] dims) { this.dims = dims; } public Vector dot(Vector rhs) { return times(rhs).plus(rhs.times(this)).times(0.5); } public Vector unaryMinus() { return times(-1.0); } public Vector plus(Vector rhs) { double[] result = Arrays.copyOf(dims, 32); for (int i = 0; i < rhs.dims.length; ++i) { result[i] += rhs.get(i); } return new Vector(result); } public Vector times(Vector rhs) { double[] result = new double[32]; for (int i = 0; i < dims.length; ++i) { if (dims[i] != 0.0) { for (int j = 0; j < rhs.dims.length; ++j) { if (rhs.get(j) != 0.0) { double s = reorderingSign(i, j) * dims[i] * rhs.dims[j]; int k = i ^ j; result[k] += s; } } } } return new Vector(result); } public Vector times(double scale) { double[] result = dims.clone(); for (int i = 0; i < 5; ++i) { dims[i] *= scale; } return new Vector(result); } double get(int index) { return dims[index]; } void set(int index, double value) { dims[index] = value; } @Override public String toString() { StringBuilder sb = new StringBuilder("("); boolean first = true; for (double value : dims) { if (first) { first = false; } else { sb.append(", "); } sb.append(value); } return sb.append(")").toString(); } } private static Vector e(int n) { if (n > 4) { throw new IllegalArgumentException("n must be less than 5"); } Vector result = new Vector(new double[32]); result.set(1 << n, 1.0); return result; } private static final Random rand = new Random(); private static Vector randomVector() { Vector result = new Vector(new double[32]); for (int i = 0; i < 5; ++i) { Vector temp = new Vector(new double[]{rand.nextDouble()}); result = result.plus(temp.times(e(i))); } return result; } private static Vector randomMultiVector() { Vector result = new Vector(new double[32]); for (int i = 0; i < 32; ++i) { result.set(i, rand.nextDouble()); } return result; } public static void main(String[] args) { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { if (i < j) { if (e(i).dot(e(j)).get(0) != 0.0) { System.out.println("Unexpected non-null scalar product."); return; } } } } Vector a = randomMultiVector(); Vector b = randomMultiVector(); Vector c = randomMultiVector(); Vector x = randomVector(); System.out.println(a.times(b).times(c)); System.out.println(a.times(b.times(c))); System.out.println(); System.out.println(a.times(b.plus(c))); System.out.println(a.times(b).plus(a.times(c))); System.out.println(); System.out.println(a.plus(b).times(c)); System.out.println(a.times(c).plus(b.times(c))); System.out.println(); System.out.println(x.times(x)); } }
package main import ( "fmt" "math/rand" "time" ) type vector []float64 func e(n uint) vector { if n > 4 { panic("n must be less than 5") } result := make(vector, 32) result[1<<n] = 1.0 return result } func cdot(a, b vector) vector { return mul(vector{0.5}, add(mul(a, b), mul(b, a))) } func neg(x vector) vector { return mul(vector{-1}, x) } func bitCount(i int) int { i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) i = (i + (i >> 4)) & 0x0F0F0F0F i = i + (i >> 8) i = i + (i >> 16) return i & 0x0000003F } func reorderingSign(i, j int) float64 { i >>= 1 sum := 0 for i != 0 { sum += bitCount(i & j) i >>= 1 } cond := (sum & 1) == 0 if cond { return 1.0 } return -1.0 } func add(a, b vector) vector { result := make(vector, 32) copy(result, a) for i, _ := range b { result[i] += b[i] } return result } func mul(a, b vector) vector { result := make(vector, 32) for i, _ := range a { if a[i] != 0 { for j, _ := range b { if b[j] != 0 { s := reorderingSign(i, j) * a[i] * b[j] k := i ^ j result[k] += s } } } } return result } func randomVector() vector { result := make(vector, 32) for i := uint(0); i < 5; i++ { result = add(result, mul(vector{rand.Float64()}, e(i))) } return result } func randomMultiVector() vector { result := make(vector, 32) for i := 0; i < 32; i++ { result[i] = rand.Float64() } return result } func main() { rand.Seed(time.Now().UnixNano()) for i := uint(0); i < 5; i++ { for j := uint(0); j < 5; j++ { if i < j { if cdot(e(i), e(j))[0] != 0 { fmt.Println("Unexpected non-null scalar product.") return } } else if i == j { if cdot(e(i), e(j))[0] == 0 { fmt.Println("Unexpected null scalar product.") } } } } a := randomMultiVector() b := randomMultiVector() c := randomMultiVector() x := randomVector() fmt.Println(mul(mul(a, b), c)) fmt.Println(mul(a, mul(b, c))) fmt.Println(mul(a, add(b, c))) fmt.Println(add(mul(a, b), mul(a, c))) fmt.Println(mul(add(a, b), c)) fmt.Println(add(mul(a, c), mul(b, c))) fmt.Println(mul(x, x)) }
Write the same algorithm in Go as shown in this Java implementation.
import java.util.ArrayList; import java.util.List; public class SuffixTreeProblem { private static class Node { String sub = ""; List<Integer> ch = new ArrayList<>(); } private static class SuffixTree { private List<Node> nodes = new ArrayList<>(); public SuffixTree(String str) { nodes.add(new Node()); for (int i = 0; i < str.length(); ++i) { addSuffix(str.substring(i)); } } private void addSuffix(String suf) { int n = 0; int i = 0; while (i < suf.length()) { char b = suf.charAt(i); List<Integer> children = nodes.get(n).ch; int x2 = 0; int n2; while (true) { if (x2 == children.size()) { n2 = nodes.size(); Node temp = new Node(); temp.sub = suf.substring(i); nodes.add(temp); children.add(n2); return; } n2 = children.get(x2); if (nodes.get(n2).sub.charAt(0) == b) break; x2++; } String sub2 = nodes.get(n2).sub; int j = 0; while (j < sub2.length()) { if (suf.charAt(i + j) != sub2.charAt(j)) { int n3 = n2; n2 = nodes.size(); Node temp = new Node(); temp.sub = sub2.substring(0, j); temp.ch.add(n3); nodes.add(temp); nodes.get(n3).sub = sub2.substring(j); nodes.get(n).ch.set(x2, n2); break; } j++; } i += j; n = n2; } } public void visualize() { if (nodes.isEmpty()) { System.out.println("<empty>"); return; } visualize_f(0, ""); } private void visualize_f(int n, String pre) { List<Integer> children = nodes.get(n).ch; if (children.isEmpty()) { System.out.println("- " + nodes.get(n).sub); return; } System.out.println("┐ " + nodes.get(n).sub); for (int i = 0; i < children.size() - 1; i++) { Integer c = children.get(i); System.out.print(pre + "├─"); visualize_f(c, pre + "│ "); } System.out.print(pre + "└─"); visualize_f(children.get(children.size() - 1), pre + " "); } } public static void main(String[] args) { new SuffixTree("banana$").visualize(); } }
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree { n := 0 for i := 0; i < len(suf); { b := suf[i] ch := t[n].ch var x2, n2 int for ; ; x2++ { if x2 == len(ch) { n2 = len(t) t = append(t, node{sub: suf[i:]}) t[n].ch = append(t[n].ch, n2) return t } n2 = ch[x2] if t[n2].sub[0] == b { break } } sub2 := t[n2].sub j := 0 for ; j < len(sub2); j++ { if suf[i+j] != sub2[j] { n3 := n2 n2 = len(t) t = append(t, node{sub2[:j], []int{n3}}) t[n3].sub = sub2[j:] t[n].ch[x2] = n2 break } } i += j n = n2 } return t } func vis(t tree) { if len(t) == 0 { fmt.Println("<empty>") return } var f func(int, string) f = func(n int, pre string) { children := t[n].ch if len(children) == 0 { fmt.Println("╴", t[n].sub) return } fmt.Println("┐", t[n].sub) last := len(children) - 1 for _, ch := range children[:last] { fmt.Print(pre, "├─") f(ch, pre+"│ ") } fmt.Print(pre, "└─") f(children[last], pre+" ") } f(0, "") }
Change the following Java code into Go without altering its purpose.
import java.util.ArrayList; import java.util.List; public class SuffixTreeProblem { private static class Node { String sub = ""; List<Integer> ch = new ArrayList<>(); } private static class SuffixTree { private List<Node> nodes = new ArrayList<>(); public SuffixTree(String str) { nodes.add(new Node()); for (int i = 0; i < str.length(); ++i) { addSuffix(str.substring(i)); } } private void addSuffix(String suf) { int n = 0; int i = 0; while (i < suf.length()) { char b = suf.charAt(i); List<Integer> children = nodes.get(n).ch; int x2 = 0; int n2; while (true) { if (x2 == children.size()) { n2 = nodes.size(); Node temp = new Node(); temp.sub = suf.substring(i); nodes.add(temp); children.add(n2); return; } n2 = children.get(x2); if (nodes.get(n2).sub.charAt(0) == b) break; x2++; } String sub2 = nodes.get(n2).sub; int j = 0; while (j < sub2.length()) { if (suf.charAt(i + j) != sub2.charAt(j)) { int n3 = n2; n2 = nodes.size(); Node temp = new Node(); temp.sub = sub2.substring(0, j); temp.ch.add(n3); nodes.add(temp); nodes.get(n3).sub = sub2.substring(j); nodes.get(n).ch.set(x2, n2); break; } j++; } i += j; n = n2; } } public void visualize() { if (nodes.isEmpty()) { System.out.println("<empty>"); return; } visualize_f(0, ""); } private void visualize_f(int n, String pre) { List<Integer> children = nodes.get(n).ch; if (children.isEmpty()) { System.out.println("- " + nodes.get(n).sub); return; } System.out.println("┐ " + nodes.get(n).sub); for (int i = 0; i < children.size() - 1; i++) { Integer c = children.get(i); System.out.print(pre + "├─"); visualize_f(c, pre + "│ "); } System.out.print(pre + "└─"); visualize_f(children.get(children.size() - 1), pre + " "); } } public static void main(String[] args) { new SuffixTree("banana$").visualize(); } }
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree { n := 0 for i := 0; i < len(suf); { b := suf[i] ch := t[n].ch var x2, n2 int for ; ; x2++ { if x2 == len(ch) { n2 = len(t) t = append(t, node{sub: suf[i:]}) t[n].ch = append(t[n].ch, n2) return t } n2 = ch[x2] if t[n2].sub[0] == b { break } } sub2 := t[n2].sub j := 0 for ; j < len(sub2); j++ { if suf[i+j] != sub2[j] { n3 := n2 n2 = len(t) t = append(t, node{sub2[:j], []int{n3}}) t[n3].sub = sub2[j:] t[n].ch[x2] = n2 break } } i += j n = n2 } return t } func vis(t tree) { if len(t) == 0 { fmt.Println("<empty>") return } var f func(int, string) f = func(n int, pre string) { children := t[n].ch if len(children) == 0 { fmt.Println("╴", t[n].sub) return } fmt.Println("┐", t[n].sub) last := len(children) - 1 for _, ch := range children[:last] { fmt.Print(pre, "├─") f(ch, pre+"│ ") } fmt.Print(pre, "└─") f(children[last], pre+" ") } f(0, "") }
Port the provided Java code into Go while preserving the original functionality.
Map<String, Integer> map = new HashMap<String, Integer>(); map.put("hello", 1); map.put("world", 2); map.put("!", 3); for (Map.Entry<String, Integer> e : map.entrySet()) { String key = e.getKey(); Integer value = e.getValue(); System.out.println("key = " + key + ", value = " + value); } for (String key : map.keySet()) { System.out.println("key = " + key); } for (Integer value : map.values()) { System.out.println("value = " + value); }
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
Translate the given Java code snippet into Go without altering its behavior.
class BoundedIntOutOfBoundsException extends Exception { public BoundedIntOutOfBoundsException(int v, int l, int u) { super("value " + v + " is out of bounds [" + l + "," + u + "]"); } } class BoundedInt { private int value; private int lower; private int upper; public BoundedInt(int l, int u) { lower = Math.min(l, u); upper = Math.max(l, u); } private boolean checkBounds(int v) { return (v >= this.lower) && (v <= this.upper); } public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{ assign(i.value()); } public void assign(int v) throws BoundedIntOutOfBoundsException { if ( checkBounds(v) ) { this.value = v; } else { throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper); } } public int add(BoundedInt i) throws BoundedIntOutOfBoundsException { return add(i.value()); } public int add(int i) throws BoundedIntOutOfBoundsException { if ( checkBounds(this.value + i) ) { this.value += i; } else { throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper); } return this.value; } public int value() { return this.value; } } public class Bounded { public static void main(String[] args) throws BoundedIntOutOfBoundsException { BoundedInt a = new BoundedInt(1, 10); BoundedInt b = new BoundedInt(1, 10); a.assign(6); try { b.assign(12); } catch (Exception e) { System.out.println(e.getMessage()); } b.assign(9); try { a.add(b.value()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
package main import "fmt" type TinyInt int func NewTinyInt(i int) TinyInt { if i < 1 { i = 1 } else if i > 10 { i = 10 } return TinyInt(i) } func (t1 TinyInt) Add(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) + int(t2)) } func (t1 TinyInt) Sub(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) - int(t2)) } func (t1 TinyInt) Mul(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) * int(t2)) } func (t1 TinyInt) Div(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) / int(t2)) } func (t1 TinyInt) Rem(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) % int(t2)) } func (t TinyInt) Inc() TinyInt { return t.Add(TinyInt(1)) } func (t TinyInt) Dec() TinyInt { return t.Sub(TinyInt(1)) } func main() { t1 := NewTinyInt(6) t2 := NewTinyInt(3) fmt.Println("t1 =", t1) fmt.Println("t2 =", t2) fmt.Println("t1 + t2 =", t1.Add(t2)) fmt.Println("t1 - t2 =", t1.Sub(t2)) fmt.Println("t1 * t2 =", t1.Mul(t2)) fmt.Println("t1 / t2 =", t1.Div(t2)) fmt.Println("t1 % t2 =", t1.Rem(t2)) fmt.Println("t1 + 1 =", t1.Inc()) fmt.Println("t1 - 1 =", t1.Dec()) }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
class BoundedIntOutOfBoundsException extends Exception { public BoundedIntOutOfBoundsException(int v, int l, int u) { super("value " + v + " is out of bounds [" + l + "," + u + "]"); } } class BoundedInt { private int value; private int lower; private int upper; public BoundedInt(int l, int u) { lower = Math.min(l, u); upper = Math.max(l, u); } private boolean checkBounds(int v) { return (v >= this.lower) && (v <= this.upper); } public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{ assign(i.value()); } public void assign(int v) throws BoundedIntOutOfBoundsException { if ( checkBounds(v) ) { this.value = v; } else { throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper); } } public int add(BoundedInt i) throws BoundedIntOutOfBoundsException { return add(i.value()); } public int add(int i) throws BoundedIntOutOfBoundsException { if ( checkBounds(this.value + i) ) { this.value += i; } else { throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper); } return this.value; } public int value() { return this.value; } } public class Bounded { public static void main(String[] args) throws BoundedIntOutOfBoundsException { BoundedInt a = new BoundedInt(1, 10); BoundedInt b = new BoundedInt(1, 10); a.assign(6); try { b.assign(12); } catch (Exception e) { System.out.println(e.getMessage()); } b.assign(9); try { a.add(b.value()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
package main import "fmt" type TinyInt int func NewTinyInt(i int) TinyInt { if i < 1 { i = 1 } else if i > 10 { i = 10 } return TinyInt(i) } func (t1 TinyInt) Add(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) + int(t2)) } func (t1 TinyInt) Sub(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) - int(t2)) } func (t1 TinyInt) Mul(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) * int(t2)) } func (t1 TinyInt) Div(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) / int(t2)) } func (t1 TinyInt) Rem(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) % int(t2)) } func (t TinyInt) Inc() TinyInt { return t.Add(TinyInt(1)) } func (t TinyInt) Dec() TinyInt { return t.Sub(TinyInt(1)) } func main() { t1 := NewTinyInt(6) t2 := NewTinyInt(3) fmt.Println("t1 =", t1) fmt.Println("t2 =", t2) fmt.Println("t1 + t2 =", t1.Add(t2)) fmt.Println("t1 - t2 =", t1.Sub(t2)) fmt.Println("t1 * t2 =", t1.Mul(t2)) fmt.Println("t1 / t2 =", t1.Div(t2)) fmt.Println("t1 % t2 =", t1.Rem(t2)) fmt.Println("t1 + 1 =", t1.Inc()) fmt.Println("t1 - 1 =", t1.Dec()) }
Keep all operations the same but rewrite the snippet in Go.
public class AVLtree { private Node root; private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent; Node(int key, Node parent) { this.key = key; this.parent = parent; } } public boolean insert(int key) { if (root == null) { root = new Node(key, null); return true; } Node n = root; while (true) { if (n.key == key) return false; Node parent = n; boolean goLeft = n.key > key; n = goLeft ? n.left : n.right; if (n == null) { if (goLeft) { parent.left = new Node(key, parent); } else { parent.right = new Node(key, parent); } rebalance(parent); break; } } return true; } private void delete(Node node) { if (node.left == null && node.right == null) { if (node.parent == null) { root = null; } else { Node parent = node.parent; if (parent.left == node) { parent.left = null; } else { parent.right = null; } rebalance(parent); } return; } if (node.left != null) { Node child = node.left; while (child.right != null) child = child.right; node.key = child.key; delete(child); } else { Node child = node.right; while (child.left != null) child = child.left; node.key = child.key; delete(child); } } public void delete(int delKey) { if (root == null) return; Node child = root; while (child != null) { Node node = child; child = delKey >= node.key ? node.right : node.left; if (delKey == node.key) { delete(node); return; } } } private void rebalance(Node n) { setBalance(n); if (n.balance == -2) { if (height(n.left.left) >= height(n.left.right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n.balance == 2) { if (height(n.right.right) >= height(n.right.left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); } if (n.parent != null) { rebalance(n.parent); } else { root = n; } } private Node rotateLeft(Node a) { Node b = a.right; b.parent = a.parent; a.right = b.left; if (a.right != null) a.right.parent = a; b.left = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateRight(Node a) { Node b = a.left; b.parent = a.parent; a.left = b.right; if (a.left != null) a.left.parent = a; b.right = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateLeftThenRight(Node n) { n.left = rotateLeft(n.left); return rotateRight(n); } private Node rotateRightThenLeft(Node n) { n.right = rotateRight(n.right); return rotateLeft(n); } private int height(Node n) { if (n == null) return -1; return n.height; } private void setBalance(Node... nodes) { for (Node n : nodes) { reheight(n); n.balance = height(n.right) - height(n.left); } } public void printBalance() { printBalance(root); } private void printBalance(Node n) { if (n != null) { printBalance(n.left); System.out.printf("%s ", n.balance); printBalance(n.right); } } private void reheight(Node node) { if (node != null) { node.height = 1 + Math.max(height(node.left), height(node.right)); } } public static void main(String[] args) { AVLtree tree = new AVLtree(); System.out.println("Inserting values 1 to 10"); for (int i = 1; i < 10; i++) tree.insert(i); System.out.print("Printing balance: "); tree.printBalance(); } }
package avl type Key interface { Less(Key) bool Eq(Key) bool } type Node struct { Data Key Balance int Link [2]*Node } func opp(dir int) int { return 1 - dir } func single(root *Node, dir int) *Node { save := root.Link[opp(dir)] root.Link[opp(dir)] = save.Link[dir] save.Link[dir] = root return save } func double(root *Node, dir int) *Node { save := root.Link[opp(dir)].Link[dir] root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)] save.Link[opp(dir)] = root.Link[opp(dir)] root.Link[opp(dir)] = save save = root.Link[opp(dir)] root.Link[opp(dir)] = save.Link[dir] save.Link[dir] = root return save } func adjustBalance(root *Node, dir, bal int) { n := root.Link[dir] nn := n.Link[opp(dir)] switch nn.Balance { case 0: root.Balance = 0 n.Balance = 0 case bal: root.Balance = -bal n.Balance = 0 default: root.Balance = 0 n.Balance = bal } nn.Balance = 0 } func insertBalance(root *Node, dir int) *Node { n := root.Link[dir] bal := 2*dir - 1 if n.Balance == bal { root.Balance = 0 n.Balance = 0 return single(root, opp(dir)) } adjustBalance(root, dir, bal) return double(root, opp(dir)) } func insertR(root *Node, data Key) (*Node, bool) { if root == nil { return &Node{Data: data}, false } dir := 0 if root.Data.Less(data) { dir = 1 } var done bool root.Link[dir], done = insertR(root.Link[dir], data) if done { return root, true } root.Balance += 2*dir - 1 switch root.Balance { case 0: return root, true case 1, -1: return root, false } return insertBalance(root, dir), true } func Insert(tree **Node, data Key) { *tree, _ = insertR(*tree, data) } func removeBalance(root *Node, dir int) (*Node, bool) { n := root.Link[opp(dir)] bal := 2*dir - 1 switch n.Balance { case -bal: root.Balance = 0 n.Balance = 0 return single(root, dir), false case bal: adjustBalance(root, opp(dir), -bal) return double(root, dir), false } root.Balance = -bal n.Balance = bal return single(root, dir), true } func removeR(root *Node, data Key) (*Node, bool) { if root == nil { return nil, false } if root.Data.Eq(data) { switch { case root.Link[0] == nil: return root.Link[1], false case root.Link[1] == nil: return root.Link[0], false } heir := root.Link[0] for heir.Link[1] != nil { heir = heir.Link[1] } root.Data = heir.Data data = heir.Data } dir := 0 if root.Data.Less(data) { dir = 1 } var done bool root.Link[dir], done = removeR(root.Link[dir], data) if done { return root, true } root.Balance += 1 - 2*dir switch root.Balance { case 1, -1: return root, true case 0: return root, false } return removeBalance(root, dir) } func Remove(tree **Node, data Key) { *tree, _ = removeR(*tree, data) }
Rewrite the snippet below in Go so it works the same as the original Java code.
public class AVLtree { private Node root; private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent; Node(int key, Node parent) { this.key = key; this.parent = parent; } } public boolean insert(int key) { if (root == null) { root = new Node(key, null); return true; } Node n = root; while (true) { if (n.key == key) return false; Node parent = n; boolean goLeft = n.key > key; n = goLeft ? n.left : n.right; if (n == null) { if (goLeft) { parent.left = new Node(key, parent); } else { parent.right = new Node(key, parent); } rebalance(parent); break; } } return true; } private void delete(Node node) { if (node.left == null && node.right == null) { if (node.parent == null) { root = null; } else { Node parent = node.parent; if (parent.left == node) { parent.left = null; } else { parent.right = null; } rebalance(parent); } return; } if (node.left != null) { Node child = node.left; while (child.right != null) child = child.right; node.key = child.key; delete(child); } else { Node child = node.right; while (child.left != null) child = child.left; node.key = child.key; delete(child); } } public void delete(int delKey) { if (root == null) return; Node child = root; while (child != null) { Node node = child; child = delKey >= node.key ? node.right : node.left; if (delKey == node.key) { delete(node); return; } } } private void rebalance(Node n) { setBalance(n); if (n.balance == -2) { if (height(n.left.left) >= height(n.left.right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n.balance == 2) { if (height(n.right.right) >= height(n.right.left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); } if (n.parent != null) { rebalance(n.parent); } else { root = n; } } private Node rotateLeft(Node a) { Node b = a.right; b.parent = a.parent; a.right = b.left; if (a.right != null) a.right.parent = a; b.left = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateRight(Node a) { Node b = a.left; b.parent = a.parent; a.left = b.right; if (a.left != null) a.left.parent = a; b.right = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateLeftThenRight(Node n) { n.left = rotateLeft(n.left); return rotateRight(n); } private Node rotateRightThenLeft(Node n) { n.right = rotateRight(n.right); return rotateLeft(n); } private int height(Node n) { if (n == null) return -1; return n.height; } private void setBalance(Node... nodes) { for (Node n : nodes) { reheight(n); n.balance = height(n.right) - height(n.left); } } public void printBalance() { printBalance(root); } private void printBalance(Node n) { if (n != null) { printBalance(n.left); System.out.printf("%s ", n.balance); printBalance(n.right); } } private void reheight(Node node) { if (node != null) { node.height = 1 + Math.max(height(node.left), height(node.right)); } } public static void main(String[] args) { AVLtree tree = new AVLtree(); System.out.println("Inserting values 1 to 10"); for (int i = 1; i < 10; i++) tree.insert(i); System.out.print("Printing balance: "); tree.printBalance(); } }
package avl type Key interface { Less(Key) bool Eq(Key) bool } type Node struct { Data Key Balance int Link [2]*Node } func opp(dir int) int { return 1 - dir } func single(root *Node, dir int) *Node { save := root.Link[opp(dir)] root.Link[opp(dir)] = save.Link[dir] save.Link[dir] = root return save } func double(root *Node, dir int) *Node { save := root.Link[opp(dir)].Link[dir] root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)] save.Link[opp(dir)] = root.Link[opp(dir)] root.Link[opp(dir)] = save save = root.Link[opp(dir)] root.Link[opp(dir)] = save.Link[dir] save.Link[dir] = root return save } func adjustBalance(root *Node, dir, bal int) { n := root.Link[dir] nn := n.Link[opp(dir)] switch nn.Balance { case 0: root.Balance = 0 n.Balance = 0 case bal: root.Balance = -bal n.Balance = 0 default: root.Balance = 0 n.Balance = bal } nn.Balance = 0 } func insertBalance(root *Node, dir int) *Node { n := root.Link[dir] bal := 2*dir - 1 if n.Balance == bal { root.Balance = 0 n.Balance = 0 return single(root, opp(dir)) } adjustBalance(root, dir, bal) return double(root, opp(dir)) } func insertR(root *Node, data Key) (*Node, bool) { if root == nil { return &Node{Data: data}, false } dir := 0 if root.Data.Less(data) { dir = 1 } var done bool root.Link[dir], done = insertR(root.Link[dir], data) if done { return root, true } root.Balance += 2*dir - 1 switch root.Balance { case 0: return root, true case 1, -1: return root, false } return insertBalance(root, dir), true } func Insert(tree **Node, data Key) { *tree, _ = insertR(*tree, data) } func removeBalance(root *Node, dir int) (*Node, bool) { n := root.Link[opp(dir)] bal := 2*dir - 1 switch n.Balance { case -bal: root.Balance = 0 n.Balance = 0 return single(root, dir), false case bal: adjustBalance(root, opp(dir), -bal) return double(root, dir), false } root.Balance = -bal n.Balance = bal return single(root, dir), true } func removeR(root *Node, data Key) (*Node, bool) { if root == nil { return nil, false } if root.Data.Eq(data) { switch { case root.Link[0] == nil: return root.Link[1], false case root.Link[1] == nil: return root.Link[0], false } heir := root.Link[0] for heir.Link[1] != nil { heir = heir.Link[1] } root.Data = heir.Data data = heir.Data } dir := 0 if root.Data.Less(data) { dir = 1 } var done bool root.Link[dir], done = removeR(root.Link[dir], data) if done { return root, true } root.Balance += 1 - 2*dir switch root.Balance { case 1, -1: return root, true case 0: return root, false } return removeBalance(root, dir) } func Remove(tree **Node, data Key) { *tree, _ = removeR(*tree, data) }
Generate an equivalent Go version of this Java code.
import java.awt.*; import java.util.List; import java.awt.geom.Path2D; import java.util.*; import javax.swing.*; import static java.lang.Math.*; import static java.util.stream.Collectors.toList; public class PenroseTiling extends JPanel { class Tile { double x, y, angle, size; Type type; Tile(Type t, double x, double y, double a, double s) { type = t; this.x = x; this.y = y; angle = a; size = s; } @Override public boolean equals(Object o) { if (o instanceof Tile) { Tile t = (Tile) o; return type == t.type && x == t.x && y == t.y && angle == t.angle; } return false; } } enum Type { Kite, Dart } static final double G = (1 + sqrt(5)) / 2; static final double T = toRadians(36); List<Tile> tiles = new ArrayList<>(); public PenroseTiling() { int w = 700, h = 450; setPreferredSize(new Dimension(w, h)); setBackground(Color.white); tiles = deflateTiles(setupPrototiles(w, h), 5); } List<Tile> setupPrototiles(int w, int h) { List<Tile> proto = new ArrayList<>(); for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T) proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5)); return proto; } List<Tile> deflateTiles(List<Tile> tls, int generation) { if (generation <= 0) return tls; List<Tile> next = new ArrayList<>(); for (Tile tile : tls) { double x = tile.x, y = tile.y, a = tile.angle, nx, ny; double size = tile.size / G; if (tile.type == Type.Dart) { next.add(new Tile(Type.Kite, x, y, a + 5 * T, size)); for (int i = 0, sign = 1; i < 2; i++, sign *= -1) { nx = x + cos(a - 4 * T * sign) * G * tile.size; ny = y - sin(a - 4 * T * sign) * G * tile.size; next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size)); } } else { for (int i = 0, sign = 1; i < 2; i++, sign *= -1) { next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size)); nx = x + cos(a - T * sign) * G * tile.size; ny = y - sin(a - T * sign) * G * tile.size; next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size)); } } } tls = next.stream().distinct().collect(toList()); return deflateTiles(tls, generation - 1); } void drawTiles(Graphics2D g) { double[][] dist = {{G, G, G}, {-G, -1, -G}}; for (Tile tile : tiles) { double angle = tile.angle - T; Path2D path = new Path2D.Double(); path.moveTo(tile.x, tile.y); int ord = tile.type.ordinal(); for (int i = 0; i < 3; i++) { double x = tile.x + dist[ord][i] * tile.size * cos(angle); double y = tile.y - dist[ord][i] * tile.size * sin(angle); path.lineTo(x, y); angle += T; } path.closePath(); g.setColor(ord == 0 ? Color.orange : Color.yellow); g.fill(path); g.setColor(Color.darkGray); g.draw(path); } } @Override public void paintComponent(Graphics og) { super.paintComponent(og); Graphics2D g = (Graphics2D) og; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawTiles(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Penrose Tiling"); f.setResizable(false); f.add(new PenroseTiling(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package main import ( "github.com/fogleman/gg" "math" ) type tiletype int const ( kite tiletype = iota dart ) type tile struct { tt tiletype x, y float64 angle, size float64 } var gr = (1 + math.Sqrt(5)) / 2 const theta = math.Pi / 5 func setupPrototiles(w, h int) []tile { var proto []tile for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta { ww := float64(w / 2) hh := float64(h / 2) proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5}) } return proto } func distinctTiles(tls []tile) []tile { tileset := make(map[tile]bool) for _, tl := range tls { tileset[tl] = true } distinct := make([]tile, len(tileset)) for tl, _ := range tileset { distinct = append(distinct, tl) } return distinct } func deflateTiles(tls []tile, gen int) []tile { if gen <= 0 { return tls } var next []tile for _, tl := range tls { x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr var nx, ny float64 if tl.tt == dart { next = append(next, tile{kite, x, y, a + 5*theta, size}) for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign { nx = x + math.Cos(a-4*theta*sign)*gr*tl.size ny = y - math.Sin(a-4*theta*sign)*gr*tl.size next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size}) } } else { for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign { next = append(next, tile{dart, x, y, a - 4*theta*sign, size}) nx = x + math.Cos(a-theta*sign)*gr*tl.size ny = y - math.Sin(a-theta*sign)*gr*tl.size next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size}) } } } tls = distinctTiles(next) return deflateTiles(tls, gen-1) } func drawTiles(dc *gg.Context, tls []tile) { dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}} for _, tl := range tls { angle := tl.angle - theta dc.MoveTo(tl.x, tl.y) ord := tl.tt for i := 0; i < 3; i++ { x := tl.x + dist[ord][i]*tl.size*math.Cos(angle) y := tl.y - dist[ord][i]*tl.size*math.Sin(angle) dc.LineTo(x, y) angle += theta } dc.ClosePath() if ord == kite { dc.SetHexColor("FFA500") } else { dc.SetHexColor("FFFF00") } dc.FillPreserve() dc.SetHexColor("A9A9A9") dc.SetLineWidth(1) dc.Stroke() } } func main() { w, h := 700, 450 dc := gg.NewContext(w, h) dc.SetRGB(1, 1, 1) dc.Clear() tiles := deflateTiles(setupPrototiles(w, h), 5) drawTiles(dc, tiles) dc.SavePNG("penrose_tiling.png") }
Preserve the algorithm and functionality while converting the code from Java to Go.
import java.util.Arrays; import java.util.ArrayList; import java.util.List; public class SphenicNumbers { public static void main(String[] args) { final int limit = 1000000; final int imax = limit / 6; boolean[] sieve = primeSieve(imax + 1); boolean[] sphenic = new boolean[limit + 1]; for (int i = 0; i <= imax; ++i) { if (!sieve[i]) continue; int jmax = Math.min(imax, limit / (i * i)); if (jmax <= i) break; for (int j = i + 1; j <= jmax; ++j) { if (!sieve[j]) continue; int p = i * j; int kmax = Math.min(imax, limit / p); if (kmax <= j) break; for (int k = j + 1; k <= kmax; ++k) { if (!sieve[k]) continue; assert(p * k <= limit); sphenic[p * k] = true; } } } System.out.println("Sphenic numbers < 1000:"); for (int i = 0, n = 0; i < 1000; ++i) { if (!sphenic[i]) continue; ++n; System.out.printf("%3d%c", i, n % 15 == 0 ? '\n' : ' '); } System.out.println("\nSphenic triplets < 10,000:"); for (int i = 0, n = 0; i < 10000; ++i) { if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) { ++n; System.out.printf("(%d, %d, %d)%c", i - 2, i - 1, i, n % 3 == 0 ? '\n' : ' '); } } int count = 0, triplets = 0, s200000 = 0, t5000 = 0; for (int i = 0; i < limit; ++i) { if (!sphenic[i]) continue; ++count; if (count == 200000) s200000 = i; if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) { ++triplets; if (triplets == 5000) t5000 = i; } } System.out.printf("\nNumber of sphenic numbers < 1,000,000: %d\n", count); System.out.printf("Number of sphenic triplets < 1,000,000: %d\n", triplets); List<Integer> factors = primeFactors(s200000); assert(factors.size() == 3); System.out.printf("The 200,000th sphenic number: %d = %d * %d * %d\n", s200000, factors.get(0), factors.get(1), factors.get(2)); System.out.printf("The 5,000th sphenic triplet: (%d, %d, %d)\n", t5000 - 2, t5000 - 1, t5000); } private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3, sq = 9; sq < limit; p += 2) { if (sieve[p]) { for (int q = sq; q < limit; q += p << 1) sieve[q] = false; } sq += (p + 1) << 2; } return sieve; } private static List<Integer> primeFactors(int n) { List<Integer> factors = new ArrayList<>(); if (n > 1 && (n & 1) == 0) { factors.add(2); while ((n & 1) == 0) n >>= 1; } for (int p = 3; p * p <= n; p += 2) { if (n % p == 0) { factors.add(p); while (n % p == 0) n /= p; } } if (n > 1) factors.add(n); return factors; } }
package main import ( "fmt" "math" "rcu" "sort" ) func main() { const limit = 1000000 limit2 := int(math.Cbrt(limit)) primes := rcu.Primes(limit / 6) pc := len(primes) var sphenic []int fmt.Println("Sphenic numbers less than 1,000:") for i := 0; i < pc-2; i++ { if primes[i] > limit2 { break } for j := i + 1; j < pc-1; j++ { prod := primes[i] * primes[j] if prod+primes[j+1] >= limit { break } for k := j + 1; k < pc; k++ { res := prod * primes[k] if res >= limit { break } sphenic = append(sphenic, res) } } } sort.Ints(sphenic) ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 }) rcu.PrintTable(sphenic[:ix], 15, 3, false) fmt.Println("\nSphenic triplets less than 10,000:") var triplets [][3]int for i := 0; i < len(sphenic)-2; i++ { s := sphenic[i] if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 { triplets = append(triplets, [3]int{s, s + 1, s + 2}) } } ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 }) for i := 0; i < ix; i++ { fmt.Printf("%4d ", triplets[i]) if (i+1)%3 == 0 { fmt.Println() } } fmt.Printf("\nThere are %s sphenic numbers less than 1,000,000.\n", rcu.Commatize(len(sphenic))) fmt.Printf("There are %s sphenic triplets less than 1,000,000.\n", rcu.Commatize(len(triplets))) s := sphenic[199999] pf := rcu.PrimeFactors(s) fmt.Printf("The 200,000th sphenic number is %s (%d*%d*%d).\n", rcu.Commatize(s), pf[0], pf[1], pf[2]) fmt.Printf("The 5,000th sphenic triplet is %v.\n.", triplets[4999]) }
Please provide an equivalent version of this Java code in Go.
import java.io.*; import java.nio.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.security.*; import java.util.*; public class DuplicateFiles { public static void main(String[] args) { if (args.length != 2) { System.err.println("Directory name and minimum file size are required."); System.exit(1); } try { findDuplicateFiles(args[0], Long.parseLong(args[1])); } catch (Exception e) { e.printStackTrace(); } } private static void findDuplicateFiles(String directory, long minimumSize) throws IOException, NoSuchAlgorithmException { System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes."); Path path = FileSystems.getDefault().getPath(directory); FileVisitor visitor = new FileVisitor(path, minimumSize); Files.walkFileTree(path, visitor); System.out.println("The following sets of files have the same size and checksum:"); for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) { Map<Object, List<String>> map = e.getValue(); if (!containsDuplicates(map)) continue; List<List<String>> fileSets = new ArrayList<>(map.values()); for (List<String> files : fileSets) Collections.sort(files); Collections.sort(fileSets, new StringListComparator()); FileKey key = e.getKey(); System.out.println(); System.out.println("Size: " + key.size_ + " bytes"); for (List<String> files : fileSets) { for (int i = 0, n = files.size(); i < n; ++i) { if (i > 0) System.out.print(" = "); System.out.print(files.get(i)); } System.out.println(); } } } private static class StringListComparator implements Comparator<List<String>> { public int compare(List<String> a, List<String> b) { int len1 = a.size(), len2 = b.size(); for (int i = 0; i < len1 && i < len2; ++i) { int c = a.get(i).compareTo(b.get(i)); if (c != 0) return c; } return Integer.compare(len1, len2); } } private static boolean containsDuplicates(Map<Object, List<String>> map) { if (map.size() > 1) return true; for (List<String> files : map.values()) { if (files.size() > 1) return true; } return false; } private static class FileVisitor extends SimpleFileVisitor<Path> { private MessageDigest digest_; private Path directory_; private long minimumSize_; private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>(); private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException { directory_ = directory; minimumSize_ = minimumSize; digest_ = MessageDigest.getInstance("MD5"); } public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.size() >= minimumSize_) { FileKey key = new FileKey(file, attrs, getMD5Sum(file)); Map<Object, List<String>> map = fileMap_.get(key); if (map == null) fileMap_.put(key, map = new HashMap<>()); List<String> files = map.get(attrs.fileKey()); if (files == null) map.put(attrs.fileKey(), files = new ArrayList<>()); Path relative = directory_.relativize(file); files.add(relative.toString()); } return FileVisitResult.CONTINUE; } private byte[] getMD5Sum(Path file) throws IOException { digest_.reset(); try (InputStream in = new FileInputStream(file.toString())) { byte[] buffer = new byte[8192]; int bytes; while ((bytes = in.read(buffer)) != -1) { digest_.update(buffer, 0, bytes); } } return digest_.digest(); } } private static class FileKey implements Comparable<FileKey> { private byte[] hash_; private long size_; private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException { size_ = attrs.size(); hash_ = hash; } public int compareTo(FileKey other) { int c = Long.compare(other.size_, size_); if (c == 0) c = hashCompare(hash_, other.hash_); return c; } } private static int hashCompare(byte[] a, byte[] b) { int len1 = a.length, len2 = b.length; for (int i = 0; i < len1 && i < len2; ++i) { int c = Byte.compare(a[i], b[i]); if (c != 0) return c; } return Integer.compare(len1, len2); } }
package main import ( "fmt" "crypto/md5" "io/ioutil" "log" "os" "path/filepath" "sort" "time" ) type fileData struct { filePath string info os.FileInfo } type hash [16]byte func check(err error) { if err != nil { log.Fatal(err) } } func checksum(filePath string) hash { bytes, err := ioutil.ReadFile(filePath) check(err) return hash(md5.Sum(bytes)) } func findDuplicates(dirPath string, minSize int64) [][2]fileData { var dups [][2]fileData m := make(map[hash]fileData) werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && info.Size() >= minSize { h := checksum(path) fd, ok := m[h] fd2 := fileData{path, info} if !ok { m[h] = fd2 } else { dups = append(dups, [2]fileData{fd, fd2}) } } return nil }) check(werr) return dups } func main() { dups := findDuplicates(".", 1) fmt.Println("The following pairs of files have the same size and the same hash:\n") fmt.Println("File name Size Date last modified") fmt.Println("==========================================================") sort.Slice(dups, func(i, j int) bool { return dups[i][0].info.Size() > dups[j][0].info.Size() }) for _, dup := range dups { for i := 0; i < 2; i++ { d := dup[i] fmt.Printf("%-20s %8d %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC)) } fmt.Println() } }
Generate a Go translation of this Java snippet without changing its computational steps.
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; private final static int base = 12; private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; private static int[][] grid; private static int total = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } private static boolean solve(int r, int c, int count) { if (count == total) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != total) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Ensure the translated Go code behaves exactly like the original Java snippet.
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; private final static int base = 12; private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; private static int[][] grid; private static int total = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } private static boolean solve(int r, int c, int count) { if (count == total) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != total) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Write the same algorithm in Go as shown in this Java implementation.
import java.util.Arrays; import java.util.BitSet; import org.apache.commons.lang3.ArrayUtils; public class OrderDisjointItems { public static void main(String[] args) { final String[][] MNs = {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}}; for (String[] a : MNs) { String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" ")); System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r)); } } static String[] orderDisjointItems(String[] m, String[] n) { for (String e : n) { int idx = ArrayUtils.indexOf(m, e); if (idx != -1) m[idx] = null; } for (int i = 0, j = 0; i < m.length; i++) { if (m[i] == null) m[i] = n[j++]; } return m; } static String[] orderDisjointItems2(String[] m, String[] n) { BitSet bitSet = new BitSet(m.length); for (String e : n) { int idx = -1; do { idx = ArrayUtils.indexOf(m, e, idx + 1); } while (idx != -1 && bitSet.get(idx)); if (idx != -1) bitSet.set(idx); } for (int i = 0, j = 0; i < m.length; i++) { if (bitSet.get(i)) m[i] = n[j++]; } return m; } }
package main import ( "fmt" "sort" "strings" ) type indexSort struct { val sort.Interface ind []int } func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], s.ind[j] = s.ind[j], s.ind[i] } func disjointSliceSort(m, n []string) []string { s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))} used := make(map[int]bool) for _, nw := range n { for i, mw := range m { if used[i] || mw != nw { continue } used[i] = true s.ind = append(s.ind, i) break } } sort.Sort(s) return s.val.(sort.StringSlice) } func disjointStringSort(m, n string) string { return strings.Join( disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ") } func main() { for _, data := range []struct{ m, n string }{ {"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, } { mp := disjointStringSort(data.m, data.n) fmt.Printf("%s → %s » %s\n", data.m, data.n, mp) } }
Convert the following code from Java to Go, ensuring the logic remains intact.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
var m = ` leading spaces and blank lines`
Convert this Java snippet to Go and keep its semantics consistent.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
var m = ` leading spaces and blank lines`
Ensure the translated Go code behaves exactly like the original Java snippet.
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, {"Bob", "foo"}}; hashJoin(table1, 1, table2, 0).stream() .forEach(r -> System.out.println(Arrays.deepToString(r))); } static List<String[][]> hashJoin(String[][] records1, int idx1, String[][] records2, int idx2) { List<String[][]> result = new ArrayList<>(); Map<String, List<String[]>> map = new HashMap<>(); for (String[] record : records1) { List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>()); v.add(record); map.put(record[idx1], v); } for (String[] record : records2) { List<String[]> lst = map.get(record[idx2]); if (lst != null) { lst.stream().forEach(r -> { result.add(new String[][]{r, record}); }); } } return result; } }
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
Change the following Java code into Go without altering its purpose.
import java.util.Arrays; public class RamanujanPrimes { public static void main(String[] args) { long start = System.nanoTime(); System.out.println("First 100 Ramanujan primes:"); PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000)); for (int i = 1; i <= 100; ++i) { int p = ramanujanPrime(pc, i); System.out.printf("%,5d%c", p, i % 10 == 0 ? '\n' : ' '); } System.out.println(); for (int i = 1000; i <= 100000; i *= 10) { int p = ramanujanPrime(pc, i); System.out.printf("The %,dth Ramanujan prime is %,d.\n", i, p); } long end = System.nanoTime(); System.out.printf("\nElapsed time: %.1f milliseconds\n", (end - start) / 1e6); } private static int ramanujanMax(int n) { return (int)Math.ceil(4 * n * Math.log(4 * n)); } private static int ramanujanPrime(PrimeCounter pc, int n) { for (int i = ramanujanMax(n); i >= 0; --i) { if (pc.primeCount(i) - pc.primeCount(i / 2) < n) return i + 1; } return 0; } private static class PrimeCounter { private PrimeCounter(int limit) { count = new int[limit]; Arrays.fill(count, 1); if (limit > 0) count[0] = 0; if (limit > 1) count[1] = 0; for (int i = 4; i < limit; i += 2) count[i] = 0; for (int p = 3, sq = 9; sq < limit; p += 2) { if (count[p] != 0) { for (int q = sq; q < limit; q += p << 1) count[q] = 0; } sq += (p + 1) << 2; } Arrays.parallelPrefix(count, (x, y) -> x + y); } private int primeCount(int n) { return n < 1 ? 0 : count[n]; } private int[] count; } }
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < limit; i += 2 { count[i] = 0 } for p, sq := 3, 9; sq < limit; p += 2 { if count[p] != 0 { for q := sq; q < limit; q += p << 1 { count[q] = 0 } } sq += (p + 1) << 2 } sum := 0 for i := 0; i < limit; i++ { sum += count[i] count[i] = sum } } func primeCount(n int) int { if n < 1 { return 0 } return count[n] } func ramanujanMax(n int) int { fn := float64(n) return int(math.Ceil(4 * fn * math.Log(4*fn))) } func ramanujanPrime(n int) int { if n == 1 { return 2 } for i := ramanujanMax(n); i >= 2*n; i-- { if i%2 == 1 { continue } if primeCount(i)-primeCount(i/2) < n { return i + 1 } } return 0 } func main() { start := time.Now() primeCounter(1 + ramanujanMax(1e6)) fmt.Println("The first 100 Ramanujan primes are:") rams := make([]int, 100) for n := 0; n < 100; n++ { rams[n] = ramanujanPrime(n + 1) } for i, r := range rams { fmt.Printf("%5s ", rcu.Commatize(r)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000))) fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000))) fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000))) fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000))) fmt.Println("\nTook", time.Since(start)) }
Convert this Java block to Go, preserving its control flow and logic.
import java.util.Arrays; public class RamanujanPrimes { public static void main(String[] args) { long start = System.nanoTime(); System.out.println("First 100 Ramanujan primes:"); PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000)); for (int i = 1; i <= 100; ++i) { int p = ramanujanPrime(pc, i); System.out.printf("%,5d%c", p, i % 10 == 0 ? '\n' : ' '); } System.out.println(); for (int i = 1000; i <= 100000; i *= 10) { int p = ramanujanPrime(pc, i); System.out.printf("The %,dth Ramanujan prime is %,d.\n", i, p); } long end = System.nanoTime(); System.out.printf("\nElapsed time: %.1f milliseconds\n", (end - start) / 1e6); } private static int ramanujanMax(int n) { return (int)Math.ceil(4 * n * Math.log(4 * n)); } private static int ramanujanPrime(PrimeCounter pc, int n) { for (int i = ramanujanMax(n); i >= 0; --i) { if (pc.primeCount(i) - pc.primeCount(i / 2) < n) return i + 1; } return 0; } private static class PrimeCounter { private PrimeCounter(int limit) { count = new int[limit]; Arrays.fill(count, 1); if (limit > 0) count[0] = 0; if (limit > 1) count[1] = 0; for (int i = 4; i < limit; i += 2) count[i] = 0; for (int p = 3, sq = 9; sq < limit; p += 2) { if (count[p] != 0) { for (int q = sq; q < limit; q += p << 1) count[q] = 0; } sq += (p + 1) << 2; } Arrays.parallelPrefix(count, (x, y) -> x + y); } private int primeCount(int n) { return n < 1 ? 0 : count[n]; } private int[] count; } }
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < limit; i += 2 { count[i] = 0 } for p, sq := 3, 9; sq < limit; p += 2 { if count[p] != 0 { for q := sq; q < limit; q += p << 1 { count[q] = 0 } } sq += (p + 1) << 2 } sum := 0 for i := 0; i < limit; i++ { sum += count[i] count[i] = sum } } func primeCount(n int) int { if n < 1 { return 0 } return count[n] } func ramanujanMax(n int) int { fn := float64(n) return int(math.Ceil(4 * fn * math.Log(4*fn))) } func ramanujanPrime(n int) int { if n == 1 { return 2 } for i := ramanujanMax(n); i >= 2*n; i-- { if i%2 == 1 { continue } if primeCount(i)-primeCount(i/2) < n { return i + 1 } } return 0 } func main() { start := time.Now() primeCounter(1 + ramanujanMax(1e6)) fmt.Println("The first 100 Ramanujan primes are:") rams := make([]int, 100) for n := 0; n < 100; n++ { rams[n] = ramanujanPrime(n + 1) } for i, r := range rams { fmt.Printf("%5s ", rcu.Commatize(r)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000))) fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000))) fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000))) fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000))) fmt.Println("\nTook", time.Since(start)) }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; s.currentY = 10; s.lineLength = 7; s.begin(545); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiCurve(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': case 'G': 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 = AXIOM; 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 == 'X') sb.append(PRODUCTION); 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 String AXIOM = "F--XF--F--XF"; private static final String PRODUCTION = "XF+G+XF--F--XF+G+X"; private static final int ANGLE = 45; }
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx, cy-2*h) } func lineS() { lineTo(cx, cy+2*h) } func lineE() { lineTo(cx+2*h, cy) } func lineW() { lineTo(cx-2*h, cy) } func lineNW() { lineTo(cx-h, cy-h) } func lineNE() { lineTo(cx+h, cy-h) } func lineSE() { lineTo(cx+h, cy+h) } func lineSW() { lineTo(cx-h, cy+h) } func sierN(level int) { if level == 1 { lineNE() lineN() lineNW() } else { sierN(level - 1) lineNE() sierE(level - 1) lineN() sierW(level - 1) lineNW() sierN(level - 1) } } func sierE(level int) { if level == 1 { lineSE() lineE() lineNE() } else { sierE(level - 1) lineSE() sierS(level - 1) lineE() sierN(level - 1) lineNE() sierE(level - 1) } } func sierS(level int) { if level == 1 { lineSW() lineS() lineSE() } else { sierS(level - 1) lineSW() sierW(level - 1) lineS() sierE(level - 1) lineSE() sierS(level - 1) } } func sierW(level int) { if level == 1 { lineNW() lineW() lineSW() } else { sierW(level - 1) lineNW() sierN(level - 1) lineW() sierS(level - 1) lineSW() sierW(level - 1) } } func squareCurve(level int) { sierN(level) lineNE() sierE(level) lineSE() sierS(level) lineSW() sierW(level) lineNW() lineNE() } func main() { dc.SetRGB(0, 0, 1) dc.Clear() level := 5 cx, cy = width/2, height h = cx / math.Pow(2, float64(level+1)) squareCurve(level) dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_curve.png") }
Generate an equivalent Go version of this Java code.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; s.currentY = 10; s.lineLength = 7; s.begin(545); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiCurve(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': case 'G': 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 = AXIOM; 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 == 'X') sb.append(PRODUCTION); 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 String AXIOM = "F--XF--F--XF"; private static final String PRODUCTION = "XF+G+XF--F--XF+G+X"; private static final int ANGLE = 45; }
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx, cy-2*h) } func lineS() { lineTo(cx, cy+2*h) } func lineE() { lineTo(cx+2*h, cy) } func lineW() { lineTo(cx-2*h, cy) } func lineNW() { lineTo(cx-h, cy-h) } func lineNE() { lineTo(cx+h, cy-h) } func lineSE() { lineTo(cx+h, cy+h) } func lineSW() { lineTo(cx-h, cy+h) } func sierN(level int) { if level == 1 { lineNE() lineN() lineNW() } else { sierN(level - 1) lineNE() sierE(level - 1) lineN() sierW(level - 1) lineNW() sierN(level - 1) } } func sierE(level int) { if level == 1 { lineSE() lineE() lineNE() } else { sierE(level - 1) lineSE() sierS(level - 1) lineE() sierN(level - 1) lineNE() sierE(level - 1) } } func sierS(level int) { if level == 1 { lineSW() lineS() lineSE() } else { sierS(level - 1) lineSW() sierW(level - 1) lineS() sierE(level - 1) lineSE() sierS(level - 1) } } func sierW(level int) { if level == 1 { lineNW() lineW() lineSW() } else { sierW(level - 1) lineNW() sierN(level - 1) lineW() sierS(level - 1) lineSW() sierW(level - 1) } } func squareCurve(level int) { sierN(level) lineNE() sierE(level) lineSE() sierS(level) lineSW() sierW(level) lineNW() lineNE() } func main() { dc.SetRGB(0, 0, 1) dc.Clear() level := 5 cx, cy = width/2, height h = cx / math.Pow(2, float64(level+1)) squareCurve(level) dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_curve.png") }
Translate this program into Go but keep the logic exactly as in Java.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; s.currentY = 10; s.lineLength = 7; s.begin(545); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiCurve(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': case 'G': 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 = AXIOM; 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 == 'X') sb.append(PRODUCTION); 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 String AXIOM = "F--XF--F--XF"; private static final String PRODUCTION = "XF+G+XF--F--XF+G+X"; private static final int ANGLE = 45; }
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx, cy-2*h) } func lineS() { lineTo(cx, cy+2*h) } func lineE() { lineTo(cx+2*h, cy) } func lineW() { lineTo(cx-2*h, cy) } func lineNW() { lineTo(cx-h, cy-h) } func lineNE() { lineTo(cx+h, cy-h) } func lineSE() { lineTo(cx+h, cy+h) } func lineSW() { lineTo(cx-h, cy+h) } func sierN(level int) { if level == 1 { lineNE() lineN() lineNW() } else { sierN(level - 1) lineNE() sierE(level - 1) lineN() sierW(level - 1) lineNW() sierN(level - 1) } } func sierE(level int) { if level == 1 { lineSE() lineE() lineNE() } else { sierE(level - 1) lineSE() sierS(level - 1) lineE() sierN(level - 1) lineNE() sierE(level - 1) } } func sierS(level int) { if level == 1 { lineSW() lineS() lineSE() } else { sierS(level - 1) lineSW() sierW(level - 1) lineS() sierE(level - 1) lineSE() sierS(level - 1) } } func sierW(level int) { if level == 1 { lineNW() lineW() lineSW() } else { sierW(level - 1) lineNW() sierN(level - 1) lineW() sierS(level - 1) lineSW() sierW(level - 1) } } func squareCurve(level int) { sierN(level) lineNE() sierE(level) lineSE() sierS(level) lineSW() sierW(level) lineNW() lineNE() } func main() { dc.SetRGB(0, 0, 1) dc.Clear() level := 5 cx, cy = width/2, height h = cx / math.Pow(2, float64(level+1)) squareCurve(level) dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_curve.png") }
Translate this program into Go but keep the logic exactly as in Java.
import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SDF { public static HashMap<Character, Integer> countElementOcurrences(char[] array) { HashMap<Character, Integer> countMap = new HashMap<Character, Integer>(); for (char element : array) { Integer count = countMap.get(element); count = (count == null) ? 1 : count + 1; countMap.put(element, count); } return countMap; } private static <K, V extends Comparable<? super V>> HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return o2.getValue().compareTo(o1.getValue()); } }); HashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; } public static String mostOcurrencesElement(char[] array, int k) { HashMap<Character, Integer> countMap = countElementOcurrences(array); System.out.println(countMap); Map<Character, Integer> map = descendingSortByValues(countMap); System.out.println(map); int i = 0; String output = ""; for (Map.Entry<Character, Integer> pairs : map.entrySet()) { if (i++ >= k) break; output += "" + pairs.getKey() + pairs.getValue(); } return output; } public static int getDiff(String str1, String str2, int limit) { int similarity = 0; int k = 0; for (int i = 0; i < str1.length() ; i = k) { k ++; if (Character.isLetter(str1.charAt(i))) { int pos = str2.indexOf(str1.charAt(i)); if (pos >= 0) { String digitStr1 = ""; while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) { digitStr1 += str1.charAt(k); k++; } int k2 = pos+1; String digitStr2 = ""; while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) { digitStr2 += str2.charAt(k2); k2++; } similarity += Integer.parseInt(digitStr2) + Integer.parseInt(digitStr1); } } } return Math.abs(limit - similarity); } public static int SDFfunc(String str1, String str2, int limit) { return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit); } public static void main(String[] args) { String input1 = "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"; String input2 = "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"; System.out.println(SDF.SDFfunc(input1,input2,100)); } }
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) int { for i, cf := range cfs { if cf.c == r { return i } } return -1 } func minOf(i, j int) int { if i < j { return i } return j } func mostFreqKHashing(input string, k int) string { var cfs []cf for _, r := range input { ix := indexOfCf(cfs, r) if ix >= 0 { cfs[ix].f++ } else { cfs = append(cfs, cf{r, 1}) } } sort.SliceStable(cfs, func(i, j int) bool { return cfs[i].f > cfs[j].f }) acc := "" min := minOf(len(cfs), k) for _, cf := range cfs[:min] { acc += fmt.Sprintf("%c%c", cf.c, cf.f) } return acc } func mostFreqKSimilarity(input1, input2 string) int { similarity := 0 runes1, runes2 := []rune(input1), []rune(input2) for i := 0; i < len(runes1); i += 2 { for j := 0; j < len(runes2); j += 2 { if runes1[i] == runes2[j] { freq1, freq2 := runes1[i+1], runes2[j+1] if freq1 != freq2 { continue } similarity += int(freq1) } } } return similarity } func mostFreqKSDF(input1, input2 string, k, maxDistance int) { fmt.Println("input1 :", input1) fmt.Println("input2 :", input2) s1 := mostFreqKHashing(input1, k) s2 := mostFreqKHashing(input2, k) fmt.Printf("mfkh(input1, %d) = ", k) for i, c := range s1 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } fmt.Printf("\nmfkh(input2, %d) = ", k) for i, c := range s2 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } result := maxDistance - mostFreqKSimilarity(s1, s2) fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result) } func main() { pairs := [][2]string{ {"research", "seeking"}, {"night", "nacht"}, {"my", "a"}, {"research", "research"}, {"aaaaabbbb", "ababababa"}, {"significant", "capabilities"}, } for _, pair := range pairs { mostFreqKSDF(pair[0], pair[1], 2, 10) } s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" mostFreqKSDF(s1, s2, 2, 100) s1 = "abracadabra12121212121abracadabra12121212121" s2 = reverseStr(s1) mostFreqKSDF(s1, s2, 2, 100) }
Generate an equivalent Go version of this Java code.
import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Scanner; public class textCompletionConcept { public static int correct = 0; public static ArrayList<String> listed = new ArrayList<>(); public static void main(String[]args) throws IOException, URISyntaxException { Scanner input = new Scanner(System.in); System.out.println("Input word: "); String errorRode = input.next(); File file = new File(new File(textCompletionConcept.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath() + File.separator + "words.txt"); Scanner reader = new Scanner(file); while(reader.hasNext()){ double percent; String compareToThis = reader.nextLine(); char[] s1 = errorRode.toCharArray(); char[] s2 = compareToThis.toCharArray(); int maxlen = Math.min(s1.length, s2.length); for (int index = 0; index < maxlen; index++) { String x = String.valueOf(s1[index]); String y = String.valueOf(s2[index]); if (x.equals(y)) { correct++; } } double length = Math.max(s1.length, s2.length); percent = correct / length; percent *= 100; boolean perfect = false; if (percent >= 80 && compareToThis.charAt(0) == errorRode.charAt(0)) { if(String.valueOf(percent).equals("100.00")){ perfect = true; } String addtoit = compareToThis + " : " + String.format("%.2f", percent) + "% similar."; listed.add(addtoit); } if(compareToThis.contains(errorRode) && !perfect && errorRode.length() * 2 > compareToThis.length()){ String addtoit = compareToThis + " : 80.00% similar."; listed.add(addtoit); } correct = 0; } for(String x : listed){ if(x.contains("100.00% similar.")){ System.out.println(x); listed.clear(); break; } } for(String x : listed){ System.out.println(x); } } }
package main import ( "bytes" "fmt" "io/ioutil" "log" ) func levenshtein(s, t string) int { d := make([][]int, len(s)+1) for i := range d { d[i] = make([]int, len(t)+1) } for i := range d { d[i][0] = i } for j := range d[0] { d[0][j] = j } for j := 1; j <= len(t); j++ { for i := 1; i <= len(s); i++ { if s[i-1] == t[j-1] { d[i][j] = d[i-1][j-1] } else { min := d[i-1][j] if d[i][j-1] < min { min = d[i][j-1] } if d[i-1][j-1] < min { min = d[i-1][j-1] } d[i][j] = min + 1 } } } return d[len(s)][len(t)] } func main() { search := "complition" b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } words := bytes.Fields(b) var lev [4][]string for _, word := range words { s := string(word) ld := levenshtein(search, s) if ld < 4 { lev[ld] = append(lev[ld], s) } } fmt.Printf("Input word: %s\n\n", search) for i := 1; i < 4; i++ { length := float64(len(search)) similarity := (length - float64(i)) * 100 / length fmt.Printf("Words which are %4.1f%% similar:\n", similarity) fmt.Println(lev[i]) fmt.Println() } }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if(nextInt > 0) { players = nextInt; break; } } else { System.out.println("That wasn't an integer. Try again. \n"); scan.next(); } } System.out.println("Alright, starting with " + players + " players. \n"); play(players, scan); scan.close(); } public static void play(int group, Scanner scan) { final int STRATEGIES = 5; Dice dice = new Dice(); Player[] players = new Player[group]; for(int count = 0; count < group; count++) { players[count] = new Player(count); System.out.println("Player " + players[count].getNumber() + " is alive! "); } System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: "); System.out.println(">> Enter '0' for a human player. "); System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+."); System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. "); System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. "); System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. "); for(Player player : players) { System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? "); while(true) { if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if (nextInt < Strategy.STRATEGIES.length) { player.setStrategy(Strategy.STRATEGIES[nextInt]); break; } } else { System.out.println("That wasn't an option. Try again. "); scan.next(); } } } int max = 0; while(max < 100) { for(Player player : players) { System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. "); player.setTurnPoints(0); player.setMax(max); while(true) { Move choice = player.choose(); if(choice == Move.ROLL) { int roll = dice.roll(); System.out.println(" A " + roll + " was rolled. "); player.setTurnPoints(player.getTurnPoints() + roll); player.incIter(); if(roll == 1) { player.setTurnPoints(0); break; } } else { System.out.println(" The player has held. "); break; } } player.addPoints(player.getTurnPoints()); System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n"); player.resetIter(); if(max < player.getPoints()) { max = player.getPoints(); } if(max >= 100) { System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: "); for(Player p : players) { System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. "); } break; } } } } }
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
Translate the given Java code snippet into Go without altering its behavior.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if(nextInt > 0) { players = nextInt; break; } } else { System.out.println("That wasn't an integer. Try again. \n"); scan.next(); } } System.out.println("Alright, starting with " + players + " players. \n"); play(players, scan); scan.close(); } public static void play(int group, Scanner scan) { final int STRATEGIES = 5; Dice dice = new Dice(); Player[] players = new Player[group]; for(int count = 0; count < group; count++) { players[count] = new Player(count); System.out.println("Player " + players[count].getNumber() + " is alive! "); } System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: "); System.out.println(">> Enter '0' for a human player. "); System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+."); System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. "); System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. "); System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. "); for(Player player : players) { System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? "); while(true) { if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if (nextInt < Strategy.STRATEGIES.length) { player.setStrategy(Strategy.STRATEGIES[nextInt]); break; } } else { System.out.println("That wasn't an option. Try again. "); scan.next(); } } } int max = 0; while(max < 100) { for(Player player : players) { System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. "); player.setTurnPoints(0); player.setMax(max); while(true) { Move choice = player.choose(); if(choice == Move.ROLL) { int roll = dice.roll(); System.out.println(" A " + roll + " was rolled. "); player.setTurnPoints(player.getTurnPoints() + roll); player.incIter(); if(roll == 1) { player.setTurnPoints(0); break; } } else { System.out.println(" The player has held. "); break; } } player.addPoints(player.getTurnPoints()); System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n"); player.resetIter(); if(max < player.getPoints()) { max = player.getPoints(); } if(max >= 100) { System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: "); for(Player p : players) { System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. "); } break; } } } } }
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if(nextInt > 0) { players = nextInt; break; } } else { System.out.println("That wasn't an integer. Try again. \n"); scan.next(); } } System.out.println("Alright, starting with " + players + " players. \n"); play(players, scan); scan.close(); } public static void play(int group, Scanner scan) { final int STRATEGIES = 5; Dice dice = new Dice(); Player[] players = new Player[group]; for(int count = 0; count < group; count++) { players[count] = new Player(count); System.out.println("Player " + players[count].getNumber() + " is alive! "); } System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: "); System.out.println(">> Enter '0' for a human player. "); System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+."); System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. "); System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. "); System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. "); for(Player player : players) { System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? "); while(true) { if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if (nextInt < Strategy.STRATEGIES.length) { player.setStrategy(Strategy.STRATEGIES[nextInt]); break; } } else { System.out.println("That wasn't an option. Try again. "); scan.next(); } } } int max = 0; while(max < 100) { for(Player player : players) { System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. "); player.setTurnPoints(0); player.setMax(max); while(true) { Move choice = player.choose(); if(choice == Move.ROLL) { int roll = dice.roll(); System.out.println(" A " + roll + " was rolled. "); player.setTurnPoints(player.getTurnPoints() + roll); player.incIter(); if(roll == 1) { player.setTurnPoints(0); break; } } else { System.out.println(" The player has held. "); break; } } player.addPoints(player.getTurnPoints()); System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n"); player.resetIter(); if(max < player.getPoints()) { max = player.getPoints(); } if(max >= 100) { System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: "); for(Player p : players) { System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. "); } break; } } } } }
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if(nextInt > 0) { players = nextInt; break; } } else { System.out.println("That wasn't an integer. Try again. \n"); scan.next(); } } System.out.println("Alright, starting with " + players + " players. \n"); play(players, scan); scan.close(); } public static void play(int group, Scanner scan) { final int STRATEGIES = 5; Dice dice = new Dice(); Player[] players = new Player[group]; for(int count = 0; count < group; count++) { players[count] = new Player(count); System.out.println("Player " + players[count].getNumber() + " is alive! "); } System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: "); System.out.println(">> Enter '0' for a human player. "); System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+."); System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. "); System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. "); System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. "); for(Player player : players) { System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? "); while(true) { if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if (nextInt < Strategy.STRATEGIES.length) { player.setStrategy(Strategy.STRATEGIES[nextInt]); break; } } else { System.out.println("That wasn't an option. Try again. "); scan.next(); } } } int max = 0; while(max < 100) { for(Player player : players) { System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. "); player.setTurnPoints(0); player.setMax(max); while(true) { Move choice = player.choose(); if(choice == Move.ROLL) { int roll = dice.roll(); System.out.println(" A " + roll + " was rolled. "); player.setTurnPoints(player.getTurnPoints() + roll); player.incIter(); if(roll == 1) { player.setTurnPoints(0); break; } } else { System.out.println(" The player has held. "); break; } } player.addPoints(player.getTurnPoints()); System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n"); player.resetIter(); if(max < player.getPoints()) { max = player.getPoints(); } if(max >= 100) { System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: "); for(Player p : players) { System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. "); } break; } } } } }
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
Keep all operations the same but rewrite the snippet in Go.
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } static BigInteger rev(BigInteger bi) { String s = new StringBuilder(bi.toString()).reverse().toString(); return new BigInteger(s); } static Tuple lychrel(BigInteger n) { Tuple res; if ((res = cache.get(n)) != null) return res; BigInteger r = rev(n); res = new Tuple(true, n); List<BigInteger> seen = new ArrayList<>(); for (int i = 0; i < 500; i++) { n = n.add(r); r = rev(n); if (n.equals(r)) { res = new Tuple(false, BigInteger.ZERO); break; } if (cache.containsKey(n)) { res = cache.get(n); break; } seen.add(n); } for (BigInteger bi : seen) cache.put(bi, res); return res; } public static void main(String[] args) { List<BigInteger> seeds = new ArrayList<>(); List<BigInteger> related = new ArrayList<>(); List<BigInteger> palin = new ArrayList<>(); for (int i = 1; i <= 10_000; i++) { BigInteger n = BigInteger.valueOf(i); Tuple t = lychrel(n); if (!t.flag) continue; if (n.equals(t.bi)) seeds.add(t.bi); else related.add(t.bi); if (n.equals(t.bi)) palin.add(t.bi); } System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds); System.out.printf("%d Lychrel related%n", related.size()); System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin); } }
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } static BigInteger rev(BigInteger bi) { String s = new StringBuilder(bi.toString()).reverse().toString(); return new BigInteger(s); } static Tuple lychrel(BigInteger n) { Tuple res; if ((res = cache.get(n)) != null) return res; BigInteger r = rev(n); res = new Tuple(true, n); List<BigInteger> seen = new ArrayList<>(); for (int i = 0; i < 500; i++) { n = n.add(r); r = rev(n); if (n.equals(r)) { res = new Tuple(false, BigInteger.ZERO); break; } if (cache.containsKey(n)) { res = cache.get(n); break; } seen.add(n); } for (BigInteger bi : seen) cache.put(bi, res); return res; } public static void main(String[] args) { List<BigInteger> seeds = new ArrayList<>(); List<BigInteger> related = new ArrayList<>(); List<BigInteger> palin = new ArrayList<>(); for (int i = 1; i <= 10_000; i++) { BigInteger n = BigInteger.valueOf(i); Tuple t = lychrel(n); if (!t.flag) continue; if (n.equals(t.bi)) seeds.add(t.bi); else related.add(t.bi); if (n.equals(t.bi)) palin.add(t.bi); } System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds); System.out.printf("%d Lychrel related%n", related.size()); System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin); } }
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.util.*; public class ErdosSelfridge { private int[] primes; private int[] category; public static void main(String[] args) { ErdosSelfridge es = new ErdosSelfridge(1000000); System.out.println("First 200 primes:"); for (var e : es.getPrimesByCategory(200).entrySet()) { int category = e.getKey(); List<Integer> primes = e.getValue(); System.out.printf("Category %d:\n", category); for (int i = 0, n = primes.size(); i != n; ++i) System.out.printf("%4d%c", primes.get(i), (i + 1) % 15 == 0 ? '\n' : ' '); System.out.printf("\n\n"); } System.out.println("First 1,000,000 primes:"); for (var e : es.getPrimesByCategory(1000000).entrySet()) { int category = e.getKey(); List<Integer> primes = e.getValue(); System.out.printf("Category %2d: first = %7d last = %8d count = %d\n", category, primes.get(0), primes.get(primes.size() - 1), primes.size()); } } private ErdosSelfridge(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 200000); List<Integer> primeList = new ArrayList<>(); for (int i = 0; i < limit; ++i) primeList.add(primeGen.nextPrime()); primes = new int[primeList.size()]; for (int i = 0; i < primes.length; ++i) primes[i] = primeList.get(i); category = new int[primes.length]; } private Map<Integer, List<Integer>> getPrimesByCategory(int limit) { Map<Integer, List<Integer>> result = new TreeMap<>(); for (int i = 0; i < limit; ++i) { var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>()); p.add(primes[i]); } return result; } private int getCategory(int index) { if (category[index] != 0) return category[index]; int maxCategory = 0; int n = primes[index] + 1; for (int i = 0; n > 1; ++i) { int p = primes[i]; if (p * p > n) break; int count = 0; for (; n % p == 0; ++count) n /= p; if (count != 0) { int category = (p <= 3) ? 1 : 1 + getCategory(i); maxCategory = Math.max(maxCategory, category); } } if (n > 1) { int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n)); maxCategory = Math.max(maxCategory, category); } category[index] = maxCategory; return maxCategory; } private int getIndex(int prime) { return Arrays.binarySearch(primes, prime); } }
package main import ( "fmt" "math" "rcu" ) var limit = int(math.Log(1e6) * 1e6 * 1.2) var primes = rcu.Primes(limit) var prevCats = make(map[int]int) func cat(p int) int { if v, ok := prevCats[p]; ok { return v } pf := rcu.PrimeFactors(p + 1) all := true for _, f := range pf { if f != 2 && f != 3 { all = false break } } if all { return 1 } if p > 2 { len := len(pf) for i := len - 1; i >= 1; i-- { if pf[i-1] == pf[i] { pf = append(pf[:i], pf[i+1:]...) } } } for c := 2; c <= 11; c++ { all := true for _, f := range pf { if cat(f) >= c { all = false break } } if all { prevCats[p] = c return c } } return 12 } func main() { es := make([][]int, 12) fmt.Println("First 200 primes:\n") for _, p := range primes[0:200] { c := cat(p) es[c-1] = append(es[c-1], p) } for c := 1; c <= 6; c++ { if len(es[c-1]) > 0 { fmt.Println("Category", c, "\b:") fmt.Println(es[c-1]) fmt.Println() } } fmt.Println("First million primes:\n") for _, p := range primes[200:1e6] { c := cat(p) es[c-1] = append(es[c-1], p) } for c := 1; c <= 12; c++ { e := es[c-1] if len(e) > 0 { format := "Category %-2d: First = %7d Last = %8d Count = %6d\n" fmt.Printf(format, c, e[0], e[len(e)-1], len(e)) } } }
Generate an equivalent Go version of this Java code.
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; s.currentAngle = 0; s.currentX = (size - length)/2; s.currentY = length; s.lineLength = length; s.begin(size); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiSquareCurve(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 = AXIOM; 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 == 'X') sb.append(PRODUCTION); 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 String AXIOM = "F+XF+F+XF"; private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X"; private static final int ANGLE = 90; }
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.Clear() cx, cy = 10, height/2+5 h = 6 sys := lindenmayer.Lsystem{ Variables: []rune{'X'}, Constants: []rune{'F', '+', '-'}, Axiom: "F+XF+F+XF", Rules: []lindenmayer.Rule{ {"X", "XF-F+F-XF+F+XF-F+F-X"}, }, Angle: math.Pi / 2, } result := lindenmayer.Iterate(&sys, 5) operations := map[rune]func(){ 'F': func() { newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta) dc.LineTo(newX, newY) cx, cy = newX, newY }, '+': func() { theta = math.Mod(theta+sys.Angle, twoPi) }, '-': func() { theta = math.Mod(theta-sys.Angle, twoPi) }, } if err := lindenmayer.Process(result, operations); err != nil { log.Fatal(err) } operations['+']() operations['F']() dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_square_curve.png") }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; s.currentAngle = 0; s.currentX = (size - length)/2; s.currentY = length; s.lineLength = length; s.begin(size); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiSquareCurve(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 = AXIOM; 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 == 'X') sb.append(PRODUCTION); 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 String AXIOM = "F+XF+F+XF"; private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X"; private static final int ANGLE = 90; }
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.Clear() cx, cy = 10, height/2+5 h = 6 sys := lindenmayer.Lsystem{ Variables: []rune{'X'}, Constants: []rune{'F', '+', '-'}, Axiom: "F+XF+F+XF", Rules: []lindenmayer.Rule{ {"X", "XF-F+F-XF+F+XF-F+F-X"}, }, Angle: math.Pi / 2, } result := lindenmayer.Iterate(&sys, 5) operations := map[rune]func(){ 'F': func() { newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta) dc.LineTo(newX, newY) cx, cy = newX, newY }, '+': func() { theta = math.Mod(theta+sys.Angle, twoPi) }, '-': func() { theta = math.Mod(theta-sys.Angle, twoPi) }, } if err := lindenmayer.Process(result, operations); err != nil { log.Fatal(err) } operations['+']() operations['F']() dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_square_curve.png") }
Keep all operations the same but rewrite the snippet in Go.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n"); for ( int k = 2 ; k <= 10 ; k++ ) { BigInteger max = BigInteger.valueOf(10).pow(k); List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k); System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers)); } System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n"); for ( int k = 2 ; k <= 10 ; k++ ) { List<Integer> powCount = new ArrayList<>(); for ( int j = 0 ; j < k+10 ; j++ ) { BigInteger max = BigInteger.valueOf(10).pow(j); powCount.add(countPowerFulNumbers(max, k)); } System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount); } } private static String getList(List<BigInteger> list) { StringBuilder sb = new StringBuilder(); sb.append(list.subList(0, 5).toString().replace("]", "")); sb.append(" ... "); sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", "")); return sb.toString(); } private static int countPowerFulNumbers(BigInteger max, int k) { return potentialPowerful(max, k).size(); } private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) { List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k)); Collections.sort(powerfulNumbers); return powerfulNumbers; } private static Set<BigInteger> potentialPowerful(BigInteger max, int k) { int[] indexes = new int[k]; for ( int i = 0 ; i < k ; i++ ) { indexes[i] = 1; } Set<BigInteger> powerful = new HashSet<>(); boolean foundPower = true; while ( foundPower ) { boolean genPowerful = false; for ( int index = 0 ; index < k ; index++ ) { BigInteger power = BigInteger.ONE; for ( int i = 0 ; i < k ; i++ ) { power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i)); } if ( power.compareTo(max) <= 0 ) { powerful.add(power); indexes[0] += 1; genPowerful = true; break; } else { indexes[index] = 1; if ( index < k-1 ) { indexes[index+1] += 1; } } } if ( ! genPowerful ) { foundPower = false; } } return powerful; } }
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x uint64) bool { for _, p := range primes { p2 := p * p if p2 > x { break } if x%p2 == 0 { return false } } return true } func iroot(x, p uint64) uint64 { return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj) } func ipow(x, p uint64) uint64 { prod := uint64(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func powerful(n, k uint64) []uint64 { set := make(map[uint64]bool) var f func(m, r uint64) f = func(m, r uint64) { if r < k { set[m] = true return } for v := uint64(1); v <= iroot(n/m, r); v++ { if r > k { if !isSquareFree(v) || gcd(m, v) != 1 { continue } } f(m*ipow(v, r), r-1) } } f(1, (1<<k)-1) list := make([]uint64, 0, len(set)) for key := range set { list = append(list, key) } sort.Slice(list, func(i, j int) bool { return list[i] < list[j] }) return list } func main() { power := uint64(10) for k := uint64(2); k <= 10; k++ { power *= 10 a := powerful(power, k) le := len(a) h, t := a[0:5], a[le-5:] fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t) } fmt.Println() for k := uint64(2); k <= 10; k++ { power := uint64(1) var counts []int for j := uint64(0); j < k+10; j++ { a := powerful(power, k) counts = append(counts, len(a)) power *= 10 } j := k + 10 fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts) } }
Keep all operations the same but rewrite the snippet in Go.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n"); for ( int k = 2 ; k <= 10 ; k++ ) { BigInteger max = BigInteger.valueOf(10).pow(k); List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k); System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers)); } System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n"); for ( int k = 2 ; k <= 10 ; k++ ) { List<Integer> powCount = new ArrayList<>(); for ( int j = 0 ; j < k+10 ; j++ ) { BigInteger max = BigInteger.valueOf(10).pow(j); powCount.add(countPowerFulNumbers(max, k)); } System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount); } } private static String getList(List<BigInteger> list) { StringBuilder sb = new StringBuilder(); sb.append(list.subList(0, 5).toString().replace("]", "")); sb.append(" ... "); sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", "")); return sb.toString(); } private static int countPowerFulNumbers(BigInteger max, int k) { return potentialPowerful(max, k).size(); } private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) { List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k)); Collections.sort(powerfulNumbers); return powerfulNumbers; } private static Set<BigInteger> potentialPowerful(BigInteger max, int k) { int[] indexes = new int[k]; for ( int i = 0 ; i < k ; i++ ) { indexes[i] = 1; } Set<BigInteger> powerful = new HashSet<>(); boolean foundPower = true; while ( foundPower ) { boolean genPowerful = false; for ( int index = 0 ; index < k ; index++ ) { BigInteger power = BigInteger.ONE; for ( int i = 0 ; i < k ; i++ ) { power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i)); } if ( power.compareTo(max) <= 0 ) { powerful.add(power); indexes[0] += 1; genPowerful = true; break; } else { indexes[index] = 1; if ( index < k-1 ) { indexes[index+1] += 1; } } } if ( ! genPowerful ) { foundPower = false; } } return powerful; } }
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x uint64) bool { for _, p := range primes { p2 := p * p if p2 > x { break } if x%p2 == 0 { return false } } return true } func iroot(x, p uint64) uint64 { return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj) } func ipow(x, p uint64) uint64 { prod := uint64(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func powerful(n, k uint64) []uint64 { set := make(map[uint64]bool) var f func(m, r uint64) f = func(m, r uint64) { if r < k { set[m] = true return } for v := uint64(1); v <= iroot(n/m, r); v++ { if r > k { if !isSquareFree(v) || gcd(m, v) != 1 { continue } } f(m*ipow(v, r), r-1) } } f(1, (1<<k)-1) list := make([]uint64, 0, len(set)) for key := range set { list = append(list, key) } sort.Slice(list, func(i, j int) bool { return list[i] < list[j] }) return list } func main() { power := uint64(10) for k := uint64(2); k <= 10; k++ { power *= 10 a := powerful(power, k) le := len(a) h, t := a[0:5], a[le-5:] fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t) } fmt.Println() for k := uint64(2); k <= 10; k++ { power := uint64(1) var counts []int for j := uint64(0); j < k+10; j++ { a := powerful(power, k) counts = append(counts, len(a)) power *= 10 } j := k + 10 fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts) } }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSyntheticDivision(N, D))); } static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) { int[] out = dividend.clone(); int normalizer = divisor[0]; for (int i = 0; i < dividend.length - (divisor.length - 1); i++) { out[i] /= normalizer; int coef = out[i]; if (coef != 0) { for (int j = 1; j < divisor.length; j++) out[i + j] += -divisor[j] * coef; } } int separator = out.length - (divisor.length - 1); return new int[][]{ Arrays.copyOfRange(out, 0, separator), Arrays.copyOfRange(out, separator, out.length) }; } }
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
Write the same algorithm in Go as shown in this Java implementation.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSyntheticDivision(N, D))); } static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) { int[] out = dividend.clone(); int normalizer = divisor[0]; for (int i = 0; i < dividend.length - (divisor.length - 1); i++) { out[i] /= normalizer; int coef = out[i]; if (coef != 0) { for (int j = 1; j < divisor.length; j++) out[i + j] += -divisor[j] * coef; } } int separator = out.length - (divisor.length - 1); return new int[][]{ Arrays.copyOfRange(out, 0, separator), Arrays.copyOfRange(out, separator, out.length) }; } }
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.io.*; import java.util.*; public class OddWords { public static void main(String[] args) { try { Set<String> dictionary = new TreeSet<>(); final int minLength = 5; String fileName = "unixdict.txt"; if (args.length != 0) fileName = args[0]; try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { if (line.length() >= minLength) dictionary.add(line); } } StringBuilder word1 = new StringBuilder(); StringBuilder word2 = new StringBuilder(); List<StringPair> evenWords = new ArrayList<>(); List<StringPair> oddWords = new ArrayList<>(); for (String word : dictionary) { int length = word.length(); if (length < minLength + 2 * (minLength/2)) continue; word1.setLength(0); word2.setLength(0); for (int i = 0; i < length; ++i) { if ((i & 1) == 0) word1.append(word.charAt(i)); else word2.append(word.charAt(i)); } String oddWord = word1.toString(); String evenWord = word2.toString(); if (dictionary.contains(oddWord)) oddWords.add(new StringPair(word, oddWord)); if (dictionary.contains(evenWord)) evenWords.add(new StringPair(word, evenWord)); } System.out.println("Odd words:"); printWords(oddWords); System.out.println("\nEven words:"); printWords(evenWords); } catch (Exception e) { e.printStackTrace(); } } private static void printWords(List<StringPair> strings) { int n = 1; for (StringPair pair : strings) { System.out.printf("%2d: %-14s%s\n", n++, pair.string1, pair.string2); } } private static class StringPair { private String string1; private String string2; private StringPair(String s1, String s2) { string1 = s1; string2 = s2; } } }
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } count := 0 fmt.Println("The odd words with length > 4 in", wordList, "are:") for _, word := range words { rword := []rune(word) if len(rword) > 8 { var sb strings.Builder for i := 0; i < len(rword); i += 2 { sb.WriteRune(rword[i]) } s := sb.String() idx := sort.SearchStrings(words, s) if idx < len(words) && words[idx] == s { count = count + 1 fmt.Printf("%2d: %-12s -> %s\n", count, word, s) } } } }
Maintain the same structure and functionality when rewriting this code in Go.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Heegner numbers yielding 'almost' integers:%n"); List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163); List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320); for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) { int heegnerNumber = heegnerNumbers.get(i); int heegnerVal = heegnerVals.get(i); BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744)); BigDecimal compute = ramanujanConstant(heegnerNumber, 50); System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString()); } } public static BigDecimal ramanujanConstant(int sqrt, int digits) { MathContext mc = new MathContext(digits + 5); return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits)); } public static BigDecimal bigE(BigDecimal exponent, MathContext mc) { BigDecimal e = BigDecimal.ONE; BigDecimal ak = e; int k = 0; BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision())); while ( true ) { k++; ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc); e = e.add(ak, mc); if ( ak.compareTo(min) < 0 ) { break; } } return e; } public static BigDecimal bigPi(MathContext mc) { int k = 0; BigDecimal ak = BigDecimal.ONE; BigDecimal a = ak; BigDecimal b = BigDecimal.ZERO; BigDecimal c = BigDecimal.valueOf(640320); BigDecimal c3 = c.pow(3); double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72); double digits = 0; while ( digits < mc.getPrecision() ) { k++; digits += digitePerTerm; BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1)); BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc); ak = ak.multiply(term, mc); a = a.add(ak, mc); b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc); } BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc); return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc); } public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) { double sqrt = Math.sqrt(squareDecimal.doubleValue()); BigDecimal x0 = new BigDecimal(sqrt, mc); BigDecimal two = BigDecimal.valueOf(2); while ( true ) { BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc); String x1String = x1.toPlainString(); String x0String = x0.toPlainString(); if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) { break; } x0 = x1; } return x0; } }
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
Generate an equivalent Go version of this Java code.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Heegner numbers yielding 'almost' integers:%n"); List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163); List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320); for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) { int heegnerNumber = heegnerNumbers.get(i); int heegnerVal = heegnerVals.get(i); BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744)); BigDecimal compute = ramanujanConstant(heegnerNumber, 50); System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString()); } } public static BigDecimal ramanujanConstant(int sqrt, int digits) { MathContext mc = new MathContext(digits + 5); return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits)); } public static BigDecimal bigE(BigDecimal exponent, MathContext mc) { BigDecimal e = BigDecimal.ONE; BigDecimal ak = e; int k = 0; BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision())); while ( true ) { k++; ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc); e = e.add(ak, mc); if ( ak.compareTo(min) < 0 ) { break; } } return e; } public static BigDecimal bigPi(MathContext mc) { int k = 0; BigDecimal ak = BigDecimal.ONE; BigDecimal a = ak; BigDecimal b = BigDecimal.ZERO; BigDecimal c = BigDecimal.valueOf(640320); BigDecimal c3 = c.pow(3); double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72); double digits = 0; while ( digits < mc.getPrecision() ) { k++; digits += digitePerTerm; BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1)); BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc); ak = ak.multiply(term, mc); a = a.add(ak, mc); b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc); } BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc); return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc); } public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) { double sqrt = Math.sqrt(squareDecimal.doubleValue()); BigDecimal x0 = new BigDecimal(sqrt, mc); BigDecimal two = BigDecimal.valueOf(2); while ( true ) { BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc); String x1String = x1.toPlainString(); String x0String = x0.toPlainString(); if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) { break; } x0 = x1; } return x0; } }
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList("aab", "aa b") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d"); for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } } private static List<List<String>> wordBreak(String s, List<String> dictionary) { List<List<String>> matches = new ArrayList<>(); Queue<Node> queue = new LinkedList<>(); queue.add(new Node(s)); while ( ! queue.isEmpty() ) { Node node = queue.remove(); if ( node.val.length() == 0 ) { matches.add(node.parsed); } else { for ( String word : dictionary ) { if ( node.val.startsWith(word) ) { String valNew = node.val.substring(word.length(), node.val.length()); List<String> parsedNew = new ArrayList<>(); parsedNew.addAll(node.parsed); parsedNew.add(word); queue.add(new Node(valNew, parsedNew)); } } } } return matches; } private static class Node { private String val; private List<String> parsed; public Node(String initial) { val = initial; parsed = new ArrayList<>(); } public Node(String s, List<String> p) { val = s; parsed = p; } } }
package main import ( "fmt" "strings" ) type dict map[string]bool func newDict(words ...string) dict { d := dict{} for _, w := range words { d[w] = true } return d } func (d dict) wordBreak(s string) (broken []string, ok bool) { if s == "" { return nil, true } type prefix struct { length int broken []string } bp := []prefix{{0, nil}} for end := 1; end <= len(s); end++ { for i := len(bp) - 1; i >= 0; i-- { w := s[bp[i].length:end] if d[w] { b := append(bp[i].broken, w) if end == len(s) { return b, true } bp = append(bp, prefix{end, b}) break } } } return nil, false } func main() { d := newDict("a", "bc", "abc", "cd", "b") for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} { if b, ok := d.wordBreak(s); ok { fmt.Printf("%s: %s\n", s, strings.Join(b, " ")) } else { fmt.Println("can't break") } } }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) { int n = primes.size(); for (int i = 0; i < n; ++i) { int prime1 = primes.get(i); for (int j = i; j < n; ++j) { int prime2 = primes.get(j); brilliantNumbers.add(prime1 * prime2); } } if (brilliantNumbers.size() >= 100) break; } Collections.sort(brilliantNumbers); for (int i = 0; i < 100; ++i) { char c = (i + 1) % 10 == 0 ? '\n' : ' '; System.out.printf("%,5d%c", brilliantNumbers.get(i), c); } System.out.println(); long power = 10; long count = 0; for (int p = 1; p < 2 * primesByDigits.size(); ++p) { var primes = primesByDigits.get(p / 2); long position = count + 1; long minProduct = 0; int n = primes.size(); for (int i = 0; i < n; ++i) { long prime1 = primes.get(i); var primes2 = primes.subList(i, n); int q = (int)((power + prime1 - 1) / prime1); int j = Collections.binarySearch(primes2, q); if (j == n) continue; if (j < 0) j = -(j + 1); long prime2 = primes2.get(j); long product = prime1 * prime2; if (minProduct == 0 || product < minProduct) minProduct = product; position += j; if (prime1 >= prime2) break; } System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n", p, minProduct, position); power *= 10; if (p % 2 == 1) { long size = primes.size(); count += size * (size + 1) / 2; } } } private static List<List<Integer>> getPrimesByDigits(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 100000); List<List<Integer>> primesByDigits = new ArrayList<>(); List<Integer> primes = new ArrayList<>(); for (int p = 10; p <= limit; ) { int prime = primeGen.nextPrime(); if (prime > p) { primesByDigits.add(primes); primes = new ArrayList<>(); p *= 10; } primes.add(prime); } return primesByDigits; } }
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits; k++ { var s []int for _, p := range primes { if p >= pow*10 { break } if p > pow { s = append(s, p) } } for i := 0; i < len(s); i++ { for j := i; j < len(s); j++ { prod := s[i] * s[j] if prod < limit { if countOnly { count++ } else { brilliant = append(brilliant, prod) } } else { if next > prod { next = prod } break } } } pow *= 10 } if countOnly { return res{count, next} } return res{brilliant, next} } func main() { fmt.Println("First 100 brilliant numbers:") brilliant := getBrilliant(2, 10000, false).bc.([]int) sort.Ints(brilliant) brilliant = brilliant[0:100] for i := 0; i < len(brilliant); i++ { fmt.Printf("%4d ", brilliant[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() for k := 1; k <= 13; k++ { limit := int(math.Pow(10, float64(k))) r := getBrilliant(k, limit, true) total := r.bc.(int) next := r.next climit := rcu.Commatize(limit) ctotal := rcu.Commatize(total + 1) cnext := rcu.Commatize(next) fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext) } }
Convert this Java block to Go, preserving its control flow and logic.
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) { int n = primes.size(); for (int i = 0; i < n; ++i) { int prime1 = primes.get(i); for (int j = i; j < n; ++j) { int prime2 = primes.get(j); brilliantNumbers.add(prime1 * prime2); } } if (brilliantNumbers.size() >= 100) break; } Collections.sort(brilliantNumbers); for (int i = 0; i < 100; ++i) { char c = (i + 1) % 10 == 0 ? '\n' : ' '; System.out.printf("%,5d%c", brilliantNumbers.get(i), c); } System.out.println(); long power = 10; long count = 0; for (int p = 1; p < 2 * primesByDigits.size(); ++p) { var primes = primesByDigits.get(p / 2); long position = count + 1; long minProduct = 0; int n = primes.size(); for (int i = 0; i < n; ++i) { long prime1 = primes.get(i); var primes2 = primes.subList(i, n); int q = (int)((power + prime1 - 1) / prime1); int j = Collections.binarySearch(primes2, q); if (j == n) continue; if (j < 0) j = -(j + 1); long prime2 = primes2.get(j); long product = prime1 * prime2; if (minProduct == 0 || product < minProduct) minProduct = product; position += j; if (prime1 >= prime2) break; } System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n", p, minProduct, position); power *= 10; if (p % 2 == 1) { long size = primes.size(); count += size * (size + 1) / 2; } } } private static List<List<Integer>> getPrimesByDigits(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 100000); List<List<Integer>> primesByDigits = new ArrayList<>(); List<Integer> primes = new ArrayList<>(); for (int p = 10; p <= limit; ) { int prime = primeGen.nextPrime(); if (prime > p) { primesByDigits.add(primes); primes = new ArrayList<>(); p *= 10; } primes.add(prime); } return primesByDigits; } }
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits; k++ { var s []int for _, p := range primes { if p >= pow*10 { break } if p > pow { s = append(s, p) } } for i := 0; i < len(s); i++ { for j := i; j < len(s); j++ { prod := s[i] * s[j] if prod < limit { if countOnly { count++ } else { brilliant = append(brilliant, prod) } } else { if next > prod { next = prod } break } } } pow *= 10 } if countOnly { return res{count, next} } return res{brilliant, next} } func main() { fmt.Println("First 100 brilliant numbers:") brilliant := getBrilliant(2, 10000, false).bc.([]int) sort.Ints(brilliant) brilliant = brilliant[0:100] for i := 0; i < len(brilliant); i++ { fmt.Printf("%4d ", brilliant[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() for k := 1; k <= 13; k++ { limit := int(math.Pow(10, float64(k))) r := getBrilliant(k, limit, true) total := r.bc.(int) next := r.next climit := rcu.Commatize(limit) ctotal := rcu.Commatize(total + 1) cnext := rcu.Commatize(next) fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext) } }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadder { private static int distance(String s1, String s2) { assert s1.length() == s2.length(); return (int) IntStream.range(0, s1.length()) .filter(i -> s1.charAt(i) != s2.charAt(i)) .count(); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) { wordLadder(words, fw, tw, 8); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) { if (fw.length() != tw.length()) { throw new IllegalArgumentException("From word and to word must have the same length"); } Set<String> ws = words.get(fw.length()); if (ws.contains(fw)) { List<String> primeList = new ArrayList<>(); primeList.add(fw); PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> { int cmp1 = Integer.compare(chain1.size(), chain2.size()); if (cmp1 == 0) { String last1 = chain1.get(chain1.size() - 1); int d1 = distance(last1, tw); String last2 = chain2.get(chain2.size() - 1); int d2 = distance(last2, tw); return Integer.compare(d1, d2); } return cmp1; }); queue.add(primeList); while (queue.size() > 0) { List<String> curr = queue.remove(); if (curr.size() > limit) { continue; } String last = curr.get(curr.size() - 1); for (String word : ws) { if (distance(last, word) == 1) { if (word.equals(tw)) { curr.add(word); System.out.println(String.join(" -> ", curr)); return; } if (!curr.contains(word)) { List<String> cp = new ArrayList<>(curr); cp.add(word); queue.add(cp); } } } } } System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw); } public static void main(String[] args) throws IOException { Map<Integer, Set<String>> words = new HashMap<>(); for (String line : Files.readAllLines(Path.of("unixdict.txt"))) { Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new); wl.add(line); } wordLadder(words, "boy", "man"); wordLadder(words, "girl", "lady"); wordLadder(words, "john", "jane"); wordLadder(words, "child", "adult"); wordLadder(words, "cat", "dog"); wordLadder(words, "lead", "gold"); wordLadder(words, "white", "black"); wordLadder(words, "bubble", "tickle", 12); } }
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { if a[i] != b[i] { sum++ } } return sum == 1 } func wordLadder(words []string, a, b string) { l := len(a) var poss []string for _, word := range words { if len(word) == l { poss = append(poss, word) } } todo := [][]string{{a}} for len(todo) > 0 { curr := todo[0] todo = todo[1:] var next []string for _, word := range poss { if oneAway(word, curr[len(curr)-1]) { next = append(next, word) } } if contains(next, b) { curr = append(curr, b) fmt.Println(strings.Join(curr, " -> ")) return } for i := len(poss) - 1; i >= 0; i-- { if contains(next, poss[i]) { copy(poss[i:], poss[i+1:]) poss[len(poss)-1] = "" poss = poss[:len(poss)-1] } } for _, s := range next { temp := make([]string, len(curr)) copy(temp, curr) temp = append(temp, s) todo = append(todo, temp) } } fmt.Println(a, "into", b, "cannot be done.") } func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } pairs := [][]string{ {"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}, } for _, pair := range pairs { wordLadder(words, pair[0], pair[1]) } }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadder { private static int distance(String s1, String s2) { assert s1.length() == s2.length(); return (int) IntStream.range(0, s1.length()) .filter(i -> s1.charAt(i) != s2.charAt(i)) .count(); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) { wordLadder(words, fw, tw, 8); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) { if (fw.length() != tw.length()) { throw new IllegalArgumentException("From word and to word must have the same length"); } Set<String> ws = words.get(fw.length()); if (ws.contains(fw)) { List<String> primeList = new ArrayList<>(); primeList.add(fw); PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> { int cmp1 = Integer.compare(chain1.size(), chain2.size()); if (cmp1 == 0) { String last1 = chain1.get(chain1.size() - 1); int d1 = distance(last1, tw); String last2 = chain2.get(chain2.size() - 1); int d2 = distance(last2, tw); return Integer.compare(d1, d2); } return cmp1; }); queue.add(primeList); while (queue.size() > 0) { List<String> curr = queue.remove(); if (curr.size() > limit) { continue; } String last = curr.get(curr.size() - 1); for (String word : ws) { if (distance(last, word) == 1) { if (word.equals(tw)) { curr.add(word); System.out.println(String.join(" -> ", curr)); return; } if (!curr.contains(word)) { List<String> cp = new ArrayList<>(curr); cp.add(word); queue.add(cp); } } } } } System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw); } public static void main(String[] args) throws IOException { Map<Integer, Set<String>> words = new HashMap<>(); for (String line : Files.readAllLines(Path.of("unixdict.txt"))) { Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new); wl.add(line); } wordLadder(words, "boy", "man"); wordLadder(words, "girl", "lady"); wordLadder(words, "john", "jane"); wordLadder(words, "child", "adult"); wordLadder(words, "cat", "dog"); wordLadder(words, "lead", "gold"); wordLadder(words, "white", "black"); wordLadder(words, "bubble", "tickle", 12); } }
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { if a[i] != b[i] { sum++ } } return sum == 1 } func wordLadder(words []string, a, b string) { l := len(a) var poss []string for _, word := range words { if len(word) == l { poss = append(poss, word) } } todo := [][]string{{a}} for len(todo) > 0 { curr := todo[0] todo = todo[1:] var next []string for _, word := range poss { if oneAway(word, curr[len(curr)-1]) { next = append(next, word) } } if contains(next, b) { curr = append(curr, b) fmt.Println(strings.Join(curr, " -> ")) return } for i := len(poss) - 1; i >= 0; i-- { if contains(next, poss[i]) { copy(poss[i:], poss[i+1:]) poss[len(poss)-1] = "" poss = poss[:len(poss)-1] } } for _, s := range next { temp := make([]string, len(curr)) copy(temp, curr) temp = append(temp, s) todo = append(todo, temp) } } fmt.Println(a, "into", b, "cannot be done.") } func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } pairs := [][]string{ {"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}, } for _, pair := range pairs { wordLadder(words, pair[0], pair[1]) } }
Please provide an equivalent version of this Java code in Go.
import java.util.HashMap; import java.util.Map; public class PrimeGaps { private Map<Integer, Integer> gapStarts = new HashMap<>(); private int lastPrime; private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000); public static void main(String[] args) { final int limit = 100000000; PrimeGaps pg = new PrimeGaps(); for (int pm = 10, gap1 = 2;;) { int start1 = pg.findGapStart(gap1); int gap2 = gap1 + 2; int start2 = pg.findGapStart(gap2); int diff = start2 > start1 ? start2 - start1 : start1 - start2; if (diff > pm) { System.out.printf( "Earliest difference > %,d between adjacent prime gap starting primes:\n" + "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n", pm, gap1, start1, gap2, start2, diff); if (pm == limit) break; pm *= 10; } else { gap1 = gap2; } } } private int findGapStart(int gap) { Integer start = gapStarts.get(gap); if (start != null) return start; for (;;) { int prev = lastPrime; lastPrime = primeGenerator.nextPrime(); int diff = lastPrime - prev; gapStarts.putIfAbsent(diff, prev); if (diff == gap) return prev; } } }
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] } } pm := 10 gap1 := 2 for { for _, ok := gapStarts[gap1]; !ok; { gap1 += 2 } start1 := gapStarts[gap1] gap2 := gap1 + 2 if _, ok := gapStarts[gap2]; !ok { gap1 = gap2 + 2 continue } start2 := gapStarts[gap2] diff := start2 - start1 if diff < 0 { diff = -diff } if diff > pm { cpm := rcu.Commatize(pm) cst1 := rcu.Commatize(start1) cst2 := rcu.Commatize(start2) cd := rcu.Commatize(diff) fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm) fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd) if pm == limit { break } pm *= 10 } else { gap1 = gap2 } } }
Write the same algorithm in Go as shown in this Java implementation.
import java.util.HashMap; import java.util.Map; public class PrimeGaps { private Map<Integer, Integer> gapStarts = new HashMap<>(); private int lastPrime; private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000); public static void main(String[] args) { final int limit = 100000000; PrimeGaps pg = new PrimeGaps(); for (int pm = 10, gap1 = 2;;) { int start1 = pg.findGapStart(gap1); int gap2 = gap1 + 2; int start2 = pg.findGapStart(gap2); int diff = start2 > start1 ? start2 - start1 : start1 - start2; if (diff > pm) { System.out.printf( "Earliest difference > %,d between adjacent prime gap starting primes:\n" + "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n", pm, gap1, start1, gap2, start2, diff); if (pm == limit) break; pm *= 10; } else { gap1 = gap2; } } } private int findGapStart(int gap) { Integer start = gapStarts.get(gap); if (start != null) return start; for (;;) { int prev = lastPrime; lastPrime = primeGenerator.nextPrime(); int diff = lastPrime - prev; gapStarts.putIfAbsent(diff, prev); if (diff == gap) return prev; } } }
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] } } pm := 10 gap1 := 2 for { for _, ok := gapStarts[gap1]; !ok; { gap1 += 2 } start1 := gapStarts[gap1] gap2 := gap1 + 2 if _, ok := gapStarts[gap2]; !ok { gap1 = gap2 + 2 continue } start2 := gapStarts[gap2] diff := start2 - start1 if diff < 0 { diff = -diff } if diff > pm { cpm := rcu.Commatize(pm) cst1 := rcu.Commatize(start1) cst2 := rcu.Commatize(start2) cd := rcu.Commatize(diff) fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm) fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd) if pm == limit { break } pm *= 10 } else { gap1 = gap2 } } }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LatinSquaresInReducedForm { public static void main(String[] args) { System.out.printf("Reduced latin squares of order 4:%n"); for ( LatinSquare square : getReducedLatinSquares(4) ) { System.out.printf("%s%n", square); } System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n"); for ( int n = 1 ; n <= 6 ; n++ ) { List<LatinSquare> list = getReducedLatinSquares(n); System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1)); } } private static long fact(int n) { if ( n == 0 ) { return 1; } int prod = 1; for ( int i = 1 ; i <= n ; i++ ) { prod *= i; } return prod; } private static List<LatinSquare> getReducedLatinSquares(int n) { List<LatinSquare> squares = new ArrayList<>(); squares.add(new LatinSquare(n)); PermutationGenerator permGen = new PermutationGenerator(n); for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) { List<LatinSquare> squaresNext = new ArrayList<>(); for ( LatinSquare square : squares ) { while ( permGen.hasMore() ) { int[] perm = permGen.getNext(); if ( (perm[0]+1) != (fillRow+1) ) { continue; } boolean permOk = true; done: for ( int row = 0 ; row < fillRow ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { if ( square.get(row, col) == (perm[col]+1) ) { permOk = false; break done; } } } if ( permOk ) { LatinSquare newSquare = new LatinSquare(square); for ( int col = 0 ; col < n ; col++ ) { newSquare.set(fillRow, col, perm[col]+1); } squaresNext.add(newSquare); } } permGen.reset(); } squares = squaresNext; } return squares; } @SuppressWarnings("unused") private static int[] display(int[] in) { int [] out = new int[in.length]; for ( int i = 0 ; i < in.length ; i++ ) { out[i] = in[i] + 1; } return out; } private static class LatinSquare { int[][] square; int size; public LatinSquare(int n) { square = new int[n][n]; size = n; for ( int col = 0 ; col < n ; col++ ) { set(0, col, col + 1); } } public LatinSquare(LatinSquare ls) { int n = ls.size; square = new int[n][n]; size = n; for ( int row = 0 ; row < n ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { set(row, col, ls.get(row, col)); } } } public void set(int row, int col, int value) { square[row][col] = value; } public int get(int row, int col) { return square[row][col]; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for ( int row = 0 ; row < size ; row++ ) { sb.append(Arrays.toString(square[row])); sb.append("\n"); } return sb.toString(); } } private static class PermutationGenerator { private int[] a; private BigInteger numLeft; private BigInteger total; public PermutationGenerator (int n) { if (n < 1) { throw new IllegalArgumentException ("Min 1"); } a = new int[n]; total = getFactorial(n); reset(); } private void reset () { for ( int i = 0 ; i < a.length ; i++ ) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public boolean hasMore() { return numLeft.compareTo(BigInteger.ZERO) == 1; } private static BigInteger getFactorial (int n) { BigInteger fact = BigInteger.ONE; for ( int i = n ; i > 1 ; i-- ) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } public int[] getNext() { if ( numLeft.equals(total) ) { numLeft = numLeft.subtract (BigInteger.ONE); return a; } int j = a.length - 2; while ( a[j] > a[j+1] ) { j--; } int k = a.length - 1; while ( a[j] > a[k] ) { k--; } int temp = a[k]; a[k] = a[j]; a[j] = temp; int r = a.length - 1; int s = j + 1; while (r > s) { int temp2 = a[s]; a[s] = a[r]; a[r] = temp2; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } }
package main import ( "fmt" "sort" ) type matrix [][]int func dList(n, start int) (r matrix) { start-- a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] sort.Ints(a[1:]) first := a[1] var recurse func(last int) recurse = func(last int) { if last == first { for j, v := range a[1:] { if j+1 == v { return } } b := make([]int, n) copy(b, a) for i := range b { b[i]++ } r = append(r, b) return } for i := last; i >= 1; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func reducedLatinSquare(n int, echo bool) uint64 { if n <= 0 { if echo { fmt.Println("[]\n") } return 0 } else if n == 1 { if echo { fmt.Println("[1]\n") } return 1 } rlatin := make(matrix, n) for i := 0; i < n; i++ { rlatin[i] = make([]int, n) } for j := 0; j < n; j++ { rlatin[0][j] = j + 1 } count := uint64(0) var recurse func(i int) recurse = func(i int) { rows := dList(n, i) outer: for r := 0; r < len(rows); r++ { copy(rlatin[i-1], rows[r]) for k := 0; k < i-1; k++ { for j := 1; j < n; j++ { if rlatin[k][j] == rlatin[i-1][j] { if r < len(rows)-1 { continue outer } else if i > 2 { return } } } } if i < n { recurse(i + 1) } else { count++ if echo { printSquare(rlatin, n) } } } return } recurse(2) return count } func printSquare(latin matrix, n int) { for i := 0; i < n; i++ { fmt.Println(latin[i]) } fmt.Println() } func factorial(n uint64) uint64 { if n == 0 { return 1 } prod := uint64(1) for i := uint64(2); i <= n; i++ { prod *= i } return prod } func main() { fmt.Println("The four reduced latin squares of order 4 are:\n") reducedLatinSquare(4, true) fmt.Println("The size of the set of reduced latin squares for the following orders") fmt.Println("and hence the total number of latin squares of these orders are:\n") for n := uint64(1); n <= 6; n++ { size := reducedLatinSquare(int(n), false) f := factorial(n - 1) f *= f * n * size fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f) } }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ## #", 0, " ## #", 1, " # ##", 2, " #### #", 3, " # ##", 4, " ## #", 5, " # ####", 6, " ### ##", 7, " ## ###", 8, " # ##", 9 ); private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey() .replace(' ', 's') .replace('#', ' ') .replace('s', '#'), Map.Entry::getValue )); private static final String END_SENTINEL = "# #"; private static final String MID_SENTINEL = " # # "; private static void decodeUPC(String input) { Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> { int pos = 0; var part = candidate.substring(pos, pos + END_SENTINEL.length()); List<Integer> output = new ArrayList<>(); if (END_SENTINEL.equals(part)) { pos += END_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (LEFT_DIGITS.containsKey(part)) { output.add(LEFT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + MID_SENTINEL.length()); if (MID_SENTINEL.equals(part)) { pos += MID_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (RIGHT_DIGITS.containsKey(part)) { output.add(RIGHT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + END_SENTINEL.length()); if (!END_SENTINEL.equals(part)) { return Map.entry(false, output); } int sum = 0; for (int i = 0; i < output.size(); i++) { if (i % 2 == 0) { sum += 3 * output.get(i); } else { sum += output.get(i); } } return Map.entry(sum % 10 == 0, output); }; Consumer<List<Integer>> printList = list -> { var it = list.iterator(); System.out.print('['); if (it.hasNext()) { System.out.print(it.next()); } while (it.hasNext()) { System.out.print(", "); System.out.print(it.next()); } System.out.print(']'); }; var candidate = input.trim(); var out = decode.apply(candidate); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(); } else { StringBuilder builder = new StringBuilder(candidate); builder.reverse(); out = decode.apply(builder.toString()); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(" Upside down"); } else if (out.getValue().size() == 12) { System.out.println("Invalid checksum"); } else { System.out.println("Invalid digit(s)"); } } } public static void main(String[] args) { var barcodes = List.of( " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ); barcodes.forEach(UPC::decodeUPC); } }
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[string]int) rhs = make(map[string]int) ) var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1} const ( s = "# #" m = " # # " e = "# #" d = "(?:#| ){7}" ) func init() { for i := 0; i <= 9; i++ { lt := make([]byte, 7) rt := make([]byte, 7) for j := 0; j < 14; j += 2 { if bits[i][j] == '1' { lt[j/2] = '#' rt[j/2] = ' ' } else { lt[j/2] = ' ' rt[j/2] = '#' } } lhs[string(lt)] = i rhs[string(rt)] = i } } func reverse(s string) string { b := []byte(s) for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) } func main() { barcodes := []string{ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", } expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`, s, d, d, d, d, d, d, m, d, d, d, d, d, d, e) rx := regexp.MustCompile(expr) fmt.Println("UPC-A barcodes:") for i, bc := range barcodes { for j := 0; j <= 1; j++ { if !rx.MatchString(bc) { fmt.Printf("%2d: Invalid format\n", i+1) break } codes := rx.FindStringSubmatch(bc) digits := make([]int, 12) var invalid, ok bool for i := 1; i <= 6; i++ { digits[i-1], ok = lhs[codes[i]] if !ok { invalid = true } digits[i+5], ok = rhs[codes[i+6]] if !ok { invalid = true } } if invalid { if j == 0 { bc = reverse(bc) continue } else { fmt.Printf("%2d: Invalid digit(s)\n", i+1) break } } sum := 0 for i, d := range digits { sum += weights[i] * d } if sum%10 != 0 { fmt.Printf("%2d: Checksum error\n", i+1) break } else { ud := "" if j == 1 { ud = "(upside down)" } fmt.Printf("%2d: %v %s\n", i+1, digits, ud) break } } } }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ## #", 0, " ## #", 1, " # ##", 2, " #### #", 3, " # ##", 4, " ## #", 5, " # ####", 6, " ### ##", 7, " ## ###", 8, " # ##", 9 ); private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey() .replace(' ', 's') .replace('#', ' ') .replace('s', '#'), Map.Entry::getValue )); private static final String END_SENTINEL = "# #"; private static final String MID_SENTINEL = " # # "; private static void decodeUPC(String input) { Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> { int pos = 0; var part = candidate.substring(pos, pos + END_SENTINEL.length()); List<Integer> output = new ArrayList<>(); if (END_SENTINEL.equals(part)) { pos += END_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (LEFT_DIGITS.containsKey(part)) { output.add(LEFT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + MID_SENTINEL.length()); if (MID_SENTINEL.equals(part)) { pos += MID_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (RIGHT_DIGITS.containsKey(part)) { output.add(RIGHT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + END_SENTINEL.length()); if (!END_SENTINEL.equals(part)) { return Map.entry(false, output); } int sum = 0; for (int i = 0; i < output.size(); i++) { if (i % 2 == 0) { sum += 3 * output.get(i); } else { sum += output.get(i); } } return Map.entry(sum % 10 == 0, output); }; Consumer<List<Integer>> printList = list -> { var it = list.iterator(); System.out.print('['); if (it.hasNext()) { System.out.print(it.next()); } while (it.hasNext()) { System.out.print(", "); System.out.print(it.next()); } System.out.print(']'); }; var candidate = input.trim(); var out = decode.apply(candidate); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(); } else { StringBuilder builder = new StringBuilder(candidate); builder.reverse(); out = decode.apply(builder.toString()); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(" Upside down"); } else if (out.getValue().size() == 12) { System.out.println("Invalid checksum"); } else { System.out.println("Invalid digit(s)"); } } } public static void main(String[] args) { var barcodes = List.of( " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ); barcodes.forEach(UPC::decodeUPC); } }
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[string]int) rhs = make(map[string]int) ) var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1} const ( s = "# #" m = " # # " e = "# #" d = "(?:#| ){7}" ) func init() { for i := 0; i <= 9; i++ { lt := make([]byte, 7) rt := make([]byte, 7) for j := 0; j < 14; j += 2 { if bits[i][j] == '1' { lt[j/2] = '#' rt[j/2] = ' ' } else { lt[j/2] = ' ' rt[j/2] = '#' } } lhs[string(lt)] = i rhs[string(rt)] = i } } func reverse(s string) string { b := []byte(s) for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) } func main() { barcodes := []string{ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", } expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`, s, d, d, d, d, d, d, m, d, d, d, d, d, d, e) rx := regexp.MustCompile(expr) fmt.Println("UPC-A barcodes:") for i, bc := range barcodes { for j := 0; j <= 1; j++ { if !rx.MatchString(bc) { fmt.Printf("%2d: Invalid format\n", i+1) break } codes := rx.FindStringSubmatch(bc) digits := make([]int, 12) var invalid, ok bool for i := 1; i <= 6; i++ { digits[i-1], ok = lhs[codes[i]] if !ok { invalid = true } digits[i+5], ok = rhs[codes[i+6]] if !ok { invalid = true } } if invalid { if j == 0 { bc = reverse(bc) continue } else { fmt.Printf("%2d: Invalid digit(s)\n", i+1) break } } sum := 0 for i, d := range digits { sum += weights[i] * d } if sum%10 != 0 { fmt.Printf("%2d: Checksum error\n", i+1) break } else { ud := "" if j == 1 { ud = "(upside down)" } fmt.Printf("%2d: %v %s\n", i+1, digits, ud) break } } } }
Translate the given Java code snippet into Go without altering its behavior.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message: %n%s%n", enc); System.out.printf("%nDecoded message: %n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ { used[16] = true } else { used[9] = true } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { plainText = strings.ToUpper(plainText) var cleanText strings.Builder prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message: %n%s%n", enc); System.out.printf("%nDecoded message: %n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ { used[16] = true } else { used[9] = true } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { plainText = strings.ToUpper(plainText) var cleanText strings.Builder prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message: %n%s%n", enc); System.out.printf("%nDecoded message: %n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ { used[16] = true } else { used[9] = true } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { plainText = strings.ToUpper(plainText) var cleanText strings.Builder prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
Preserve the algorithm and functionality while converting the code from Java to Go.
import java.util.*; public class ClosestPair { public static class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } } public static class Pair { public Point point1 = null; public Point point2 = null; public double distance = 0.0; public Pair() { } public Pair(Point point1, Point point2) { this.point1 = point1; this.point2 = point2; calcDistance(); } public void update(Point point1, Point point2, double distance) { this.point1 = point1; this.point2 = point2; this.distance = distance; } public void calcDistance() { this.distance = distance(point1, point2); } public String toString() { return point1 + "-" + point2 + " : " + distance; } } public static double distance(Point p1, Point p2) { double xdist = p2.x - p1.x; double ydist = p2.y - p1.y; return Math.hypot(xdist, ydist); } public static Pair bruteForce(List<? extends Point> points) { int numPoints = points.size(); if (numPoints < 2) return null; Pair pair = new Pair(points.get(0), points.get(1)); if (numPoints > 2) { for (int i = 0; i < numPoints - 1; i++) { Point point1 = points.get(i); for (int j = i + 1; j < numPoints; j++) { Point point2 = points.get(j); double distance = distance(point1, point2); if (distance < pair.distance) pair.update(point1, point2, distance); } } } return pair; } public static void sortByX(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.x < point2.x) return -1; if (point1.x > point2.x) return 1; return 0; } } ); } public static void sortByY(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.y < point2.y) return -1; if (point1.y > point2.y) return 1; return 0; } } ); } public static Pair divideAndConquer(List<? extends Point> points) { List<Point> pointsSortedByX = new ArrayList<Point>(points); sortByX(pointsSortedByX); List<Point> pointsSortedByY = new ArrayList<Point>(points); sortByY(pointsSortedByY); return divideAndConquer(pointsSortedByX, pointsSortedByY); } private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY) { int numPoints = pointsSortedByX.size(); if (numPoints <= 3) return bruteForce(pointsSortedByX); int dividingIndex = numPoints >>> 1; List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex); List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints); List<Point> tempList = new ArrayList<Point>(leftOfCenter); sortByY(tempList); Pair closestPair = divideAndConquer(leftOfCenter, tempList); tempList.clear(); tempList.addAll(rightOfCenter); sortByY(tempList); Pair closestPairRight = divideAndConquer(rightOfCenter, tempList); if (closestPairRight.distance < closestPair.distance) closestPair = closestPairRight; tempList.clear(); double shortestDistance =closestPair.distance; double centerX = rightOfCenter.get(0).x; for (Point point : pointsSortedByY) if (Math.abs(centerX - point.x) < shortestDistance) tempList.add(point); for (int i = 0; i < tempList.size() - 1; i++) { Point point1 = tempList.get(i); for (int j = i + 1; j < tempList.size(); j++) { Point point2 = tempList.get(j); if ((point2.y - point1.y) >= shortestDistance) break; double distance = distance(point1, point2); if (distance < closestPair.distance) { closestPair.update(point1, point2, distance); shortestDistance = distance; } } } return closestPair; } public static void main(String[] args) { int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]); List<Point> points = new ArrayList<Point>(); Random r = new Random(); for (int i = 0; i < numPoints; i++) points.add(new Point(r.nextDouble(), r.nextDouble())); System.out.println("Generated " + numPoints + " random points"); long startTime = System.currentTimeMillis(); Pair bruteForceClosestPair = bruteForce(points); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair); startTime = System.currentTimeMillis(); Pair dqClosestPair = divideAndConquer(points); elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair); if (bruteForceClosestPair.distance != dqClosestPair.distance) System.out.println("MISMATCH"); } }
package main import ( "fmt" "math" "math/rand" "time" ) type xy struct { x, y float64 } const n = 1000 const scale = 100. func d(p1, p2 xy) float64 { return math.Hypot(p2.x-p1.x, p2.y-p1.y) } func main() { rand.Seed(time.Now().Unix()) points := make([]xy, n) for i := range points { points[i] = xy{rand.Float64() * scale, rand.Float64() * scale} } p1, p2 := closestPair(points) fmt.Println(p1, p2) fmt.Println("distance:", d(p1, p2)) } func closestPair(points []xy) (p1, p2 xy) { if len(points) < 2 { panic("at least two points expected") } min := 2 * scale for i, q1 := range points[:len(points)-1] { for _, q2 := range points[i+1:] { if dq := d(q1, q2); dq < min { p1, p2 = q1, q2 min = dq } } } return }
Produce a functionally identical Go code for the snippet given in Java.
public class Animal{ }
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
Maintain the same structure and functionality when rewriting this code in Go.
Map<String, Int> map = new HashMap(); map["foo"] = 5; map["bar"] = 10; map["baz"] = 15; map["foo"] = 6;
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
Generate a Go translation of this Java snippet without changing its computational steps.
import java.math.BigInteger; import java.util.*; public class WilsonPrimes { public static void main(String[] args) { final int limit = 11000; BigInteger[] f = new BigInteger[limit]; f[0] = BigInteger.ONE; BigInteger factorial = BigInteger.ONE; for (int i = 1; i < limit; ++i) { factorial = factorial.multiply(BigInteger.valueOf(i)); f[i] = factorial; } List<Integer> primes = generatePrimes(limit); System.out.printf(" n | Wilson primes\n--------------------\n"); BigInteger s = BigInteger.valueOf(-1); for (int n = 1; n <= 11; ++n) { System.out.printf("%2d |", n); for (int p : primes) { if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s) .mod(BigInteger.valueOf(p * p)) .equals(BigInteger.ZERO)) System.out.printf(" %d", p); } s = s.negate(); System.out.println(); } } private static List<Integer> generatePrimes(int limit) { boolean[] sieve = new boolean[limit >> 1]; Arrays.fill(sieve, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } List<Integer> primes = new ArrayList<>(); if (limit > 2) primes.add(2); for (int i = 1; i < sieve.length; ++i) { if (sieve[i]) primes.add((i << 1) + 1); } return primes; } }
package main import ( "fmt" "math/big" "rcu" ) func main() { const LIMIT = 11000 primes := rcu.Primes(LIMIT) facts := make([]*big.Int, LIMIT) facts[0] = big.NewInt(1) for i := int64(1); i < LIMIT; i++ { facts[i] = new(big.Int) facts[i].Mul(facts[i-1], big.NewInt(i)) } sign := int64(1) f := new(big.Int) zero := new(big.Int) fmt.Println(" n: Wilson primes") fmt.Println("--------------------") for n := 1; n < 12; n++ { fmt.Printf("%2d: ", n) sign = -sign for _, p := range primes { if p < n { continue } f.Mul(facts[n-1], facts[p-n]) f.Sub(f, big.NewInt(sign)) p2 := int64(p * p) bp2 := big.NewInt(p2) if f.Rem(f, bp2).Cmp(zero) == 0 { fmt.Printf("%d ", p) } } fmt.Println() } }
Please provide an equivalent version of this Java code in Go.
import java.awt.*; import javax.swing.*; public class ColorWheel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ColorWheelFrame frame = new ColorWheelFrame(); frame.setVisible(true); } }); } private static class ColorWheelFrame extends JFrame { private ColorWheelFrame() { super("Color Wheel"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().add(new ColorWheelPanel()); pack(); } } private static class ColorWheelPanel extends JComponent { private ColorWheelPanel() { setPreferredSize(new Dimension(400, 400)); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; int w = getWidth(); int h = getHeight(); int margin = 10; int radius = (Math.min(w, h) - 2 * margin)/2; int cx = w/2; int cy = h/2; float[] dist = {0.F, 1.0F}; g2.setColor(Color.BLACK); g2.fillRect(0, 0, w, h); for (int angle = 0; angle < 360; ++angle) { Color color = hsvToRgb(angle, 1.0, 1.0); Color[] colors = {Color.WHITE, color}; RadialGradientPaint paint = new RadialGradientPaint(cx, cy, radius, dist, colors); g2.setPaint(paint); g2.fillArc(cx - radius, cy - radius, radius*2, radius*2, angle, 1); } } } private static Color hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - Math.abs(hp % 2.0 - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255)); } }
package main import ( "github.com/fogleman/gg" "math" ) const tau = 2 * math.Pi func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func colorWheel(dc *gg.Context) { width, height := dc.Width(), dc.Height() centerX, centerY := width/2, height/2 radius := centerX if centerY < radius { radius = centerY } for y := 0; y < height; y++ { dy := float64(y - centerY) for x := 0; x < width; x++ { dx := float64(x - centerX) dist := math.Sqrt(dx*dx + dy*dy) if dist <= float64(radius) { theta := math.Atan2(dy, dx) hue := (theta + math.Pi) / tau r, g, b := hsb2rgb(hue, 1, 1) dc.SetRGB255(r, g, b) dc.SetPixel(x, y) } } } } func main() { const width, height = 480, 480 dc := gg.NewContext(width, height) dc.SetRGB(1, 1, 1) dc.Clear() colorWheel(dc) dc.SavePNG("color_wheel.png") }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB); plasma = createPlasma(dim.height, dim.width); new Timer(42, (ActionEvent e) -> { hueShift = (hueShift + 0.02f) % 1; repaint(); }).start(); } float[][] createPlasma(int w, int h) { float[][] buffer = new float[h][w]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { double value = sin(x / 16.0); value += sin(y / 8.0); value += sin((x + y) / 16.0); value += sin(sqrt(x * x + y * y) / 8.0); value += 4; value /= 8; assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds"; buffer[y][x] = (float) value; } return buffer; } void drawPlasma(Graphics2D g) { int h = plasma.length; int w = plasma[0].length; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float hue = hueShift + plasma[y][x] % 1; img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1)); } g.drawImage(img, 0, 0, null); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPlasma(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Plasma Effect"); f.setResizable(false); f.add(new PlasmaEffect(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package main import ( "image" "image/color" "image/gif" "log" "math" "os" ) func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func main() { const degToRad = math.Pi / 180 const nframes = 100 const delay = 4 w, h := 640, 640 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, w, h) palette := make([]color.Color, nframes+1) palette[0] = color.White for i := 1; i <= nframes; i++ { r, g, b := hsb2rgb(float64(i)/nframes, 1, 1) palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255} } for f := 1; f <= nframes; f++ { img := image.NewPaletted(rect, palette) setBackgroundColor(img, w, h, 0) for y := 0; y < h; y++ { for x := 0; x < w; x++ { fx, fy := float64(x), float64(y) value := math.Sin(fx / 16) value += math.Sin(fy / 8) value += math.Sin((fx + fy) / 16) value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8) value += 4 value /= 8 _, rem := math.Modf(value + float64(f)/float64(nframes)) ci := uint8(nframes*rem) + 1 img.SetColorIndex(x, y, ci) } } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } file, err := os.Create("plasma.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
Convert this Java block to Go, preserving its control flow and logic.
public class RhondaNumbers { public static void main(String[] args) { final int limit = 15; for (int base = 2; base <= 36; ++base) { if (isPrime(base)) continue; System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base); int numbers[] = new int[limit]; for (int n = 1, count = 0; count < limit; ++n) { if (isRhonda(base, n)) numbers[count++] = n; } System.out.printf("In base 10:"); for (int i = 0; i < limit; ++i) System.out.printf(" %d", numbers[i]); System.out.printf("\nIn base %d:", base); for (int i = 0; i < limit; ++i) System.out.printf(" %s", Integer.toString(numbers[i], base)); System.out.printf("\n\n"); } } private static int digitProduct(int base, int n) { int product = 1; for (; n != 0; n /= base) product *= n % base; return product; } private static int primeFactorSum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2; for (int p = 3; p * p <= n; p += 2) for (; n % p == 0; n /= p) sum += p; if (n > 1) sum += n; return sum; } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static boolean isRhonda(int base, int n) { return digitProduct(base, n) == base * primeFactorSum(n); } }
package main import ( "fmt" "rcu" "strconv" ) func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false } func main() { for b := 2; b <= 36; b++ { if rcu.IsPrime(b) { continue } count := 0 var rhonda []int for n := 1; count < 15; n++ { digits := rcu.Digits(n, b) if !contains(digits, 0) { var anyEven = false for _, d := range digits { if d%2 == 0 { anyEven = true break } } if b != 10 || (contains(digits, 5) && anyEven) { calc1 := 1 for _, d := range digits { calc1 *= d } calc2 := b * rcu.SumInts(rcu.PrimeFactors(n)) if calc1 == calc2 { rhonda = append(rhonda, n) count++ } } } } if len(rhonda) > 0 { fmt.Printf("\nFirst 15 Rhonda numbers in base %d:\n", b) rhonda2 := make([]string, len(rhonda)) counts2 := make([]int, len(rhonda)) for i, r := range rhonda { rhonda2[i] = fmt.Sprintf("%d", r) counts2[i] = len(rhonda2[i]) } rhonda3 := make([]string, len(rhonda)) counts3 := make([]int, len(rhonda)) for i, r := range rhonda { rhonda3[i] = strconv.FormatInt(int64(r), b) counts3[i] = len(rhonda3[i]) } maxLen2 := rcu.MaxInts(counts2) maxLen3 := rcu.MaxInts(counts3) maxLen := maxLen2 if maxLen3 > maxLen { maxLen = maxLen3 } maxLen++ fmt.Printf("In base 10: %*s\n", maxLen, rhonda2) fmt.Printf("In base %-2d: %*s\n", b, maxLen, rhonda3) } } }
Change the programming language of this snippet from Java to Go without modifying what it does.
class Point { protected int x, y; public Point() { this(0); } public Point(int x) { this(x, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point p) { this(p.x, p.y); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); } } class Circle extends Point { private int r; public Circle(Point p) { this(p, 0); } public Circle(Point p, int r) { super(p); this.r = r; } public Circle() { this(0); } public Circle(int x) { this(x, 0); } public Circle(int x, int y) { this(x, y, 0); } public Circle(int x, int y, int r) { super(x, y); this.r = r; } public Circle(Circle c) { this(c.x, c.y, c.r); } public int getR() { return this.r; } public void setR(int r) { this.r = r; } public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); } } public class test { public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }