Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.util.Arrays; import java.util.stream.IntStream; public class RamseysTheorem { static char[][] createMatrix() { String r = "-" + Integer.toBinaryString(53643); int len = r.length(); return IntStream.range(0, len) .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i)) .map(String::toCharArray) .toArray(char[][]::new); } static String ramseyCheck(char[][] mat) { int len = mat.length; char[] connectivity = "------".toCharArray(); for (int a = 0; a < len; a++) { for (int b = 0; b < len; b++) { if (a == b) continue; connectivity[0] = mat[a][b]; for (int c = 0; c < len; c++) { if (a == c || b == c) continue; connectivity[1] = mat[a][c]; connectivity[2] = mat[b][c]; for (int d = 0; d < len; d++) { if (a == d || b == d || c == d) continue; connectivity[3] = mat[a][d]; connectivity[4] = mat[b][d]; connectivity[5] = mat[c][d]; String conn = new String(connectivity); if (conn.indexOf('0') == -1) return String.format("Fail, found wholly connected: " + "%d %d %d %d", a, b, c, d); else if (conn.indexOf('1') == -1) return String.format("Fail, found wholly unconnected: " + "%d %d %d %d", a, b, c, d); } } } } return "Satisfies Ramsey condition."; } public static void main(String[] a) { char[][] mat = createMatrix(); for (char[] s : mat) System.out.println(Arrays.toString(s)); System.out.println(ramseyCheck(mat)); } }
package main import "fmt" var ( a [17][17]int idx [4]int ) func findGroup(ctype, min, max, depth int) bool { if depth == 4 { cs := "" if ctype == 0 { cs = "un" } fmt.Printf("Totally %sconnected group:", cs) for i := 0; i < 4; i++ { fmt.Printf(" %d", idx[i]) } fmt.Println() return true } for i := min; i < max; i++ { n := 0 for ; n < depth; n++ { if a[idx[n]][i] != ctype { break } } if n == depth { idx[n] = i if findGroup(ctype, 1, max, depth+1) { return true } } } return false } func main() { const mark = "01-" for i := 0; i < 17; i++ { a[i][i] = 2 } for k := 1; k <= 8; k <<= 1 { for i := 0; i < 17; i++ { j := (i + k) % 17 a[i][j], a[j][i] = 1, 1 } } for i := 0; i < 17; i++ { for j := 0; j < 17; j++ { fmt.Printf("%c ", mark[a[i][j]]) } fmt.Println() } for i := 0; i < 17; i++ { idx[0] = i if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) { fmt.Println("No good.") return } } fmt.Println("All good.") }
Maintain the same structure and functionality when rewriting this code in Go.
import java.awt.*; import javax.swing.JFrame; public class Test extends JFrame { public static void main(String[] args) { new Test(); } Test() { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); System.out.println("Physical screen size: " + screenSize); Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration()); System.out.println("Insets: " + insets); screenSize.width -= (insets.left + insets.right); screenSize.height -= (insets.top + insets.bottom); System.out.println("Max available: " + screenSize); } }
package main import ( "fmt" "github.com/go-vgo/robotgo" ) func main() { w, h := robotgo.GetScreenSize() fmt.Printf("Screen size: %d x %d\n", w, h) fpid, err := robotgo.FindIds("firefox") if err == nil && len(fpid) > 0 { pid := fpid[0] robotgo.ActivePID(pid) robotgo.MaxWindow(pid) _, _, w, h = robotgo.GetBounds(pid) fmt.Printf("Max usable : %d x %d\n", w, h) } }
Rewrite the snippet below in Go so it works the same as the original Java code.
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { String magic = fourIsMagic(n); System.out.printf("%d = %s%n", n, toSentence(magic)); } } private static final String toSentence(String s) { return s.substring(0,1).toUpperCase() + s.substring(1) + "."; } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String fourIsMagic(long n) { if ( n == 4 ) { return numToString(n) + " is magic"; } String result = numToString(n); return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length()); } private static final String numToString(long n) { if ( n < 0 ) { return "negative " + numToString(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : ""); } }
package main import ( "fmt" "math" "strings" ) func main() { for _, n := range [...]int64{ 0, 4, 6, 11, 13, 75, 100, 337, -164, math.MaxInt64, } { fmt.Println(fourIsMagic(n)) } } func fourIsMagic(n int64) string { s := say(n) s = strings.ToUpper(s[:1]) + s[1:] t := s for n != 4 { n = int64(len(s)) s = say(n) t += " is " + s + ", " + s } t += " is magic." return t } var small = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} var tens = [...]string{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} var illions = [...]string{"", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"} func say(n int64) string { var t string if n < 0 { t = "negative " n = -n } switch { case n < 20: t += small[n] case n < 100: t += tens[n/10] s := n % 10 if s > 0 { t += "-" + small[s] } case n < 1000: t += small[n/100] + " hundred" s := n % 100 if s > 0 { t += " " + say(s) } default: sx := "" for i := 0; n > 0; i++ { p := n % 1000 n /= 1000 if p > 0 { ix := say(p) + illions[i] if sx != "" { ix += " " + sx } sx = ix } } t += sx } return t }
Convert the following code from Java to Go, ensuring the logic remains intact.
public static int findNumOfDec(double x){ String str = String.valueOf(x); if(str.endsWith(".0")) return 0; else return (str.substring(str.indexOf('.')).length() - 1); }
package main import ( "fmt" "log" "math" "strings" ) var error = "Argument must be a numeric literal or a decimal numeric string." func getNumDecimals(n interface{}) int { switch v := n.(type) { case int: return 0 case float64: if v == math.Trunc(v) { return 0 } s := fmt.Sprintf("%g", v) return len(strings.Split(s, ".")[1]) case string: if v == "" { log.Fatal(error) } if v[0] == '+' || v[0] == '-' { v = v[1:] } for _, c := range v { if strings.IndexRune("0123456789.", c) == -1 { log.Fatal(error) } } s := strings.Split(v, ".") ls := len(s) if ls == 1 { return 0 } else if ls == 2 { return len(s[1]) } else { log.Fatal("Too many decimal points") } default: log.Fatal(error) } return 0 } func main() { var a = []interface{}{12, 12.345, 12.345555555555, "12.3450", "12.34555555555555555555", 12.345e53} for _, n := range a { d := getNumDecimals(n) switch v := n.(type) { case string: fmt.Printf("%q has %d decimals\n", v, d) case float32, float64: fmt.Printf("%g has %d decimals\n", v, d) default: fmt.Printf("%d has %d decimals\n", v, d) } } }
Produce a language-to-language conversion: from Java to Go, same semantics.
enum Fruits{ APPLE, BANANA, CHERRY }
const ( apple = iota banana cherry )
Change the following Java code into Go without altering its purpose.
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d: %s%n", n, unrooted[n]); } } }
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } } func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } } func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d: %d\n", n, &unrooted[n]) } }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d: %s%n", n, unrooted[n]); } } }
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } } func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } } func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d: %d\n", n, &unrooted[n]) } }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d: %s%n", n, unrooted[n]); } } }
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } } func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } } func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d: %d\n", n, &unrooted[n]) } }
Write a version of this Java function in Go with identical behavior.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package main import ( "github.com/fogleman/gg" "math" ) func Pentagram(x, y, r float64) []gg.Point { points := make([]gg.Point, 5) for i := 0; i < 5; i++ { fi := float64(i) angle := 2*math.Pi*fi/5 - math.Pi/2 points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)} } return points } func main() { points := Pentagram(320, 320, 250) dc := gg.NewContext(640, 640) dc.SetRGB(1, 1, 1) dc.Clear() for i := 0; i <= 5; i++ { index := (i * 2) % 5 p := points[index] dc.LineTo(p.X, p.Y) } dc.SetHexColor("#6495ED") dc.SetFillRule(gg.FillRuleWinding) dc.FillPreserve() dc.SetRGB(0, 0, 0) dc.SetLineWidth(5) dc.Stroke() dc.SavePNG("pentagram.png") }
Write a version of this Java function in Go with identical behavior.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package main import ( "github.com/fogleman/gg" "math" ) func Pentagram(x, y, r float64) []gg.Point { points := make([]gg.Point, 5) for i := 0; i < 5; i++ { fi := float64(i) angle := 2*math.Pi*fi/5 - math.Pi/2 points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)} } return points } func main() { points := Pentagram(320, 320, 250) dc := gg.NewContext(640, 640) dc.SetRGB(1, 1, 1) dc.Clear() for i := 0; i <= 5; i++ { index := (i * 2) % 5 p := points[index] dc.LineTo(p.X, p.Y) } dc.SetHexColor("#6495ED") dc.SetFillRule(gg.FillRuleWinding) dc.FillPreserve() dc.SetRGB(0, 0, 0) dc.SetLineWidth(5) dc.Stroke() dc.SavePNG("pentagram.png") }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"}; System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port"); for ( String ip : tests ) { try { String [] parsed = parseIP(ip); System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]); } catch (IllegalArgumentException e) { System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage()); } } } private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$"); private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$"); private static String ipv6Pattern; static { ipv6Pattern = "^\\[{0,1}"; for ( int i = 1 ; i <= 7 ; i ++ ) { ipv6Pattern += "([0-9a-f]+):"; } ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$"; } private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern); private static String[] parseIP(String ip) { String hex = ""; String port = ""; Matcher ipv4Matcher = IPV4_PAT.matcher(ip); if ( ipv4Matcher.matches() ) { for ( int i = 1 ; i <= 4 ; i++ ) { hex += toHex4(ipv4Matcher.group(i)); } if ( ipv4Matcher.group(5) != null ) { port = ipv4Matcher.group(5); } return new String[] {hex, port}; } Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip); if ( ipv6DoubleColonMatcher.matches() ) { String p1 = ipv6DoubleColonMatcher.group(1); if ( p1.isEmpty() ) { p1 = "0"; } String p2 = ipv6DoubleColonMatcher.group(2); if ( p2.isEmpty() ) { p2 = "0"; } ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2; if ( ipv6DoubleColonMatcher.group(3) != null ) { ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3); } } Matcher ipv6Matcher = IPV6_PAT.matcher(ip); if ( ipv6Matcher.matches() ) { for ( int i = 1 ; i <= 8 ; i++ ) { hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0"); } if ( ipv6Matcher.group(9) != null ) { port = ipv6Matcher.group(9); } return new String[] {hex, port}; } throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip); } private static int numCount(String s) { return s.split(":").length; } private static String getZero(int count) { StringBuilder sb = new StringBuilder(); sb.append(":"); while ( count > 0 ) { sb.append("0:"); count--; } return sb.toString(); } private static String toHex4(String s) { int val = Integer.parseInt(s); if ( val < 0 || val > 255 ) { throw new IllegalArgumentException("ERROR 101: Invalid value : " + s); } return String.format("%2s", Integer.toHexString(val)).replace(" ", "0"); } private static String toHex6(String s) { int val = Integer.parseInt(s, 16); if ( val < 0 || val > 65536 ) { throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s); } return s; } }
package main import ( "encoding/hex" "fmt" "io" "net" "os" "strconv" "strings" "text/tabwriter" ) func parseIPPort(address string) (net.IP, *uint64, error) { ip := net.ParseIP(address) if ip != nil { return ip, nil, nil } host, portStr, err := net.SplitHostPort(address) if err != nil { return nil, nil, fmt.Errorf("splithostport failed: %w", err) } port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, nil, fmt.Errorf("failed to parse port: %w", err) } ip = net.ParseIP(host) if ip == nil { return nil, nil, fmt.Errorf("failed to parse ip address") } return ip, &port, nil } func ipVersion(ip net.IP) int { if ip.To4() == nil { return 6 } return 4 } func main() { testCases := []string{ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:443", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) writeTSV := func(w io.Writer, args ...interface{}) { fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...) fmt.Fprintf(w, "\n") } writeTSV(w, "Input", "Address", "Space", "Port") for _, addr := range testCases { ip, port, err := parseIPPort(addr) if err != nil { panic(err) } portStr := "n/a" if port != nil { portStr = fmt.Sprint(*port) } ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip)) writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr) } w.Flush() }
Maintain the same structure and functionality when rewriting this code in Go.
package hu.pj.alg; import hu.pj.obj.Item; import java.text.*; public class UnboundedKnapsack { protected Item [] items = { new Item("panacea", 3000, 0.3, 0.025), new Item("ichor" , 1800, 0.2, 0.015), new Item("gold" , 2500, 2.0, 0.002) }; protected final int n = items.length; protected Item sack = new Item("sack" , 0, 25.0, 0.250); protected Item best = new Item("best" , 0, 0.0, 0.000); protected int [] maxIt = new int [n]; protected int [] iIt = new int [n]; protected int [] bestAm = new int [n]; public UnboundedKnapsack() { for (int i = 0; i < n; i++) { maxIt [i] = Math.min( (int)(sack.getWeight() / items[i].getWeight()), (int)(sack.getVolume() / items[i].getVolume()) ); } calcWithRecursion(0); NumberFormat nf = NumberFormat.getInstance(); System.out.println("Maximum value achievable is: " + best.getValue()); System.out.print("This is achieved by carrying (one solution): "); for (int i = 0; i < n; i++) { System.out.print(bestAm[i] + " " + items[i].getName() + ", "); } System.out.println(); System.out.println("The weight to carry is: " + nf.format(best.getWeight()) + " and the volume used is: " + nf.format(best.getVolume()) ); } public void calcWithRecursion(int item) { for (int i = 0; i <= maxIt[item]; i++) { iIt[item] = i; if (item < n-1) { calcWithRecursion(item+1); } else { int currVal = 0; double currWei = 0.0; double currVol = 0.0; for (int j = 0; j < n; j++) { currVal += iIt[j] * items[j].getValue(); currWei += iIt[j] * items[j].getWeight(); currVol += iIt[j] * items[j].getVolume(); } if (currVal > best.getValue() && currWei <= sack.getWeight() && currVol <= sack.getVolume() ) { best.setValue (currVal); best.setWeight(currWei); best.setVolume(currVol); for (int j = 0; j < n; j++) bestAm[j] = iIt[j]; } } } } public static void main(String[] args) { new UnboundedKnapsack(); } }
package main import "fmt" type Item struct { Name string Value int Weight, Volume float64 } type Result struct { Counts []int Sum int } func min(a, b int) int { if a < b { return a } return b } func Knapsack(items []Item, weight, volume float64) (best Result) { if len(items) == 0 { return } n := len(items) - 1 maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume)) for count := 0; count <= maxCount; count++ { sol := Knapsack(items[:n], weight-float64(count)*items[n].Weight, volume-float64(count)*items[n].Volume) sol.Sum += items[n].Value * count if sol.Sum > best.Sum { sol.Counts = append(sol.Counts, count) best = sol } } return } func main() { items := []Item{ {"Panacea", 3000, 0.3, 0.025}, {"Ichor", 1800, 0.2, 0.015}, {"Gold", 2500, 2.0, 0.002}, } var sumCount, sumValue int var sumWeight, sumVolume float64 result := Knapsack(items, 25, 0.25) for i := range result.Counts { fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n", items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]), items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i]) sumCount += result.Counts[i] sumValue += items[i].Value * result.Counts[i] sumWeight += items[i].Weight * float64(result.Counts[i]) sumVolume += items[i].Volume * float64(result.Counts[i]) } fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n", sumCount, sumWeight, sumVolume, sumValue) }
Write the same algorithm in Go as shown in this Java implementation.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static final Map<Character, Character> mapping; private int total, elements, textonyms, max_found; private String filename, mappingResult; private Vector<String> max_strings; private Map<String, Vector<String>> values; static { mapping = new HashMap<Character, Character>(); mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2'); mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3'); mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4'); mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5'); mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6'); mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7'); mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8'); mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9'); } public RTextonyms(String filename) { this.filename = filename; this.total = this.elements = this.textonyms = this.max_found = 0; this.values = new HashMap<String, Vector<String>>(); this.max_strings = new Vector<String>(); return; } public void add(String line) { String mapping = ""; total++; if (!get_mapping(line)) { return; } mapping = mappingResult; if (values.get(mapping) == null) { values.put(mapping, new Vector<String>()); } int num_strings; num_strings = values.get(mapping).size(); textonyms += num_strings == 1 ? 1 : 0; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.add(mapping); max_found = num_strings; } else if (num_strings == max_found) { max_strings.add(mapping); } values.get(mapping).add(line); return; } public void results() { System.out.printf("Read %,d words from %s%n%n", total, filename); System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements, filename); System.out.printf("They require %,d digit combinations to represent them.%n", values.size()); System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms); System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1); for (String key : max_strings) { System.out.printf("%16s maps to: %s%n", key, values.get(key).toString()); } System.out.println(); return; } public void match(String key) { Vector<String> match; match = values.get(key); if (match == null) { System.out.printf("Key %s not found%n", key); } else { System.out.printf("Key %s matches: %s%n", key, match.toString()); } return; } private boolean get_mapping(String line) { mappingResult = line; StringBuilder mappingBuilder = new StringBuilder(); for (char cc : line.toCharArray()) { if (Character.isAlphabetic(cc)) { mappingBuilder.append(mapping.get(Character.toUpperCase(cc))); } else if (Character.isDigit(cc)) { mappingBuilder.append(cc); } else { return false; } } mappingResult = mappingBuilder.toString(); return true; } public static void main(String[] args) { String filename; if (args.length > 0) { filename = args[0]; } else { filename = "./unixdict.txt"; } RTextonyms tc; tc = new RTextonyms(filename); Path fp = Paths.get(filename); try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) { while (fs.hasNextLine()) { tc.add(fs.nextLine()); } } catch (IOException ex) { ex.printStackTrace(); } List<String> numbers = Arrays.asList( "001", "228", "27484247", "7244967473642", "." ); tc.results(); for (String number : numbers) { if (number.equals(".")) { System.out.println(); } else { tc.match(number); } } return; } }
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t := NewTextonym(phoneMap) _, err := ReadFromFile(t, *wordlist) if err != nil { log.Fatal(err) } t.Report(os.Stdout, *wordlist) } var phoneMap = map[byte][]rune{ '2': []rune("ABC"), '3': []rune("DEF"), '4': []rune("GHI"), '5': []rune("JKL"), '6': []rune("MNO"), '7': []rune("PQRS"), '8': []rune("TUV"), '9': []rune("WXYZ"), } func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) { f, err := os.Open(filename) if err != nil { return 0, err } n, err := r.ReadFrom(f) if cerr := f.Close(); err == nil && cerr != nil { err = cerr } return n, err } type Textonym struct { numberMap map[string][]string letterMap map[rune]byte count int textonyms int } func NewTextonym(dm map[byte][]rune) *Textonym { lm := make(map[rune]byte, 26) for d, ll := range dm { for _, l := range ll { lm[l] = d } } return &Textonym{letterMap: lm} } func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) { t.numberMap = make(map[string][]string) buf := make([]byte, 0, 32) sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) scan: for sc.Scan() { buf = buf[:0] word := sc.Text() n += int64(len(word)) + 1 for _, r := range word { d, ok := t.letterMap[unicode.ToUpper(r)] if !ok { continue scan } buf = append(buf, d) } num := string(buf) t.numberMap[num] = append(t.numberMap[num], word) t.count++ if len(t.numberMap[num]) == 2 { t.textonyms++ } } return n, sc.Err() } func (t *Textonym) Most() (most int, subset map[string][]string) { for k, v := range t.numberMap { switch { case len(v) > most: subset = make(map[string][]string) most = len(v) fallthrough case len(v) == most: subset[k] = v } } return most, subset } func (t *Textonym) Report(w io.Writer, name string) { fmt.Fprintf(w, ` There are %v words in %q which can be represented by the digit key mapping. They require %v digit combinations to represent them. %v digit combinations represent Textonyms. `, t.count, name, len(t.numberMap), t.textonyms) n, sub := t.Most() fmt.Fprintln(w, "\nThe numbers mapping to the most words map to", n, "words each:") for k, v := range sub { fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", ")) } }
Port the following code from Java to Go with equivalent syntax and logic.
package astar; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.Comparator; import java.util.LinkedList; import java.util.Queue; class AStar { private final List<Node> open; private final List<Node> closed; private final List<Node> path; private final int[][] maze; private Node now; private final int xstart; private final int ystart; private int xend, yend; private final boolean diag; static class Node implements Comparable { public Node parent; public int x, y; public double g; public double h; Node(Node parent, int xpos, int ypos, double g, double h) { this.parent = parent; this.x = xpos; this.y = ypos; this.g = g; this.h = h; } @Override public int compareTo(Object o) { Node that = (Node) o; return (int)((this.g + this.h) - (that.g + that.h)); } } AStar(int[][] maze, int xstart, int ystart, boolean diag) { this.open = new ArrayList<>(); this.closed = new ArrayList<>(); this.path = new ArrayList<>(); this.maze = maze; this.now = new Node(null, xstart, ystart, 0, 0); this.xstart = xstart; this.ystart = ystart; this.diag = diag; } public List<Node> findPathTo(int xend, int yend) { this.xend = xend; this.yend = yend; this.closed.add(this.now); addNeigborsToOpenList(); while (this.now.x != this.xend || this.now.y != this.yend) { if (this.open.isEmpty()) { return null; } this.now = this.open.get(0); this.open.remove(0); this.closed.add(this.now); addNeigborsToOpenList(); } this.path.add(0, this.now); while (this.now.x != this.xstart || this.now.y != this.ystart) { this.now = this.now.parent; this.path.add(0, this.now); } return this.path; } public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){ Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>(); if(maze[stateNode.getR()][stateNode.getC()] == 2){ if(isNodeILegal(stateNode, stateNode.expandDirection())){ exploreNodes.add(stateNode.expandDirection()); } } public void AStarSearch(){ this.start.setCostToGoal(this.start.calculateCost(this.goal)); this.start.setPathCost(0); this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal()); Mazecoord intialNode = this.start; Mazecoord stateNode = intialNode; frontier.add(intialNode); while (true){ if(frontier.isEmpty()){ System.out.println("fail"); System.out.println(explored.size()); System.exit(-1); } } public int calculateCost(Mazecoord goal){ int rState = this.getR(); int rGoal = goal.getR(); int diffR = rState - rGoal; int diffC = this.getC() - goal.getC(); if(diffR * diffC > 0) { return Math.abs(diffR) + Math.abs(diffC); } else { return Math.max(Math.abs(diffR), Math.abs(diffC)); } } public Coord getFather(){ return this.father; } public void setFather(Mazecoord node){ this.father = node; } public int getAStartCost() { return AStartCost; } public void setAStartCost(int aStartCost) { AStartCost = aStartCost; } public int getCostToGoal() { return costToGoal; } public void setCostToGoal(int costToGoal) { this.costToGoal = costToGoal; } private double distance(int dx, int dy) { if (this.diag) { return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); } else { return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); } } private void addNeigborsToOpenList() { Node node; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if (!this.diag && x != 0 && y != 0) { continue; } node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y)); if ((x != 0 || y != 0) && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length && this.now.y + y >= 0 && this.now.y + y < this.maze.length && this.maze[this.now.y + y][this.now.x + x] != -1 && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { node.g = node.parent.g + 1.; node.g += maze[this.now.y + y][this.now.x + x]; this.open.add(node); } } } Collections.sort(this.open); } public static void main(String[] args) { int[][] maze = { { 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0,100,100,100, 0, 0}, { 0, 0, 0, 0, 0,100, 0, 0}, { 0, 0,100, 0, 0,100, 0, 0}, { 0, 0,100, 0, 0,100, 0, 0}, { 0, 0,100,100,100,100, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0}, }; AStar as = new AStar(maze, 0, 0, true); List<Node> path = as.findPathTo(7, 7); if (path != null) { path.forEach((n) -> { System.out.print("[" + n.x + ", " + n.y + "] "); maze[n.y][n.x] = -1; }); System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g); for (int[] maze_row : maze) { for (int maze_entry : maze_row) { switch (maze_entry) { case 0: System.out.print("_"); break; case -1: System.out.print("*"); break; default: System.out.print("#"); } } System.out.println(); } } } }
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
Keep all operations the same but rewrite the snippet in Go.
package astar; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.Comparator; import java.util.LinkedList; import java.util.Queue; class AStar { private final List<Node> open; private final List<Node> closed; private final List<Node> path; private final int[][] maze; private Node now; private final int xstart; private final int ystart; private int xend, yend; private final boolean diag; static class Node implements Comparable { public Node parent; public int x, y; public double g; public double h; Node(Node parent, int xpos, int ypos, double g, double h) { this.parent = parent; this.x = xpos; this.y = ypos; this.g = g; this.h = h; } @Override public int compareTo(Object o) { Node that = (Node) o; return (int)((this.g + this.h) - (that.g + that.h)); } } AStar(int[][] maze, int xstart, int ystart, boolean diag) { this.open = new ArrayList<>(); this.closed = new ArrayList<>(); this.path = new ArrayList<>(); this.maze = maze; this.now = new Node(null, xstart, ystart, 0, 0); this.xstart = xstart; this.ystart = ystart; this.diag = diag; } public List<Node> findPathTo(int xend, int yend) { this.xend = xend; this.yend = yend; this.closed.add(this.now); addNeigborsToOpenList(); while (this.now.x != this.xend || this.now.y != this.yend) { if (this.open.isEmpty()) { return null; } this.now = this.open.get(0); this.open.remove(0); this.closed.add(this.now); addNeigborsToOpenList(); } this.path.add(0, this.now); while (this.now.x != this.xstart || this.now.y != this.ystart) { this.now = this.now.parent; this.path.add(0, this.now); } return this.path; } public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){ Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>(); if(maze[stateNode.getR()][stateNode.getC()] == 2){ if(isNodeILegal(stateNode, stateNode.expandDirection())){ exploreNodes.add(stateNode.expandDirection()); } } public void AStarSearch(){ this.start.setCostToGoal(this.start.calculateCost(this.goal)); this.start.setPathCost(0); this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal()); Mazecoord intialNode = this.start; Mazecoord stateNode = intialNode; frontier.add(intialNode); while (true){ if(frontier.isEmpty()){ System.out.println("fail"); System.out.println(explored.size()); System.exit(-1); } } public int calculateCost(Mazecoord goal){ int rState = this.getR(); int rGoal = goal.getR(); int diffR = rState - rGoal; int diffC = this.getC() - goal.getC(); if(diffR * diffC > 0) { return Math.abs(diffR) + Math.abs(diffC); } else { return Math.max(Math.abs(diffR), Math.abs(diffC)); } } public Coord getFather(){ return this.father; } public void setFather(Mazecoord node){ this.father = node; } public int getAStartCost() { return AStartCost; } public void setAStartCost(int aStartCost) { AStartCost = aStartCost; } public int getCostToGoal() { return costToGoal; } public void setCostToGoal(int costToGoal) { this.costToGoal = costToGoal; } private double distance(int dx, int dy) { if (this.diag) { return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); } else { return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); } } private void addNeigborsToOpenList() { Node node; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if (!this.diag && x != 0 && y != 0) { continue; } node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y)); if ((x != 0 || y != 0) && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length && this.now.y + y >= 0 && this.now.y + y < this.maze.length && this.maze[this.now.y + y][this.now.x + x] != -1 && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { node.g = node.parent.g + 1.; node.g += maze[this.now.y + y][this.now.x + x]; this.open.add(node); } } } Collections.sort(this.open); } public static void main(String[] args) { int[][] maze = { { 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0,100,100,100, 0, 0}, { 0, 0, 0, 0, 0,100, 0, 0}, { 0, 0,100, 0, 0,100, 0, 0}, { 0, 0,100, 0, 0,100, 0, 0}, { 0, 0,100,100,100,100, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0}, }; AStar as = new AStar(maze, 0, 0, true); List<Node> path = as.findPathTo(7, 7); if (path != null) { path.forEach((n) -> { System.out.print("[" + n.x + ", " + n.y + "] "); maze[n.y][n.x] = -1; }); System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g); for (int[] maze_row : maze) { for (int maze_entry : maze_row) { switch (maze_entry) { case 0: System.out.print("_"); break; case -1: System.out.print("*"); break; default: System.out.print("#"); } } System.out.println(); } } } }
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
Please provide an equivalent version of this Java code in Go.
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static Set<String> loadDictionary(String fileName) throws IOException { Set<String> words = new TreeSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String word; while ((word = reader.readLine()) != null) words.add(word); return words; } } private static void findTeacupWords(Set<String> words) { List<String> teacupWords = new ArrayList<>(); Set<String> found = new HashSet<>(); for (String word : words) { int len = word.length(); if (len < 3 || found.contains(word)) continue; teacupWords.clear(); teacupWords.add(word); char[] chars = word.toCharArray(); for (int i = 0; i < len - 1; ++i) { String rotated = new String(rotate(chars)); if (rotated.equals(word) || !words.contains(rotated)) break; teacupWords.add(rotated); } if (teacupWords.size() == len) { found.addAll(teacupWords); System.out.print(word); for (int i = 1; i < len; ++i) System.out.print(" " + teacupWords.get(i)); System.out.println(); } } } private static char[] rotate(char[] ch) { char c = ch[0]; System.arraycopy(ch, 1, ch, 0, ch.length - 1); ch[ch.length - 1] = c; return ch; } }
package main import ( "bufio" "fmt" "log" "os" "sort" "strings" ) 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 len(word) >= 3 { words = append(words, word) } } check(scanner.Err()) return words } func rotate(runes []rune) { first := runes[0] copy(runes, runes[1:]) runes[len(runes)-1] = first } func main() { dicts := []string{"mit_10000.txt", "unixdict.txt"} for _, dict := range dicts { fmt.Printf("Using %s:\n\n", dict) words := readWords(dict) n := len(words) used := make(map[string]bool) outer: for _, word := range words { runes := []rune(word) variants := []string{word} for i := 0; i < len(runes)-1; i++ { rotate(runes) word2 := string(runes) if word == word2 || used[word2] { continue outer } ix := sort.SearchStrings(words, word2) if ix == n || words[ix] != word2 { continue outer } variants = append(variants, word2) } for _, variant := range variants { used[variant] = true } fmt.Println(variants) } fmt.Println() } }
Ensure the translated Go code behaves exactly like the original Java snippet.
public class NivenNumberGaps { public static void main(String[] args) { long prevGap = 0; long prevN = 1; long index = 0; System.out.println("Gap Gap Index Starting Niven"); for ( long n = 2 ; n < 20_000_000_000l ; n++ ) { if ( isNiven(n) ) { index++; long curGap = n - prevN; if ( curGap > prevGap ) { System.out.printf("%3d  %,13d  %,15d%n", curGap, index, prevN); prevGap = curGap; } prevN = n; } } } public static boolean isNiven(long n) { long sum = 0; long nSave = n; while ( n > 0 ) { sum += n % 10; n /= 10; } return nSave % sum == 0; } }
package main import "fmt" type is func() uint64 func newSum() is { var ms is ms = func() uint64 { ms = newSum() return ms() } var msd, d uint64 return func() uint64 { if d < 9 { d++ } else { d = 0 msd = ms() } return msd + d } } func newHarshard() is { i := uint64(0) sum := newSum() return func() uint64 { for i++; i%sum() != 0; i++ { } return i } } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { fmt.Println("Gap Index of gap Starting Niven") fmt.Println("=== ============= ==============") h := newHarshard() pg := uint64(0) pn := h() for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() { g := n - pn if g > pg { fmt.Printf("%3d %13s %14s\n", g, commatize(i), commatize(pn)) pg = g } pn = n } }
Change the following Java code into Go without altering its purpose.
import java.util.Objects; public class PrintDebugStatement { private static void printDebug(String message) { Objects.requireNonNull(message); RuntimeException exception = new RuntimeException(); StackTraceElement[] stackTrace = exception.getStackTrace(); StackTraceElement stackTraceElement = stackTrace[1]; String fileName = stackTraceElement.getFileName(); String className = stackTraceElement.getClassName(); String methodName = stackTraceElement.getMethodName(); int lineNumber = stackTraceElement.getLineNumber(); System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message); } private static void blah() { printDebug("Made It!"); } public static void main(String[] args) { printDebug("Hello world."); blah(); Runnable oops = () -> printDebug("oops"); oops.run(); } }
package main import ( "fmt" "runtime" ) type point struct { x, y float64 } func add(x, y int) int { result := x + y debug("x", x) debug("y", y) debug("result", result) debug("result+1", result+1) return result } func debug(s string, x interface{}) { _, _, lineNo, _ := runtime.Caller(1) fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x) } func main() { add(2, 7) b := true debug("b", b) s := "Hello" debug("s", s) p := point{2, 3} debug("p", p) q := &p debug("q", q) }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.awt.*; import java.awt.geom.Path2D; import static java.lang.Math.pow; import java.util.Hashtable; import javax.swing.*; import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Dimension(650, 650)); setBackground(Color.white); setFont(new Font("Serif", Font.PLAIN, 18)); } void drawGrid(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(new Color(0xEEEEEE)); int w = getWidth(); int h = getHeight(); int spacing = 25; for (int i = 0; i < w / spacing; i++) { g.drawLine(0, i * spacing, w, i * spacing); g.drawLine(i * spacing, 0, i * spacing, w); } g.drawLine(0, h - 1, w, h - 1); g.setColor(new Color(0xAAAAAA)); g.drawLine(0, w / 2, w, w / 2); g.drawLine(w / 2, 0, w / 2, w); } void drawLegend(Graphics2D g) { g.setColor(Color.black); g.setFont(getFont()); g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45); g.drawString("a = b = 200", getWidth() - 150, 75); } void drawEllipse(Graphics2D g) { final int a = 200; double[] points = new double[a + 1]; Path2D p = new Path2D.Double(); p.moveTo(a, 0); for (int x = a; x >= 0; x--) { points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); p.lineTo(x, -points[x]); } for (int x = 0; x <= a; x++) p.lineTo(x, points[x]); for (int x = a; x >= 0; x--) p.lineTo(-x, points[x]); for (int x = 0; x <= a; x++) p.lineTo(-x, -points[x]); g.translate(getWidth() / 2, getHeight() / 2); g.setStroke(new BasicStroke(2)); g.setColor(new Color(0x25B0C4DE, true)); g.fill(p); g.setColor(new Color(0xB0C4DE)); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawGrid(g); drawLegend(g); drawEllipse(g); } @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); exp = source.getValue() / 2.0; repaint(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Super Ellipse"); f.setResizable(false); SuperEllipse panel = new SuperEllipse(); f.add(panel, BorderLayout.CENTER); JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5); exponent.addChangeListener(panel); exponent.setMajorTickSpacing(1); exponent.setPaintLabels(true); exponent.setBackground(Color.white); exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); for (int i = 1; i < 10; i++) labelTable.put(i, new JLabel(String.valueOf(i * 0.5))); exponent.setLabelTable(labelTable); f.add(exponent, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package main import ( "github.com/fogleman/gg" "math" ) func superEllipse(dc *gg.Context, n float64, a int) { hw := float64(dc.Width() / 2) hh := float64(dc.Height() / 2) y := make([]float64, a+1) for x := 0; x <= a; x++ { aa := math.Pow(float64(a), n) xx := math.Pow(float64(x), n) y[x] = math.Pow(aa-xx, 1.0/n) } for x := a; x >= 0; x-- { dc.LineTo(hw+float64(x), hh-y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw+float64(x), hh+y[x]) } for x := a; x >= 0; x-- { dc.LineTo(hw-float64(x), hh+y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw-float64(x), hh-y[x]) } dc.SetRGB(1, 1, 1) dc.Fill() } func main() { dc := gg.NewContext(500, 500) dc.SetRGB(0, 0, 0) dc.Clear() superEllipse(dc, 2.5, 200) dc.SavePNG("superellipse.png") }
Convert this Java block to Go, preserving its control flow and logic.
import java.awt.*; import java.awt.geom.Path2D; import static java.lang.Math.pow; import java.util.Hashtable; import javax.swing.*; import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Dimension(650, 650)); setBackground(Color.white); setFont(new Font("Serif", Font.PLAIN, 18)); } void drawGrid(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(new Color(0xEEEEEE)); int w = getWidth(); int h = getHeight(); int spacing = 25; for (int i = 0; i < w / spacing; i++) { g.drawLine(0, i * spacing, w, i * spacing); g.drawLine(i * spacing, 0, i * spacing, w); } g.drawLine(0, h - 1, w, h - 1); g.setColor(new Color(0xAAAAAA)); g.drawLine(0, w / 2, w, w / 2); g.drawLine(w / 2, 0, w / 2, w); } void drawLegend(Graphics2D g) { g.setColor(Color.black); g.setFont(getFont()); g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45); g.drawString("a = b = 200", getWidth() - 150, 75); } void drawEllipse(Graphics2D g) { final int a = 200; double[] points = new double[a + 1]; Path2D p = new Path2D.Double(); p.moveTo(a, 0); for (int x = a; x >= 0; x--) { points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); p.lineTo(x, -points[x]); } for (int x = 0; x <= a; x++) p.lineTo(x, points[x]); for (int x = a; x >= 0; x--) p.lineTo(-x, points[x]); for (int x = 0; x <= a; x++) p.lineTo(-x, -points[x]); g.translate(getWidth() / 2, getHeight() / 2); g.setStroke(new BasicStroke(2)); g.setColor(new Color(0x25B0C4DE, true)); g.fill(p); g.setColor(new Color(0xB0C4DE)); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawGrid(g); drawLegend(g); drawEllipse(g); } @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); exp = source.getValue() / 2.0; repaint(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Super Ellipse"); f.setResizable(false); SuperEllipse panel = new SuperEllipse(); f.add(panel, BorderLayout.CENTER); JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5); exponent.addChangeListener(panel); exponent.setMajorTickSpacing(1); exponent.setPaintLabels(true); exponent.setBackground(Color.white); exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); for (int i = 1; i < 10; i++) labelTable.put(i, new JLabel(String.valueOf(i * 0.5))); exponent.setLabelTable(labelTable); f.add(exponent, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package main import ( "github.com/fogleman/gg" "math" ) func superEllipse(dc *gg.Context, n float64, a int) { hw := float64(dc.Width() / 2) hh := float64(dc.Height() / 2) y := make([]float64, a+1) for x := 0; x <= a; x++ { aa := math.Pow(float64(a), n) xx := math.Pow(float64(x), n) y[x] = math.Pow(aa-xx, 1.0/n) } for x := a; x >= 0; x-- { dc.LineTo(hw+float64(x), hh-y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw+float64(x), hh+y[x]) } for x := a; x >= 0; x-- { dc.LineTo(hw-float64(x), hh+y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw-float64(x), hh-y[x]) } dc.SetRGB(1, 1, 1) dc.Fill() } func main() { dc := gg.NewContext(500, 500) dc.SetRGB(0, 0, 0) dc.Clear() superEllipse(dc, 2.5, 200) dc.SavePNG("superellipse.png") }
Port the following code from Java to Go with equivalent syntax and logic.
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.valueOf(n - i)); int digit = 0; int v = -1; while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i]) digit++; usedDigits.set(v); rank = rank.add(BigInteger.valueOf(digit)); } return rank; } public static int[] getPermutation(int n, BigInteger rank) { int[] digits = new int[n]; for (int digit = 2; digit <= n; digit++) { BigInteger divisor = BigInteger.valueOf(digit); digits[n - digit] = rank.mod(divisor).intValue(); if (digit < n) rank = rank.divide(divisor); } BitSet usedDigits = new BitSet(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { int v = usedDigits.nextClearBit(0); for (int j = 0; j < digits[i]; j++) v = usedDigits.nextClearBit(v + 1); permutation[i] = v; usedDigits.set(v); } return permutation; } public static void main(String[] args) { for (int i = 0; i < 6; i++) { int[] permutation = getPermutation(3, BigInteger.valueOf(i)); System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } Random rnd = new Random(); for (int n : new int[] { 12, 144 }) { BigInteger factorial = BigInteger.ONE; for (int i = 2; i <= n; i++) factorial = factorial.multiply(BigInteger.valueOf(i)); System.out.println("n = " + n); for (int i = 0; i < 5; i++) { BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd); rank = rank.mod(factorial); int[] permutation = getPermutation(n, rank); System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } } } }
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } return p } func MRRank(p []int) (r int) { p = append([]int{}, p...) inv := inverse(p) for i := len(p) - 1; i > 0; i-- { s := p[i] p[inv[i]] = s inv[s] = inv[i] } for i := 1; i < len(p); i++ { r = r*(i+1) + p[i] } return } func inverse(p []int) []int { r := make([]int, len(p)) for i, x := range p { r[x] = i } return r } func fact(n int) (f int) { for f = n; n > 2; { n-- f *= n } return } func main() { n := 3 fmt.Println("permutations of", n, "items") f := fact(n) for i := 0; i < f; i++ { p := MRPerm(i, n) fmt.Println(i, p, MRRank(p)) } n = 12 fmt.Println("permutations of", n, "items") f = fact(n) m := map[int]bool{} for len(m) < 4 { r := rand.Intn(f) if m[r] { continue } m[r] = true fmt.Println(r, MRPerm(r, n)) } }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.valueOf(n - i)); int digit = 0; int v = -1; while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i]) digit++; usedDigits.set(v); rank = rank.add(BigInteger.valueOf(digit)); } return rank; } public static int[] getPermutation(int n, BigInteger rank) { int[] digits = new int[n]; for (int digit = 2; digit <= n; digit++) { BigInteger divisor = BigInteger.valueOf(digit); digits[n - digit] = rank.mod(divisor).intValue(); if (digit < n) rank = rank.divide(divisor); } BitSet usedDigits = new BitSet(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { int v = usedDigits.nextClearBit(0); for (int j = 0; j < digits[i]; j++) v = usedDigits.nextClearBit(v + 1); permutation[i] = v; usedDigits.set(v); } return permutation; } public static void main(String[] args) { for (int i = 0; i < 6; i++) { int[] permutation = getPermutation(3, BigInteger.valueOf(i)); System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } Random rnd = new Random(); for (int n : new int[] { 12, 144 }) { BigInteger factorial = BigInteger.ONE; for (int i = 2; i <= n; i++) factorial = factorial.multiply(BigInteger.valueOf(i)); System.out.println("n = " + n); for (int i = 0; i < 5; i++) { BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd); rank = rank.mod(factorial); int[] permutation = getPermutation(n, rank); System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } } } }
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } return p } func MRRank(p []int) (r int) { p = append([]int{}, p...) inv := inverse(p) for i := len(p) - 1; i > 0; i-- { s := p[i] p[inv[i]] = s inv[s] = inv[i] } for i := 1; i < len(p); i++ { r = r*(i+1) + p[i] } return } func inverse(p []int) []int { r := make([]int, len(p)) for i, x := range p { r[x] = i } return r } func fact(n int) (f int) { for f = n; n > 2; { n-- f *= n } return } func main() { n := 3 fmt.Println("permutations of", n, "items") f := fact(n) for i := 0; i < f; i++ { p := MRPerm(i, n) fmt.Println(i, p, MRRank(p)) } n = 12 fmt.Println("permutations of", n, "items") f = fact(n) m := map[int]bool{} for len(m) < 4 { r := rand.Intn(f) if m[r] { continue } m[r] = true fmt.Println(r, MRPerm(r, n)) } }
Convert this Java snippet to Go and keep its semantics consistent.
public class RangeExtraction { public static void main(String[] args) { int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39}; int len = arr.length; int idx = 0, idx2 = 0; while (idx < len) { while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1); if (idx2 - idx > 2) { System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]); idx = idx2; } else { for (; idx < idx2; idx++) System.out.printf("%s,", arr[idx]); } } } }
package main import ( "errors" "fmt" "strconv" "strings" ) func main() { rf, err := rangeFormat([]int{ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, }) if err != nil { fmt.Println(err) return } fmt.Println("range format:", rf) } func rangeFormat(a []int) (string, error) { if len(a) == 0 { return "", nil } var parts []string for n1 := 0; ; { n2 := n1 + 1 for n2 < len(a) && a[n2] == a[n2-1]+1 { n2++ } s := strconv.Itoa(a[n1]) if n2 == n1+2 { s += "," + strconv.Itoa(a[n2-1]) } else if n2 > n1+2 { s += "-" + strconv.Itoa(a[n2-1]) } parts = append(parts, s) if n2 == len(a) { break } if a[n2] == a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence repeats value %d", a[n2])) } if a[n2] < a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence not ordered: %d < %d", a[n2], a[n2-1])) } n1 = n2 } return strings.Join(parts, ","), nil }
Convert this Java snippet to Go and keep its semantics consistent.
public class TypeDetection { private static void showType(Object a) { if (a instanceof Integer) { System.out.printf("'%s' is an integer\n", a); } else if (a instanceof Double) { System.out.printf("'%s' is a double\n", a); } else if (a instanceof Character) { System.out.printf("'%s' is a character\n", a); } else { System.out.printf("'%s' is some other type\n", a); } } public static void main(String[] args) { showType(5); showType(7.5); showType('d'); showType(true); } }
package main import "fmt" type any = interface{} func showType(a any) { switch a.(type) { case rune: fmt.Printf("The type of '%c' is %T\n", a, a) default: fmt.Printf("The type of '%v' is %T\n", a, a) } } func main() { values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"} for _, value := range values { showType(value) } }
Please provide an equivalent version of this Java code in Go.
import java.nio.file.*; import static java.util.Arrays.stream; public class MaxPathSum { public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::parseInt) .toArray()) .toArray(int[][]::new); for (int r = data.length - 1; r > 0; r--) for (int c = 0; c < data[r].length - 1; c++) data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); System.out.println(data[0][0]); } }
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
Write the same algorithm in Go as shown in this Java implementation.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "}; final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, {0, 4, 6}}}; static List<Point> toWhite = new ArrayList<>(); static char[][] grid; public static void main(String[] args) { grid = new char[image.length][]; for (int r = 0; r < image.length; r++) grid[r] = image[r].toCharArray(); thinImage(); } static void thinImage() { boolean firstStep = false; boolean hasChanged; do { hasChanged = false; firstStep = !firstStep; for (int r = 1; r < grid.length - 1; r++) { for (int c = 1; c < grid[0].length - 1; c++) { if (grid[r][c] != '#') continue; int nn = numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (numTransitions(r, c) != 1) continue; if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; toWhite.add(new Point(c, r)); hasChanged = true; } } for (Point p : toWhite) grid[p.y][p.x] = ' '; toWhite.clear(); } while (firstStep || hasChanged); printResult(); } static int numNeighbors(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++; return count; } static int numTransitions(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++; } return count; } static boolean atLeastOneIsWhite(int r, int c, int step) { int count = 0; int[][] group = nbrGroups[step]; for (int i = 0; i < 2; i++) for (int j = 0; j < group[i].length; j++) { int[] nbr = nbrs[group[i][j]]; if (grid[r + nbr[1]][c + nbr[0]] == ' ') { count++; break; } } return count > 1; } static void printResult() { for (char[] row : grid) System.out.println(row); } }
package main import ( "bytes" "fmt" "strings" ) var in = ` 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000` func main() { b := wbFromString(in, '1') b.zhangSuen() fmt.Println(b) } const ( white = 0 black = 1 ) type wbArray [][]byte func wbFromString(s string, blk byte) wbArray { lines := strings.Split(s, "\n")[1:] b := make(wbArray, len(lines)) for i, sl := range lines { bl := make([]byte, len(sl)) for j := 0; j < len(sl); j++ { bl[j] = sl[j] & 1 } b[i] = bl } return b } var sym = [2]byte{ white: ' ', black: '#', } func (b wbArray) String() string { b2 := bytes.Join(b, []byte{'\n'}) for i, b1 := range b2 { if b1 > 1 { continue } b2[i] = sym[b1] } return string(b2) } var nb = [...][2]int{ 2: {-1, 0}, 3: {-1, 1}, 4: {0, 1}, 5: {1, 1}, 6: {1, 0}, 7: {1, -1}, 8: {0, -1}, 9: {-1, -1}, } func (b wbArray) reset(en []int) (rs bool) { var r, c int var p [10]byte readP := func() { for nx := 1; nx <= 9; nx++ { n := nb[nx] p[nx] = b[r+n[0]][c+n[1]] } } shiftRead := func() { n := nb[3] p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]] n = nb[4] p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]] n = nb[5] p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]] } countA := func() (ct byte) { bit := p[9] for nx := 2; nx <= 9; nx++ { last := bit bit = p[nx] if last == white { ct += bit } } return ct } countB := func() (ct byte) { for nx := 2; nx <= 9; nx++ { ct += p[nx] } return ct } lastRow := len(b) - 1 lastCol := len(b[0]) - 1 mark := make([][]bool, lastRow) for r = range mark { mark[r] = make([]bool, lastCol) } for r = 1; r < lastRow; r++ { c = 1 readP() for { m := false if !(p[1] == black) { goto markDone } if b1 := countB(); !(2 <= b1 && b1 <= 6) { goto markDone } if !(countA() == 1) { goto markDone } { e1, e2 := p[en[1]], p[en[2]] if !(p[en[0]]&e1&e2 == 0) { goto markDone } if !(e1&e2&p[en[3]] == 0) { goto markDone } } m = true rs = true markDone: mark[r][c] = m c++ if c == lastCol { break } shiftRead() } } if rs { for r = 1; r < lastRow; r++ { for c = 1; c < lastCol; c++ { if mark[r][c] { b[r][c] = white } } } } return rs } var step1 = []int{2, 4, 6, 8} var step2 = []int{4, 2, 8, 6} func (b wbArray) zhangSuen() { for { rs1 := b.reset(step1) rs2 := b.reset(step2) if !rs1 && !rs2 { break } } }
Write the same algorithm in Go as shown in this Java implementation.
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5}; for (int i = 0; i < s.length; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) System.out.println(i); prev = curr; } int gprev = 0; for (int i = 0; i < s.length; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) System.out.println(i); gprev = curr; } } }
package main import "fmt" func main() { s := []int{1, 2, 2, 3, 4, 4, 5} for i := 0; i < len(s); i++ { curr := s[i] var prev int if i > 0 && curr == prev { fmt.Println(i) } prev = curr } var prev int for i := 0; i < len(s); i++ { curr := s[i] if i > 0 && curr == prev { fmt.Println(i) } prev = curr } }
Convert this Java block to Go, preserving its control flow and logic.
public class FirstLastBits { public static int mssb(int x) { return Integer.highestOneBit(x); } public static long mssb(long x) { return Long.highestOneBit(x); } public static int mssb_idx(int x) { return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x); } public static int mssb_idx(long x) { return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); } public static int mssb_idx(BigInteger x) { return x.bitLength() - 1; } public static int lssb(int x) { return Integer.lowestOneBit(x); } public static long lssb(long x) { return Long.lowestOneBit(x); } public static int lssb_idx(int x) { return Integer.numberOfTrailingZeros(x); } public static int lssb_idx(long x) { return Long.numberOfTrailingZeros(x); } public static int lssb_idx(BigInteger x) { return x.getLowestSetBit(); } public static void main(String[] args) { System.out.println("int:"); int n1 = 1; for (int i = 0; ; i++, n1 *= 42) { System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n1, n1, mssb(n1), mssb_idx(n1), lssb(n1), lssb_idx(n1)); if (n1 >= Integer.MAX_VALUE / 42) break; } System.out.println(); System.out.println("long:"); long n2 = 1; for (int i = 0; ; i++, n2 *= 42) { System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n", i, n2, n2, mssb(n2), mssb_idx(n2), lssb(n2), lssb_idx(n2)); if (n2 >= Long.MAX_VALUE / 42) break; } System.out.println(); System.out.println("BigInteger:"); BigInteger n3 = BigInteger.ONE; BigInteger k = BigInteger.valueOf(1302); for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) { System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n", i, n3, n3, mssb_idx(n3), lssb_idx(n3)); } } }
package main import ( "fmt" "math/big" ) const ( mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota mask1, bit1 mask2, bit2 mask3, bit3 mask4, bit4 mask5, bit5 ) func rupb(x uint64) (out int) { if x == 0 { return -1 } if x&^mask5 != 0 { x >>= bit5 out |= bit5 } if x&^mask4 != 0 { x >>= bit4 out |= bit4 } if x&^mask3 != 0 { x >>= bit3 out |= bit3 } if x&^mask2 != 0 { x >>= bit2 out |= bit2 } if x&^mask1 != 0 { x >>= bit1 out |= bit1 } if x&^mask0 != 0 { out |= bit0 } return } func rlwb(x uint64) (out int) { if x == 0 { return 0 } if x&mask5 == 0 { x >>= bit5 out |= bit5 } if x&mask4 == 0 { x >>= bit4 out |= bit4 } if x&mask3 == 0 { x >>= bit3 out |= bit3 } if x&mask2 == 0 { x >>= bit2 out |= bit2 } if x&mask1 == 0 { x >>= bit1 out |= bit1 } if x&mask0 == 0 { out |= bit0 } return } func rupbBig(x *big.Int) int { return x.BitLen() - 1 } func rlwbBig(x *big.Int) int { if x.BitLen() < 2 { return 0 } bit := uint(1) mask := big.NewInt(1) var ms []*big.Int var y, z big.Int for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 { ms = append(ms, mask) mask = new(big.Int).Or(mask, &z) bit <<= 1 } out := bit for i := len(ms) - 1; i >= 0; i-- { bit >>= 1 if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 { out |= bit } } return int(out) } func main() { show() showBig() } func show() { fmt.Println("uint64:") fmt.Println("power number rupb rlwb") const base = 42 n := uint64(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n)) n *= base } } func showBig() { fmt.Println("\nbig numbers:") fmt.Println(" power number rupb rlwb") base := big.NewInt(1302) n := big.NewInt(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n)) n.Mul(n, base) } }
Change the programming language of this snippet from Java to Go without modifying what it does.
public class FirstLastBits { public static int mssb(int x) { return Integer.highestOneBit(x); } public static long mssb(long x) { return Long.highestOneBit(x); } public static int mssb_idx(int x) { return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x); } public static int mssb_idx(long x) { return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); } public static int mssb_idx(BigInteger x) { return x.bitLength() - 1; } public static int lssb(int x) { return Integer.lowestOneBit(x); } public static long lssb(long x) { return Long.lowestOneBit(x); } public static int lssb_idx(int x) { return Integer.numberOfTrailingZeros(x); } public static int lssb_idx(long x) { return Long.numberOfTrailingZeros(x); } public static int lssb_idx(BigInteger x) { return x.getLowestSetBit(); } public static void main(String[] args) { System.out.println("int:"); int n1 = 1; for (int i = 0; ; i++, n1 *= 42) { System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n1, n1, mssb(n1), mssb_idx(n1), lssb(n1), lssb_idx(n1)); if (n1 >= Integer.MAX_VALUE / 42) break; } System.out.println(); System.out.println("long:"); long n2 = 1; for (int i = 0; ; i++, n2 *= 42) { System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n", i, n2, n2, mssb(n2), mssb_idx(n2), lssb(n2), lssb_idx(n2)); if (n2 >= Long.MAX_VALUE / 42) break; } System.out.println(); System.out.println("BigInteger:"); BigInteger n3 = BigInteger.ONE; BigInteger k = BigInteger.valueOf(1302); for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) { System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n", i, n3, n3, mssb_idx(n3), lssb_idx(n3)); } } }
package main import ( "fmt" "math/big" ) const ( mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota mask1, bit1 mask2, bit2 mask3, bit3 mask4, bit4 mask5, bit5 ) func rupb(x uint64) (out int) { if x == 0 { return -1 } if x&^mask5 != 0 { x >>= bit5 out |= bit5 } if x&^mask4 != 0 { x >>= bit4 out |= bit4 } if x&^mask3 != 0 { x >>= bit3 out |= bit3 } if x&^mask2 != 0 { x >>= bit2 out |= bit2 } if x&^mask1 != 0 { x >>= bit1 out |= bit1 } if x&^mask0 != 0 { out |= bit0 } return } func rlwb(x uint64) (out int) { if x == 0 { return 0 } if x&mask5 == 0 { x >>= bit5 out |= bit5 } if x&mask4 == 0 { x >>= bit4 out |= bit4 } if x&mask3 == 0 { x >>= bit3 out |= bit3 } if x&mask2 == 0 { x >>= bit2 out |= bit2 } if x&mask1 == 0 { x >>= bit1 out |= bit1 } if x&mask0 == 0 { out |= bit0 } return } func rupbBig(x *big.Int) int { return x.BitLen() - 1 } func rlwbBig(x *big.Int) int { if x.BitLen() < 2 { return 0 } bit := uint(1) mask := big.NewInt(1) var ms []*big.Int var y, z big.Int for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 { ms = append(ms, mask) mask = new(big.Int).Or(mask, &z) bit <<= 1 } out := bit for i := len(ms) - 1; i >= 0; i-- { bit >>= 1 if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 { out |= bit } } return int(out) } func main() { show() showBig() } func show() { fmt.Println("uint64:") fmt.Println("power number rupb rlwb") const base = 42 n := uint64(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n)) n *= base } } func showBig() { fmt.Println("\nbig numbers:") fmt.Println(" power number rupb rlwb") base := big.NewInt(1302) n := big.NewInt(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n)) n.Mul(n, base) } }
Ensure the translated Go code behaves exactly like the original Java snippet.
public class EqualRisesFalls { public static void main(String[] args) { final int limit1 = 200; final int limit2 = 10000000; System.out.printf("The first %d numbers in the sequence are:\n", limit1); int n = 0; for (int count = 0; count < limit2; ) { if (equalRisesAndFalls(++n)) { ++count; if (count <= limit1) System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' '); } } System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n); } private static boolean equalRisesAndFalls(int n) { int total = 0; for (int previousDigit = -1; n > 0; n /= 10) { int digit = n % 10; if (previousDigit > digit) ++total; else if (previousDigit >= 0 && previousDigit < digit) --total; previousDigit = digit; } return total == 0; } }
package main import "fmt" func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { falls = falls + 1 } } prev = d n /= 10 } return rises == falls } func main() { fmt.Println("The first 200 numbers in the sequence are:") count := 0 n := 1 for { if risesEqualsFalls(n) { count++ if count <= 200 { fmt.Printf("%3d ", n) if count%20 == 0 { fmt.Println() } } if count == 1e7 { fmt.Println("\nThe 10 millionth number in the sequence is ", n) break } } n++ } }
Translate the given Java code snippet into Go without altering its behavior.
int l = 300; void setup() { size(400, 400); background(0, 0, 255); stroke(255); translate(width/2.0, height/2.0); translate(-l/2.0, l*sqrt(3)/6.0); for (int i = 1; i <= 3; i++) { kcurve(0, l); rotate(radians(120)); translate(-l, 0); } } void kcurve(float x1, float x2) { float s = (x2-x1)/3; if (s < 5) { pushMatrix(); translate(x1, 0); line(0, 0, s, 0); line(2*s, 0, 3*s, 0); translate(s, 0); rotate(radians(60)); line(0, 0, s, 0); translate(s, 0); rotate(radians(-120)); line(0, 0, s, 0); popMatrix(); return; } pushMatrix(); translate(x1, 0); kcurve(0, s); kcurve(2*s, 3*s); translate(s, 0); rotate(radians(60)); kcurve(0, s); translate(s, 0); rotate(radians(-120)); kcurve(0, s); popMatrix(); }
package main import ( "github.com/fogleman/gg" "math" ) var dc = gg.NewContext(512, 512) func koch(x1, y1, x2, y2 float64, iter int) { angle := math.Pi / 3 x3 := (x1*2 + x2) / 3 y3 := (y1*2 + y2) / 3 x4 := (x1 + x2*2) / 3 y4 := (y1 + y2*2) / 3 x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle) y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle) if iter > 0 { iter-- koch(x1, y1, x3, y3, iter) koch(x3, y3, x5, y5, iter) koch(x5, y5, x4, y4, iter) koch(x4, y4, x2, y2, iter) } else { dc.LineTo(x1, y1) dc.LineTo(x3, y3) dc.LineTo(x5, y5) dc.LineTo(x4, y4) dc.LineTo(x2, y2) } } func main() { dc.SetRGB(1, 1, 1) dc.Clear() koch(100, 100, 400, 400, 4) dc.SetRGB(0, 0, 1) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("koch.png") }
Convert this Java snippet to Go and keep its semantics consistent.
size(640,480); stroke(#ffff00); ellipse(random(640),random(480),1,1);
package main import ( "fmt" "image" "image/color" "image/draw" "math/rand" "time" ) func main() { rect := image.Rect(0, 0, 640, 480) img := image.NewRGBA(rect) blue := color.RGBA{0, 0, 255, 255} draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src) yellow := color.RGBA{255, 255, 0, 255} width := img.Bounds().Dx() height := img.Bounds().Dy() rand.Seed(time.Now().UnixNano()) x := rand.Intn(width) y := rand.Intn(height) img.Set(x, y, yellow) cmap := map[color.Color]string{blue: "blue", yellow: "yellow"} for i := 0; i < width; i++ { for j := 0; j < height; j++ { c := img.At(i, j) if cmap[c] == "yellow" { fmt.Printf("The color of the pixel at (%d, %d) is yellow\n", i, j) } } } }
Write a version of this Java function in Go with identical behavior.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class DrawAPixel extends JFrame{ public DrawAPixel() { super("Red Pixel"); setSize(320, 240); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void paint(Graphics g) { g.setColor(new Color(255, 0, 0)); g.drawRect(100, 100, 1, 1); } public static void main(String[] args) { new DrawAPixel(); } }
package main import ( "fmt" "image" "image/color" "image/draw" ) func main() { rect := image.Rect(0, 0, 320, 240) img := image.NewRGBA(rect) green := color.RGBA{0, 255, 0, 255} draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src) red := color.RGBA{255, 0, 0, 255} img.Set(100, 100, red) cmap := map[color.Color]string{green: "green", red: "red"} c1 := img.At(0, 0) c2 := img.At(100, 100) fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.") fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.") }
Translate the given Java code snippet into Go without altering its behavior.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class DrawAPixel extends JFrame{ public DrawAPixel() { super("Red Pixel"); setSize(320, 240); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void paint(Graphics g) { g.setColor(new Color(255, 0, 0)); g.drawRect(100, 100, 1, 1); } public static void main(String[] args) { new DrawAPixel(); } }
package main import ( "fmt" "image" "image/color" "image/draw" ) func main() { rect := image.Rect(0, 0, 320, 240) img := image.NewRGBA(rect) green := color.RGBA{0, 255, 0, 255} draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src) red := color.RGBA{255, 0, 0, 255} img.Set(100, 100, red) cmap := map[color.Color]string{green: "green", red: "red"} c1 := img.At(0, 0) c2 := img.At(100, 100) fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.") fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.") }
Convert this Java snippet to Go and keep its semantics consistent.
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { String line; while ((line = reader.readLine()) != null) { if (line.length() >= minLength) words.add(line); } } Collections.sort(words); String previousWord = null; int count = 0; for (int i = 0, n = words.size(); i + minLength <= n; ++i) { StringBuilder sb = new StringBuilder(minLength); for (int j = 0; j < minLength; ++j) sb.append(words.get(i + j).charAt(j)); String word = sb.toString(); if (word.equals(previousWord)) continue; if (Collections.binarySearch(words, word) >= 0) System.out.printf("%2d. %s\n", ++count, word); previousWord = word; } } catch (Exception e) { e.printStackTrace(); } } }
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) >= 9 { words = append(words, s) } } count := 0 var alreadyFound []string le := len(words) var sb strings.Builder for i := 0; i < le-9; i++ { sb.Reset() for j := i; j < i+9; j++ { sb.WriteByte(words[j][j-i]) } word := sb.String() ix := sort.SearchStrings(words, word) if ix < le && word == words[ix] { ix2 := sort.SearchStrings(alreadyFound, word) if ix2 == len(alreadyFound) { count++ fmt.Printf("%2d: %s\n", count, word) alreadyFound = append(alreadyFound, word) } } } }
Convert this Java block to Go, preserving its control flow and logic.
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
Write the same algorithm in Go as shown in this Java implementation.
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
public class MagicSquareSinglyEven { public static void main(String[] args) { int n = 6; for (int[] row : magicSquareSinglyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int n) { if (n < 3 || n % 2 == 0) throw new IllegalArgumentException("base must be odd and > 2"); int value = 0; int gridSize = n * n; int c = n / 2, r = 0; int[][] result = new int[n][n]; while (++value <= gridSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } static int[][] magicSquareSinglyEven(final int n) { if (n < 6 || (n - 2) % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4 plus 2"); int size = n * n; int halfN = n / 2; int subSquareSize = size / 4; int[][] subSquare = magicSquareOdd(halfN); int[] quadrantFactors = {0, 2, 3, 1}; int[][] result = new int[n][n]; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int quadrant = (r / halfN) * 2 + (c / halfN); result[r][c] = subSquare[r % halfN][c % halfN]; result[r][c] += quadrantFactors[quadrant] * subSquareSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } }
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for value <= gridSize { result[r][c] = value if r == 0 { if c == n-1 { r++ } else { r = n - 1 c++ } } else if c == n-1 { r-- c = 0 } else if result[r-1][c+1] == 0 { r-- c++ } else { r++ } value++ } return result, nil } func magicSquareSinglyEven(n int) ([][]int, error) { if n < 6 || (n-2)%4 != 0 { return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2") } size := n * n halfN := n / 2 subSquareSize := size / 4 subSquare, err := magicSquareOdd(halfN) if err != nil { return nil, err } quadrantFactors := [4]int{0, 2, 3, 1} result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for r := 0; r < n; r++ { for c := 0; c < n; c++ { quadrant := r/halfN*2 + c/halfN result[r][c] = subSquare[r%halfN][c%halfN] result[r][c] += quadrantFactors[quadrant] * subSquareSize } } nColsLeft := halfN / 2 nColsRight := nColsLeft - 1 for r := 0; r < halfN; r++ { for c := 0; c < n; c++ { if c < nColsLeft || c >= n-nColsRight || (c == nColsLeft && r == nColsLeft) { if c == 0 && r == nColsLeft { continue } tmp := result[r][c] result[r][c] = result[r+halfN][c] result[r+halfN][c] = tmp } } } return result, nil } func main() { const n = 6 msse, err := magicSquareSinglyEven(n) if err != nil { log.Fatal(err) } for _, row := range msse { for _, x := range row { fmt.Printf("%2d ", x) } fmt.Println() } fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2) }
Generate a Go translation of this Java snippet without changing its computational steps.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); return pieces; } private static boolean check(String rank){ if(!rank.matches(".*R.*K.*R.*")) return false; if(!rank.matches(".*B(..|....|......|)B.*")) return false; return true; } public static void main(String[] args){ for(int i = 0; i < 10; i++){ System.out.println(generateFirstRank()); } } }
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn"} func (sym symbols) chess960(id int) string { var pos [8]rune q, r := id/4, id%4 pos[r*2+1] = sym.b q, r = q/4, q%4 pos[r*2] = sym.b q, r = q/6, q%6 for i := 0; ; i++ { if pos[i] != 0 { continue } if r == 0 { pos[i] = sym.q break } r-- } i := 0 for _, f := range krn[q] { for pos[i] != 0 { i++ } switch f { case 'k': pos[i] = sym.k case 'r': pos[i] = sym.r case 'n': pos[i] = sym.n } } return string(pos[:]) } func main() { fmt.Println(" ID Start position") for _, id := range []int{0, 518, 959} { fmt.Printf("%3d %s\n", id, A.chess960(id)) } fmt.Println("\nRandom") for i := 0; i < 5; i++ { fmt.Println(W.chess960(rand.Intn(960))) } }
Port the following code from Java to Go with equivalent syntax and logic.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Convert this Java snippet to Go and keep its semantics consistent.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Translate this program into Go but keep the logic exactly as in Java.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Write a version of this Java function in Go with identical behavior.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Port the provided Java code into Go while preserving the original functionality.
public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255, Z = (int)Math.floor(z) & 255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } static double lerp(double t, double a, double b) { return a + t * (b - a); } static double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } }
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fade(x) v := fade(y) w := fade(z) A := p[X] + Y AA := p[A] + Z AB := p[A+1] + Z B := p[X+1] + Y BA := p[B] + Z BB := p[B+1] + Z return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x-1, y, z)), lerp(u, grad(p[AB], x, y-1, z), grad(p[BB], x-1, y-1, z))), lerp(v, lerp(u, grad(p[AA+1], x, y, z-1), grad(p[BA+1], x-1, y, z-1)), lerp(u, grad(p[AB+1], x, y-1, z-1), grad(p[BB+1], x-1, y-1, z-1)))) } func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) } func lerp(t, a, b float64) float64 { return a + t*(b-a) } func grad(hash int, x, y, z float64) float64 { switch hash & 15 { case 0, 12: return x + y case 1, 14: return y - x case 2: return x - y case 3: return -x - y case 4: return x + z case 5: return z - x case 6: return x - z case 7: return -x - z case 8: return y + z case 9, 13: return z - y case 10: return y - z } return -y - z } var permutation = []int{ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, } var p = append(permutation, permutation...)
Generate an equivalent Go version of this Java code.
package rosetta; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class UnixLS { public static void main(String[] args) throws IOException { Files.list(Path.of("")).sorted().forEach(System.out::println); } }
package main import ( "fmt" "log" "os" "sort" ) func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
Change the following Java code into Go without altering its purpose.
import java.nio.charset.StandardCharsets; import java.util.Formatter; public class UTF8EncodeDecode { public static byte[] utf8encode(int codepoint) { return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8); } public static int utf8decode(byte[] bytes) { return new String(bytes, StandardCharsets.UTF_8).codePointAt(0); } public static void main(String[] args) { System.out.printf("%-7s %-43s %7s\t%s\t%7s%n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded"); for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] encoded = utf8encode(codepoint); Formatter formatter = new Formatter(); for (byte b : encoded) { formatter.format("%02X ", b); } String encodedHex = formatter.toString(); int decoded = utf8decode(encoded); System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n", codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded); } } }
package main import ( "bytes" "encoding/hex" "fmt" "log" "strings" ) var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, } func main() { for _, tc := range testCases { u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } e := encodeUTF8(tc.rune) d := decodeUTF8(b) fmt.Printf("%c  %-7s %X\n", d, u, e) if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } } const ( b2Lead = 0xC0 b2Mask = 0x1F b3Lead = 0xE0 b3Mask = 0x0F b4Lead = 0xF0 b4Mask = 0x07 mbLead = 0x80 mbMask = 0x3F ) func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: return []byte{byte(r)} case i <= 1<<11-1: return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } } func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
Produce a functionally identical Go code for the snippet given in Java.
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c) { g.setColor(new Color(0f, 0f, 0f, (float)c)); g.fillOval((int) x, (int) y, 2, 2); } int ipart(double x) { return (int) x; } double fpart(double x) { return x - floor(x); } double rfpart(double x) { return 1.0 - fpart(x); } void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) { boolean steep = abs(y1 - y0) > abs(x1 - x0); if (steep) drawLine(g, y0, x0, y1, x1); if (x0 > x1) drawLine(g, x1, y1, x0, y0); double dx = x1 - x0; double dy = y1 - y0; double gradient = dy / dx; double xend = round(x0); double yend = y0 + gradient * (xend - x0); double xgap = rfpart(x0 + 0.5); double xpxl1 = xend; double ypxl1 = ipart(yend); if (steep) { plot(g, ypxl1, xpxl1, rfpart(yend) * xgap); plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap); } else { plot(g, xpxl1, ypxl1, rfpart(yend) * xgap); plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap); } double intery = yend + gradient; xend = round(x1); yend = y1 + gradient * (xend - x1); xgap = fpart(x1 + 0.5); double xpxl2 = xend; double ypxl2 = ipart(yend); if (steep) { plot(g, ypxl2, xpxl2, rfpart(yend) * xgap); plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap); } else { plot(g, xpxl2, ypxl2, rfpart(yend) * xgap); plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap); } for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) { if (steep) { plot(g, ipart(intery), x, rfpart(intery)); plot(g, ipart(intery) + 1, x, fpart(intery)); } else { plot(g, x, ipart(intery), rfpart(intery)); plot(g, x, ipart(intery) + 1, fpart(intery)); } intery = intery + gradient; } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; drawLine(g, 550, 170, 50, 435); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Xiaolin Wu's line algorithm"); f.setResizable(false); f.add(new XiaolinWu(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) } func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { dx := x2 - x1 dy := y2 - y1 ax := dx if ax < 0 { ax = -ax } ay := dy if ay < 0 { ay = -ay } var plot func(int, int, float64) if ax < ay { x1, y1 = y1, x1 x2, y2 = y2, x2 dx, dy = dy, dx plot = func(x, y int, c float64) { g.SetPx(y, x, uint16(c*math.MaxUint16)) } } else { plot = func(x, y int, c float64) { g.SetPx(x, y, uint16(c*math.MaxUint16)) } } if x2 < x1 { x1, x2 = x2, x1 y1, y2 = y2, y1 } gradient := dy / dx xend := round(x1) yend := y1 + gradient*(xend-x1) xgap := rfpart(x1 + .5) xpxl1 := int(xend) ypxl1 := int(ipart(yend)) plot(xpxl1, ypxl1, rfpart(yend)*xgap) plot(xpxl1, ypxl1+1, fpart(yend)*xgap) intery := yend + gradient xend = round(x2) yend = y2 + gradient*(xend-x2) xgap = fpart(x2 + 0.5) xpxl2 := int(xend) ypxl2 := int(ipart(yend)) plot(xpxl2, ypxl2, rfpart(yend)*xgap) plot(xpxl2, ypxl2+1, fpart(yend)*xgap) for x := xpxl1 + 1; x <= xpxl2-1; x++ { plot(x, int(ipart(intery)), rfpart(intery)) plot(x, int(ipart(intery))+1, fpart(intery)) intery = intery + gradient } }
Produce a language-to-language conversion: from Java to Go, same semantics.
package keybord.macro.demo; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; class KeyboardMacroDemo { public static void main( String [] args ) { final JFrame frame = new JFrame(); String directions = "<html><b>Ctrl-S</b> to show frame title<br>" +"<b>Ctrl-H</b> to hide it</html>"; frame.add( new JLabel(directions)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener( new KeyAdapter(){ public void keyReleased( KeyEvent e ) { if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){ frame.setTitle("Hello there"); }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){ frame.setTitle(""); } } }); frame.pack(); frame.setVisible(true); } }
package main import "C" import "fmt" import "unsafe" func main() { d := C.XOpenDisplay(nil) f7, f6 := C.CString("F7"), C.CString("F6") defer C.free(unsafe.Pointer(f7)) defer C.free(unsafe.Pointer(f6)) if d != nil { C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) var event C.XEvent for { C.XNextEvent(d, &event) if C.getXEvent_type(event) == C.KeyPress { xkeyEvent := C.getXEvent_xkey(event) s := C.XLookupKeysym(&xkeyEvent, 0) if s == C.XK_F7 { fmt.Println("something's happened") } else if s == C.XK_F6 { break } } } C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) } else { fmt.Println("XOpenDisplay did not succeed") } }
Generate a Go translation of this Java snippet without changing its computational steps.
public class McNuggets { public static void main(String... args) { int[] SIZES = new int[] { 6, 9, 20 }; int MAX_TOTAL = 100; int numSizes = SIZES.length; int[] counts = new int[numSizes]; int maxFound = MAX_TOTAL + 1; boolean[] found = new boolean[maxFound]; int numFound = 0; int total = 0; boolean advancedState = false; do { if (!found[total]) { found[total] = true; numFound++; } advancedState = false; for (int i = 0; i < numSizes; i++) { int curSize = SIZES[i]; if ((total + curSize) > MAX_TOTAL) { total -= counts[i] * curSize; counts[i] = 0; } else { counts[i]++; total += curSize; advancedState = true; break; } } } while ((numFound < maxFound) && advancedState); if (numFound < maxFound) { for (int i = MAX_TOTAL; i >= 0; i--) { if (!found[i]) { System.out.println("Largest non-McNugget number in the search space is " + i); break; } } } else { System.out.println("All numbers in the search space are McNugget numbers"); } return; } }
package main import "fmt" func mcnugget(limit int) { sv := make([]bool, limit+1) for s := 0; s <= limit; s += 6 { for n := s; n <= limit; n += 9 { for t := n; t <= limit; t += 20 { sv[t] = true } } } for i := limit; i >= 0; i-- { if !sv[i] { fmt.Println("Maximum non-McNuggets number is", i) return } } } func main() { mcnugget(100) }
Convert this Java block to Go, preserving its control flow and logic.
public class MagicSquareDoublyEven { public static void main(String[] args) { int n = 8; for (int[] row : magicSquareDoublyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } static int[][] magicSquareDoublyEven(final int n) { if (n < 4 || n % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[][] result = new int[n][n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } }
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
Keep all operations the same but rewrite the snippet in Go.
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; double inf = 1.0 / 0.0; double nan = 0.0 / 0.0; double negZero = -2.0 / inf; System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == nan)); } }
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Convert the following code from Java to Go, ensuring the logic remains intact.
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; double inf = 1.0 / 0.0; double nan = 0.0 / 0.0; double negZero = -2.0 / inf; System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == nan)); } }
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Write the same code in Go as shown below in Java.
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; double inf = 1.0 / 0.0; double nan = 0.0 / 0.0; double negZero = -2.0 / inf; System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == nan)); } }
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Translate the given Java code snippet into Go without altering its behavior.
public class XorShiftStar { private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16); private long state; public void seed(long num) { state = num; } public int nextInt() { long x; int answer; x = state; x = x ^ (x >>> 12); x = x ^ (x << 25); x = x ^ (x >>> 27); state = x; answer = (int) ((x * MAGIC) >> 32); return answer; } public float nextFloat() { return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32); } public static void main(String[] args) { var rng = new XorShiftStar(); rng.seed(1234567); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; rng.seed(987654321); for (int i = 0; i < 100_000; i++) { int j = (int) Math.floor(rng.nextFloat() * 5.0); counts[j]++; } for (int i = 0; i < counts.length; i++) { System.out.printf("%d: %d\n", i, counts[i]); } } }
package main import ( "fmt" "math" ) const CONST = 0x2545F4914F6CDD1D type XorshiftStar struct{ state uint64 } func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} } func (xor *XorshiftStar) seed(state uint64) { xor.state = state } func (xor *XorshiftStar) nextInt() uint32 { x := xor.state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) xor.state = x return uint32((x * CONST) >> 32) } func (xor *XorshiftStar) nextFloat() float64 { return float64(xor.nextInt()) / (1 << 32) } func main() { randomGen := XorshiftStarNew(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.HashMap; import java.util.Map; public class FourIsTheNumberOfLetters { public static void main(String[] args) { String [] words = neverEndingSentence(201); System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1); for ( int i = 0 ; i < words.length ; i++ ) { System.out.printf("%2d ", numberOfLetters(words[i])); if ( (i+1) % 25 == 0 ) { System.out.printf("%n%3d: ", i+2); } } System.out.printf("%nTotal number of characters in the sentence is %d%n", characterCount(words)); for ( int i = 3 ; i <= 7 ; i++ ) { int index = (int) Math.pow(10, i); words = neverEndingSentence(index); String last = words[words.length-1].replace(",", ""); System.out.printf("Number of letters of the %s word is %d. The word is \"%s\". The sentence length is %,d characters.%n", toOrdinal(index), numberOfLetters(last), last, characterCount(words)); } } @SuppressWarnings("unused") private static void displaySentence(String[] words, int lineLength) { int currentLength = 0; for ( String word : words ) { if ( word.length() + currentLength > lineLength ) { String first = word.substring(0, lineLength-currentLength); String second = word.substring(lineLength-currentLength); System.out.println(first); System.out.print(second); currentLength = second.length(); } else { System.out.print(word); currentLength += word.length(); } if ( currentLength == lineLength ) { System.out.println(); currentLength = 0; } System.out.print(" "); currentLength++; if ( currentLength == lineLength ) { System.out.println(); currentLength = 0; } } System.out.println(); } private static int numberOfLetters(String word) { return word.replace(",","").replace("-","").length(); } private static long characterCount(String[] words) { int characterCount = 0; for ( int i = 0 ; i < words.length ; i++ ) { characterCount += words[i].length() + 1; } characterCount--; return characterCount; } private static String[] startSentence = new String[] {"Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,"}; private static String[] neverEndingSentence(int wordCount) { String[] words = new String[wordCount]; int index; for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) { words[index] = startSentence[index]; } int sentencePosition = 1; while ( index < wordCount ) { sentencePosition++; String word = words[sentencePosition-1]; for ( String wordLoop : numToString(numberOfLetters(word)).split(" ") ) { words[index] = wordLoop; index++; if ( index == wordCount ) { break; } } words[index] = "in"; index++; if ( index == wordCount ) { break; } words[index] = "the"; index++; if ( index == wordCount ) { break; } for ( String wordLoop : (toOrdinal(sentencePosition) + ",").split(" ") ) { words[index] = wordLoop; index++; if ( index == wordCount ) { break; } } } return words; } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String numToString(long n) { return numToStringHelper(n); } private static final String numToStringHelper(long n) { if ( n < 0 ) { return "negative " + numToStringHelper(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : ""); } private static Map<String,String> ordinalMap = new HashMap<>(); static { ordinalMap.put("one", "first"); ordinalMap.put("two", "second"); ordinalMap.put("three", "third"); ordinalMap.put("five", "fifth"); ordinalMap.put("eight", "eighth"); ordinalMap.put("nine", "ninth"); ordinalMap.put("twelve", "twelfth"); } private static String toOrdinal(long n) { String spelling = numToString(n); String[] split = spelling.split(" "); String last = split[split.length - 1]; String replace = ""; if ( last.contains("-") ) { String[] lastSplit = last.split("-"); String lastWithDash = lastSplit[1]; String lastReplace = ""; if ( ordinalMap.containsKey(lastWithDash) ) { lastReplace = ordinalMap.get(lastWithDash); } else if ( lastWithDash.endsWith("y") ) { lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth"; } else { lastReplace = lastWithDash + "th"; } replace = lastSplit[0] + "-" + lastReplace; } else { if ( ordinalMap.containsKey(last) ) { replace = ordinalMap.get(last); } else if ( last.endsWith("y") ) { replace = last.substring(0, last.length() - 1) + "ieth"; } else { replace = last + "th"; } } split[split.length - 1] = replace; return String.join(" ", split); } }
package main import ( "fmt" "strings" "unicode" ) func main() { f := NewFourIsSeq() fmt.Print("The lengths of the first 201 words are:") for i := 1; i <= 201; i++ { if i%25 == 1 { fmt.Printf("\n%3d: ", i) } _, n := f.WordLen(i) fmt.Printf(" %2d", n) } fmt.Println() fmt.Println("Length of sentence so far:", f.TotalLength()) for i := 1000; i <= 1e7; i *= 10 { w, n := f.WordLen(i) fmt.Printf("Word %8d is %q, with %d letters.", i, w, n) fmt.Println(" Length of sentence so far:", f.TotalLength()) } } type FourIsSeq struct { i int words []string } func NewFourIsSeq() *FourIsSeq { return &FourIsSeq{ words: []string{ "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,", }, } } func (f *FourIsSeq) WordLen(w int) (string, int) { for len(f.words) < w { f.i++ n := countLetters(f.words[f.i]) ns := say(int64(n)) os := sayOrdinal(int64(f.i+1)) + "," f.words = append(f.words, strings.Fields(ns)...) f.words = append(f.words, "in", "the") f.words = append(f.words, strings.Fields(os)...) } word := f.words[w-1] return word, countLetters(word) } func (f FourIsSeq) TotalLength() int { cnt := 0 for _, w := range f.words { cnt += len(w) + 1 } return cnt - 1 } func countLetters(s string) int { cnt := 0 for _, r := range s { if unicode.IsLetter(r) { cnt++ } } return cnt }
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.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| QDCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ANCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| NSCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ARCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; public static void main(String[] args) { validate(TEST); display(TEST); Map<String,List<Integer>> asciiMap = decode(TEST); displayMap(asciiMap); displayCode(asciiMap, "78477bbf5496e12e1bf169a4"); } private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) { System.out.printf("%nTest string in hex:%n%s%n%n", hex); String bin = new BigInteger(hex,16).toString(2); int length = 0; for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); length += pos.get(1) - pos.get(0) + 1; } while ( length > bin.length() ) { bin = "0" + bin; } System.out.printf("Test string in binary:%n%s%n%n", bin); System.out.printf("Name Size Bit Pattern%n"); System.out.printf("-------- ----- -----------%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); int start = pos.get(0); int end = pos.get(1); System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1)); } } private static void display(String ascii) { System.out.printf("%nDiagram:%n%n"); for ( String s : TEST.split("\\r\\n") ) { System.out.println(s); } } private static void displayMap(Map<String,List<Integer>> asciiMap) { System.out.printf("%nDecode:%n%n"); System.out.printf("Name Size Start End%n"); System.out.printf("-------- ----- ----- -----%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1)); } } private static Map<String,List<Integer>> decode(String ascii) { Map<String,List<Integer>> map = new LinkedHashMap<>(); String[] split = TEST.split("\\r\\n"); int size = split[0].indexOf("+", 1) - split[0].indexOf("+"); int length = split[0].length() - 1; for ( int i = 1 ; i < split.length ; i += 2 ) { int barIndex = 1; String test = split[i]; int next; while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) { List<Integer> startEnd = new ArrayList<>(); startEnd.add((barIndex/size) + (i/2)*(length/size)); startEnd.add(((next-1)/size) + (i/2)*(length/size)); String code = test.substring(barIndex, next).replace(" ", ""); map.put(code, startEnd); barIndex = next + 1; } } return map; } private static void validate(String ascii) { String[] split = TEST.split("\\r\\n"); if ( split.length % 2 != 1 ) { throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length); } int size = 0; for ( int i = 0 ; i < split.length ; i++ ) { String test = split[i]; if ( i % 2 == 0 ) { if ( ! test.matches("^\\+([-]+\\+)+$") ) { throw new RuntimeException("ERROR 2: Improper line format. Line = " + test); } if ( size == 0 ) { int firstPlus = test.indexOf("+"); int secondPlus = test.indexOf("+", 1); size = secondPlus - firstPlus; } if ( ((test.length()-1) % size) != 0 ) { throw new RuntimeException("ERROR 3: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { if ( test.charAt(j) != '+' ) { throw new RuntimeException("ERROR 4: Improper line format. Line = " + test); } for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) != '-' ) { throw new RuntimeException("ERROR 5: Improper line format. Line = " + test); } } } } else { if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) { throw new RuntimeException("ERROR 6: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) == '|' ) { throw new RuntimeException("ERROR 7: Improper line format. Line = " + test); } } } } } } }
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { var lines []string for _, line := range strings.Split(diagram, "\n") { line = strings.Trim(line, " \t") if line != "" { lines = append(lines, line) } } if len(lines) == 0 { log.Fatal("diagram has no non-empty lines!") } width := len(lines[0]) cols := (width - 1) / 3 if cols != 8 && cols != 16 && cols != 32 && cols != 64 { log.Fatal("number of columns should be 8, 16, 32 or 64") } if len(lines)%2 == 0 { log.Fatal("number of non-empty lines should be odd") } if lines[0] != strings.Repeat("+--", cols)+"+" { log.Fatal("incorrect header line") } for i, line := range lines { if i == 0 { continue } else if i%2 == 0 { if line != lines[0] { log.Fatal("incorrect separator line") } } else if len(line) != width { log.Fatal("inconsistent line widths") } else if line[0] != '|' || line[width-1] != '|' { log.Fatal("non-separator lines must begin and end with '|'") } } return lines } func decode(lines []string) []result { fmt.Println("Name Bits Start End") fmt.Println("======= ==== ===== ===") start := 0 width := len(lines[0]) var results []result for i, line := range lines { if i%2 == 0 { continue } line := line[1 : width-1] for _, name := range strings.Split(line, "|") { size := (len(name) + 1) / 3 name = strings.TrimSpace(name) res := result{name, size, start, start + size - 1} results = append(results, res) fmt.Println(res) start += size } } return results } func unpack(results []result, hex string) { fmt.Println("\nTest string in hex:") fmt.Println(hex) fmt.Println("\nTest string in binary:") bin := hex2bin(hex) fmt.Println(bin) fmt.Println("\nUnpacked:\n") fmt.Println("Name Size Bit pattern") fmt.Println("======= ==== ================") for _, res := range results { fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1]) } } func hex2bin(hex string) string { z := new(big.Int) z.SetString(hex, 16) return fmt.Sprintf("%0*b", 4*len(hex), z) } func main() { const diagram = ` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ` lines := validate(diagram) fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n") for _, line := range lines { fmt.Println(line) } fmt.Println("\nDecoded:\n") results := decode(lines) hex := "78477bbf5496e12e1bf169a4" unpack(results, hex) }
Change the following Java code into Go without altering its purpose.
public class LevenshteinAlignment { public static String[] alignment(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); int[][] costs = new int[a.length()+1][b.length()+1]; for (int j = 0; j <= b.length(); j++) costs[0][j] = j; for (int i = 1; i <= a.length(); i++) { costs[i][0] = i; for (int j = 1; j <= b.length(); j++) { costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1); } } StringBuilder aPathRev = new StringBuilder(); StringBuilder bPathRev = new StringBuilder(); for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) { if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) { aPathRev.append(a.charAt(--i)); bPathRev.append(b.charAt(--j)); } else if (costs[i][j] == 1 + costs[i-1][j]) { aPathRev.append(a.charAt(--i)); bPathRev.append('-'); } else if (costs[i][j] == 1 + costs[i][j-1]) { aPathRev.append('-'); bPathRev.append(b.charAt(--j)); } } return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()}; } public static void main(String[] args) { String[] result = alignment("rosettacode", "raisethysword"); System.out.println(result[0]); System.out.println(result[1]); } }
package main import ( "fmt" "github.com/biogo/biogo/align" ab "github.com/biogo/biogo/alphabet" "github.com/biogo/biogo/feat" "github.com/biogo/biogo/seq/linear" ) func main() { lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz", feat.Undefined, '-', 0, true)) nw := make(align.NW, lc.Len()) for i := range nw { r := make([]int, lc.Len()) nw[i] = r for j := range r { if j != i { r[j] = -1 } } } a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))} a.Alpha = lc b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))} b.Alpha = lc aln, err := nw.Align(a, b) if err != nil { fmt.Println(err) return } fa := align.Format(a, b, aln, '-') fmt.Printf("%s\n%s\n", fa[0], fa[1]) aa := fmt.Sprint(fa[0]) ba := fmt.Sprint(fa[1]) ma := make([]byte, len(aa)) for i := range ma { if aa[i] == ba[i] { ma[i] = ' ' } else { ma[i] = '|' } } fmt.Println(string(ma)) }
Convert this Java block to Go, preserving its control flow and logic.
import java.util.*; class SameFringe { public interface Node<T extends Comparable<? super T>> { Node<T> getLeft(); Node<T> getRight(); boolean isLeaf(); T getData(); } public static class SimpleNode<T extends Comparable<? super T>> implements Node<T> { private final T data; public SimpleNode<T> left; public SimpleNode<T> right; public SimpleNode(T data) { this(data, null, null); } public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right) { this.data = data; this.left = left; this.right = right; } public Node<T> getLeft() { return left; } public Node<T> getRight() { return right; } public boolean isLeaf() { return ((left == null) && (right == null)); } public T getData() { return data; } public SimpleNode<T> addToTree(T data) { int cmp = data.compareTo(this.data); if (cmp == 0) throw new IllegalArgumentException("Same data!"); if (cmp < 0) { if (left == null) return (left = new SimpleNode<T>(data)); return left.addToTree(data); } if (right == null) return (right = new SimpleNode<T>(data)); return right.addToTree(data); } } public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2) { Stack<Node<T>> stack1 = new Stack<Node<T>>(); Stack<Node<T>> stack2 = new Stack<Node<T>>(); stack1.push(node1); stack2.push(node2); while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null)) if (!node1.getData().equals(node2.getData())) return false; return (node1 == null) && (node2 == null); } private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack) { while (!stack.isEmpty()) { Node<T> node = stack.pop(); if (node.isLeaf()) return node; Node<T> rightNode = node.getRight(); if (rightNode != null) stack.push(rightNode); Node<T> leftNode = node.getLeft(); if (leftNode != null) stack.push(leftNode); } return null; } public static void main(String[] args) { SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50))); SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null)))); SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56))))); System.out.print("Leaves for set 1: "); simpleWalk(headNode1); System.out.println(); System.out.print("Leaves for set 2: "); simpleWalk(headNode2); System.out.println(); System.out.print("Leaves for set 3: "); simpleWalk(headNode3); System.out.println(); System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2)); System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3)); } public static void simpleWalk(Node<Integer> node) { if (node.isLeaf()) System.out.print(node.getData() + " "); else { Node<Integer> left = node.getLeft(); if (left != null) simpleWalk(left); Node<Integer> right = node.getRight(); if (right != null) simpleWalk(right); } } }
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
Preserve the algorithm and functionality while converting the code from Java to Go.
import java.awt.Robot public static void type(String str){ Robot robot = new Robot(); for(char ch:str.toCharArray()){ if(Character.isUpperCase(ch)){ robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress((int)ch); robot.keyRelease((int)ch); robot.keyRelease(KeyEvent.VK_SHIFT); }else{ char upCh = Character.toUpperCase(ch); robot.keyPress((int)upCh); robot.keyRelease((int)upCh); } } }
package main import ( "github.com/micmonay/keybd_event" "log" "runtime" "time" ) func main() { kb, err := keybd_event.NewKeyBonding() if err != nil { log.Fatal(err) } if runtime.GOOS == "linux" { time.Sleep(2 * time.Second) } kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER) err = kb.Launching() if err != nil { log.Fatal(err) } }
Write a version of this Java function in Go with identical behavior.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Peaceful { enum Piece { Empty, Black, White, } public static class Position { public int x, y; public Position(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj instanceof Position) { Position pos = (Position) obj; return pos.x == x && pos.y == y; } return false; } } private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } boolean placingBlack = true; for (int i = 0; i < n; ++i) { inner: for (int j = 0; j < n; ++j) { Position pos = new Position(i, j); for (Position queen : pBlackQueens) { if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) { continue inner; } } for (Position queen : pWhiteQueens) { if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) { continue inner; } } if (placingBlack) { pBlackQueens.add(pos); placingBlack = false; } else { pWhiteQueens.add(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.remove(pBlackQueens.size() - 1); pWhiteQueens.remove(pWhiteQueens.size() - 1); placingBlack = true; } } } if (!placingBlack) { pBlackQueens.remove(pBlackQueens.size() - 1); } return false; } private static boolean isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y); } private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { Piece[] board = new Piece[n * n]; Arrays.fill(board, Piece.Empty); for (Position queen : blackQueens) { board[queen.x + n * queen.y] = Piece.Black; } for (Position queen : whiteQueens) { board[queen.x + n * queen.y] = Piece.White; } for (int i = 0; i < board.length; ++i) { if ((i != 0) && i % n == 0) { System.out.println(); } Piece b = board[i]; if (b == Piece.Black) { System.out.print("B "); } else if (b == Piece.White) { System.out.print("W "); } else { int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { System.out.print("• "); } else { System.out.print("◦ "); } } } System.out.println('\n'); } public static void main(String[] args) { List<Position> nms = List.of( new Position(2, 1), new Position(3, 1), new Position(3, 2), new Position(4, 1), new Position(4, 2), new Position(4, 3), new Position(5, 1), new Position(5, 2), new Position(5, 3), new Position(5, 4), new Position(5, 5), new Position(6, 1), new Position(6, 2), new Position(6, 3), new Position(6, 4), new Position(6, 5), new Position(6, 6), new Position(7, 1), new Position(7, 2), new Position(7, 3), new Position(7, 4), new Position(7, 5), new Position(7, 6), new Position(7, 7) ); for (Position nm : nms) { int m = nm.y; int n = nm.x; System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n); List<Position> blackQueens = new ArrayList<>(); List<Position> whiteQueens = new ArrayList<>(); if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens); } else { System.out.println("No solution exists.\n"); } } } }
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false } func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false } func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white } for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") } func main() { nms := [][2]int{ {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, } for _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.Println("No solution exists.\n") } } }
Generate a Go translation of this Java snippet without changing its computational steps.
while (true) { System.out.println("SPAM"); }
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
Write a version of this Java function in Go with identical behavior.
import java.util.LinkedList; import java.util.List; public class MTF{ public static List<Integer> encode(String msg, String symTable){ List<Integer> output = new LinkedList<Integer>(); StringBuilder s = new StringBuilder(symTable); for(char c : msg.toCharArray()){ int idx = s.indexOf("" + c); output.add(idx); s = s.deleteCharAt(idx).insert(0, c); } return output; } public static String decode(List<Integer> idxs, String symTable){ StringBuilder output = new StringBuilder(); StringBuilder s = new StringBuilder(symTable); for(int idx : idxs){ char c = s.charAt(idx); output = output.append(c); s = s.deleteCharAt(idx).insert(0, c); } return output.toString(); } private static void test(String toEncode, String symTable){ List<Integer> encoded = encode(toEncode, symTable); System.out.println(toEncode + ": " + encoded); String decoded = decode(encoded, symTable); System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded); } public static void main(String[] args){ String symTable = "abcdefghijklmnopqrstuvwxyz"; test("broood", symTable); test("bananaaa", symTable); test("hiphophiphop", symTable); } }
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
Write a version of this Java function in Go with identical behavior.
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapSearchDemo { public static void main(String[] args) throws IOException, LdapException, CursorException { new LdapSearchDemo().demonstrateSearch(); } private void demonstrateSearch() throws IOException, LdapException, CursorException { try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) { conn.bind("uid=admin,ou=system", "********"); search(conn, "*mil*"); conn.unBind(); } } private void search(LdapConnection connection, String uid) throws LdapException, CursorException { String baseDn = "ou=users,o=mojo"; String filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; SearchScope scope = SearchScope.SUBTREE; String[] attributes = {"dn", "cn", "sn", "uid"}; int ksearch = 0; EntryCursor cursor = connection.search(baseDn, filter, scope, attributes); while (cursor.next()) { ksearch++; Entry entry = cursor.get(); System.out.printf("Search entry %d = %s%n", ksearch, entry); } } }
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, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } groups, err := client.GetGroupsOfUser("username") if err != nil { log.Fatalf("Error getting groups for user %s: %+v", "username", err) } log.Printf("Groups: %+v", groups) }
Keep all operations the same but rewrite the snippet in Go.
import Jama.Matrix; public class SingularValueDecomposition { public static void main(String[] args) { double[][] matrixArray = {{3, 0}, {4, 5}}; var matrix = new Matrix(matrixArray); var svd = matrix.svd(); svd.getU().print(0, 10); svd.getS().print(0, 10); svd.getV().print(0, 10); } }
<package main import ( "fmt" "gonum.org/v1/gonum/mat" "log" ) func matPrint(m mat.Matrix) { fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze()) fmt.Printf("%13.10f\n", fa) } func main() { var svd mat.SVD a := mat.NewDense(2, 2, []float64{3, 0, 4, 5}) ok := svd.Factorize(a, mat.SVDFull) if !ok { log.Fatal("Something went wrong!") } u := mat.NewDense(2, 2, nil) svd.UTo(u) fmt.Println("U:") matPrint(u) values := svd.Values(nil) sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]}) fmt.Println("\nΣ:") matPrint(sigma) vt := mat.NewDense(2, 2, nil) svd.VTo(vt) fmt.Println("\nVT:") matPrint(vt) }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.math.BigDecimal; import java.util.List; public class TestIntegerness { private static boolean isLong(double d) { return isLong(d, 0.0); } private static boolean isLong(double d, double tolerance) { return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance; } @SuppressWarnings("ResultOfMethodCallIgnored") private static boolean isBigInteger(BigDecimal bd) { try { bd.toBigIntegerExact(); return true; } catch (ArithmeticException ex) { return false; } } private static class Rational { long num; long denom; Rational(int num, int denom) { this.num = num; this.denom = denom; } boolean isLong() { return num % denom == 0; } @Override public String toString() { return String.format("%s/%s", num, denom); } } private static class Complex { double real; double imag; Complex(double real, double imag) { this.real = real; this.imag = imag; } boolean isLong() { return TestIntegerness.isLong(real) && imag == 0.0; } @Override public String toString() { if (imag >= 0.0) { return String.format("%s + %si", real, imag); } return String.format("%s - %si", real, imag); } } public static void main(String[] args) { List<Double> da = List.of(25.000000, 24.999999, 25.000100); for (Double d : da) { boolean exact = isLong(d); System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an"); } System.out.println(); double tolerance = 0.00001; System.out.printf("With a tolerance of %.5f:%n", tolerance); for (Double d : da) { boolean fuzzy = isLong(d, tolerance); System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an"); } System.out.println(); List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY); for (Double f : fa) { boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString())); System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an"); } System.out.println(); List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0)); for (Complex c : ca) { boolean exact = c.isLong(); System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an"); } System.out.println(); List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2)); for (Rational r : ra) { boolean exact = r.isLong(); System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an"); } } }
package main import ( "fmt" "math" "math/big" "reflect" "strings" "unsafe" ) func Float64IsInt(f float64) bool { _, frac := math.Modf(f) return frac == 0 } func Float32IsInt(f float32) bool { return Float64IsInt(float64(f)) } func Complex128IsInt(c complex128) bool { return imag(c) == 0 && Float64IsInt(real(c)) } func Complex64IsInt(c complex64) bool { return imag(c) == 0 && Float64IsInt(float64(real(c))) } type hasIsInt interface { IsInt() bool } var bigIntT = reflect.TypeOf((*big.Int)(nil)) func IsInt(i interface{}) bool { if ci, ok := i.(hasIsInt); ok { return ci.IsInt() } switch v := reflect.ValueOf(i); v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return true case reflect.Float32, reflect.Float64: return Float64IsInt(v.Float()) case reflect.Complex64, reflect.Complex128: return Complex128IsInt(v.Complex()) case reflect.String: if r, ok := new(big.Rat).SetString(v.String()); ok { return r.IsInt() } case reflect.Ptr: if v.Type() == bigIntT { return true } } return false } type intbased int16 type complexbased complex64 type customIntegerType struct { } func (customIntegerType) IsInt() bool { return true } func (customIntegerType) String() string { return "<…>" } func main() { hdr := fmt.Sprintf("%27s  %-6s %s\n", "Input", "IsInt", "Type") show2 := func(t bool, i interface{}, args ...interface{}) { istr := fmt.Sprint(i) fmt.Printf("%27s  %-6t %T ", istr, t, i) fmt.Println(args...) } show := func(i interface{}, args ...interface{}) { show2(IsInt(i), i, args...) } fmt.Print("Using Float64IsInt with float64:\n", hdr) neg1 := -1. for _, f := range []float64{ 0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3, math.Pi, math.MinInt64, math.MaxUint64, math.SmallestNonzeroFloat64, math.MaxFloat64, math.NaN(), math.Inf(1), math.Inf(-1), } { show2(Float64IsInt(f), f) } fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr) for _, c := range []complex128{ 3, 1i, 0i, 3.4, } { show2(Complex128IsInt(c), c) } fmt.Println("\nUsing reflection:") fmt.Print(hdr) show("hello") show(math.MaxFloat64) show("9e100") f := new(big.Float) show(f) f.SetString("1e-3000") show(f) show("(4+0i)", "(complex strings not parsed)") show(4 + 0i) show(rune('§'), "or rune") show(byte('A'), "or byte") var t1 intbased = 5200 var t2a, t2b complexbased = 5 + 0i, 5 + 1i show(t1) show(t2a) show(t2b) x := uintptr(unsafe.Pointer(&t2b)) show(x) show(math.MinInt32) show(uint64(math.MaxUint64)) b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0) show(b) r := new(big.Rat) show(r) r.SetString("2/3") show(r) show(r.SetFrac(b, new(big.Int).SetInt64(9))) show("12345/5") show(new(customIntegerType)) }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.Scanner; import java.io.*; public class Program { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec("cmd /C dir"); Scanner sc = new Scanner(p.getInputStream()); while (sc.hasNext()) System.out.println(sc.nextLine()); } catch (IOException e) { System.out.println(e.getMessage()); } } }
package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
Generate an equivalent Go version of this Java code.
class Vector{ private double x, y, z; public Vector(double x1,double y1,double z1){ x = x1; y = y1; z = z1; } void printVector(int x,int y){ text("( " + this.x + " ) \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y); } public double norm() { return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); } public Vector normalize(){ double length = this.norm(); return new Vector(this.x / length, this.y / length, this.z / length); } public double dotProduct(Vector v2) { return this.x*v2.x + this.y*v2.y + this.z*v2.z; } public Vector crossProduct(Vector v2) { return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x); } public double getAngle(Vector v2) { return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm())); } public Vector aRotate(Vector v, double a) { double ca = Math.cos(a), sa = Math.sin(a); double t = 1.0 - ca; double x = v.x, y = v.y, z = v.z; Vector[] r = { new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa), new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa), new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t) }; return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2])); } } void setup(){ Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d); double a = v1.getAngle(v2); Vector cp = v1.crossProduct(v2); Vector normCP = cp.normalize(); Vector np = v1.aRotate(normCP,a); size(1200,600); fill(#000000); textSize(30); text("v1 = ",10,100); v1.printVector(60,100); text("v2 = ",10,150); v2.printVector(60,150); text("rV = ",10,200); np.printVector(60,200); }
package main import ( "fmt" "math" ) type vector [3]float64 type matrix [3]vector func norm(v vector) float64 { return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) } func normalize(v vector) vector { length := norm(v) return vector{v[0] / length, v[1] / length, v[2] / length} } func dotProduct(v1, v2 vector) float64 { return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] } func crossProduct(v1, v2 vector) vector { return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]} } func getAngle(v1, v2 vector) float64 { return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2))) } func matrixMultiply(m matrix, v vector) vector { return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)} } func aRotate(p, v vector, a float64) vector { ca, sa := math.Cos(a), math.Sin(a) t := 1 - ca x, y, z := v[0], v[1], v[2] r := matrix{ {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa}, {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa}, {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}, } return matrixMultiply(r, p) } func main() { v1 := vector{5, -6, 4} v2 := vector{8, 5, -30} a := getAngle(v1, v2) cp := crossProduct(v1, v2) ncp := normalize(cp) np := aRotate(v1, ncp, a) fmt.Println(np) }
Produce a functionally identical Go code for the snippet given in Java.
class Vector{ private double x, y, z; public Vector(double x1,double y1,double z1){ x = x1; y = y1; z = z1; } void printVector(int x,int y){ text("( " + this.x + " ) \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y); } public double norm() { return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); } public Vector normalize(){ double length = this.norm(); return new Vector(this.x / length, this.y / length, this.z / length); } public double dotProduct(Vector v2) { return this.x*v2.x + this.y*v2.y + this.z*v2.z; } public Vector crossProduct(Vector v2) { return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x); } public double getAngle(Vector v2) { return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm())); } public Vector aRotate(Vector v, double a) { double ca = Math.cos(a), sa = Math.sin(a); double t = 1.0 - ca; double x = v.x, y = v.y, z = v.z; Vector[] r = { new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa), new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa), new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t) }; return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2])); } } void setup(){ Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d); double a = v1.getAngle(v2); Vector cp = v1.crossProduct(v2); Vector normCP = cp.normalize(); Vector np = v1.aRotate(normCP,a); size(1200,600); fill(#000000); textSize(30); text("v1 = ",10,100); v1.printVector(60,100); text("v2 = ",10,150); v2.printVector(60,150); text("rV = ",10,200); np.printVector(60,200); }
package main import ( "fmt" "math" ) type vector [3]float64 type matrix [3]vector func norm(v vector) float64 { return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) } func normalize(v vector) vector { length := norm(v) return vector{v[0] / length, v[1] / length, v[2] / length} } func dotProduct(v1, v2 vector) float64 { return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] } func crossProduct(v1, v2 vector) vector { return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]} } func getAngle(v1, v2 vector) float64 { return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2))) } func matrixMultiply(m matrix, v vector) vector { return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)} } func aRotate(p, v vector, a float64) vector { ca, sa := math.Cos(a), math.Sin(a) t := 1 - ca x, y, z := v[0], v[1], v[2] r := matrix{ {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa}, {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa}, {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}, } return matrixMultiply(r, p) } func main() { v1 := vector{5, -6, 4} v2 := vector{8, 5, -30} a := getAngle(v1, v2) cp := crossProduct(v1, v2) ncp := normalize(cp) np := aRotate(v1, ncp, a) fmt.Println(np) }
Generate a Go translation of this Java snippet without changing its computational steps.
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import javax.xml.ws.Holder; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class XmlValidation { public static void main(String... args) throws MalformedURLException { URL schemaLocation = new URL("http: URL documentLocation = new URL("http: if (validate(schemaLocation, documentLocation)) { System.out.println("document is valid"); } else { System.out.println("document is invalid"); } } public static boolean minimalValidate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.validate(new StreamSource(documentLocation.toString())); return true; } catch (Exception e) { return false; } } public static boolean validate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); final Holder<Boolean> valid = new Holder<>(true); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.setErrorHandler(new ErrorHandler(){ @Override public void warning(SAXParseException exception) { System.out.println("warning: " + exception.getMessage()); } @Override public void error(SAXParseException exception) { System.out.println("error: " + exception.getMessage()); valid.value = false; } @Override public void fatalError(SAXParseException exception) throws SAXException { System.out.println("fatal error: " + exception.getMessage()); throw exception; }}); validator.validate(new StreamSource(documentLocation.toString())); return valid.value; } catch (SAXException e) { return false; } catch (Exception e) { System.err.println(e); return false; } } }
package main import ( "fmt" "github.com/lestrrat-go/libxml2" "github.com/lestrrat-go/libxml2/xsd" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { xsdfile := "shiporder.xsd" f, err := os.Open(xsdfile) check(err) defer f.Close() buf, err := ioutil.ReadAll(f) check(err) s, err := xsd.Parse(buf) check(err) defer s.Free() xmlfile := "shiporder.xml" f2, err := os.Open(xmlfile) check(err) defer f2.Close() buf2, err := ioutil.ReadAll(f2) check(err) d, err := libxml2.Parse(buf2) check(err) if err := s.Validate(d); err != nil { for _, e := range err.(xsd.SchemaValidationError).Errors() { log.Printf("error: %s", e.Error()) } return } fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!") }
Ensure the translated Go code behaves exactly like the original Java snippet.
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>(); for (E x : n) { Node<E> node = new Node<E>(); node.value = x; int i = Collections.binarySearch(pileTops, node); if (i < 0) i = ~i; if (i != 0) node.pointer = pileTops.get(i-1); if (i != pileTops.size()) pileTops.set(i, node); else pileTops.add(node); } List<E> result = new ArrayList<E>(); for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1); node != null; node = node.pointer) result.add(node.value); Collections.reverse(result); return result; } private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> { public E value; public Node<E> pointer; public int compareTo(Node<E> y) { return value.compareTo(y.value); } } public static void main(String[] args) { List<Integer> d = Arrays.asList(3,2,6,4,5,1); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); } }
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
Maintain the same structure and functionality when rewriting this code in Go.
import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import javafx.scene.transform.Rotate; import javafx.stage.Stage; public class DeathStar extends Application { private static final int DIVISION = 200; float radius = 300; @Override public void start(Stage primaryStage) throws Exception { Point3D otherSphere = new Point3D(-radius, 0, -radius * 1.5); final TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere); MeshView a = new MeshView(triangleMesh); a.setTranslateY(radius); a.setTranslateX(radius); a.setRotationAxis(Rotate.Y_AXIS); Scene scene = new Scene(new Group(a)); primaryStage.setScene(scene); primaryStage.show(); } static TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) { Rotate rotate = new Rotate(180, centerOtherSphere); final int div2 = division / 2; final int nPoints = division * (div2 - 1) + 2; final int nTPoints = (division + 1) * (div2 - 1) + division * 2; final int nFaces = division * (div2 - 2) * 2 + division * 2; final float rDiv = 1.f / division; float points[] = new float[nPoints * 3]; float tPoints[] = new float[nTPoints * 2]; int faces[] = new int[nFaces * 6]; int pPos = 0, tPos = 0; for (int y = 0; y < div2 - 1; ++y) { float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI; float sin_va = (float) Math.sin(va); float cos_va = (float) Math.cos(va); float ty = 0.5f + sin_va * 0.5f; for (int i = 0; i < division; ++i) { double a = rDiv * i * 2 * (float) Math.PI; float hSin = (float) Math.sin(a); float hCos = (float) Math.cos(a); points[pPos + 0] = hSin * cos_va * radius; points[pPos + 2] = hCos * cos_va * radius; points[pPos + 1] = sin_va * radius; final Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]); double distance = centerOtherSphere.distance(point3D); if (distance <= radius) { Point3D subtract = centerOtherSphere.subtract(point3D); Point3D transform = rotate.transform(subtract); points[pPos + 0] = (float) transform.getX(); points[pPos + 1] = (float) transform.getY(); points[pPos + 2] = (float) transform.getZ(); } tPoints[tPos + 0] = 1 - rDiv * i; tPoints[tPos + 1] = ty; pPos += 3; tPos += 2; } tPoints[tPos + 0] = 0; tPoints[tPos + 1] = ty; tPos += 2; } points[pPos + 0] = 0; points[pPos + 1] = -radius; points[pPos + 2] = 0; points[pPos + 3] = 0; points[pPos + 4] = radius; points[pPos + 5] = 0; pPos += 6; int pS = (div2 - 1) * division; float textureDelta = 1.f / 256; for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = textureDelta; tPos += 2; } for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = 1 - textureDelta; tPos += 2; } int fIndex = 0; for (int y = 0; y < div2 - 2; ++y) { for (int x = 0; x < division; ++x) { int p0 = y * division + x; int p1 = p0 + 1; int p2 = p0 + division; int p3 = p1 + division; int t0 = p0 + y; int t1 = t0 + 1; int t2 = t0 + division + 1; int t3 = t1 + division + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2; faces[fIndex + 5] = t2; fIndex += 6; faces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3; faces[fIndex + 1] = t3; faces[fIndex + 2] = p2; faces[fIndex + 3] = t2; faces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 5] = t1; fIndex += 6; } } int p0 = pS; int tB = (div2 - 1) * (division + 1); for (int x = 0; x < division; ++x) { int p2 = x, p1 = x + 1, t0 = tB + x; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 == division ? 0 : p1; faces[fIndex + 3] = p1; faces[fIndex + 4] = p2; faces[fIndex + 5] = p2; fIndex += 6; } p0 = p0 + 1; tB = tB + division; int pB = (div2 - 2) * division; for (int x = 0; x < division; ++x) { int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x; int t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2; faces[fIndex + 5] = t2; fIndex += 6; } TriangleMesh m = new TriangleMesh(); m.getPoints().setAll(points); m.getTexCoords().setAll(tPoints); m.getFaces().setAll(faces); return m; } public static void main(String[] args) { launch(args); } }
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } type sphere struct { cx, cy, cz int r int } func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false } func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img } func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100} img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Change the following Java code into Go without altering its purpose.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LuckyNumbers { private static int MAX = 200000; private static List<Integer> luckyEven = luckyNumbers(MAX, true); private static List<Integer> luckyOdd = luckyNumbers(MAX, false); public static void main(String[] args) { if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) { int n = Integer.parseInt(args[0]); System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1)); } else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) { int n = Integer.parseInt(args[0]); System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1)); } else if ( args.length == 2 || args.length == 3 ) { int j = Integer.parseInt(args[0]); int k = Integer.parseInt(args[1]); if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) { System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k)); } else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) { System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k)); } else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) { int n = Collections.binarySearch(luckyOdd, j); int m = Collections.binarySearch(luckyOdd, -k); System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) { int n = Collections.binarySearch(luckyEven, j); int m = Collections.binarySearch(luckyEven, -k); System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } } } private static List<Integer> luckyNumbers(int max, boolean even) { List<Integer> luckyList = new ArrayList<>(); for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) { luckyList.add(i); } int start = 1; boolean removed = true; while ( removed ) { removed = false; int increment = luckyList.get(start); List<Integer> remove = new ArrayList<>(); for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) { remove.add(0, i); removed = true; } for ( int i : remove ) { luckyList.remove(i); } start++; } return luckyList; } }
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLuckyOdd() { for n := 2; n < len(luckyOdd); n++ { m := luckyOdd[n-1] end := (len(luckyOdd)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyOdd[j:], luckyOdd[j+1:]) luckyOdd = luckyOdd[:len(luckyOdd)-1] } } } func filterLuckyEven() { for n := 2; n < len(luckyEven); n++ { m := luckyEven[n-1] end := (len(luckyEven)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyEven[j:], luckyEven[j+1:]) luckyEven = luckyEven[:len(luckyEven)-1] } } } func printSingle(j int, odd bool) error { if odd { if j >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky number", j, "=", luckyOdd[j-1]) } else { if j >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky even number", j, "=", luckyEven[j-1]) } return nil } func printRange(j, k int, odd bool) error { if odd { if k >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky numbers", j, "to", k, "are:") fmt.Println(luckyOdd[j-1 : k]) } else { if k >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky even numbers", j, "to", k, "are:") fmt.Println(luckyEven[j-1 : k]) } return nil } func printBetween(j, k int, odd bool) error { var r []int if odd { max := luckyOdd[len(luckyOdd)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyOdd { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky numbers between", j, "and", k, "are:") fmt.Println(r) } else { max := luckyEven[len(luckyEven)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyEven { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky even numbers between", j, "and", k, "are:") fmt.Println(r) } return nil } func main() { nargs := len(os.Args) if nargs < 2 || nargs > 4 { log.Fatal("there must be between 1 and 3 command line arguments") } filterLuckyOdd() filterLuckyEven() j, err := strconv.Atoi(os.Args[1]) if err != nil || j < 1 { log.Fatalf("first argument, %s, must be a positive integer", os.Args[1]) } if nargs == 2 { if err := printSingle(j, true); err != nil { log.Fatal(err) } return } if nargs == 3 { k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatalf("second argument, %s, must be an integer", os.Args[2]) } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, true); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, true); err != nil { log.Fatal(err) } } return } var odd bool switch lucky := strings.ToLower(os.Args[3]); lucky { case "lucky": odd = true case "evenlucky": odd = false default: log.Fatalf("third argument, %s, is invalid", os.Args[3]) } if os.Args[2] == "," { if err := printSingle(j, odd); err != nil { log.Fatal(err) } return } k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatal("second argument must be an integer or a comma") } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, odd); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, odd); err != nil { log.Fatal(err) } } }
Rewrite the snippet below in Go so it works the same as the original Java code.
import java.io.*; import java.text.*; import java.util.*; public class SimpleDatabase { final static String filename = "simdb.csv"; public static void main(String[] args) { if (args.length < 1 || args.length > 3) { printUsage(); return; } switch (args[0].toLowerCase()) { case "add": addItem(args); break; case "latest": printLatest(args); break; case "all": printAll(); break; default: printUsage(); break; } } private static class Item implements Comparable<Item>{ final String name; final String date; final String category; Item(String n, String d, String c) { name = n; date = d; category = c; } @Override public int compareTo(Item item){ return date.compareTo(item.date); } @Override public String toString() { return String.format("%s,%s,%s%n", name, date, category); } } private static void addItem(String[] input) { if (input.length < 2) { printUsage(); return; } List<Item> db = load(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(new Date()); String cat = (input.length == 3) ? input[2] : "none"; db.add(new Item(input[1], date, cat)); store(db); } private static void printLatest(String[] a) { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); if (a.length == 2) { for (Item item : db) if (item.category.equals(a[1])) System.out.println(item); } else { System.out.println(db.get(0)); } } private static void printAll() { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); for (Item item : db) System.out.println(item); } private static List<Item> load() { List<Item> db = new ArrayList<>(); try (Scanner sc = new Scanner(new File(filename))) { while (sc.hasNext()) { String[] item = sc.nextLine().split(","); db.add(new Item(item[0], item[1], item[2])); } } catch (IOException e) { System.out.println(e); } return db; } private static void store(List<Item> db) { try (FileWriter fw = new FileWriter(filename)) { for (Item item : db) fw.write(item.toString()); } catch (IOException e) { System.out.println(e); } } private static void printUsage() { System.out.println("Usage:"); System.out.println(" simdb cmd [categoryName]"); System.out.println(" add add item, followed by optional category"); System.out.println(" latest print last added item(s), followed by " + "optional category"); System.out.println(" all print all"); System.out.println(" For instance: add \"some item name\" " + "\"some category name\""); } }
package main import ( "encoding/json" "fmt" "io" "os" "sort" "strings" "time" "unicode" ) type Item struct { Stamp time.Time Name string Tags []string `json:",omitempty"` Notes string `json:",omitempty"` } func (i *Item) String() string { s := i.Stamp.Format(time.ANSIC) + "\n Name: " + i.Name if len(i.Tags) > 0 { s = fmt.Sprintf("%s\n Tags: %v", s, i.Tags) } if i.Notes > "" { s += "\n Notes: " + i.Notes } return s } type db []*Item func (d db) Len() int { return len(d) } func (d db) Swap(i, j int) { d[i], d[j] = d[j], d[i] } func (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) } const fn = "sdb.json" func main() { if len(os.Args) == 1 { latest() return } switch os.Args[1] { case "add": add() case "latest": latest() case "tags": tags() case "all": all() case "help": help() default: usage("unrecognized command") } } func usage(err string) { if err > "" { fmt.Println(err) } fmt.Println(`usage: sdb [command] [data] where command is one of add, latest, tags, all, or help.`) } func help() { usage("") fmt.Println(` Commands must be in lower case. If no command is specified, the default command is latest. Latest prints the latest item. All prints all items in chronological order. Tags prints the lastest item for each tag. Help prints this message. Add adds data as a new record. The format is, name [tags] [notes] Name is the name of the item and is required for the add command. Tags are optional. A tag is a single word. A single tag can be specified without enclosing brackets. Multiple tags can be specified by enclosing them in square brackets. Text remaining after tags is taken as notes. Notes do not have to be enclosed in quotes or brackets. The brackets above are only showing that notes are optional. Quotes may be useful however--as recognized by your operating system shell or command line--to allow entry of arbitrary text. In particular, quotes or escape characters may be needed to prevent the shell from trying to interpret brackets or other special characters. Examples: sdb add Bookends sdb add Bookends rock my favorite sdb add Bookends [rock folk] sdb add Bookends [] "Simon & Garfunkel" sdb add "Simon&Garfunkel [artist]" As shown in the last example, if you use features of your shell to pass all data as a single string, the item name and tags will still be identified by separating whitespace. The database is stored in JSON format in the file "sdb.json" `) } func load() (db, bool) { d, f, ok := open() if ok { f.Close() if len(d) == 0 { fmt.Println("no items") ok = false } } return d, ok } func open() (d db, f *os.File, ok bool) { var err error f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666) if err != nil { fmt.Println("cant open??") fmt.Println(err) return } jd := json.NewDecoder(f) err = jd.Decode(&d) if err != nil && err != io.EOF { fmt.Println(err) f.Close() return } ok = true return } func latest() { d, ok := load() if !ok { return } sort.Sort(d) fmt.Println(d[len(d)-1]) } func all() { d, ok := load() if !ok { return } sort.Sort(d) for _, i := range d { fmt.Println("-----------------------------------") fmt.Println(i) } fmt.Println("-----------------------------------") } func tags() { d, ok := load() if !ok { return } latest := make(map[string]*Item) for _, item := range d { for _, tag := range item.Tags { li, ok := latest[tag] if !ok || item.Stamp.After(li.Stamp) { latest[tag] = item } } } type itemTags struct { item *Item tags []string } inv := make(map[*Item][]string) for tag, item := range latest { inv[item] = append(inv[item], tag) } li := make(db, len(inv)) i := 0 for item := range inv { li[i] = item i++ } sort.Sort(li) for _, item := range li { tags := inv[item] fmt.Println("-----------------------------------") fmt.Println("Latest item with tags", tags) fmt.Println(item) } fmt.Println("-----------------------------------") } func add() { if len(os.Args) < 3 { usage("add command requires data") return } else if len(os.Args) == 3 { add1() } else { add4() } } func add1() { data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace) if data == "" { usage("invalid name") return } sep := strings.IndexFunc(data, unicode.IsSpace) if sep < 0 { addItem(data, nil, "") return } name := data[:sep] data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace) if data == "" { addItem(name, nil, "") return } if data[0] == '[' { sep = strings.Index(data, "]") if sep < 0 { addItem(name, strings.Fields(data[1:]), "") } else { addItem(name, strings.Fields(data[1:sep]), strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) } return } sep = strings.IndexFunc(data, unicode.IsSpace) if sep < 0 { addItem(name, []string{data}, "") } else { addItem(name, []string{data[:sep]}, strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) } } func add4() { name := os.Args[2] tag1 := os.Args[3] if tag1[0] != '[' { addItem(name, []string{tag1}, strings.Join(os.Args[4:], " ")) return } if tag1[len(tag1)-1] == ']' { addItem(name, strings.Fields(tag1[1:len(tag1)-1]), strings.Join(os.Args[4:], " ")) return } var tags []string if tag1 > "[" { tags = []string{tag1[1:]} } for x, tag := range os.Args[4:] { if tag[len(tag)-1] != ']' { tags = append(tags, tag) } else { if tag > "]" { tags = append(tags, tag[:len(tag)-1]) } addItem(name, tags, strings.Join(os.Args[5+x:], " ")) return } } addItem(name, tags, "") } func addItem(name string, tags []string, notes string) { db, f, ok := open() if !ok { return } defer f.Close() db = append(db, &Item{time.Now(), name, tags, notes}) sort.Sort(db) js, err := json.MarshalIndent(db, "", " ") if err != nil { fmt.Println(err) return } if _, err = f.Seek(0, 0); err != nil { fmt.Println(err) return } f.Truncate(0) if _, err = f.Write(js); err != nil { fmt.Println(err) } }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class HoughTransform { public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast) { int width = inputData.width; int height = inputData.height; int maxRadius = (int)Math.ceil(Math.hypot(width, height)); int halfRAxisSize = rAxisSize >>> 1; ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize); double[] sinTable = new double[thetaAxisSize]; double[] cosTable = new double[thetaAxisSize]; for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double thetaRadians = theta * Math.PI / thetaAxisSize; sinTable[theta] = Math.sin(thetaRadians); cosTable[theta] = Math.cos(thetaRadians); } for (int y = height - 1; y >= 0; y--) { for (int x = width - 1; x >= 0; x--) { if (inputData.contrast(x, y, minContrast)) { for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double r = cosTable[theta] * x + sinTable[theta] * y; int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize; outputData.accumulate(theta, rScaled, 1); } } } } return outputData; } 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; } public void accumulate(int x, int y, int delta) { set(x, y, get(x, y) + delta); } public boolean contrast(int x, int y, int minContrast) { int centerValue = get(x, y); for (int i = 8; i >= 0; i--) { if (i == 4) continue; int newx = x + (i % 3) - 1; int newy = y + (i / 3) - 1; if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height)) continue; if (Math.abs(get(newx, newy) - centerValue) >= minContrast) return true; } return false; } public int getMax() { int max = dataArray[0]; for (int i = width * height - 1; i > 0; i--) if (dataArray[i] > max) max = dataArray[i]; return max; } } public static ArrayData getArrayDataFromImage(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 arrayData = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11); arrayData.set(x, height - 1 - y, rgbValue); } } return arrayData; } public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException { int max = arrayData.getMax(); BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < arrayData.height; y++) { for (int x = 0; x < arrayData.width; x++) { int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255); outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { ArrayData inputData = getArrayDataFromImage(args[0]); int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]); ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast); writeOutputImage(args[1], outputData); return; } }
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) func hough(im image.Image, ntx, mry int) draw.Image { nimx := im.Bounds().Max.X mimy := im.Bounds().Max.Y him := image.NewGray(image.Rect(0, 0, ntx, mry)) draw.Draw(him, him.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) rmax := math.Hypot(float64(nimx), float64(mimy)) dr := rmax / float64(mry/2) dth := math.Pi / float64(ntx) for jx := 0; jx < nimx; jx++ { for iy := 0; iy < mimy; iy++ { col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray) if col.Y == 255 { continue } for jtx := 0; jtx < ntx; jtx++ { th := dth * float64(jtx) r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th) iry := mry/2 - int(math.Floor(r/dr+.5)) col = him.At(jtx, iry).(color.Gray) if col.Y > 0 { col.Y-- him.SetGray(jtx, iry, col) } } } } return him } func main() { f, err := os.Open("Pentagon.png") if err != nil { fmt.Println(err) return } pent, err := png.Decode(f) if err != nil { fmt.Println(err) return } if err = f.Close(); err != nil { fmt.Println(err) } h := hough(pent, 460, 360) if f, err = os.Create("hough.png"); err != nil { fmt.Println(err) return } if err = png.Encode(f, h); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(err) } }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class HoughTransform { public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast) { int width = inputData.width; int height = inputData.height; int maxRadius = (int)Math.ceil(Math.hypot(width, height)); int halfRAxisSize = rAxisSize >>> 1; ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize); double[] sinTable = new double[thetaAxisSize]; double[] cosTable = new double[thetaAxisSize]; for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double thetaRadians = theta * Math.PI / thetaAxisSize; sinTable[theta] = Math.sin(thetaRadians); cosTable[theta] = Math.cos(thetaRadians); } for (int y = height - 1; y >= 0; y--) { for (int x = width - 1; x >= 0; x--) { if (inputData.contrast(x, y, minContrast)) { for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double r = cosTable[theta] * x + sinTable[theta] * y; int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize; outputData.accumulate(theta, rScaled, 1); } } } } return outputData; } 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; } public void accumulate(int x, int y, int delta) { set(x, y, get(x, y) + delta); } public boolean contrast(int x, int y, int minContrast) { int centerValue = get(x, y); for (int i = 8; i >= 0; i--) { if (i == 4) continue; int newx = x + (i % 3) - 1; int newy = y + (i / 3) - 1; if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height)) continue; if (Math.abs(get(newx, newy) - centerValue) >= minContrast) return true; } return false; } public int getMax() { int max = dataArray[0]; for (int i = width * height - 1; i > 0; i--) if (dataArray[i] > max) max = dataArray[i]; return max; } } public static ArrayData getArrayDataFromImage(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 arrayData = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11); arrayData.set(x, height - 1 - y, rgbValue); } } return arrayData; } public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException { int max = arrayData.getMax(); BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < arrayData.height; y++) { for (int x = 0; x < arrayData.width; x++) { int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255); outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { ArrayData inputData = getArrayDataFromImage(args[0]); int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]); ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast); writeOutputImage(args[1], outputData); return; } }
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) func hough(im image.Image, ntx, mry int) draw.Image { nimx := im.Bounds().Max.X mimy := im.Bounds().Max.Y him := image.NewGray(image.Rect(0, 0, ntx, mry)) draw.Draw(him, him.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) rmax := math.Hypot(float64(nimx), float64(mimy)) dr := rmax / float64(mry/2) dth := math.Pi / float64(ntx) for jx := 0; jx < nimx; jx++ { for iy := 0; iy < mimy; iy++ { col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray) if col.Y == 255 { continue } for jtx := 0; jtx < ntx; jtx++ { th := dth * float64(jtx) r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th) iry := mry/2 - int(math.Floor(r/dr+.5)) col = him.At(jtx, iry).(color.Gray) if col.Y > 0 { col.Y-- him.SetGray(jtx, iry, col) } } } } return him } func main() { f, err := os.Open("Pentagon.png") if err != nil { fmt.Println(err) return } pent, err := png.Decode(f) if err != nil { fmt.Println(err) return } if err = f.Close(); err != nil { fmt.Println(err) } h := hough(pent, 460, 360) if f, err = os.Create("hough.png"); err != nil { fmt.Println(err) return } if err = png.Encode(f, h); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(err) } }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma; public class Test { static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2)); return sqs / avg; } static double x2Prob(double dof, double distance) { return Gamma.regularizedGammaQ(dof / 2, distance / 2); } static boolean x2IsUniform(double[] data, double significance) { return x2Prob(data.length - 1.0, x2Dist(data)) > significance; } public static void main(String[] a) { double[][] dataSets = {{199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}}; System.out.printf(" %4s %12s %12s %8s %s%n", "dof", "distance", "probability", "Uniform?", "dataset"); for (double[] ds : dataSets) { int dof = ds.length - 1; double dist = x2Dist(ds); double prob = x2Prob(dof, dist); System.out.printf("%4d %12.3f %12.8f %5s %6s%n", dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO", Arrays.toString(ds)); } } }
package main import ( "fmt" "math" ) type ifctn func(float64) float64 func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } else { sum += 3 * f(a+h1*float64(j)) } } return h * sum / 8 } func gammaIncQ(a, x float64) float64 { aa1 := a - 1 var f ifctn = func(t float64) float64 { return math.Pow(t, aa1) * math.Exp(-t) } y := aa1 h := 1.5e-2 for f(y)*(x-y) > 2e-8 && y < x { y += .4 } if y > x { y = x } return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a))) } func chi2ud(ds []int) float64 { var sum, expected float64 for _, d := range ds { expected += float64(d) } expected /= float64(len(ds)) for _, d := range ds { x := float64(d) - expected sum += x * x } return sum / expected } func chi2p(dof int, distance float64) float64 { return gammaIncQ(.5*float64(dof), .5*distance) } const sigLevel = .05 func main() { for _, dset := range [][]int{ {199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}, } { utest(dset) } } func utest(dset []int) { fmt.Println("Uniform distribution test") var sum int for _, c := range dset { sum += c } fmt.Println(" dataset:", dset) fmt.Println(" samples: ", sum) fmt.Println(" categories: ", len(dset)) dof := len(dset) - 1 fmt.Println(" degrees of freedom: ", dof) dist := chi2ud(dset) fmt.Println(" chi square test statistic: ", dist) p := chi2p(dof, dist) fmt.Println(" p-value of test statistic: ", p) sig := p < sigLevel fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig) fmt.Println(" uniform? ", !sig, "\n") }
Keep all operations the same but rewrite the snippet in Go.
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { v += (x - m) * (x - m); } v /= (n - 1); return new double[] {m, v}; } public static double[] welch_ttest(double[] x, double[] y) { double mx, my, vx, vy, t, df, p; double[] res; int nx = x.length, ny = y.length; res = meanvar(x); mx = res[0]; vx = res[1]; res = meanvar(y); my = res[0]; vy = res[1]; t = (mx-my)/Math.sqrt(vx/nx+vy/ny); df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1))); TDistribution dist = new TDistribution(df); p = 2.0*dist.cumulativeProbability(-Math.abs(t)); return new double[] {t, df, p}; } public static void main(String[] args) { double x[] = {3.0, 4.0, 1.0, 2.1}; double y[] = {490.2, 340.0, 433.9}; double res[] = welch_ttest(x, y); System.out.println("t = " + res[0]); System.out.println("df = " + res[1]); System.out.println("p = " + res[2]); } }
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8} d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8} d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0} d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2} d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99} d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98} x = []float64{3.0, 4.0, 1.0, 2.1} y = []float64{490.2, 340.0, 433.9} ) func main() { fmt.Printf("%.6f\n", pValue(d1, d2)) fmt.Printf("%.6f\n", pValue(d3, d4)) fmt.Printf("%.6f\n", pValue(d5, d6)) fmt.Printf("%.6f\n", pValue(d7, d8)) fmt.Printf("%.6f\n", pValue(x, y)) } func mean(a []float64) float64 { sum := 0. for _, x := range a { sum += x } return sum / float64(len(a)) } func sv(a []float64) float64 { m := mean(a) sum := 0. for _, x := range a { d := x - m sum += d * d } return sum / float64(len(a)-1) } func welch(a, b []float64) float64 { return (mean(a) - mean(b)) / math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b))) } func dof(a, b []float64) float64 { sva := sv(a) svb := sv(b) n := sva/float64(len(a)) + svb/float64(len(b)) return n * n / (sva*sva/float64(len(a)*len(a)*(len(a)-1)) + svb*svb/float64(len(b)*len(b)*(len(b)-1))) } func simpson0(n int, upper float64, f func(float64) float64) float64 { sum := 0. nf := float64(n) dx0 := upper / nf sum += f(0) * dx0 sum += f(dx0*.5) * dx0 * 4 x0 := dx0 for i := 1; i < n; i++ { x1 := float64(i+1) * upper / nf xmid := (x0 + x1) * .5 dx := x1 - x0 sum += f(x0) * dx * 2 sum += f(xmid) * dx * 4 x0 = x1 } return (sum + f(upper)*dx0) / 6 } func pValue(a, b []float64) float64 { ν := dof(a, b) t := welch(a, b) g1, _ := math.Lgamma(ν / 2) g2, _ := math.Lgamma(.5) g3, _ := math.Lgamma(ν/2 + .5) return simpson0(2000, ν/(t*t+ν), func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) / math.Exp(g1+g2-g3) }
Write the same code in Go as shown below in Java.
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { v += (x - m) * (x - m); } v /= (n - 1); return new double[] {m, v}; } public static double[] welch_ttest(double[] x, double[] y) { double mx, my, vx, vy, t, df, p; double[] res; int nx = x.length, ny = y.length; res = meanvar(x); mx = res[0]; vx = res[1]; res = meanvar(y); my = res[0]; vy = res[1]; t = (mx-my)/Math.sqrt(vx/nx+vy/ny); df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1))); TDistribution dist = new TDistribution(df); p = 2.0*dist.cumulativeProbability(-Math.abs(t)); return new double[] {t, df, p}; } public static void main(String[] args) { double x[] = {3.0, 4.0, 1.0, 2.1}; double y[] = {490.2, 340.0, 433.9}; double res[] = welch_ttest(x, y); System.out.println("t = " + res[0]); System.out.println("df = " + res[1]); System.out.println("p = " + res[2]); } }
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8} d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8} d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0} d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2} d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99} d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98} x = []float64{3.0, 4.0, 1.0, 2.1} y = []float64{490.2, 340.0, 433.9} ) func main() { fmt.Printf("%.6f\n", pValue(d1, d2)) fmt.Printf("%.6f\n", pValue(d3, d4)) fmt.Printf("%.6f\n", pValue(d5, d6)) fmt.Printf("%.6f\n", pValue(d7, d8)) fmt.Printf("%.6f\n", pValue(x, y)) } func mean(a []float64) float64 { sum := 0. for _, x := range a { sum += x } return sum / float64(len(a)) } func sv(a []float64) float64 { m := mean(a) sum := 0. for _, x := range a { d := x - m sum += d * d } return sum / float64(len(a)-1) } func welch(a, b []float64) float64 { return (mean(a) - mean(b)) / math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b))) } func dof(a, b []float64) float64 { sva := sv(a) svb := sv(b) n := sva/float64(len(a)) + svb/float64(len(b)) return n * n / (sva*sva/float64(len(a)*len(a)*(len(a)-1)) + svb*svb/float64(len(b)*len(b)*(len(b)-1))) } func simpson0(n int, upper float64, f func(float64) float64) float64 { sum := 0. nf := float64(n) dx0 := upper / nf sum += f(0) * dx0 sum += f(dx0*.5) * dx0 * 4 x0 := dx0 for i := 1; i < n; i++ { x1 := float64(i+1) * upper / nf xmid := (x0 + x1) * .5 dx := x1 - x0 sum += f(x0) * dx * 2 sum += f(xmid) * dx * 4 x0 = x1 } return (sum + f(upper)*dx0) / 6 } func pValue(a, b []float64) float64 { ν := dof(a, b) t := welch(a, b) g1, _ := math.Lgamma(ν / 2) g2, _ := math.Lgamma(.5) g3, _ := math.Lgamma(ν/2 + .5) return simpson0(2000, ν/(t*t+ν), func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) / math.Exp(g1+g2-g3) }
Keep all operations the same but rewrite the snippet in Go.
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1"; Graph g = new Graph(s, new int[][]{ {0, 10}, {0, 2}, {0, 3}, {1, 10}, {1, 3}, {1, 4}, {2, 17}, {2, 5}, {2, 9}, {3, 6}, {3, 7}, {3, 8}, {3, 9}, {10, 11}, {10, 12}, {10, 13}, {11, 14}, {11, 15}, {13, 16}, {13, 17},}); System.out.println("Top levels: " + g.toplevels()); String[] files = {"top1", "top2", "ip1"}; for (String f : files) System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f)); } } class Graph { List<String> vertices; boolean[][] adjacency; int numVertices; public Graph(String s, int[][] edges) { vertices = asList(s.split(",")); numVertices = vertices.size(); adjacency = new boolean[numVertices][numVertices]; for (int[] edge : edges) adjacency[edge[0]][edge[1]] = true; } List<String> toplevels() { List<String> result = new ArrayList<>(); outer: for (int c = 0; c < numVertices; c++) { for (int r = 0; r < numVertices; r++) { if (adjacency[r][c]) continue outer; } result.add(vertices.get(c)); } return result; } List<String> compileOrder(String item) { LinkedList<String> result = new LinkedList<>(); LinkedList<Integer> queue = new LinkedList<>(); queue.add(vertices.indexOf(item)); while (!queue.isEmpty()) { int r = queue.poll(); for (int c = 0; c < numVertices; c++) { if (adjacency[r][c] && !queue.contains(c)) { queue.add(c); } } result.addFirst(vertices.get(r)); } return result.stream().distinct().collect(toList()); } }
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
Port the following code from Java to Go with equivalent syntax and logic.
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1"; Graph g = new Graph(s, new int[][]{ {0, 10}, {0, 2}, {0, 3}, {1, 10}, {1, 3}, {1, 4}, {2, 17}, {2, 5}, {2, 9}, {3, 6}, {3, 7}, {3, 8}, {3, 9}, {10, 11}, {10, 12}, {10, 13}, {11, 14}, {11, 15}, {13, 16}, {13, 17},}); System.out.println("Top levels: " + g.toplevels()); String[] files = {"top1", "top2", "ip1"}; for (String f : files) System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f)); } } class Graph { List<String> vertices; boolean[][] adjacency; int numVertices; public Graph(String s, int[][] edges) { vertices = asList(s.split(",")); numVertices = vertices.size(); adjacency = new boolean[numVertices][numVertices]; for (int[] edge : edges) adjacency[edge[0]][edge[1]] = true; } List<String> toplevels() { List<String> result = new ArrayList<>(); outer: for (int c = 0; c < numVertices; c++) { for (int r = 0; r < numVertices; r++) { if (adjacency[r][c]) continue outer; } result.add(vertices.get(c)); } return result; } List<String> compileOrder(String item) { LinkedList<String> result = new LinkedList<>(); LinkedList<Integer> queue = new LinkedList<>(); queue.add(vertices.indexOf(item)); while (!queue.isEmpty()) { int r = queue.poll(); for (int c = 0; c < numVertices; c++) { if (adjacency[r][c] && !queue.contains(c)) { queue.add(c); } } result.addFirst(vertices.get(r)); } return result.stream().distinct().collect(toList()); } }
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
Port the following code from Java to Go with equivalent syntax and logic.
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) { System.out.println(); expand(s); } } public static void expand(String s) { expandR("", s, ""); } private static void expandR(String pre, String s, String suf) { int i1 = -1, i2 = 0; String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " "); StringBuilder sb = null; outer: while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) { i2 = i1 + 1; sb = new StringBuilder(s); for (int depth = 1; i2 < s.length() && depth > 0; i2++) { char c = noEscape.charAt(i2); depth = (c == '{') ? ++depth : depth; depth = (c == '}') ? --depth : depth; if (c == ',' && depth == 1) { sb.setCharAt(i2, '\u0000'); } else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1) break outer; } } if (i1 == -1) { if (suf.length() > 0) expandR(pre + s, suf, ""); else System.out.printf("%s%s%s%n", pre, s, suf); } else { for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1)) expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf); } } }
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } type Sequence []Expander func (seq Sequence) Expand() []string { if len(seq) == 0 { return nil } out := seq[0].Expand() for _, e := range seq[1:] { out = combine(out, e.Expand()) } return out } func combine(al, bl []string) []string { out := make([]string, 0, len(al)*len(bl)) for _, a := range al { for _, b := range bl { out = append(out, a+b) } } return out } const ( escape = '\\' altStart = '{' altEnd = '}' altSep = ',' ) type piT struct{ pos, cnt, depth int } type Brace string func Expand(s string) []string { return Brace(s).Expand() } func (b Brace) Expand() []string { return b.Expander().Expand() } func (b Brace) Expander() Expander { s := string(b) var posInfo []piT var stack []int removePosInfo := func(i int) { end := len(posInfo) - 1 copy(posInfo[i:end], posInfo[i+1:]) posInfo = posInfo[:end] } inEscape := false for i, r := range s { if inEscape { inEscape = false continue } switch r { case escape: inEscape = true case altStart: stack = append(stack, len(posInfo)) posInfo = append(posInfo, piT{i, 0, len(stack)}) case altEnd: if len(stack) == 0 { continue } si := len(stack) - 1 pi := stack[si] if posInfo[pi].cnt == 0 { removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == len(stack) { removePosInfo(pi) } else { pi++ } } } else { posInfo = append(posInfo, piT{i, -2, len(stack)}) } stack = stack[:si] case altSep: if len(stack) == 0 { continue } posInfo = append(posInfo, piT{i, -1, len(stack)}) posInfo[stack[len(stack)-1]].cnt++ } } for len(stack) > 0 { si := len(stack) - 1 pi := stack[si] depth := posInfo[pi].depth removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == depth { removePosInfo(pi) } else { pi++ } } stack = stack[:si] } return buildExp(s, 0, posInfo) } func buildExp(s string, off int, info []piT) Expander { if len(info) == 0 { return Text(s) } var seq Sequence i := 0 var dj, j, depth int for dk, piK := range info { k := piK.pos - off switch s[k] { case altStart: if depth == 0 { dj = dk j = k depth = piK.depth } case altEnd: if piK.depth != depth { continue } if j > i { seq = append(seq, Text(s[i:j])) } alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk]) seq = append(seq, alt) i = k + 1 depth = 0 } } if j := len(s); j > i { seq = append(seq, Text(s[i:j])) } if len(seq) == 1 { return seq[0] } return seq } func buildAlt(s string, depth, off int, info []piT) Alternation { var alt Alternation i := 0 var di int for dk, piK := range info { if piK.depth != depth { continue } if k := piK.pos - off; s[k] == altSep { sub := buildExp(s[i:k], i+off, info[di:dk]) alt = append(alt, sub) i = k + 1 di = dk + 1 } } sub := buildExp(s[i:], i+off, info[di:]) alt = append(alt, sub) return alt }
Please provide an equivalent version of this Java code in Go.
foo(); Int x = bar();
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
Produce a language-to-language conversion: from Java to Go, same semantics.
foo(); Int x = bar();
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
Write the same code in Go as shown below in Java.
import static java.util.stream.IntStream.rangeClosed; public class Test { final static int nMax = 12; static char[] superperm; static int pos; static int[] count = new int[nMax]; static int factSum(int n) { return rangeClosed(1, n) .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum(); } static boolean r(int n) { if (n == 0) return false; char c = superperm[pos - n]; if (--count[n] == 0) { count[n] = n; if (!r(n - 1)) return false; } superperm[pos++] = c; return true; } static void superPerm(int n) { String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pos = n; superperm = new char[factSum(n)]; for (int i = 0; i < n + 1; i++) count[i] = i; for (int i = 1; i < n + 1; i++) superperm[i - 1] = chars.charAt(i); while (r(n)) { } } public static void main(String[] args) { for (int n = 0; n < nMax; n++) { superPerm(n); System.out.printf("superPerm(%2d) len = %d", n, superperm.length); System.out.println(); } } }
package main import "fmt" const max = 12 var ( super []byte pos int cnt [max]int ) func factSum(n int) int { s := 0 for x, f := 0, 1; x < n; { x++ f *= x s += f } return s } func r(n int) bool { if n == 0 { return false } c := super[pos-n] cnt[n]-- if cnt[n] == 0 { cnt[n] = n if !r(n - 1) { return false } } super[pos] = c pos++ return true } func superperm(n int) { pos = n le := factSum(n) super = make([]byte, le) for i := 0; i <= n; i++ { cnt[i] = i } for i := 1; i <= n; i++ { super[i-1] = byte(i) + '0' } for r(n) { } } func main() { for n := 0; n < max; n++ { fmt.Printf("superperm(%2d) ", n) superperm(n) fmt.Printf("len = %d\n", len(super)) } }
Maintain the same structure and functionality when rewriting this code in Go.
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class Interact extends JFrame{ final JTextField numberField; final JButton incButton, randButton; public Interact(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); numberField = new JTextField(); incButton = new JButton("Increment"); randButton = new JButton("Random"); numberField.setText("0"); numberField.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if(!Character.isDigit(e.getKeyChar())){ e.consume(); } } @Override public void keyReleased(KeyEvent e){} @Override public void keyPressed(KeyEvent e){} }); incButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = numberField.getText(); if(text.isEmpty()){ numberField.setText("1"); }else{ numberField.setText((Long.valueOf(text) + 1) + ""); } } }); randButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if(JOptionPane.showConfirmDialog(null, "Are you sure?") == JOptionPane.YES_OPTION){ numberField.setText(Long.toString((long)(Math.random() * Long.MAX_VALUE))); } } }); setLayout(new GridLayout(2, 1)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); buttonPanel.add(incButton); buttonPanel.add(randButton); add(numberField); add(buttonPanel); pack(); } public static void main(String[] args){ new Interact().setVisible(true); } }
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str string) (int64, bool) { i, err := strconv.ParseInt(str, 10, 64) if err != nil { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid value", ) dialog.Run() dialog.Destroy() return 0, false } return i, true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create box:") box.SetBorderWidth(1) label, err := gtk.LabelNew("Value:") check(err, "Unable to create label:") entry, err := gtk.EntryNew() check(err, "Unable to create entry:") entry.SetText("0") entry.Connect("activate", func() { str, _ := entry.GetText() validateInput(window, str) }) ib, err := gtk.ButtonNewWithLabel("Increment") check(err, "Unable to create increment button:") ib.Connect("clicked", func() { str, _ := entry.GetText() if i, ok := validateInput(window, str); ok { entry.SetText(strconv.FormatInt(i+1, 10)) } }) rb, err := gtk.ButtonNewWithLabel("Random") check(err, "Unable to create random button:") rb.Connect("clicked", func() { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Set random value", ) answer := dialog.Run() dialog.Destroy() if answer == gtk.RESPONSE_YES { entry.SetText(strconv.Itoa(rand.Intn(10000))) } }) box.PackStart(label, false, false, 2) box.PackStart(entry, false, false, 2) box.PackStart(ib, false, false, 2) box.PackStart(rb, false, false, 2) window.Add(box) window.ShowAll() gtk.Main() }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.Arrays; import java.util.Random; public class OneOfNLines { static Random rand; public static int oneOfN(int n) { int choice = 0; for(int i = 1; i < n; i++) { if(rand.nextInt(i+1) == 0) choice = i; } return choice; } public static void main(String[] args) { int n = 10; int trials = 1000000; int[] bins = new int[n]; rand = new Random(); for(int i = 0; i < trials; i++) bins[oneOfN(n)]++; System.out.println(Arrays.toString(bins)); } }
package main import ( "bufio" "fmt" "io" "math/rand" "time" ) func choseLineRandomly(r io.Reader) (s string, ln int, err error) { br := bufio.NewReader(r) s, err = br.ReadString('\n') if err != nil { return } ln = 1 lnLast := 1. var sLast string for { sLast, err = br.ReadString('\n') if err == io.EOF { return s, ln, nil } if err != nil { break } lnLast++ if rand.Float64() < 1/lnLast { s = sLast ln = int(lnLast) } } return } func oneOfN(n int, file io.Reader) int { _, ln, err := choseLineRandomly(file) if err != nil { panic(err) } return ln } type simReader int func (r *simReader) Read(b []byte) (int, error) { if *r <= 0 { return 0, io.EOF } b[0] = '\n' *r-- return 1, nil } func main() { n := 10 freq := make([]int, n) rand.Seed(time.Now().UnixNano()) for times := 0; times < 1e6; times++ { sr := simReader(n) freq[oneOfN(n, &sr)-1]++ } fmt.Println(freq) }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class SelfReferentialSequence { static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000); public static void main(String[] args) { Seeds res = IntStream.range(0, 1000_000) .parallel() .mapToObj(n -> summarize(n, false)) .collect(Seeds::new, Seeds::accept, Seeds::combine); System.out.println("Seeds:"); res.seeds.forEach(e -> System.out.println(Arrays.toString(e))); System.out.println("\nSequence:"); summarize(res.seeds.get(0)[0], true); } static int[] summarize(int seed, boolean display) { String n = String.valueOf(seed); String k = Arrays.toString(n.chars().sorted().toArray()); if (!display && cache.get(k) != null) return new int[]{seed, cache.get(k)}; Set<String> seen = new HashSet<>(); StringBuilder sb = new StringBuilder(); int[] freq = new int[10]; while (!seen.contains(n)) { seen.add(n); int len = n.length(); for (int i = 0; i < len; i++) freq[n.charAt(i) - '0']++; sb.setLength(0); for (int i = 9; i >= 0; i--) { if (freq[i] != 0) { sb.append(freq[i]).append(i); freq[i] = 0; } } if (display) System.out.println(n); n = sb.toString(); } cache.put(k, seen.size()); return new int[]{seed, seen.size()}; } static class Seeds { int largest = Integer.MIN_VALUE; List<int[]> seeds = new ArrayList<>(); void accept(int[] s) { int size = s[1]; if (size >= largest) { if (size > largest) { largest = size; seeds.clear(); } seeds.add(s); } } void combine(Seeds acc) { acc.seeds.forEach(this::accept); } } }
package main import ( "fmt" "strconv" ) func main() { var maxLen int var seqMaxLen [][]string for n := 1; n < 1e6; n++ { switch s := seq(n); { case len(s) == maxLen: seqMaxLen = append(seqMaxLen, s) case len(s) > maxLen: maxLen = len(s) seqMaxLen = [][]string{s} } } fmt.Println("Max sequence length:", maxLen) fmt.Println("Sequences:", len(seqMaxLen)) for _, seq := range seqMaxLen { fmt.Println("Sequence:") for _, t := range seq { fmt.Println(t) } } } func seq(n int) []string { s := strconv.Itoa(n) ss := []string{s} for { dSeq := sortD(s) d := dSeq[0] nd := 1 s = "" for i := 1; ; i++ { if i == len(dSeq) { s = fmt.Sprintf("%s%d%c", s, nd, d) break } if dSeq[i] == d { nd++ } else { s = fmt.Sprintf("%s%d%c", s, nd, d) d = dSeq[i] nd = 1 } } for _, s0 := range ss { if s == s0 { return ss } } ss = append(ss, s) } panic("unreachable") } func sortD(s string) []rune { r := make([]rune, len(s)) for i, d := range s { j := 0 for ; j < i; j++ { if d > r[j] { copy(r[j+1:], r[j:i]) break } } r[j] = d } return r }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class SelfReferentialSequence { static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000); public static void main(String[] args) { Seeds res = IntStream.range(0, 1000_000) .parallel() .mapToObj(n -> summarize(n, false)) .collect(Seeds::new, Seeds::accept, Seeds::combine); System.out.println("Seeds:"); res.seeds.forEach(e -> System.out.println(Arrays.toString(e))); System.out.println("\nSequence:"); summarize(res.seeds.get(0)[0], true); } static int[] summarize(int seed, boolean display) { String n = String.valueOf(seed); String k = Arrays.toString(n.chars().sorted().toArray()); if (!display && cache.get(k) != null) return new int[]{seed, cache.get(k)}; Set<String> seen = new HashSet<>(); StringBuilder sb = new StringBuilder(); int[] freq = new int[10]; while (!seen.contains(n)) { seen.add(n); int len = n.length(); for (int i = 0; i < len; i++) freq[n.charAt(i) - '0']++; sb.setLength(0); for (int i = 9; i >= 0; i--) { if (freq[i] != 0) { sb.append(freq[i]).append(i); freq[i] = 0; } } if (display) System.out.println(n); n = sb.toString(); } cache.put(k, seen.size()); return new int[]{seed, seen.size()}; } static class Seeds { int largest = Integer.MIN_VALUE; List<int[]> seeds = new ArrayList<>(); void accept(int[] s) { int size = s[1]; if (size >= largest) { if (size > largest) { largest = size; seeds.clear(); } seeds.add(s); } } void combine(Seeds acc) { acc.seeds.forEach(this::accept); } } }
package main import ( "fmt" "strconv" ) func main() { var maxLen int var seqMaxLen [][]string for n := 1; n < 1e6; n++ { switch s := seq(n); { case len(s) == maxLen: seqMaxLen = append(seqMaxLen, s) case len(s) > maxLen: maxLen = len(s) seqMaxLen = [][]string{s} } } fmt.Println("Max sequence length:", maxLen) fmt.Println("Sequences:", len(seqMaxLen)) for _, seq := range seqMaxLen { fmt.Println("Sequence:") for _, t := range seq { fmt.Println(t) } } } func seq(n int) []string { s := strconv.Itoa(n) ss := []string{s} for { dSeq := sortD(s) d := dSeq[0] nd := 1 s = "" for i := 1; ; i++ { if i == len(dSeq) { s = fmt.Sprintf("%s%d%c", s, nd, d) break } if dSeq[i] == d { nd++ } else { s = fmt.Sprintf("%s%d%c", s, nd, d) d = dSeq[i] nd = 1 } } for _, s0 := range ss { if s == s0 { return ss } } ss = append(ss, s) } panic("unreachable") } func sortD(s string) []rune { r := make([]rune, len(s)) for i, d := range s { j := 0 for ; j < i; j++ { if d > r[j] { copy(r[j+1:], r[j:i]) break } } r[j] = d } return r }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.HashMap; import java.util.Map; public class SpellingOfOrdinalNumbers { public static void main(String[] args) { for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) { System.out.printf("%d = %s%n", test, toOrdinal(test)); } } private static Map<String,String> ordinalMap = new HashMap<>(); static { ordinalMap.put("one", "first"); ordinalMap.put("two", "second"); ordinalMap.put("three", "third"); ordinalMap.put("five", "fifth"); ordinalMap.put("eight", "eighth"); ordinalMap.put("nine", "ninth"); ordinalMap.put("twelve", "twelfth"); } private static String toOrdinal(long n) { String spelling = numToString(n); String[] split = spelling.split(" "); String last = split[split.length - 1]; String replace = ""; if ( last.contains("-") ) { String[] lastSplit = last.split("-"); String lastWithDash = lastSplit[1]; String lastReplace = ""; if ( ordinalMap.containsKey(lastWithDash) ) { lastReplace = ordinalMap.get(lastWithDash); } else if ( lastWithDash.endsWith("y") ) { lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth"; } else { lastReplace = lastWithDash + "th"; } replace = lastSplit[0] + "-" + lastReplace; } else { if ( ordinalMap.containsKey(last) ) { replace = ordinalMap.get(last); } else if ( last.endsWith("y") ) { replace = last.substring(0, last.length() - 1) + "ieth"; } else { replace = last + "th"; } } split[split.length - 1] = replace; return String.join(" ", split); } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String numToString(long n) { return numToStringHelper(n); } private static final String numToStringHelper(long n) { if ( n < 0 ) { return "negative " + numToStringHelper(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : ""); } }
import ( "fmt" "strings" ) func main() { for _, n := range []int64{ 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, } { fmt.Println(sayOrdinal(n)) } } var irregularOrdinals = map[string]string{ "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } func sayOrdinal(n int64) string { s := say(n) i := strings.LastIndexAny(s, " -") i++ if x, ok := irregularOrdinals[s[i:]]; ok { s = s[:i] + x } else if s[len(s)-1] == 'y' { s = s[:i] + s[i:len(s)-1] + "ieth" } else { s = s[:i] + s[i:] + "th" } return s } var small = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} var tens = [...]string{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} var illions = [...]string{"", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"} func say(n int64) string { var t string if n < 0 { t = "negative " n = -n } switch { case n < 20: t += small[n] case n < 100: t += tens[n/10] s := n % 10 if s > 0 { t += "-" + small[s] } case n < 1000: t += small[n/100] + " hundred" s := n % 100 if s > 0 { t += " " + say(s) } default: sx := "" for i := 0; n > 0; i++ { p := n % 1000 n /= 1000 if p > 0 { ix := say(p) + illions[i] if sx != "" { ix += " " + sx } sx = ix } } t += sx } return t }
Write the same code in Go as shown below in Java.
public class SelfDescribingNumbers{ public static boolean isSelfDescribing(int a){ String s = Integer.toString(a); for(int i = 0; i < s.length(); i++){ String s0 = s.charAt(i) + ""; int b = Integer.parseInt(s0); int count = 0; for(int j = 0; j < s.length(); j++){ int temp = Integer.parseInt(s.charAt(j) + ""); if(temp == i){ count++; } if (count > b) return false; } if(count != b) return false; } return true; } public static void main(String[] args){ for(int i = 0; i < 100000000; i++){ if(isSelfDescribing(i)){ System.out.println(i); } } } }
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } func main() { for n := int64(0); n < 1e10; n++ { if sdn(n) { fmt.Println(n) } } }
Keep all operations the same but rewrite the snippet in Go.
public class AdditionChains { private static class Pair { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1]; result[0] = n; System.arraycopy(seq, 0, result, 1, seq.length); return result; } private static Pair check_seq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Pair(min_len, 0); else if (seq[0] == n) return new Pair(pos, 1); else if (pos < min_len) return try_perm(0, pos, seq, n, min_len); else return new Pair(min_len, 0); } private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Pair(min_len, 0); Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len); Pair res2 = try_perm(i + 1, pos, seq, n, res1.f); if (res2.f < res1.f) return res2; else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s); else throw new RuntimeException("Try_perm exception"); } private static Pair init_try_perm(int x) { return try_perm(0, 0, new int[]{1}, x, 12); } private static void find_brauer(int num) { Pair res = init_try_perm(num); System.out.println(); System.out.println("N = " + num); System.out.println("Minimum length of chains: L(n)= " + res.f); System.out.println("Number of minimum length Brauer chains: " + res.s); } public static void main(String[] args) { int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; for (int i : nums) { find_brauer(i); } } }
package main import "fmt" var example []int func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func checkSeq(pos, n, minLen int, seq []int) (int, int) { switch { case pos > minLen || seq[0] > n: return minLen, 0 case seq[0] == n: example = seq return pos, 1 case pos < minLen: return tryPerm(0, pos, n, minLen, seq) default: return minLen, 0 } } func tryPerm(i, pos, n, minLen int, seq []int) (int, int) { if i > pos { return minLen, 0 } seq2 := make([]int, len(seq)+1) copy(seq2[1:], seq) seq2[0] = seq[0] + seq[i] res11, res12 := checkSeq(pos+1, n, minLen, seq2) res21, res22 := tryPerm(i+1, pos, n, res11, seq) switch { case res21 < res11: return res21, res22 case res21 == res11: return res21, res12 + res22 default: fmt.Println("Error in tryPerm") return 0, 0 } } func initTryPerm(x, minLen int) (int, int) { return tryPerm(0, 0, x, minLen, []int{1}) } func findBrauer(num, minLen, nbLimit int) { actualMin, brauer := initTryPerm(num, minLen) fmt.Println("\nN =", num) fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin) fmt.Println("Number of minimum length Brauer chains :", brauer) if brauer > 0 { reverse(example) fmt.Println("Brauer example :", example) } example = nil if num <= nbLimit { nonBrauer := findNonBrauer(num, actualMin+1, brauer) fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer) if nonBrauer > 0 { fmt.Println("Non-Brauer example :", example) } example = nil } else { println("Non-Brauer analysis suppressed") } } func isAdditionChain(a []int) bool { for i := 2; i < len(a); i++ { if a[i] > a[i-1]*2 { return false } ok := false jloop: for j := i - 1; j >= 0; j-- { for k := j; k >= 0; k-- { if a[j]+a[k] == a[i] { ok = true break jloop } } } if !ok { return false } } if example == nil && !isBrauer(a) { example = make([]int, len(a)) copy(example, a) } return true } func isBrauer(a []int) bool { for i := 2; i < len(a); i++ { ok := false for j := i - 1; j >= 0; j-- { if a[i-1]+a[j] == a[i] { ok = true break } } if !ok { return false } } return true } func nextChains(index, le int, seq []int, pcount *int) { for { if index < le-1 { nextChains(index+1, le, seq, pcount) } if seq[index]+le-1-index >= seq[le-1] { return } seq[index]++ for i := index + 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } if isAdditionChain(seq) { (*pcount)++ } } } func findNonBrauer(num, le, brauer int) int { seq := make([]int, le) seq[0] = 1 seq[le-1] = num for i := 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } count := 0 if isAdditionChain(seq) { count = 1 } nextChains(2, le, seq, &count) return count - brauer } func main() { nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} fmt.Println("Searching for Brauer chains up to a minimum length of 12:") for _, num := range nums { findBrauer(num, 12, 79) } }
Convert this Java block to Go, preserving its control flow and logic.
public class NumericSeparatorSyntax { public static void main(String[] args) { runTask("Underscore allowed as seperator", 1_000); runTask("Multiple consecutive underscores allowed:", 1__0_0_0); runTask("Many multiple consecutive underscores allowed:", 1________________________00); runTask("Underscores allowed in multiple positions", 1__4__4); runTask("Underscores allowed in negative number", -1__4__4); runTask("Underscores allowed in floating point number", 1__4__4e-5); runTask("Underscores allowed in floating point exponent", 1__4__440000e-1_2); } private static void runTask(String description, long n) { runTask(description, n, "%d"); } private static void runTask(String description, double n) { runTask(description, n, "%3.7f"); } private static void runTask(String description, Number n, String format) { System.out.printf("%s: " + format + "%n", description, n); } }
package main import "fmt" func main() { integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef} for _, integer := range integers { fmt.Printf("%d ", integer) } floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2} for _, float := range floats { fmt.Printf("%g ", float) } fmt.Println() }
Write the same algorithm in Go as shown in this Java implementation.
import java.util.function.Consumer; import java.util.stream.IntStream; public class Repeat { public static void main(String[] args) { repeat(3, (x) -> System.out.println("Example " + x)); } static void repeat (int n, Consumer<Integer> fun) { IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); } }
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
Ensure the translated Go code behaves exactly like the original Java snippet.
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; now.display1D(arr1); System.out.println(now.getSparkline(arr1)); } public void display1D(float[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public String getSparkline(float[] arr) { float min=Integer.MAX_VALUE; float max=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } float range=max-min; int num=bars.length()-1; String line=""; for(int i=0;i<arr.length;i++) { line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num))); } return line; } }
package main import ( "bufio" "errors" "fmt" "math" "os" "regexp" "strconv" "strings" ) func main() { fmt.Println("Numbers please separated by space/commas:") sc := bufio.NewScanner(os.Stdin) sc.Scan() s, n, min, max, err := spark(sc.Text()) if err != nil { fmt.Println(err) return } if n == 1 { fmt.Println("1 value =", min) } else { fmt.Println(n, "values. Min:", min, "Max:", max) } fmt.Println(s) } var sep = regexp.MustCompile(`[\s,]+`) func spark(s0 string) (sp string, n int, min, max float64, err error) { ss := sep.Split(s0, -1) n = len(ss) vs := make([]float64, n) var v float64 min = math.Inf(1) max = math.Inf(-1) for i, s := range ss { switch v, err = strconv.ParseFloat(s, 64); { case err != nil: case math.IsNaN(v): err = errors.New("NaN not supported.") case math.IsInf(v, 0): err = errors.New("Inf not supported.") default: if v < min { min = v } if v > max { max = v } vs[i] = v continue } return } if min == max { sp = strings.Repeat("▄", n) } else { rs := make([]rune, n) f := 8 / (max - min) for j, v := range vs { i := rune(f * (v - min)) if i > 7 { i = 7 } rs[j] = '▁' + i } sp = string(rs) } return }
Write the same code in Go as shown below in Java.
System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
Transform the following Java implementation into Go, maintaining the same output and logic.
Point p = component.getLocation(); Robot robot = new Robot(); robot.mouseMove(p.getX(), p.getY()); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK);
package main import "github.com/go-vgo/robotgo" func main() { robotgo.MouseClick("left", false) robotgo.MouseClick("right", true) }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class HelloWorld{ public static void main(String[] args) throws IOException{ ServerSocket listener = new ServerSocket(8080); while(true){ Socket sock = listener.accept(); new PrintWriter(sock.getOutputStream(), true). println("Goodbye, World!"); sock.close(); } } }
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Goodbye, World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
Please provide an equivalent version of this Java code in Go.
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
cls
Maintain the same structure and functionality when rewriting this code in Go.
size(1000,1000); surface.setTitle("Sunflower..."); int iter = 3000; float factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5; float x = width/2.0, y = height/2.0; double maxRad = pow(iter,factor)/iter; int i; background(#add8e6); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; if(r/maxRad < diskRatio){ stroke(#000000); } else stroke(#ffff00); theta = 2*PI*factor*i; ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter)); }
package main import ( "github.com/fogleman/gg" "math" ) func main() { dc := gg.NewContext(400, 400) dc.SetRGB(1, 1, 1) dc.Clear() dc.SetRGB(0, 0, 1) c := (math.Sqrt(5) + 1) / 2 numberOfSeeds := 3000 for i := 0; i <= numberOfSeeds; i++ { fi := float64(i) fn := float64(numberOfSeeds) r := math.Pow(fi, c) / fn angle := 2 * math.Pi * c * fi x := r*math.Sin(angle) + 200 y := r*math.Cos(angle) + 200 fi /= fn / 5 dc.DrawCircle(x, y, fi) } dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("sunflower_fractal.png") }
Convert this Java snippet to Go and keep its semantics consistent.
import java.util.Arrays; import static java.util.Arrays.stream; import java.util.concurrent.*; public class VogelsApproximationMethod { final static int[] demand = {30, 20, 70, 30, 60}; final static int[] supply = {50, 60, 50, 50}; final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}}; final static int nRows = supply.length; final static int nCols = demand.length; static boolean[] rowDone = new boolean[nRows]; static boolean[] colDone = new boolean[nCols]; static int[][] result = new int[nRows][nCols]; static ExecutorService es = Executors.newFixedThreadPool(2); public static void main(String[] args) throws Exception { int supplyLeft = stream(supply).sum(); int totalCost = 0; while (supplyLeft > 0) { int[] cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = Math.min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) colDone[c] = true; supply[r] -= quantity; if (supply[r] == 0) rowDone[r] = true; result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } stream(result).forEach(a -> System.out.println(Arrays.toString(a))); System.out.println("Total cost: " + totalCost); es.shutdown(); } static int[] nextCell() throws Exception { Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true)); Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false)); int[] res1 = f1.get(); int[] res2 = f2.get(); if (res1[3] == res2[3]) return res1[2] < res2[2] ? res1 : res2; return (res1[3] > res2[3]) ? res2 : res1; } static int[] diff(int j, int len, boolean isRow) { int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) continue; int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) min2 = c; } return new int[]{min2 - min1, min1, minP}; } static int[] maxPenalty(int len1, int len2, boolean isRow) { int md = Integer.MIN_VALUE; int pc = -1, pm = -1, mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) continue; int[] res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; pm = i; mc = res[1]; pc = res[2]; } } return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md}; } }
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 5 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 461, 277, 356, 488, 393 }; int demand[N_COLS] = { 278, 60, 461, 116, 1060 }; int costs[N_ROWS][N_COLS] = { { 46, 74, 9, 28, 99 }, { 12, 75, 6, 36, 48 }, { 35, 199, 4, 5, 71 }, { 61, 81, 44, 88, 9 }, { 85, 60, 14, 25, 79 } }; int main() { printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'V' + i); for (j = 0; j < N_COLS; ++j) printf(" %3d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }