Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in Java as shown below in C#.
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
class Point { protected int x, y; public Point() { this(0); } public Point(int x) { this(x, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point p) { this(p.x, p.y); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); } } class Circle extends Point { private int r; public Circle(Point p) { this(p, 0); } public Circle(Point p, int r) { super(p); this.r = r; } public Circle() { this(0); } public Circle(int x) { this(x, 0); } public Circle(int x, int y) { this(x, y, 0); } public Circle(int x, int y, int r) { super(x, y); this.r = r; } public Circle(Circle c) { this(c.x, c.y, c.r); } public int getR() { return this.r; } public void setR(int r) { this.r = r; } public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); } } public class test { public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
Maintain the same structure and functionality when rewriting this code in Java.
using System; using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { BI i, j, k, d; i = 2; int n = -1; int n0 = -1; j = (BI)Floor(Sqrt((double)i)); k = j; d = j; DateTime st = DateTime.Now; if (args.Length > 0) int.TryParse(args[0], out n); if (n > 0) n0 = n; else n = 1; do { Write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d++) if ((k + d) * d > i) { d -= 1; break; } j = j * 10 + d; k += d; if (n0 > 0) n--; } while (n > 0); if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); } }
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0))); var k = j; var d = j; int n = 500; int n0 = n; do { System.out.print(d); i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED); k = TWENTY.multiply(j); for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) { if (k.add(d).multiply(d).compareTo(i) > 0) { d = d.subtract(BigInteger.ONE); break; } } j = j.multiply(BigInteger.TEN).add(d); k = k.add(d); if (n0 > 0) { n--; } } while (n > 0); System.out.println(); } }
Rewrite this program in Java while keeping its functionality equivalent to the C# version.
using System; using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { BI i, j, k, d; i = 2; int n = -1; int n0 = -1; j = (BI)Floor(Sqrt((double)i)); k = j; d = j; DateTime st = DateTime.Now; if (args.Length > 0) int.TryParse(args[0], out n); if (n > 0) n0 = n; else n = 1; do { Write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d++) if ((k + d) * d > i) { d -= 1; break; } j = j * 10 + d; k += d; if (n0 > 0) n--; } while (n > 0); if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); } }
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0))); var k = j; var d = j; int n = 500; int n0 = n; do { System.out.print(d); i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED); k = TWENTY.multiply(j); for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) { if (k.add(d).multiply(d).compareTo(i) > 0) { d = d.subtract(BigInteger.ONE); break; } } j = j.multiply(BigInteger.TEN).add(d); k = k.add(d); if (n0 > 0) { n--; } } while (n > 0); System.out.println(); } }
Write the same algorithm in Java as shown in this C# implementation.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetPropertyValues(t, flags)) { Console.WriteLine(prop); } foreach (var field in GetFieldValues(t, flags)) { Console.WriteLine(field); } } public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) => from p in typeof(T).GetProperties(flags) where p.GetIndexParameters().Length == 0 select (p.Name, p.GetValue(obj, null)); public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) => typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj))); class TestClass { private int privateField = 7; public int PublicNumber { get; } = 4; private int PrivateNumber { get; } = 2; } }
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); System.out.println("All public fields (including inherited):"); for (Field f : clazz.getFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } System.out.println(); System.out.println("All declared fields (excluding inherited):"); for (Field f : clazz.getDeclaredFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } } }
Write a version of this C# function in Java with identical behavior.
using System; using System.Collections.Generic; using System.Linq; public static class MinimalSteps { public static void Main() { var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 }); var lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); Console.WriteLine(); subtractors = new [] { 2 }; lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); } private static void PrintRange((char op, int param, int steps)[] lookup, int limit) { for (int goal = 1; goal <= limit; goal++) { var x = lookup[goal]; if (x.param == 0) { Console.WriteLine($"{goal} cannot be reached with these numbers."); continue; } Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: "); for (int n = goal; n > 1; ) { Console.Write($"{n},{x.op}{x.param}=> "); n = x.op == '/' ? n / x.param : n - x.param; x = lookup[n]; } Console.WriteLine("1"); } } private static void PrintMaxMins((char op, int param, int steps)[] lookup) { var maxSteps = lookup.Max(x => x.steps); var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList(); Console.WriteLine(items.Count == 1 ? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}" : $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}" ); } private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors) { var lookup = new (char op, int param, int steps)[goal+1]; lookup[1] = ('/', 1, 0); for (int n = 1; n < lookup.Length; n++) { var ln = lookup[n]; if (ln.param == 0) continue; for (int d = 0; d < divisors.Length; d++) { int target = n * divisors[d]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1); } for (int s = 0; s < subtractors.Length; s++) { int target = n + subtractors[s]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1); } } return lookup; } private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source); }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MinimalStepsDownToOne { public static void main(String[] args) { runTasks(getFunctions1()); runTasks(getFunctions2()); runTasks(getFunctions3()); } private static void runTasks(List<Function> functions) { Map<Integer,List<String>> minPath = getInitialMap(functions, 5); int max = 10; populateMap(minPath, functions, max); System.out.printf("%nWith functions: %s%n", functions); System.out.printf(" Minimum steps to 1:%n"); for ( int n = 2 ; n <= max ; n++ ) { int steps = minPath.get(n).size(); System.out.printf(" %2d: %d step%1s: %s%n", n, steps, steps == 1 ? "" : "s", minPath.get(n)); } displayMaxMin(minPath, functions, 2000); displayMaxMin(minPath, functions, 20000); displayMaxMin(minPath, functions, 100000); } private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) { populateMap(minPath, functions, max); List<Integer> maxIntegers = getMaxMin(minPath, max); int maxSteps = maxIntegers.remove(0); int numCount = maxIntegers.size(); System.out.printf(" There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n %s%n", numCount == 1 ? "is" : "are", numCount, numCount == 1 ? "" : "s", max, maxSteps, maxIntegers); } private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) { int maxSteps = Integer.MIN_VALUE; List<Integer> maxIntegers = new ArrayList<Integer>(); for ( int n = 2 ; n <= max ; n++ ) { int len = minPath.get(n).size(); if ( len > maxSteps ) { maxSteps = len; maxIntegers.clear(); maxIntegers.add(n); } else if ( len == maxSteps ) { maxIntegers.add(n); } } maxIntegers.add(0, maxSteps); return maxIntegers; } private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) { for ( int n = 2 ; n <= max ; n++ ) { if ( minPath.containsKey(n) ) { continue; } Function minFunction = null; int minSteps = Integer.MAX_VALUE; for ( Function f : functions ) { if ( f.actionOk(n) ) { int result = f.action(n); int steps = 1 + minPath.get(result).size(); if ( steps < minSteps ) { minFunction = f; minSteps = steps; } } } int result = minFunction.action(n); List<String> path = new ArrayList<String>(); path.add(minFunction.toString(n)); path.addAll(minPath.get(result)); minPath.put(n, path); } } private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) { Map<Integer,List<String>> minPath = new HashMap<>(); for ( int i = 2 ; i <= max ; i++ ) { for ( Function f : functions ) { if ( f.actionOk(i) ) { int result = f.action(i); if ( result == 1 ) { List<String> path = new ArrayList<String>(); path.add(f.toString(i)); minPath.put(i, path); } } } } return minPath; } private static List<Function> getFunctions3() { List<Function> functions = new ArrayList<>(); functions.add(new Divide2Function()); functions.add(new Divide3Function()); functions.add(new Subtract2Function()); functions.add(new Subtract1Function()); return functions; } private static List<Function> getFunctions2() { List<Function> functions = new ArrayList<>(); functions.add(new Divide3Function()); functions.add(new Divide2Function()); functions.add(new Subtract2Function()); return functions; } private static List<Function> getFunctions1() { List<Function> functions = new ArrayList<>(); functions.add(new Divide3Function()); functions.add(new Divide2Function()); functions.add(new Subtract1Function()); return functions; } public abstract static class Function { abstract public int action(int n); abstract public boolean actionOk(int n); abstract public String toString(int n); } public static class Divide2Function extends Function { @Override public int action(int n) { return n/2; } @Override public boolean actionOk(int n) { return n % 2 == 0; } @Override public String toString(int n) { return "/2 -> " + n/2; } @Override public String toString() { return "Divisor 2"; } } public static class Divide3Function extends Function { @Override public int action(int n) { return n/3; } @Override public boolean actionOk(int n) { return n % 3 == 0; } @Override public String toString(int n) { return "/3 -> " + n/3; } @Override public String toString() { return "Divisor 3"; } } public static class Subtract1Function extends Function { @Override public int action(int n) { return n-1; } @Override public boolean actionOk(int n) { return true; } @Override public String toString(int n) { return "-1 -> " + (n-1); } @Override public String toString() { return "Subtractor 1"; } } public static class Subtract2Function extends Function { @Override public int action(int n) { return n-2; } @Override public boolean actionOk(int n) { return n > 2; } @Override public String toString(int n) { return "-2 -> " + (n-2); } @Override public String toString() { return "Subtractor 2"; } } }
Convert this C# snippet to Java and keep its semantics consistent.
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width); static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; string[][] table = new string[lines.Length][]; int columns = 0; for (int i = 0; i < lines.Length; i++) { string[] row = lines[i].TrimEnd(Separator).Split(Separator); if (columns < row.Length) columns = row.Length; table[i] = row; } string[][] formattedTable = new string[table.Length][]; for (int i = 0; i < formattedTable.Length; i++) { formattedTable[i] = new string[columns]; } for (int j = 0; j < columns; j++) { int columnWidth = 0; for (int i = 0; i < table.Length; i++) { if (j < table[i].Length && columnWidth < table[i][j].Length) columnWidth = table[i][j].Length; } for (int i = 0; i < formattedTable.Length; i++) { if (j < table[i].Length) formattedTable[i][j] = justification(table[i][j], columnWidth); else formattedTable[i][j] = new String(' ', columnWidth); } } string[] result = new string[formattedTable.Length]; for (int i = 0; i < result.Length; i++) { result[i] = String.Join(" ", formattedTable[i]); } return result; } static string JustifyLeft(string s, int width) { return s.PadRight(width); } static string JustifyRight(string s, int width) { return s.PadLeft(width); } static string JustifyCenter(string s, int width) { return s.PadLeft((width + s.Length) / 2).PadRight(width); } static void Main() { string[] input = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column.", }; foreach (string line in AlignColumns(input, JustifyCenter)) { Console.WriteLine(line); } } }
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class ColumnAligner { private List<String[]> words = new ArrayList<>(); private int columns = 0; private List<Integer> columnWidths = new ArrayList<>(); public ColumnAligner(String s) { String[] lines = s.split("\\n"); for (String line : lines) { processInputLine(line); } } public ColumnAligner(List<String> lines) { for (String line : lines) { processInputLine(line); } } private void processInputLine(String line) { String[] lineWords = line.split("\\$"); words.add(lineWords); columns = Math.max(columns, lineWords.length); for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i >= columnWidths.size()) { columnWidths.add(word.length()); } else { columnWidths.set(i, Math.max(columnWidths.get(i), word.length())); } } } interface AlignFunction { String align(String s, int length); } public String alignLeft() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.rightPad(s, length); } }); } public String alignRight() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.leftPad(s, length); } }); } public String alignCenter() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.center(s, length); } }); } private String align(AlignFunction a) { StringBuilder result = new StringBuilder(); for (String[] lineWords : words) { for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i == 0) { result.append("|"); } result.append(a.align(word, columnWidths.get(i)) + "|"); } result.append("\n"); } return result.toString(); } public static void main(String args[]) throws IOException { if (args.length < 1) { System.out.println("Usage: ColumnAligner file [left|right|center]"); return; } String filePath = args[0]; String alignment = "left"; if (args.length >= 2) { alignment = args[1]; } ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8)); switch (alignment) { case "left": System.out.print(ca.alignLeft()); break; case "right": System.out.print(ca.alignRight()); break; case "center": System.out.print(ca.alignCenter()); break; default: System.err.println(String.format("Error! Unknown alignment: '%s'", alignment)); break; } } }
Produce a language-to-language conversion: from C# to Java, same semantics.
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Write the same algorithm in Java as shown in this C# implementation.
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Port the provided C# code into Java while preserving the original functionality.
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Produce a language-to-language conversion: from C# to Java, same semantics.
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
Please provide an equivalent version of this C# code in Java.
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
Write the same code in Java as shown below in C#.
using System; using System.Dynamic; using System.Collections.Generic; public class Program { public static void Main() { string varname = Console.ReadLine(); dynamic expando = new ExpandoObject(); var map = expando as IDictionary<string, object>; map.Add(varname, "Hello world!"); Console.WriteLine(expando.foo); } }
public static void main(String... args){ HashMap<String, Integer> vars = new HashMap<String, Integer>(); vars.put("Variable name", 3); vars.put("Next variable name", 5); Scanner sc = new Scanner(System.in); String str = sc.next(); vars.put(str, sc.nextInt()); System.out.println(vars.get("Variable name")); System.out.println(vars.get(str)); }
Translate the given C# code snippet into Java without altering its behavior.
using System; using System.IO; using System.Security.Cryptography; namespace DES { class Program { static string ByteArrayToString(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); } static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) { byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv); CryptoStreamMode mode = CryptoStreamMode.Write; MemoryStream memStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode); cryptoStream.Write(messageBytes, 0, messageBytes.Length); cryptoStream.FlushFinalBlock(); byte[] encryptedMessageBytes = new byte[memStream.Length]; memStream.Position = 0; memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length); return encryptedMessageBytes; } static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) { byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv); CryptoStreamMode mode = CryptoStreamMode.Write; MemoryStream memStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode); cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length); cryptoStream.FlushFinalBlock(); byte[] decryptedMessageBytes = new byte[memStream.Length]; memStream.Position = 0; memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length); return decryptedMessageBytes; } static void Main(string[] args) { byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 }; byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 }; byte[] encStr = Encrypt(plainBytes, keyBytes); Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr)); byte[] decBytes = Decrypt(encStr, keyBytes); Console.WriteLine("Decoded: {0}", ByteArrayToString(decBytes)); } } }
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class DataEncryptionStandard { private static byte[] toHexByteArray(String self) { byte[] bytes = new byte[self.length() / 2]; for (int i = 0; i < bytes.length; ++i) { bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16)); } return bytes; } private static void printHexBytes(byte[] self, String label) { System.out.printf("%s: ", label); for (byte b : self) { int bb = (b >= 0) ? ((int) b) : b + 256; String ts = Integer.toString(bb, 16); if (ts.length() < 2) { ts = "0" + ts; } System.out.print(ts); } System.out.println(); } public static void main(String[] args) throws Exception { String strKey = "0e329232ea6d0d73"; byte[] keyBytes = toHexByteArray(strKey); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); Cipher encCipher = Cipher.getInstance("DES"); encCipher.init(Cipher.ENCRYPT_MODE, key); String strPlain = "8787878787878787"; byte[] plainBytes = toHexByteArray(strPlain); byte[] encBytes = encCipher.doFinal(plainBytes); printHexBytes(encBytes, "Encoded"); Cipher decCipher = Cipher.getInstance("DES"); decCipher.init(Cipher.DECRYPT_MODE, key); byte[] decBytes = decCipher.doFinal(encBytes); printHexBytes(decBytes, "Decoded"); } }
Port the provided C# code into Java while preserving the original functionality.
using System; using System.IO; using System.Numerics; using System.Threading; using System.Diagnostics; using System.Globalization; namespace Fibonacci { class Program { private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } }; private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" }; private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B) { if (A.GetLength(1) != B.GetLength(0)) { throw new ArgumentException("Illegal matrix dimensions for multiplication."); } var C = new BigInteger[A.GetLength(0), B.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < B.GetLength(1); ++j) { for (int k = 0; k < A.GetLength(1); ++k) { C[i, j] += A[i, k] * B[k, j]; } } } return C; } private static BigInteger[,] Power(in BigInteger[,] A, ulong n) { if (A.GetLength(1) != A.GetLength(0)) { throw new ArgumentException("Not a square matrix."); } var C = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { C[i, i] = BigInteger.One; } if (0 == n) return C; var S = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < A.GetLength(1); ++j) { S[i, j] = A[i, j]; } } while (0 < n) { if (1 == n % 2) C = Multiply(C, S); S = Multiply(S,S); n /= 2; } return C; } public static BigInteger Fib(in ulong n) { var C = Power(F, n); return C[0, 1]; } public static void Task(in ulong p) { var ans = Fib(p).ToString(); var sp = p.ToString("N0", nfi); if (ans.Length <= 40) { Console.WriteLine("Fibonacci({0}) = {1}", sp, ans); } else { Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]); } } public static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (ulong p = 10; p <= 10_000_000; p *= 10) { Task(p); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Took " + elapsedTime); } } }
import java.math.BigInteger; import java.util.Arrays; public class FibonacciMatrixExponentiation { public static void main(String[] args) { BigInteger mod = BigInteger.TEN.pow(20); for ( int exp : Arrays.asList(32, 64) ) { System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod)); } for ( int i = 1 ; i <= 7 ; i++ ) { BigInteger n = BigInteger.TEN.pow(i); System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n))); } } private static String displayFib(BigInteger fib) { String s = fib.toString(); if ( s.length() <= 40 ) { return s; } return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length()); } private static BigInteger fib(BigInteger k) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes; } private static BigInteger fibMod(BigInteger k, BigInteger mod) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes.mod(mod); } }
Keep all operations the same but rewrite the snippet in Java.
using System; using System.IO; using System.Numerics; using System.Threading; using System.Diagnostics; using System.Globalization; namespace Fibonacci { class Program { private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } }; private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" }; private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B) { if (A.GetLength(1) != B.GetLength(0)) { throw new ArgumentException("Illegal matrix dimensions for multiplication."); } var C = new BigInteger[A.GetLength(0), B.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < B.GetLength(1); ++j) { for (int k = 0; k < A.GetLength(1); ++k) { C[i, j] += A[i, k] * B[k, j]; } } } return C; } private static BigInteger[,] Power(in BigInteger[,] A, ulong n) { if (A.GetLength(1) != A.GetLength(0)) { throw new ArgumentException("Not a square matrix."); } var C = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { C[i, i] = BigInteger.One; } if (0 == n) return C; var S = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < A.GetLength(1); ++j) { S[i, j] = A[i, j]; } } while (0 < n) { if (1 == n % 2) C = Multiply(C, S); S = Multiply(S,S); n /= 2; } return C; } public static BigInteger Fib(in ulong n) { var C = Power(F, n); return C[0, 1]; } public static void Task(in ulong p) { var ans = Fib(p).ToString(); var sp = p.ToString("N0", nfi); if (ans.Length <= 40) { Console.WriteLine("Fibonacci({0}) = {1}", sp, ans); } else { Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]); } } public static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (ulong p = 10; p <= 10_000_000; p *= 10) { Task(p); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Took " + elapsedTime); } } }
import java.math.BigInteger; import java.util.Arrays; public class FibonacciMatrixExponentiation { public static void main(String[] args) { BigInteger mod = BigInteger.TEN.pow(20); for ( int exp : Arrays.asList(32, 64) ) { System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod)); } for ( int i = 1 ; i <= 7 ; i++ ) { BigInteger n = BigInteger.TEN.pow(i); System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n))); } } private static String displayFib(BigInteger fib) { String s = fib.toString(); if ( s.length() <= 40 ) { return s; } return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length()); } private static BigInteger fib(BigInteger k) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes; } private static BigInteger fibMod(BigInteger k, BigInteger mod) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes.mod(mod); } }
Can you help me rewrite this code in Java instead of C#, keeping it the same logically?
static string[] inputs = { "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "\"-in Aus$+1411.8millions\"", "===US$0017440 millions=== (in 2000 dollars)" }; void Main() { inputs.Select(s => Commatize(s, 0, 3, ",")) .ToList() .ForEach(Console.WriteLine); } string Commatize(string text, int startPosition, int interval, string separator) { var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*"); var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList(); return string.Join("", x); } string Commatize(Match match, int interval, string separator, string original) { if (match.Length <= interval) return original.Substring(match.Index, match.Index == original.Length ? 0 : Math.Max(match.Length, 1)); return string.Join(separator, match.Value.Split(interval)); } public static class Extension { public static string[] Split(this string source, int interval) { return SplitImpl(source, interval).ToArray(); } static IEnumerable<string>SplitImpl(string source, int interval) { for (int i = 1; i < source.Length; i++) { if (i % interval != 0) continue; yield return source.Substring(i - interval, interval); } } }
import java.io.File; import java.util.*; import java.util.regex.*; public class CommatizingNumbers { public static void main(String[] args) throws Exception { commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " "); commatize("The author has two Z$100000000000000 Zimbabwe notes (100 " + "trillion).", 0, 3, "."); try (Scanner sc = new Scanner(new File("input.txt"))) { while(sc.hasNext()) commatize(sc.nextLine()); } } static void commatize(String s) { commatize(s, 0, 3, ","); } static void commatize(String s, int start, int step, String ins) { if (start < 0 || start > s.length() || step < 1 || step > s.length()) return; Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start)); StringBuffer result = new StringBuffer(s.substring(0, start)); if (m.find()) { StringBuilder sb = new StringBuilder(m.group(1)).reverse(); for (int i = step; i < sb.length(); i += step) sb.insert(i++, ins); m.appendReplacement(result, sb.reverse().toString()); } System.out.println(m.appendTail(result)); } }
Write the same code in Java as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; namespace AruthmeticCoding { using Freq = Dictionary<char, long>; using Triple = Tuple<BigInteger, int, Dictionary<char, long>>; class Program { static Freq CumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; i++) { char c = (char)i; if (freq.ContainsKey(c)) { long v = freq[c]; cf[c] = total; total += v; } } return cf; } static Triple ArithmeticCoding(string str, long radix) { Freq freq = new Freq(); foreach (char c in str) { if (freq.ContainsKey(c)) { freq[c] += 1; } else { freq[c] = 1; } } Freq cf = CumulativeFreq(freq); BigInteger @base = str.Length; BigInteger lower = 0; BigInteger pf = 1; foreach (char c in str) { BigInteger x = cf[c]; lower = lower * @base + x * pf; pf = pf * freq[c]; } BigInteger upper = lower + pf; int powr = 0; BigInteger bigRadix = radix; while (true) { pf = pf / bigRadix; if (pf == 0) break; powr++; } BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)); return new Triple(diff, powr, freq); } static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = radix; BigInteger enc = num * BigInteger.Pow(powr, pwr); long @base = freq.Values.Sum(); Freq cf = CumulativeFreq(freq); Dictionary<long, char> dict = new Dictionary<long, char>(); foreach (char key in cf.Keys) { long value = cf[key]; dict[value] = key; } long lchar = -1; for (long i = 0; i < @base; i++) { if (dict.ContainsKey(i)) { lchar = dict[i]; } else if (lchar != -1) { dict[i] = (char)lchar; } } StringBuilder decoded = new StringBuilder((int)@base); BigInteger bigBase = @base; for (long i = @base - 1; i >= 0; --i) { BigInteger pow = BigInteger.Pow(bigBase, (int)i); BigInteger div = enc / pow; char c = dict[(long)div]; BigInteger fv = freq[c]; BigInteger cv = cf[c]; BigInteger diff = enc - pow * cv; enc = diff / fv; decoded.Append(c); } return decoded.ToString(); } static void Main(string[] args) { long radix = 10; string[] strings = { "DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT" }; foreach (string str in strings) { Triple encoded = ArithmeticCoding(str, radix); string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3); Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", str, encoded.Item1, radix, encoded.Item2); if (str != dec) { throw new Exception("\tHowever that is incorrect!"); } } } } }
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ArithmeticCoding { private static class Triple<A, B, C> { A a; B b; C c; Triple(A a, B b, C c) { this.a = a; this.b = b; this.c = c; } } private static class Freq extends HashMap<Character, Long> { } private static Freq cumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; ++i) { char c = (char) i; Long v = freq.get(c); if (v != null) { cf.put(c, total); total += v; } } return cf; } private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) { char[] chars = str.toCharArray(); Freq freq = new Freq(); for (char c : chars) { if (!freq.containsKey(c)) freq.put(c, 1L); else freq.put(c, freq.get(c) + 1); } Freq cf = cumulativeFreq(freq); BigInteger base = BigInteger.valueOf(chars.length); BigInteger lower = BigInteger.ZERO; BigInteger pf = BigInteger.ONE; for (char c : chars) { BigInteger x = BigInteger.valueOf(cf.get(c)); lower = lower.multiply(base).add(x.multiply(pf)); pf = pf.multiply(BigInteger.valueOf(freq.get(c))); } BigInteger upper = lower.add(pf); int powr = 0; BigInteger bigRadix = BigInteger.valueOf(radix); while (true) { pf = pf.divide(bigRadix); if (pf.equals(BigInteger.ZERO)) break; powr++; } BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr)); return new Triple<>(diff, powr, freq); } private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = BigInteger.valueOf(radix); BigInteger enc = num.multiply(powr.pow(pwr)); long base = 0; for (Long v : freq.values()) base += v; Freq cf = cumulativeFreq(freq); Map<Long, Character> dict = new HashMap<>(); for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey()); long lchar = -1; for (long i = 0; i < base; ++i) { Character v = dict.get(i); if (v != null) { lchar = v; } else if (lchar != -1) { dict.put(i, (char) lchar); } } StringBuilder decoded = new StringBuilder((int) base); BigInteger bigBase = BigInteger.valueOf(base); for (long i = base - 1; i >= 0; --i) { BigInteger pow = bigBase.pow((int) i); BigInteger div = enc.divide(pow); Character c = dict.get(div.longValue()); BigInteger fv = BigInteger.valueOf(freq.get(c)); BigInteger cv = BigInteger.valueOf(cf.get(c)); BigInteger diff = enc.subtract(pow.multiply(cv)); enc = diff.divide(fv); decoded.append(c); } return decoded.toString(); } public static void main(String[] args) { long radix = 10; String[] strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"}; String fmt = "%-25s=> %19s * %d^%s\n"; for (String str : strings) { Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix); String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c); System.out.printf(fmt, str, encoded.a, radix, encoded.b); if (!Objects.equals(str, dec)) throw new RuntimeException("\tHowever that is incorrect!"); } } }
Can you help me rewrite this code in Java instead of C#, keeping it the same logically?
using System; class Program { public static void Main() { } }
module EmptyProgram { void run() { } }
Translate the given C# code snippet into Java without altering its behavior.
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; public class Kosaraju { static class Recursive<I> { I func; } private static List<Integer> kosaraju(List<List<Integer>> g) { int size = g.size(); boolean[] vis = new boolean[size]; int[] l = new int[size]; AtomicInteger x = new AtomicInteger(size); List<List<Integer>> t = new ArrayList<>(); for (int i = 0; i < size; ++i) { t.add(new ArrayList<>()); } Recursive<IntConsumer> visit = new Recursive<>(); visit.func = (int u) -> { if (!vis[u]) { vis[u] = true; for (Integer v : g.get(u)) { visit.func.accept(v); t.get(v).add(u); } int xval = x.decrementAndGet(); l[xval] = u; } }; for (int i = 0; i < size; ++i) { visit.func.accept(i); } int[] c = new int[size]; Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>(); assign.func = (Integer u, Integer root) -> { if (vis[u]) { vis[u] = false; c[u] = root; for (Integer v : t.get(u)) { assign.func.accept(v, root); } } }; for (int u : l) { assign.func.accept(u, u); } return Arrays.stream(c).boxed().collect(Collectors.toList()); } public static void main(String[] args) { List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < 8; ++i) { g.add(new ArrayList<>()); } g.get(0).add(1); g.get(1).add(2); g.get(2).add(0); g.get(3).add(1); g.get(3).add(2); g.get(3).add(4); g.get(4).add(3); g.get(4).add(5); g.get(5).add(2); g.get(5).add(6); g.get(6).add(5); g.get(7).add(4); g.get(7).add(6); g.get(7).add(7); List<Integer> output = kosaraju(g); System.out.println(output); } }
Produce a language-to-language conversion: from C# to Java, same semantics.
using System; using System.Reflection; public class Rosetta { public static void Main() { BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; foreach (var method in typeof(TestForMethodReflection).GetMethods(flags)) Console.WriteLine(method); } class TestForMethodReflection { public void MyPublicMethod() {} private void MyPrivateMethod() {} public static void MyPublicStaticMethod() {} private static void MyPrivateStaticMethod() {} } }
import java.lang.reflect.Method; public class ListMethods { public int examplePublicInstanceMethod(char c, double d) { return 42; } private boolean examplePrivateInstanceMethod(String s) { return true; } public static void main(String[] args) { Class clazz = ListMethods.class; System.out.println("All public methods (including inherited):"); for (Method m : clazz.getMethods()) { System.out.println(m); } System.out.println(); System.out.println("All declared methods (excluding inherited):"); for (Method m : clazz.getDeclaredMethods()) { System.out.println(m); } } }
Please provide an equivalent version of this C# code in Java.
using System; class Example { public int foo(int x) { return 42 + x; } } class Program { static void Main(string[] args) { var example = new Example(); var method = "foo"; var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 }); Console.WriteLine("{0}(5) = {1}", method, result); } }
import java.lang.reflect.Method; class Example { public int foo(int x) { return 42 + x; } } public class Main { public static void main(String[] args) throws Exception { Object example = new Example(); String name = "foo"; Class<?> clazz = example.getClass(); Method meth = clazz.getMethod(name, int.class); Object result = meth.invoke(example, 5); System.out.println(result); } }
Change the following C# code into Java without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
public class LogicPuzzle { boolean S[] = new boolean[13]; int Count = 0; public boolean check2 () { int count = 0; for (int k = 7; k <= 12; k++) if (S[k]) count++; return S[2] == (count == 3); } public boolean check3 () { int count = 0; for (int k = 2; k <= 12; k += 2) if (S[k]) count++; return S[3] == (count == 2); } public boolean check4 () { return S[4] == ( !S[5] || S[6] && S[7]); } public boolean check5 () { return S[5] == ( !S[2] && !S[3] && !S[4]); } public boolean check6 () { int count = 0; for (int k = 1; k <= 11; k += 2) if (S[k]) count++; return S[6] == (count == 4); } public boolean check7 () { return S[7] == ((S[2] || S[3]) && !(S[2] && S[3])); } public boolean check8 () { return S[8] == ( !S[7] || S[5] && S[6]); } public boolean check9 () { int count = 0; for (int k = 1; k <= 6; k++) if (S[k]) count++; return S[9] == (count == 3); } public boolean check10 () { return S[10] == (S[11] && S[12]); } public boolean check11 () { int count = 0; for (int k = 7; k <= 9; k++) if (S[k]) count++; return S[11] == (count == 1); } public boolean check12 () { int count = 0; for (int k = 1; k <= 11; k++) if (S[k]) count++; return S[12] == (count == 4); } public void check () { if (check2() && check3() && check4() && check5() && check6() && check7() && check8() && check9() && check10() && check11() && check12()) { for (int k = 1; k <= 12; k++) if (S[k]) System.out.print(k + " "); System.out.println(); Count++; } } public void recurseAll (int k) { if (k == 13) check(); else { S[k] = false; recurseAll(k + 1); S[k] = true; recurseAll(k + 1); } } public static void main (String args[]) { LogicPuzzle P = new LogicPuzzle(); P.S[1] = true; P.recurseAll(2); System.out.println(); System.out.println(P.Count + " Solutions found."); } }
Write the same algorithm in Java as shown in this C# implementation.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace TransportationProblem { class Shipment { public Shipment(double q, double cpu, int r, int c) { Quantity = q; CostPerUnit = cpu; R = r; C = c; } public double CostPerUnit { get; } public double Quantity { get; set; } public int R { get; } public int C { get; } } class Program { private static int[] demand; private static int[] supply; private static double[,] costs; private static Shipment[,] matrix; static void Init(string filename) { string line; using (StreamReader file = new StreamReader(filename)) { line = file.ReadLine(); var numArr = line.Split(); int numSources = int.Parse(numArr[0]); int numDestinations = int.Parse(numArr[1]); List<int> src = new List<int>(); List<int> dst = new List<int>(); line = file.ReadLine(); numArr = line.Split(); for (int i = 0; i < numSources; i++) { src.Add(int.Parse(numArr[i])); } line = file.ReadLine(); numArr = line.Split(); for (int i = 0; i < numDestinations; i++) { dst.Add(int.Parse(numArr[i])); } int totalSrc = src.Sum(); int totalDst = dst.Sum(); if (totalSrc > totalDst) { dst.Add(totalSrc - totalDst); } else if (totalDst > totalSrc) { src.Add(totalDst - totalSrc); } supply = src.ToArray(); demand = dst.ToArray(); costs = new double[supply.Length, demand.Length]; matrix = new Shipment[supply.Length, demand.Length]; for (int i = 0; i < numSources; i++) { line = file.ReadLine(); numArr = line.Split(); for (int j = 0; j < numDestinations; j++) { costs[i, j] = int.Parse(numArr[j]); } } } } static void NorthWestCornerRule() { for (int r = 0, northwest = 0; r < supply.Length; r++) { for (int c = northwest; c < demand.Length; c++) { int quantity = Math.Min(supply[r], demand[c]); if (quantity > 0) { matrix[r, c] = new Shipment(quantity, costs[r, c], r, c); supply[r] -= quantity; demand[c] -= quantity; if (supply[r] == 0) { northwest = c; break; } } } } } static void SteppingStone() { double maxReduction = 0; Shipment[] move = null; Shipment leaving = null; FixDegenerateCase(); for (int r = 0; r < supply.Length; r++) { for (int c = 0; c < demand.Length; c++) { if (matrix[r, c] != null) { continue; } Shipment trial = new Shipment(0, costs[r, c], r, c); Shipment[] path = GetClosedPath(trial); double reduction = 0; double lowestQuantity = int.MaxValue; Shipment leavingCandidate = null; bool plus = true; foreach (var s in path) { if (plus) { reduction += s.CostPerUnit; } else { reduction -= s.CostPerUnit; if (s.Quantity < lowestQuantity) { leavingCandidate = s; lowestQuantity = s.Quantity; } } plus = !plus; } if (reduction < maxReduction) { move = path; leaving = leavingCandidate; maxReduction = reduction; } } } if (move != null) { double q = leaving.Quantity; bool plus = true; foreach (var s in move) { s.Quantity += plus ? q : -q; matrix[s.R, s.C] = s.Quantity == 0 ? null : s; plus = !plus; } SteppingStone(); } } static List<Shipment> MatrixToList() { List<Shipment> newList = new List<Shipment>(); foreach (var item in matrix) { if (null != item) { newList.Add(item); } } return newList; } static Shipment[] GetClosedPath(Shipment s) { List<Shipment> path = MatrixToList(); path.Add(s); int before; do { before = path.Count; path.RemoveAll(ship => { var nbrs = GetNeighbors(ship, path); return nbrs[0] == null || nbrs[1] == null; }); } while (before != path.Count); Shipment[] stones = path.ToArray(); Shipment prev = s; for (int i = 0; i < stones.Length; i++) { stones[i] = prev; prev = GetNeighbors(prev, path)[i % 2]; } return stones; } static Shipment[] GetNeighbors(Shipment s, List<Shipment> lst) { Shipment[] nbrs = new Shipment[2]; foreach (var o in lst) { if (o != s) { if (o.R == s.R && nbrs[0] == null) { nbrs[0] = o; } else if (o.C == s.C && nbrs[1] == null) { nbrs[1] = o; } if (nbrs[0] != null && nbrs[1] != null) { break; } } } return nbrs; } static void FixDegenerateCase() { const double eps = double.Epsilon; if (supply.Length + demand.Length - 1 != MatrixToList().Count) { for (int r = 0; r < supply.Length; r++) { for (int c = 0; c < demand.Length; c++) { if (matrix[r, c] == null) { Shipment dummy = new Shipment(eps, costs[r, c], r, c); if (GetClosedPath(dummy).Length == 0) { matrix[r, c] = dummy; return; } } } } } } static void PrintResult(string filename) { Console.WriteLine("Optimal solution {0}\n", filename); double totalCosts = 0; for (int r = 0; r < supply.Length; r++) { for (int c = 0; c < demand.Length; c++) { Shipment s = matrix[r, c]; if (s != null && s.R == r && s.C == c) { Console.Write(" {0,3} ", s.Quantity); totalCosts += (s.Quantity * s.CostPerUnit); } else { Console.Write(" - "); } } Console.WriteLine(); } Console.WriteLine("\nTotal costs: {0}\n", totalCosts); } static void Main() { foreach (var filename in new string[] { "input1.txt", "input2.txt", "input3.txt" }) { Init(filename); NorthWestCornerRule(); SteppingStone(); PrintResult(filename); } } } }
import java.io.File; import java.util.*; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toCollection; public class TransportationProblem { private static int[] demand; private static int[] supply; private static double[][] costs; private static Shipment[][] matrix; private static class Shipment { final double costPerUnit; final int r, c; double quantity; public Shipment(double q, double cpu, int r, int c) { quantity = q; costPerUnit = cpu; this.r = r; this.c = c; } } static void init(String filename) throws Exception { try (Scanner sc = new Scanner(new File(filename))) { int numSources = sc.nextInt(); int numDestinations = sc.nextInt(); List<Integer> src = new ArrayList<>(); List<Integer> dst = new ArrayList<>(); for (int i = 0; i < numSources; i++) src.add(sc.nextInt()); for (int i = 0; i < numDestinations; i++) dst.add(sc.nextInt()); int totalSrc = src.stream().mapToInt(i -> i).sum(); int totalDst = dst.stream().mapToInt(i -> i).sum(); if (totalSrc > totalDst) dst.add(totalSrc - totalDst); else if (totalDst > totalSrc) src.add(totalDst - totalSrc); supply = src.stream().mapToInt(i -> i).toArray(); demand = dst.stream().mapToInt(i -> i).toArray(); costs = new double[supply.length][demand.length]; matrix = new Shipment[supply.length][demand.length]; for (int i = 0; i < numSources; i++) for (int j = 0; j < numDestinations; j++) costs[i][j] = sc.nextDouble(); } } static void northWestCornerRule() { for (int r = 0, northwest = 0; r < supply.length; r++) for (int c = northwest; c < demand.length; c++) { int quantity = Math.min(supply[r], demand[c]); if (quantity > 0) { matrix[r][c] = new Shipment(quantity, costs[r][c], r, c); supply[r] -= quantity; demand[c] -= quantity; if (supply[r] == 0) { northwest = c; break; } } } } static void steppingStone() { double maxReduction = 0; Shipment[] move = null; Shipment leaving = null; fixDegenerateCase(); for (int r = 0; r < supply.length; r++) { for (int c = 0; c < demand.length; c++) { if (matrix[r][c] != null) continue; Shipment trial = new Shipment(0, costs[r][c], r, c); Shipment[] path = getClosedPath(trial); double reduction = 0; double lowestQuantity = Integer.MAX_VALUE; Shipment leavingCandidate = null; boolean plus = true; for (Shipment s : path) { if (plus) { reduction += s.costPerUnit; } else { reduction -= s.costPerUnit; if (s.quantity < lowestQuantity) { leavingCandidate = s; lowestQuantity = s.quantity; } } plus = !plus; } if (reduction < maxReduction) { move = path; leaving = leavingCandidate; maxReduction = reduction; } } } if (move != null) { double q = leaving.quantity; boolean plus = true; for (Shipment s : move) { s.quantity += plus ? q : -q; matrix[s.r][s.c] = s.quantity == 0 ? null : s; plus = !plus; } steppingStone(); } } static LinkedList<Shipment> matrixToList() { return stream(matrix) .flatMap(row -> stream(row)) .filter(s -> s != null) .collect(toCollection(LinkedList::new)); } static Shipment[] getClosedPath(Shipment s) { LinkedList<Shipment> path = matrixToList(); path.addFirst(s); while (path.removeIf(e -> { Shipment[] nbrs = getNeighbors(e, path); return nbrs[0] == null || nbrs[1] == null; })); Shipment[] stones = path.toArray(new Shipment[path.size()]); Shipment prev = s; for (int i = 0; i < stones.length; i++) { stones[i] = prev; prev = getNeighbors(prev, path)[i % 2]; } return stones; } static Shipment[] getNeighbors(Shipment s, LinkedList<Shipment> lst) { Shipment[] nbrs = new Shipment[2]; for (Shipment o : lst) { if (o != s) { if (o.r == s.r && nbrs[0] == null) nbrs[0] = o; else if (o.c == s.c && nbrs[1] == null) nbrs[1] = o; if (nbrs[0] != null && nbrs[1] != null) break; } } return nbrs; } static void fixDegenerateCase() { final double eps = Double.MIN_VALUE; if (supply.length + demand.length - 1 != matrixToList().size()) { for (int r = 0; r < supply.length; r++) for (int c = 0; c < demand.length; c++) { if (matrix[r][c] == null) { Shipment dummy = new Shipment(eps, costs[r][c], r, c); if (getClosedPath(dummy).length == 0) { matrix[r][c] = dummy; return; } } } } } static void printResult(String filename) { System.out.printf("Optimal solution %s%n%n", filename); double totalCosts = 0; for (int r = 0; r < supply.length; r++) { for (int c = 0; c < demand.length; c++) { Shipment s = matrix[r][c]; if (s != null && s.r == r && s.c == c) { System.out.printf(" %3s ", (int) s.quantity); totalCosts += (s.quantity * s.costPerUnit); } else System.out.printf(" - "); } System.out.println(); } System.out.printf("%nTotal costs: %s%n%n", totalCosts); } public static void main(String[] args) throws Exception { for (String filename : new String[]{"input1.txt", "input2.txt", "input3.txt"}) { init(filename); northWestCornerRule(); steppingStone(); printResult(filename); } } }
Convert the following code from Java to Go, ensuring the logic remains intact.
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
package main import ( "fmt" ) const numbers = 3 func main() { max := 20 words := map[int]string{ 3: "Fizz", 5: "Buzz", 7: "Baxx", } keys := []int{3, 5, 7} divisible := false for i := 1; i <= max; i++ { for _, n := range keys { if i % n == 0 { fmt.Print(words[n]) divisible = true } } if !divisible { fmt.Print(i) } fmt.Println() divisible = false } }
Convert the following code from Java to Go, ensuring the logic remains intact.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
Change the programming language of this snippet from Java to Go without modifying what it does.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
Port the provided Java code into Go while preserving the original functionality.
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
Please provide an equivalent version of this Java code in Go.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void play() { digits = getSolvableDigits(); Scanner in = new Scanner(System.in); while (true) { System.out.print("Make 24 using these digits: "); System.out.println(digits); System.out.println("(Enter 'q' to quit, 's' for a solution)"); System.out.print("> "); String line = in.nextLine(); if (line.equalsIgnoreCase("q")) { System.out.println("\nThanks for playing"); return; } if (line.equalsIgnoreCase("s")) { System.out.println(solution); digits = getSolvableDigits(); continue; } char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray(); try { validate(entry); if (evaluate(infixToPostfix(entry))) { System.out.println("\nCorrect! Want to try another? "); digits = getSolvableDigits(); } else { System.out.println("\nNot correct."); } } catch (Exception e) { System.out.printf("%n%s Try again.%n", e.getMessage()); } } } void validate(char[] input) throws Exception { int total1 = 0, parens = 0, opsCount = 0; for (char c : input) { if (Character.isDigit(c)) total1 += 1 << (c - '0') * 4; else if (c == '(') parens++; else if (c == ')') parens--; else if (ops.indexOf(c) != -1) opsCount++; if (parens < 0) throw new Exception("Parentheses mismatch."); } if (parens != 0) throw new Exception("Parentheses mismatch."); if (opsCount != 3) throw new Exception("Wrong number of operators."); int total2 = 0; for (int d : digits) total2 += 1 << d * 4; if (total1 != total2) throw new Exception("Not the same digits."); } boolean evaluate(char[] line) throws Exception { Stack<Float> s = new Stack<>(); try { for (char c : line) { if ('0' <= c && c <= '9') s.push((float) c - '0'); else s.push(applyOperator(s.pop(), s.pop(), c)); } } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return (Math.abs(24 - s.peek()) < 0.001F); } float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } List<Integer> randomDigits() { Random r = new Random(); List<Integer> result = new ArrayList<>(4); for (int i = 0; i < 4; i++) result.add(r.nextInt(9) + 1); return result; } List<Integer> getSolvableDigits() { List<Integer> result; do { result = randomDigits(); } while (!isSolvable(result)); return result; } boolean isSolvable(List<Integer> digits) { Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2); permute(digits, dPerms, 0); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>(total); permuteOperators(oPerms, 4, total); StringBuilder sb = new StringBuilder(4 + 3); for (String pattern : patterns) { char[] patternChars = pattern.toCharArray(); for (List<Integer> dig : dPerms) { for (List<Integer> opr : oPerms) { int i = 0, j = 0; for (char c : patternChars) { if (c == 'n') sb.append(dig.get(i++)); else sb.append(ops.charAt(opr.get(j++))); } String candidate = sb.toString(); try { if (evaluate(candidate.toCharArray())) { solution = postfixToInfix(candidate); return true; } } catch (Exception ignored) { } sb.setLength(0); } } } return false; } String postfixToInfix(String postfix) { class Expression { String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format("%s %s %s", e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } } Stack<Expression> expr = new Stack<>(); for (char c : postfix.toCharArray()) { int idx = ops.indexOf(c); if (idx != -1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec) l.ex = '(' + l.ex + ')'; if (r.prec <= opPrec) r.ex = '(' + r.ex + ')'; expr.push(new Expression(l.ex, r.ex, "" + c)); } else { expr.push(new Expression("" + c)); } } return expr.peek().ex; } char[] infixToPostfix(char[] infix) throws Exception { StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); try { for (char c : infix) { int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 >= prec1) sb.append(ops.charAt(s.pop())); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())); s.pop(); } else { sb.append(c); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())); } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return sb.toString().toCharArray(); } void permute(List<Integer> lst, Set<List<Integer>> res, int k) { for (int i = k; i < lst.size(); i++) { Collections.swap(lst, i, k); permute(lst, res, k + 1); Collections.swap(lst, k, i); } if (k == lst.size()) res.add(new ArrayList<>(lst)); } void permuteOperators(List<List<Integer>> res, int n, int total) { for (int i = 0, npow = n * n; i < total; i++) res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); } }
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
Please provide an equivalent version of this Java code in Go.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void play() { digits = getSolvableDigits(); Scanner in = new Scanner(System.in); while (true) { System.out.print("Make 24 using these digits: "); System.out.println(digits); System.out.println("(Enter 'q' to quit, 's' for a solution)"); System.out.print("> "); String line = in.nextLine(); if (line.equalsIgnoreCase("q")) { System.out.println("\nThanks for playing"); return; } if (line.equalsIgnoreCase("s")) { System.out.println(solution); digits = getSolvableDigits(); continue; } char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray(); try { validate(entry); if (evaluate(infixToPostfix(entry))) { System.out.println("\nCorrect! Want to try another? "); digits = getSolvableDigits(); } else { System.out.println("\nNot correct."); } } catch (Exception e) { System.out.printf("%n%s Try again.%n", e.getMessage()); } } } void validate(char[] input) throws Exception { int total1 = 0, parens = 0, opsCount = 0; for (char c : input) { if (Character.isDigit(c)) total1 += 1 << (c - '0') * 4; else if (c == '(') parens++; else if (c == ')') parens--; else if (ops.indexOf(c) != -1) opsCount++; if (parens < 0) throw new Exception("Parentheses mismatch."); } if (parens != 0) throw new Exception("Parentheses mismatch."); if (opsCount != 3) throw new Exception("Wrong number of operators."); int total2 = 0; for (int d : digits) total2 += 1 << d * 4; if (total1 != total2) throw new Exception("Not the same digits."); } boolean evaluate(char[] line) throws Exception { Stack<Float> s = new Stack<>(); try { for (char c : line) { if ('0' <= c && c <= '9') s.push((float) c - '0'); else s.push(applyOperator(s.pop(), s.pop(), c)); } } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return (Math.abs(24 - s.peek()) < 0.001F); } float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } List<Integer> randomDigits() { Random r = new Random(); List<Integer> result = new ArrayList<>(4); for (int i = 0; i < 4; i++) result.add(r.nextInt(9) + 1); return result; } List<Integer> getSolvableDigits() { List<Integer> result; do { result = randomDigits(); } while (!isSolvable(result)); return result; } boolean isSolvable(List<Integer> digits) { Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2); permute(digits, dPerms, 0); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>(total); permuteOperators(oPerms, 4, total); StringBuilder sb = new StringBuilder(4 + 3); for (String pattern : patterns) { char[] patternChars = pattern.toCharArray(); for (List<Integer> dig : dPerms) { for (List<Integer> opr : oPerms) { int i = 0, j = 0; for (char c : patternChars) { if (c == 'n') sb.append(dig.get(i++)); else sb.append(ops.charAt(opr.get(j++))); } String candidate = sb.toString(); try { if (evaluate(candidate.toCharArray())) { solution = postfixToInfix(candidate); return true; } } catch (Exception ignored) { } sb.setLength(0); } } } return false; } String postfixToInfix(String postfix) { class Expression { String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format("%s %s %s", e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } } Stack<Expression> expr = new Stack<>(); for (char c : postfix.toCharArray()) { int idx = ops.indexOf(c); if (idx != -1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec) l.ex = '(' + l.ex + ')'; if (r.prec <= opPrec) r.ex = '(' + r.ex + ')'; expr.push(new Expression(l.ex, r.ex, "" + c)); } else { expr.push(new Expression("" + c)); } } return expr.peek().ex; } char[] infixToPostfix(char[] infix) throws Exception { StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); try { for (char c : infix) { int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 >= prec1) sb.append(ops.charAt(s.pop())); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())); s.pop(); } else { sb.append(c); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())); } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return sb.toString().toCharArray(); } void permute(List<Integer> lst, Set<List<Integer>> res, int k) { for (int i = k; i < lst.size(); i++) { Collections.swap(lst, i, k); permute(lst, res, k + 1); Collections.swap(lst, k, i); } if (k == lst.size()) res.add(new ArrayList<>(lst)); } void permuteOperators(List<List<Integer>> res, int n, int total) { for (int i = 0, npow = n * n; i < total; i++) res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); } }
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.Scanner; import java.util.Random; public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks(in.nextInt()); } private static void runTasks(int nTasks){ for(int i = 0; i < nTasks; i++){ System.out.println("Starting task number " + (i+1) + "."); runThreads(); Worker.checkpoint(); } } private static void runThreads(){ for(int i = 0; i < Worker.nWorkers; i ++){ new Thread(new Worker(i+1)).start(); } } public static class Worker implements Runnable{ public Worker(int threadID){ this.threadID = threadID; } public void run(){ work(); } private synchronized void work(){ try { int workTime = rgen.nextInt(900) + 100; System.out.println("Worker " + threadID + " will work for " + workTime + " msec."); Thread.sleep(workTime); nFinished++; System.out.println("Worker " + threadID + " is ready"); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } public static synchronized void checkpoint(){ while(nFinished != nWorkers){ try { Thread.sleep(10); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } nFinished = 0; } private int threadID; private static Random rgen = new Random(); private static int nFinished = 0; public static int nWorkers = 0; } }
package main import ( "log" "math/rand" "sync" "time" ) func worker(part string) { log.Println(part, "worker begins part") time.Sleep(time.Duration(rand.Int63n(1e6))) log.Println(part, "worker completes part") wg.Done() } var ( partList = []string{"A", "B", "C", "D"} nAssemblies = 3 wg sync.WaitGroup ) func main() { rand.Seed(time.Now().UnixNano()) for c := 1; c <= nAssemblies; c++ { log.Println("begin assembly cycle", c) wg.Add(len(partList)) for _, part := range partList { go worker(part) } wg.Wait() log.Println("assemble. cycle", c, "complete") } }
Port the following code from Java to Go with equivalent syntax and logic.
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curByte = (int)(n & 0x7F); if (i != (numBytes - 1)) curByte |= 0x80; output[i] = (byte)curByte; n >>>= 7; } return output; } public static long decode(byte[] b) { long n = 0; for (int i = 0; i < b.length; i++) { int curByte = b[i] & 0xFF; n = (n << 7) | (curByte & 0x7F); if ((curByte & 0x80) == 0) break; } return n; } public static String byteArrayToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { if (i > 0) sb.append(", "); String s = Integer.toHexString(b[i] & 0xFF); if (s.length() < 2) s = "0" + s; sb.append(s); } return sb.toString(); } public static void main(String[] args) { long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; for (long n : testNumbers) { byte[] encoded = encode(n); long decoded = decode(encoded); System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); } } }
package main import ( "fmt" "encoding/binary" ) func main() { buf := make([]byte, binary.MaxVarintLen64) for _, x := range []int64{0x200000, 0x1fffff} { v := buf[:binary.PutVarint(buf, x)] fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v) x, _ = binary.Varint(v) fmt.Println(x, "decoded") } }
Write the same code in Go as shown below in Java.
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curByte = (int)(n & 0x7F); if (i != (numBytes - 1)) curByte |= 0x80; output[i] = (byte)curByte; n >>>= 7; } return output; } public static long decode(byte[] b) { long n = 0; for (int i = 0; i < b.length; i++) { int curByte = b[i] & 0xFF; n = (n << 7) | (curByte & 0x7F); if ((curByte & 0x80) == 0) break; } return n; } public static String byteArrayToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { if (i > 0) sb.append(", "); String s = Integer.toHexString(b[i] & 0xFF); if (s.length() < 2) s = "0" + s; sb.append(s); } return sb.toString(); } public static void main(String[] args) { long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; for (long n : testNumbers) { byte[] encoded = encode(n); long decoded = decode(encoded); System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); } } }
package main import ( "fmt" "encoding/binary" ) func main() { buf := make([]byte, binary.MaxVarintLen64) for _, x := range []int64{0x200000, 0x1fffff} { v := buf[:binary.PutVarint(buf, x)] fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v) x, _ = binary.Varint(v) fmt.Println(x, "decoded") } }
Keep all operations the same but rewrite the snippet in Go.
import java.io.*; import java.security.*; import java.util.*; public class SHA256MerkleTree { public static void main(String[] args) { if (args.length != 1) { System.err.println("missing file argument"); System.exit(1); } try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) { byte[] digest = sha256MerkleTree(in, 1024); if (digest != null) System.out.println(digestToString(digest)); } catch (Exception e) { e.printStackTrace(); } } private static String digestToString(byte[] digest) { StringBuilder result = new StringBuilder(); for (int i = 0; i < digest.length; ++i) result.append(String.format("%02x", digest[i])); return result.toString(); } private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception { byte[] buffer = new byte[blockSize]; int bytes; MessageDigest md = MessageDigest.getInstance("SHA-256"); List<byte[]> digests = new ArrayList<>(); while ((bytes = in.read(buffer)) > 0) { md.reset(); md.update(buffer, 0, bytes); digests.add(md.digest()); } int length = digests.size(); if (length == 0) return null; while (length > 1) { int j = 0; for (int i = 0; i < length; i += 2, ++j) { byte[] digest1 = digests.get(i); if (i + 1 < length) { byte[] digest2 = digests.get(i + 1); md.reset(); md.update(digest1); md.update(digest2); digests.set(j, md.digest()); } else { digests.set(j, digest1); } } length = j; } return digests.get(0); } }
package main import ( "crypto/sha256" "fmt" "io" "log" "os" ) func main() { const blockSize = 1024 f, err := os.Open("title.png") if err != nil { log.Fatal(err) } defer f.Close() var hashes [][]byte buffer := make([]byte, blockSize) h := sha256.New() for { bytesRead, err := f.Read(buffer) if err != nil { if err != io.EOF { log.Fatal(err) } break } h.Reset() h.Write(buffer[:bytesRead]) hashes = append(hashes, h.Sum(nil)) } buffer = make([]byte, 64) for len(hashes) > 1 { var hashes2 [][]byte for i := 0; i < len(hashes); i += 2 { if i < len(hashes)-1 { copy(buffer, hashes[i]) copy(buffer[32:], hashes[i+1]) h.Reset() h.Write(buffer) hashes2 = append(hashes2, h.Sum(nil)) } else { hashes2 = append(hashes2, hashes[i]) } } hashes = hashes2 } fmt.Printf("%x", hashes[0]) fmt.Println() }
Transform the following Java implementation into Go, maintaining the same output and logic.
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("äàâáçñßæεбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
package main import ( "fmt" "strings" "unicode" "unicode/utf8" ) func main() { show("alphaBETA") show("alpha BETA") show("DŽLjnj") show("o'hare O'HARE o’hare don't") } func show(s string) { fmt.Println("\nstring: ", s, " len:", utf8.RuneCountInString(s), "runes") fmt.Println("All upper case: ", strings.ToUpper(s)) fmt.Println("All lower case: ", strings.ToLower(s)) fmt.Println("All title case: ", strings.ToTitle(s)) fmt.Println("Title words: ", strings.Title(s)) fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) }
Rewrite the snippet below in Go so it works the same as the original Java code.
import javax.swing.*; public class GetInputSwing { public static void main(String[] args) throws Exception { int number = Integer.parseInt( JOptionPane.showInputDialog ("Enter an Integer")); String string = JOptionPane.showInputDialog ("Enter a String"); } }
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str1, str2 string) bool { n, err := strconv.ParseFloat(str2, 64) if len(str1) == 0 || err != nil || n != 75000 { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid input", ) dialog.Run() dialog.Destroy() return false } return 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() }) vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1) check(err, "Unable to create vertical box:") vbox.SetBorderWidth(1) hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create first horizontal box:") hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create second horizontal box:") label, err := gtk.LabelNew("Enter a string and the number 75000 \n") check(err, "Unable to create label:") sel, err := gtk.LabelNew("String: ") check(err, "Unable to create string entry label:") nel, err := gtk.LabelNew("Number: ") check(err, "Unable to create number entry label:") se, err := gtk.EntryNew() check(err, "Unable to create string entry:") ne, err := gtk.EntryNew() check(err, "Unable to create number entry:") hbox1.PackStart(sel, false, false, 2) hbox1.PackStart(se, false, false, 2) hbox2.PackStart(nel, false, false, 2) hbox2.PackStart(ne, false, false, 2) ab, err := gtk.ButtonNewWithLabel("Accept") check(err, "Unable to create accept button:") ab.Connect("clicked", func() { str1, _ := se.GetText() str2, _ := ne.GetText() if validateInput(window, str1, str2) { window.Destroy() } }) vbox.Add(label) vbox.Add(hbox1) vbox.Add(hbox2) vbox.Add(ab) window.Add(vbox) window.ShowAll() gtk.Main() }
Keep all operations the same but rewrite the snippet in Go.
final PVector t = new PVector(20, 30, 60); void setup() { size(450, 400); noLoop(); background(0, 0, 200); stroke(-1); sc(7, 400, -60, t); } PVector sc(int o, float l, final int a, final PVector s) { if (o > 0) { sc(--o, l *= .5, -a, s).z += a; sc(o, l, a, s).z += a; sc(o, l, -a, s); } else line(s.x, s.y, s.x += cos(radians(s.z)) * l, s.y += sin(radians(s.z)) * l); return s; }
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) iy = 1.0 theta = 0 ) var cx, cy, h float64 func arrowhead(order int, length float64) { if order&1 == 0 { curve(order, length, 60) } else { turn(60) curve(order, length, -60) } drawLine(length) } func drawLine(length float64) { dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h) rads := gg.Radians(float64(theta)) cx += length * math.Cos(rads) cy += length * math.Sin(rads) } func turn(angle int) { theta = (theta + angle) % 360 } func curve(order int, length float64, angle int) { if order == 0 { drawLine(length) } else { curve(order-1, length/2, -angle) turn(angle) curve(order-1, length/2, angle) turn(angle) curve(order-1, length/2, -angle) } } func main() { dc.SetRGB(0, 0, 0) dc.Clear() order := 6 if order&1 == 0 { iy = -1 } cx, cy = width/2, height h = cx / 2 arrowhead(order, cx) dc.SetRGB255(255, 0, 255) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_arrowhead_curve.png") }
Convert this Java block to Go, preserving its control flow and logic.
import java.io.File; import java.util.*; import static java.lang.System.out; public class TextProcessing1 { public static void main(String[] args) throws Exception { Locale.setDefault(new Locale("en", "US")); Metrics metrics = new Metrics(); int dataGap = 0; String gapBeginDate = null; try (Scanner lines = new Scanner(new File("readings.txt"))) { while (lines.hasNextLine()) { double lineTotal = 0.0; int linePairs = 0; int lineInvalid = 0; String lineDate; try (Scanner line = new Scanner(lines.nextLine())) { lineDate = line.next(); while (line.hasNext()) { final double value = line.nextDouble(); if (line.nextInt() <= 0) { if (dataGap == 0) gapBeginDate = lineDate; dataGap++; lineInvalid++; continue; } lineTotal += value; linePairs++; metrics.addDataGap(dataGap, gapBeginDate, lineDate); dataGap = 0; } } metrics.addLine(lineTotal, linePairs); metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal); } metrics.report(); } } private static class Metrics { private List<String[]> gapDates; private int maxDataGap = -1; private double total; private int pairs; private int lineResultCount; void addLine(double tot, double prs) { total += tot; pairs += prs; } void addDataGap(int gap, String begin, String end) { if (gap > 0 && gap >= maxDataGap) { if (gap > maxDataGap) { maxDataGap = gap; gapDates = new ArrayList<>(); } gapDates.add(new String[]{begin, end}); } } void lineResult(String date, int invalid, int prs, double tot) { if (lineResultCount >= 3) return; out.printf("%10s out: %2d in: %2d tot: %10.3f avg: %10.3f%n", date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0); lineResultCount++; } void report() { out.printf("%ntotal = %10.3f%n", total); out.printf("readings = %6d%n", pairs); out.printf("average = %010.3f%n", total / pairs); out.printf("%nmaximum run(s) of %d invalid measurements: %n", maxDataGap); for (String[] dates : gapDates) out.printf("begins at %s and ends at %s%n", dates[0], dates[1]); } } }
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) const ( filename = "readings.txt" readings = 24 fields = readings*2 + 1 ) func main() { file, err := os.Open(filename) if err != nil { log.Fatal(err) } defer file.Close() var ( badRun, maxRun int badDate, maxDate string fileSum float64 fileAccept int ) endBadRun := func() { if badRun > maxRun { maxRun = badRun maxDate = badDate } badRun = 0 } s := bufio.NewScanner(file) for s.Scan() { f := strings.Fields(s.Text()) if len(f) != fields { log.Fatal("unexpected format,", len(f), "fields.") } var accept int var sum float64 for i := 1; i < fields; i += 2 { flag, err := strconv.Atoi(f[i+1]) if err != nil { log.Fatal(err) } if flag <= 0 { if badRun++; badRun == 1 { badDate = f[0] } } else { endBadRun() value, err := strconv.ParseFloat(f[i], 64) if err != nil { log.Fatal(err) } sum += value accept++ } } fmt.Printf("Line: %s Reject %2d Accept: %2d Line_tot:%9.3f", f[0], readings-accept, accept, sum) if accept > 0 { fmt.Printf(" Line_avg:%8.3f\n", sum/float64(accept)) } else { fmt.Println() } fileSum += sum fileAccept += accept } if err := s.Err(); err != nil { log.Fatal(err) } endBadRun() fmt.Println("\nFile =", filename) fmt.Printf("Total = %.3f\n", fileSum) fmt.Println("Readings = ", fileAccept) if fileAccept > 0 { fmt.Printf("Average =  %.3f\n", fileSum/float64(fileAccept)) } if maxRun == 0 { fmt.Println("\nAll data valid.") } else { fmt.Printf("\nMax data gap = %d, beginning on line %s.\n", maxRun, maxDate) } }
Write the same algorithm in Go as shown in this Java implementation.
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digester { public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); } static String hexDigest(String str, String digestName) { try { MessageDigest md = MessageDigest.getInstance(digestName); byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8)); char[] hex = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4); hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f); } return new String(hex); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
package main import ( "crypto/md5" "fmt" ) func main() { for _, p := range [][2]string{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, {"e38ca1d920c4b8b8d3946b2c72f01680", "The quick brown fox jumped over the lazy dog's back"}, } { validate(p[0], p[1]) } } var h = md5.New() func validate(check, s string) { h.Reset() h.Write([]byte(s)) sum := fmt.Sprintf("%x", h.Sum(nil)) if sum != check { fmt.Println("MD5 fail") fmt.Println(" for string,", s) fmt.Println(" expected: ", check) fmt.Println(" got: ", sum) } }
Preserve the algorithm and functionality while converting the code from Java to Go.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Keep all operations the same but rewrite the snippet in Go.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Translate this program into Go but keep the logic exactly as in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.time.*; import java.time.format.*; class Main { public static void main(String args[]) { String dateStr = "March 7 2009 7:30pm EST"; DateTimeFormatter df = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("MMMM d yyyy h:mma zzz") .toFormatter(); ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12); System.out.println("Date: " + dateStr); System.out.println("+12h: " + after12Hours.format(df)); ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET")); System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df)); } }
package main import ( "fmt" "time" ) const taskDate = "March 7 2009 7:30pm EST" const taskFormat = "January 2 2006 3:04pm MST" func main() { if etz, err := time.LoadLocation("US/Eastern"); err == nil { time.Local = etz } fmt.Println("Input: ", taskDate) t, err := time.Parse(taskFormat, taskDate) if err != nil { fmt.Println(err) return } t = t.Add(12 * time.Hour) fmt.Println("+12 hrs: ", t) if _, offset := t.Zone(); offset == 0 { fmt.Println("No time zone info.") return } atz, err := time.LoadLocation("US/Arizona") if err == nil { fmt.Println("+12 hrs in Arizona:", t.In(atz)) } }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await(); Thread.sleep(num * 1000); System.out.println(num); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { int[] nums = new int[args.length]; for (int i = 0; i < args.length; i++) nums[i] = Integer.parseInt(args[i]); sleepSortAndPrint(nums); } }
package main import ( "fmt" "log" "os" "strconv" "time" ) func main() { out := make(chan uint64) for _, a := range os.Args[1:] { i, err := strconv.ParseUint(a, 10, 64) if err != nil { log.Fatal(err) } go func(n uint64) { time.Sleep(time.Duration(n) * time.Millisecond) out <- n }(i) } for _ = range os.Args[1:] { fmt.Println(<-out) } }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) values := make([][]int, 10) for i := range values { values[i] = make([]int, 10) for j := range values[i] { values[i][j] = rand.Intn(20) + 1 } } outerLoop: for i, row := range values { fmt.Printf("%3d)", i) for _, value := range row { fmt.Printf(" %3d", value) if value == 20 { break outerLoop } } fmt.Printf("\n") } fmt.Printf("\n") }
Convert this Java snippet to Go and keep its semantics consistent.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
Write a version of this Java function in Go with identical behavior.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
Transform the following Java implementation into Go, maintaining the same output and logic.
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
package main import "fmt" func uniq(list []int) []int { unique_set := make(map[int]bool, len(list)) for _, x := range list { unique_set[x] = true } result := make([]int, 0, len(unique_set)) for x := range unique_set { result = append(result, x) } return result } func main() { fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) }
Preserve the algorithm and functionality while converting the code from Java to Go.
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
Convert this Java snippet to Go and keep its semantics consistent.
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
Convert this Java snippet to Go and keep its semantics consistent.
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
var intStack []int
Transform the following Java implementation into Go, maintaining the same output and logic.
public class TotientFunction { public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max)); } } private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; } private static final int max = 10000000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { t >>= 1 } if t > 0 { n = t } else { k = -t } t = n - k } return n * s } func totient(n int) int { tot := 0 for k := 1; k <= n; k++ { if gcd(n, k) == 1 { tot++ } } return tot } func main() { fmt.Println(" n phi prime") fmt.Println("---------------") count := 0 for n := 1; n <= 25; n++ { tot := totient(n) isPrime := n-1 == tot if isPrime { count++ } fmt.Printf("%2d %2d %t\n", n, tot, isPrime) } fmt.Println("\nNumber of primes up to 25 =", count) for n := 26; n <= 100000; n++ { tot := totient(n) if tot == n-1 { count++ } if n == 100 || n == 1000 || n%10000 == 0 { fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count) } } }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
if booleanExpression { statements }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Fractran{ public static void main(String []args){ new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); } final int limit = 15; Vector<Integer> num = new Vector<>(); Vector<Integer> den = new Vector<>(); public Fractran(String prog, Integer val){ compile(prog); dump(); exec(2); } void compile(String prog){ Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); Matcher matcher = regexp.matcher(prog); while(matcher.find()){ num.add(Integer.parseInt(matcher.group(1))); den.add(Integer.parseInt(matcher.group(2))); matcher = regexp.matcher(matcher.group(3)); } } void exec(Integer val){ int n = 0; while(val != null && n<limit){ System.out.println(n+": "+val); val = step(val); n++; } } Integer step(int val){ int i=0; while(i<den.size() && val%den.get(i) != 0) i++; if(i<den.size()) return num.get(i)*val/den.get(i); return null; } void dump(){ for(int i=0; i<den.size(); i++) System.out.print(num.get(i)+"/"+den.get(i)+" "); System.out.println(); } }
package main import ( "fmt" "log" "math/big" "os" "strconv" "strings" ) func compile(src string) ([]big.Rat, bool) { s := strings.Fields(src) r := make([]big.Rat, len(s)) for i, s1 := range s { if _, ok := r[i].SetString(s1); !ok { return nil, false } } return r, true } func exec(p []big.Rat, n *big.Int, limit int) { var q, r big.Int rule: for i := 0; i < limit; i++ { fmt.Printf("%d ", n) for j := range p { q.QuoRem(n, p[j].Denom(), &r) if r.BitLen() == 0 { n.Mul(&q, p[j].Num()) continue rule } } break } fmt.Println() } func usage() { log.Fatal("usage: ft <limit> <n> <prog>") } func main() { if len(os.Args) != 4 { usage() } limit, err := strconv.Atoi(os.Args[1]) if err != nil { usage() } var n big.Int _, ok := n.SetString(os.Args[2], 10) if !ok { usage() } p, ok := compile(os.Args[3]) if !ok { usage() } exec(p, &n, limit) }
Please provide an equivalent version of this Java code in Go.
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Fractran{ public static void main(String []args){ new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); } final int limit = 15; Vector<Integer> num = new Vector<>(); Vector<Integer> den = new Vector<>(); public Fractran(String prog, Integer val){ compile(prog); dump(); exec(2); } void compile(String prog){ Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); Matcher matcher = regexp.matcher(prog); while(matcher.find()){ num.add(Integer.parseInt(matcher.group(1))); den.add(Integer.parseInt(matcher.group(2))); matcher = regexp.matcher(matcher.group(3)); } } void exec(Integer val){ int n = 0; while(val != null && n<limit){ System.out.println(n+": "+val); val = step(val); n++; } } Integer step(int val){ int i=0; while(i<den.size() && val%den.get(i) != 0) i++; if(i<den.size()) return num.get(i)*val/den.get(i); return null; } void dump(){ for(int i=0; i<den.size(); i++) System.out.print(num.get(i)+"/"+den.get(i)+" "); System.out.println(); } }
package main import ( "fmt" "log" "math/big" "os" "strconv" "strings" ) func compile(src string) ([]big.Rat, bool) { s := strings.Fields(src) r := make([]big.Rat, len(s)) for i, s1 := range s { if _, ok := r[i].SetString(s1); !ok { return nil, false } } return r, true } func exec(p []big.Rat, n *big.Int, limit int) { var q, r big.Int rule: for i := 0; i < limit; i++ { fmt.Printf("%d ", n) for j := range p { q.QuoRem(n, p[j].Denom(), &r) if r.BitLen() == 0 { n.Mul(&q, p[j].Num()) continue rule } } break } fmt.Println() } func usage() { log.Fatal("usage: ft <limit> <n> <prog>") } func main() { if len(os.Args) != 4 { usage() } limit, err := strconv.Atoi(os.Args[1]) if err != nil { usage() } var n big.Int _, ok := n.SetString(os.Args[2], 10) if !ok { usage() } p, ok := compile(os.Args[3]) if !ok { usage() } exec(p, &n, limit) }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.Arrays; public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); } public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1); } public static void stoogeSort(int[] L, int i, int j) { if (L[j] < L[i]) { int tmp = L[i]; L[i] = L[j]; L[j] = tmp; } if (j - i > 1) { int t = (j - i + 1) / 3; stoogeSort(L, i, j - t); stoogeSort(L, i + t, j); stoogeSort(L, i, j - t); } } }
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] } if last > 1 { t := len(a) / 3 stoogesort(a[:len(a)-t]) stoogesort(a[t:]) stoogesort(a[:len(a)-t]) } }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; private final Random m_random = new Random(); public GaltonBox( final int pinRows, final int ballCount ) { m_pinRows = pinRows; m_startRow = pinRows + 1; m_balls = new Position[ ballCount ]; for ( int ball = 0; ball < ballCount; ball++ ) m_balls[ ball ] = new Position( m_startRow, 0, 'o' ); } private static class Position { int m_row; int m_col; char m_char; Position( final int row, final int col, final char ch ) { m_row = row; m_col = col; m_char = ch; } } public void run() { for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) { ballsInPlay = dropBalls(); print(); } } private int dropBalls() { int ballsInPlay = 0; int ballToStart = -1; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == m_startRow ) ballToStart = ball; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( ball == ballToStart ) { m_balls[ ball ].m_row = m_pinRows; ballsInPlay++; } else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) { m_balls[ ball ].m_row -= 1; m_balls[ ball ].m_col += m_random.nextInt( 2 ); if ( 0 != m_balls[ ball ].m_row ) ballsInPlay++; } return ballsInPlay; } private void print() { for ( int row = m_startRow; row --> 1; ) { for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == row ) printBall( m_balls[ ball ] ); System.out.println(); printPins( row ); } printCollectors(); System.out.println(); } private static void printBall( final Position pos ) { for ( int col = pos.m_row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = 0; col < pos.m_col; col++ ) System.out.print( " " ); System.out.print( pos.m_char ); } private void printPins( final int row ) { for ( int col = row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = m_startRow - row; col --> 0; ) System.out.print( ". " ); System.out.println(); } private void printCollectors() { final List<List<Position>> collectors = new ArrayList<List<Position>>(); for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = new ArrayList<Position>(); collectors.add( collector ); for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col ) collector.add( m_balls[ ball ] ); } for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) { for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = collectors.get( col ); final int pos = row + collector.size() - rows; System.out.print( '|' ); if ( pos >= 0 ) System.out.print( collector.get( pos ).m_char ); else System.out.print( ' ' ); } System.out.println( '|' ); } } private static final int longest( final List<List<Position>> collectors ) { int result = 0; for ( final List<Position> collector : collectors ) result = Math.max( collector.size(), result ); return result; } }
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) type Ball struct{ x, y int } func newBall(x, y int) *Ball { if box[y][x] != empty { panic("Tried to create a new ball in a non-empty cell. Program terminated.") } b := Ball{x, y} box[y][x] = ball return &b } func (b *Ball) doStep() { if b.y <= 0 { return } cell := box[b.y-1][b.x] switch cell { case empty: box[b.y][b.x] = empty b.y-- box[b.y][b.x] = ball case pin: box[b.y][b.x] = empty b.y-- if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty { b.x += rand.Intn(2)*2 - 1 box[b.y][b.x] = ball return } else if box[b.y][b.x-1] == empty { b.x++ } else { b.x-- } box[b.y][b.x] = ball default: } } type Cell = byte var box [boxH][boxW]Cell func initializeBox() { box[0][0] = corner box[0][boxW-1] = corner for i := 1; i < boxW-1; i++ { box[0][i] = floor } for i := 0; i < boxW; i++ { box[boxH-1][i] = box[0][i] } for r := 1; r < boxH-1; r++ { box[r][0] = wall box[r][boxW-1] = wall } for i := 1; i < boxH-1; i++ { for j := 1; j < boxW-1; j++ { box[i][j] = empty } } for nPins := 1; nPins <= pinsBaseW; nPins++ { for p := 0; p < nPins; p++ { box[boxH-2-nPins][centerH+1-nPins+p*2] = pin } } } func drawBox() { for r := boxH - 1; r >= 0; r-- { for c := 0; c < boxW; c++ { fmt.Printf("%c", box[r][c]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) initializeBox() var balls []*Ball for i := 0; i < nMaxBalls+boxH; i++ { fmt.Println("\nStep", i, ":") if i < nMaxBalls { balls = append(balls, newBall(centerH, boxH-2)) } drawBox() for _, b := range balls { b.doStep() } } }
Port the provided Java code into Go while preserving the original functionality.
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toString(arr)); } while (circleSortR(arr, 0, arr.length - 1, 0) != 0); } private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps; int high = hi; int low = lo; int mid = (hi - lo) / 2; while (lo < hi) { if (arr[lo] > arr[hi]) { swap(arr, lo, hi); numSwaps++; } lo++; hi--; } if (lo == hi && arr[lo] > arr[hi + 1]) { swap(arr, lo, hi + 1); numSwaps++; } numSwaps = circleSortR(arr, low, low + mid, numSwaps); numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps); return numSwaps; } private static void swap(int[] arr, int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } }
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circleSort(a, low, low+mid, swaps) swaps = circleSort(a, low+mid+1, high, swaps) return swaps } func main() { aa := [][]int{ {6, 7, 8, 9, 2, 5, 3, 4, 1}, {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}, } for _, a := range aa { fmt.Printf("Original: %v\n", a) for circleSort(a, 0, len(a)-1, 0) != 0 { } fmt.Printf("Sorted  : %v\n\n", a) } }
Maintain the same structure and functionality when rewriting this code in Go.
package kronecker; public class ProductFractals { public static int[][] product(final int[][] a, final int[][] b) { final int[][] c = new int[a.length*b.length][]; for (int ix = 0; ix < c.length; ix++) { final int num_cols = a[0].length*b[0].length; c[ix] = new int[num_cols]; } for (int ia = 0; ia < a.length; ia++) { for (int ja = 0; ja < a[ia].length; ja++) { for (int ib = 0; ib < b.length; ib++) { for (int jb = 0; jb < b[ib].length; jb++) { c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb]; } } } } return c; } public static void show_matrix(final int[][] m, final char nz, final char z) { for (int im = 0; im < m.length; im++) { for (int jm = 0; jm < m[im].length; jm++) { System.out.print(m[im][jm] == 0 ? z : nz); } System.out.println(); } } public static int[][] power(final int[][] m, final int n) { int[][] m_pow = m; for (int ix = 1; ix < n; ix++) { m_pow = product(m, m_pow); } return m_pow; } private static void test(final int[][] m, final int n) { System.out.println("Test matrix"); show_matrix(m, '*', ' '); final int[][] m_pow = power(m, n); System.out.println("Matrix power " + n); show_matrix(m_pow, '*', ' '); } private static void test1() { final int[][] m = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}; test(m, 4); } private static void test2() { final int[][] m = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; test(m, 4); } private static void test3() { final int[][] m = {{1, 0, 1}, {1, 0, 1}, {0, 1, 0}}; test(m, 4); } public static void main(final String[] args) { test1(); test2(); test3(); } }
package main import "fmt" type matrix [][]int func (m1 matrix) kroneckerProduct(m2 matrix) matrix { m := len(m1) n := len(m1[0]) p := len(m2) q := len(m2[0]) rtn := m * p ctn := n * q r := make(matrix, rtn) for i := range r { r[i] = make([]int, ctn) } for i := 0; i < m; i++ { for j := 0; j < n; j++ { for k := 0; k < p; k++ { for l := 0; l < q; l++ { r[p*i+k][q*j+l] = m1[i][j] * m2[k][l] } } } } return r } func (m matrix) kroneckerPower(n int) matrix { pow := m for i := 1; i < n; i++ { pow = pow.kroneckerProduct(m) } return pow } func (m matrix) print(text string) { fmt.Println(text, "fractal :\n") for i := range m { for j := range m[0] { if m[i][j] == 1 { fmt.Print("*") } else { fmt.Print(" ") } } fmt.Println() } fmt.Println() } func main() { m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}} m1.kroneckerPower(4).print("Vivsek") m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}} m2.kroneckerPower(4).print("Sierpinski carpet") }
Translate this program into Go but keep the logic exactly as in Java.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{ put( "needspeeling", false ); put( "seedsremoved", false ); }}; public static void main( final String[] args ) { System.out.println( parseFile( args[ 0 ] ) ); } public static Map<String, Object> parseFile( final String fileName ) { final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS ); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( fileName ) ); for ( String line; null != ( line = reader.readLine() ); ) { parseLine( line, result ); } } catch ( final IOException x ) { throw new RuntimeException( "Oops: " + x, x ); } finally { if ( null != reader ) try { reader.close(); } catch ( final IOException x2 ) { System.err.println( "Could not close " + fileName + " - " + x2 ); } } return result; } private static void parseLine( final String line, final Map<String, Object> map ) { if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) return; final Matcher matcher = LINE_PATTERN.matcher( line ); if ( ! matcher.matches() ) { System.err.println( "Bad config line: " + line ); return; } final String key = matcher.group( 1 ).trim().toLowerCase(); final String value = matcher.group( 2 ).trim(); if ( "".equals( value ) ) { map.put( key, true ); } else if ( -1 == value.indexOf( ',' ) ) { map.put( key, value ); } else { final String[] values = value.split( "," ); for ( int i = 0; i < values.length; i++ ) { values[ i ] = values[ i ].trim(); } map.put( key, Arrays.asList( values ) ); } } }
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.util.Comparator; import java.util.Arrays; public class Test { public static void main(String[] args) { String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; Arrays.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { int c = s2.length() - s1.length(); if (c == 0) c = s1.compareToIgnoreCase(s2); return c; } }); for (String s: strings) System.out.print(s + " "); } }
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
Translate this program into Go but keep the logic exactly as in Java.
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0) System.out.print(", "); System.out.print(p); ++count; } } System.out.println(); System.out.println("Next 4 circular primes:"); int repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; BigInteger bignum = BigInteger.valueOf(repunit); for (int count = 0; count < 4; ) { if (bignum.isProbablePrime(15)) { if (count > 0) System.out.print(", "); System.out.printf("R(%d)", digits); ++count; } ++digits; bignum = bignum.multiply(BigInteger.TEN); bignum = bignum.add(BigInteger.ONE); } System.out.println(); testRepunit(5003); testRepunit(9887); testRepunit(15073); testRepunit(25031); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static int cycle(int n) { int m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } private static boolean isCircularPrime(int p) { if (!isPrime(p)) return false; int p2 = cycle(p); while (p2 != p) { if (p2 < p || !isPrime(p2)) return false; p2 = cycle(p2); } return true; } private static void testRepunit(int digits) { BigInteger repunit = repunit(digits); if (repunit.isProbablePrime(15)) System.out.printf("R(%d) is probably prime.\n", digits); else System.out.printf("R(%d) is not prime.\n", digits); } private static BigInteger repunit(int digits) { char[] ch = new char[digits]; Arrays.fill(ch, '1'); return new BigInteger(new String(ch)); } }
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func repunit(n int) *big.Int { ones := strings.Repeat("1", n) b, _ := new(big.Int).SetString(ones, 10) return b } var circs = []int{} func alreadyFound(n int) bool { for _, i := range circs { if i == n { return true } } return false } func isCircular(n int) bool { nn := n pow := 1 for nn > 0 { pow *= 10 nn /= 10 } nn = n for { nn *= 10 f := nn / pow nn += f * (1 - pow) if alreadyFound(nn) { return false } if nn == n { break } if !isPrime(nn) { return false } } return true } func main() { fmt.Println("The first 19 circular primes are:") digits := [4]int{1, 3, 7, 9} q := []int{1, 2, 3, 5, 7, 9} fq := []int{1, 2, 3, 5, 7, 9} count := 0 for { f := q[0] fd := fq[0] if isPrime(f) && isCircular(f) { circs = append(circs, f) count++ if count == 19 { break } } copy(q, q[1:]) q = q[:len(q)-1] copy(fq, fq[1:]) fq = fq[:len(fq)-1] if f == 2 || f == 5 { continue } for _, d := range digits { if d >= fd { q = append(q, f*10+d) fq = append(fq, fd) } } } fmt.Println(circs) fmt.Println("\nThe next 4 circular primes, in repunit format, are:") count = 0 var rus []string for i := 7; count < 4; i++ { if repunit(i).ProbablyPrime(10) { count++ rus = append(rus, fmt.Sprintf("R(%d)", i)) } } fmt.Println(rus) fmt.Println("\nThe following repunits are probably circular primes:") for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} { fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10)) } }
Write the same algorithm in Go as shown in this Java implementation.
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0) System.out.print(", "); System.out.print(p); ++count; } } System.out.println(); System.out.println("Next 4 circular primes:"); int repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; BigInteger bignum = BigInteger.valueOf(repunit); for (int count = 0; count < 4; ) { if (bignum.isProbablePrime(15)) { if (count > 0) System.out.print(", "); System.out.printf("R(%d)", digits); ++count; } ++digits; bignum = bignum.multiply(BigInteger.TEN); bignum = bignum.add(BigInteger.ONE); } System.out.println(); testRepunit(5003); testRepunit(9887); testRepunit(15073); testRepunit(25031); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static int cycle(int n) { int m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } private static boolean isCircularPrime(int p) { if (!isPrime(p)) return false; int p2 = cycle(p); while (p2 != p) { if (p2 < p || !isPrime(p2)) return false; p2 = cycle(p2); } return true; } private static void testRepunit(int digits) { BigInteger repunit = repunit(digits); if (repunit.isProbablePrime(15)) System.out.printf("R(%d) is probably prime.\n", digits); else System.out.printf("R(%d) is not prime.\n", digits); } private static BigInteger repunit(int digits) { char[] ch = new char[digits]; Arrays.fill(ch, '1'); return new BigInteger(new String(ch)); } }
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func repunit(n int) *big.Int { ones := strings.Repeat("1", n) b, _ := new(big.Int).SetString(ones, 10) return b } var circs = []int{} func alreadyFound(n int) bool { for _, i := range circs { if i == n { return true } } return false } func isCircular(n int) bool { nn := n pow := 1 for nn > 0 { pow *= 10 nn /= 10 } nn = n for { nn *= 10 f := nn / pow nn += f * (1 - pow) if alreadyFound(nn) { return false } if nn == n { break } if !isPrime(nn) { return false } } return true } func main() { fmt.Println("The first 19 circular primes are:") digits := [4]int{1, 3, 7, 9} q := []int{1, 2, 3, 5, 7, 9} fq := []int{1, 2, 3, 5, 7, 9} count := 0 for { f := q[0] fd := fq[0] if isPrime(f) && isCircular(f) { circs = append(circs, f) count++ if count == 19 { break } } copy(q, q[1:]) q = q[:len(q)-1] copy(fq, fq[1:]) fq = fq[:len(fq)-1] if f == 2 || f == 5 { continue } for _, d := range digits { if d >= fd { q = append(q, f*10+d) fq = append(fq, fd) } } } fmt.Println(circs) fmt.Println("\nThe next 4 circular primes, in repunit format, are:") count = 0 var rus []string for i := 7; count < 4; i++ { if repunit(i).ProbablyPrime(10) { count++ rus = append(rus, fmt.Sprintf("R(%d)", i)) } } fmt.Println(rus) fmt.Println("\nThe following repunits are probably circular primes:") for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} { fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10)) } }
Translate the given Java code snippet into Go without altering its behavior.
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; public class Rotate { private static class State { private final String text = "Hello World! "; private int startIndex = 0; private boolean rotateRight = true; } public static void main(String[] args) { State state = new State(); JLabel label = new JLabel(state.text); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { state.rotateRight = !state.rotateRight; } }); TimerTask task = new TimerTask() { public void run() { int delta = state.rotateRight ? 1 : -1; state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length(); label.setText(rotate(state.text, state.startIndex)); } }; Timer timer = new Timer(false); timer.schedule(task, 0, 500); JFrame rot = new JFrame(); rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); rot.add(label); rot.pack(); rot.setLocationRelativeTo(null); rot.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { timer.cancel(); } }); rot.setVisible(true); } private static String rotate(String text, int startIdx) { char[] rotated = new char[text.length()]; for (int i = 0; i < text.length(); i++) { rotated[i] = text.charAt((i + startIdx) % text.length()); } return String.valueOf(rotated); } }
package main import ( "log" "time" "github.com/gdamore/tcell" ) const ( msg = "Hello World! " x0, y0 = 8, 3 shiftsPerSecond = 4 clicksToExit = 5 ) func main() { s, err := tcell.NewScreen() if err != nil { log.Fatal(err) } if err = s.Init(); err != nil { log.Fatal(err) } s.Clear() s.EnableMouse() tick := time.Tick(time.Second / shiftsPerSecond) click := make(chan bool) go func() { for { em, ok := s.PollEvent().(*tcell.EventMouse) if !ok || em.Buttons()&0xFF == tcell.ButtonNone { continue } mx, my := em.Position() if my == y0 && mx >= x0 && mx < x0+len(msg) { click <- true } } }() for inc, shift, clicks := 1, 0, 0; ; { select { case <-tick: shift = (shift + inc) % len(msg) for i, r := range msg { s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0) } s.Show() case <-click: clicks++ if clicks == clicksToExit { s.Fini() return } inc = len(msg) - inc } } }
Write the same algorithm in Go as shown in this Java implementation.
public static int[] sort(int[] old) { for (int shift = Integer.SIZE - 1; shift > -1; shift--) { int[] tmp = new int[old.length]; int j = 0; for (int i = 0; i < old.length; i++) { boolean move = old[i] << shift >= 0; if (shift == 0 ? !move : move) { tmp[j] = old[i]; j++; } else { old[i - j] = old[i]; } } for (int i = j; i < tmp.length; i++) { tmp[i] = old[i - j]; } old = tmp; } return old; }
package main import ( "bytes" "encoding/binary" "fmt" ) type word int32 const wordLen = 4 const highBit = -1 << 31 var data = []word{170, 45, 75, -90, -802, 24, 2, 66} func main() { buf := bytes.NewBuffer(nil) ds := make([][]byte, len(data)) for i, x := range data { binary.Write(buf, binary.LittleEndian, x^highBit) b := make([]byte, wordLen) buf.Read(b) ds[i] = b } bins := make([][][]byte, 256) for i := 0; i < wordLen; i++ { for _, b := range ds { bins[b[i]] = append(bins[b[i]], b) } j := 0 for k, bs := range bins { copy(ds[j:], bs) j += len(bs) bins[k] = bs[:0] } } fmt.Println("original:", data) var w word for i, b := range ds { buf.Write(b) binary.Read(buf, binary.LittleEndian, &w) data[i] = w^highBit } fmt.Println("sorted: ", data) }
Convert this Java block to Go, preserving its control flow and logic.
import java.util.Arrays; import java.util.List; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public interface PythagComp{ static void main(String... args){ System.out.println(run(20)); } static List<List<Integer>> run(int n){ return range(1, n).mapToObj( x -> range(x, n).mapToObj( y -> range(y, n).mapToObj( z -> new Integer[]{x, y, z} ) ) ) .flatMap(identity()) .flatMap(identity()) .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) .map(Arrays::asList) .collect(toList()) ; } }
package main import "fmt" type ( seq []int sofs []seq ) func newSeq(start, end int) seq { if end < start { end = start } s := make(seq, end-start+1) for i := 0; i < len(s); i++ { s[i] = start + i } return s } func newSofs() sofs { return sofs{seq{}} } func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs { var s2 sofs for _, t := range expr(s, in) { if pred(t) { s2 = append(s2, t) } } return s2 } func (s sofs) build(t seq) sofs { var u sofs for _, ss := range s { for _, tt := range t { uu := make(seq, len(ss)) copy(uu, ss) uu = append(uu, tt) u = append(u, uu) } } return u } func main() { pt := newSofs() in := newSeq(1, 20) expr := func(s sofs, t seq) sofs { return s.build(t).build(t).build(t) } pred := func(t seq) bool { if len(t) != 3 { return false } return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2] } pt = pt.listComp(in, expr, pred) fmt.Println(pt) }
Keep all operations the same but rewrite the snippet in Go.
public static void sort(int[] nums){ for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ int smallest = Integer.MAX_VALUE; int smallestAt = currentPlace+1; for(int check = currentPlace; check<nums.length;check++){ if(nums[check]<smallest){ smallestAt = check; smallest = nums[check]; } } int temp = nums[currentPlace]; nums[currentPlace] = nums[smallestAt]; nums[smallestAt] = temp; } }
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) selectionSort(a) fmt.Println("after: ", a) } func selectionSort(a []int) { last := len(a) - 1 for i := 0; i < last; i++ { aMin := a[i] iMin := i for j := i + 1; j < len(a); j++ { if a[j] < aMin { aMin = a[j] iMin = j } } a[i], a[iMin] = aMin, a[i] } }
Translate the given Java code snippet into Go without altering its behavior.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
Generate a Go translation of this Java snippet without changing its computational steps.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
Keep all operations the same but rewrite the snippet in Go.
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
Generate a Go translation of this Java snippet without changing its computational steps.
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
public class ArrayCallback7 { interface IntConsumer { void run(int x); } interface IntToInt { int run(int x); } static void forEach(int[] arr, IntConsumer consumer) { for (int i : arr) { consumer.run(i); } } static void update(int[] arr, IntToInt mapper) { for (int i = 0; i < arr.length; i++) { arr[i] = mapper.run(arr[i]); } } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); update(numbers, new IntToInt() { @Override public int run(int x) { return x * x; } }); forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); } }
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
Change the programming language of this snippet from Java to Go without modifying what it does.
public class ArrayCallback7 { interface IntConsumer { void run(int x); } interface IntToInt { int run(int x); } static void forEach(int[] arr, IntConsumer consumer) { for (int i : arr) { consumer.run(i); } } static void update(int[] arr, IntToInt mapper) { for (int i = 0; i < arr.length; i++) { arr[i] = mapper.run(arr[i]); } } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); update(numbers, new IntToInt() { @Override public int run(int x) { return x * x; } }); forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); } }
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
Produce a language-to-language conversion: from Java to Go, same semantics.
class Singleton { private static Singleton myInstance; public static Singleton getInstance() { if (myInstance == null) { synchronized(Singleton.class) { if (myInstance == null) { myInstance = new Singleton(); } } } return myInstance; } protected Singleton() { } }
package main import ( "log" "math/rand" "sync" "time" ) var ( instance string once sync.Once ) func claim(color string, w *sync.WaitGroup) { time.Sleep(time.Duration(rand.Intn(1e8))) log.Println("trying to claim", color) once.Do(func() { instance = color }) log.Printf("tried %s. instance: %s", color, instance) w.Done() } func main() { rand.Seed(time.Now().Unix()) var w sync.WaitGroup w.Add(2) go claim("red", &w) go claim("blue", &w) w.Wait() log.Println("after trying both, instance =", instance) }
Generate an equivalent Go version of this Java code.
public class SafeAddition { private static double stepDown(double d) { return Math.nextAfter(d, Double.NEGATIVE_INFINITY); } private static double stepUp(double d) { return Math.nextUp(d); } private static double[] safeAdd(double a, double b) { return new double[]{stepDown(a + b), stepUp(a + b)}; } public static void main(String[] args) { double a = 1.2; double b = 0.03; double[] result = safeAdd(a, b); System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]); } }
package main import ( "fmt" "math" ) type interval struct { lower, upper float64 } func stepAway(x float64) interval { return interval { math.Nextafter(x, math.Inf(-1)), math.Nextafter(x, math.Inf(1))} } func safeAdd(a, b float64) interval { return stepAway(a + b) } func main() { a, b := 1.2, .03 fmt.Println(a, b, safeAdd(a, b)) }
Convert the following code from Java to Go, ensuring the logic remains intact.
String dog = "Benjamin"; String Dog = "Samba"; String DOG = "Bernie"; @Inject Console console; console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
package dogs import "fmt" var dog = "Salt" var Dog = "Pepper" var DOG = "Mustard" func PackageSees() map[*string]int { fmt.Println("Package sees:", dog, Dog, DOG) return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1} }
Write the same algorithm in Go as shown in this Java implementation.
for (int i = 10; i >= 0; i--) { System.out.println(i); }
for i := 10; i >= 0; i-- { fmt.Println(i) }
Change the programming language of this snippet from Java to Go without modifying what it does.
import java.io.*; public class Test { public static void main(String[] args) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) { bw.write("abc"); } } }
import "io/ioutil" func main() { ioutil.WriteFile("path/to/your.file", []byte("data"), 0644) }
Rewrite the snippet below in Go so it works the same as the original Java code.
for (Integer i = 0; i < 5; i++) { String line = ''; for (Integer j = 0; j < i; j++) { line += '*'; } System.debug(line); } List<String> lines = new List<String> { '*', '**', '***', '****', '*****' }; for (String line : lines) { System.debug(line); }
package main import "fmt" func main() { for i := 1; i <= 5; i++ { for j := 1; j <= i; j++ { fmt.Printf("*") } fmt.Printf("\n") } }
Generate an equivalent Go version of this Java code.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) 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 ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
Write the same code in Go as shown below in Java.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) 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 ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
Can you help me rewrite this code in Go instead of Java, keeping it the same logically?
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Convert this Java block to Go, preserving its control flow and logic.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Preserve the algorithm and functionality while converting the code from Java to Go.
public class NonContinuousSubsequences { public static void main(String args[]) { seqR("1234", "", 0, 0); } private static void seqR(String s, String c, int i, int added) { if (i == s.length()) { if (c.trim().length() > added) System.out.println(c); } else { seqR(s, c + s.charAt(i), i + 1, added + 1); seqR(s, c + ' ', i + 1, added); } } }
package main import "fmt" const ( m = iota c cm cmc ) func ncs(s []int) [][]int { if len(s) < 3 { return nil } return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...) } var skip = []int{m, cm, cm, cmc} var incl = []int{c, c, cmc, cmc} func n2(ss, tail []int, seq int) [][]int { if len(tail) == 0 { if seq != cmc { return nil } return [][]int{ss} } return append(n2(append([]int{}, ss...), tail[1:], skip[seq]), n2(append(ss, tail[0]), tail[1:], incl[seq])...) } func main() { ss := ncs([]int{1, 2, 3, 4}) fmt.Println(len(ss), "non-continuous subsequences:") for _, s := range ss { fmt.Println(" ", s) } }
Change the following Java code into Go without altering its purpose.
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n) { if (n < 2) return n == 1 ? "1" : ""; StringBuilder f1 = new StringBuilder("1"); StringBuilder f2 = new StringBuilder("0"); for (n = n - 2; n > 0; n--) { String tmp = f2.toString(); f2.append(f1); f1.setLength(0); f1.append(tmp); } return f2.toString(); } void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) { for (int n = 0; n < wordFractal.length(); n++) { g.drawLine(x, y, x + dx, y + dy); x += dx; y += dy; if (wordFractal.charAt(n) == '0') { int tx = dx; dx = (n % 2 == 0) ? -dy : dy; dy = (n % 2 == 0) ? tx : -tx; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawWordFractal(g, 20, 20, 1, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Fibonacci Word Fractal"); f.setResizable(false); f.add(new FibonacciWordFractal(23), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >= 1; j-- { tmp := f2.String() f2.WriteString(f1.String()) f1.Reset() f1.WriteString(tmp) } return f2.String() } func draw(dc *gg.Context, x, y, dx, dy float64, wf string) { for i, c := range wf { dc.DrawLine(x, y, x+dx, y+dy) x += dx y += dy if c == '0' { tx := dx dx = dy if i%2 == 0 { dx = -dy } dy = -tx if i%2 == 0 { dy = tx } } } } func main() { dc := gg.NewContext(450, 620) dc.SetRGB(0, 0, 0) dc.Clear() wf := wordFractal(23) draw(dc, 20, 20, 1, 0, wf) dc.SetRGB(0, 1, 0) dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("fib_wordfractal.png") }
Produce a functionally identical Go code for the snippet given in Java.
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
package main import "fmt" func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { c := sieve(1e10 - 1) limit := 10 start := 3 twins := 0 for i := 1; i < 11; i++ { for i := start; i < limit; i += 2 { if !c[i] && !c[i-2] { twins++ } } fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins)) start = limit + 1 limit *= 10 } }
Rewrite this program in Go while keeping its functionality equivalent to the Java version.
import java.util.Locale; public class Test { public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); } public static void unity(int n) { System.out.printf("%n%d: ", n); for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) { double real = Math.cos(angle); if (Math.abs(real) < 1.0E-3) real = 0.0; double imag = Math.sin(angle); if (Math.abs(imag) < 1.0E-3) imag = 0.0; System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
package main import ( "fmt" "math" "math/cmplx" ) func main() { for n := 2; n <= 5; n++ { fmt.Printf("%d roots of 1:\n", n) for _, r := range roots(n) { fmt.Printf(" %18.15f\n", r) } } } func roots(n int) []complex128 { r := make([]complex128, n) for i := 0; i < n; i++ { r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n)) } return r }
Maintain the same structure and functionality when rewriting this code in Go.
import java.util.Locale; public class Test { public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); } public static void unity(int n) { System.out.printf("%n%d: ", n); for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) { double real = Math.cos(angle); if (Math.abs(real) < 1.0E-3) real = 0.0; double imag = Math.sin(angle); if (Math.abs(imag) < 1.0E-3) imag = 0.0; System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
package main import ( "fmt" "math" "math/cmplx" ) func main() { for n := 2; n <= 5; n++ { fmt.Printf("%d roots of 1:\n", n) for _, r := range roots(n) { fmt.Printf(" %18.15f\n", r) } } } func roots(n int) []complex128 { r := make([]complex128, n) for i := 0; i < n; i++ { r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n)) } return r }
Ensure the translated Go code behaves exactly like the original Java snippet.
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
package main import "fmt" func d(b byte) byte { if b < '0' || b > '9' { panic("digit 0-9 expected") } return b - '0' } func add(x, y string) string { if len(y) > len(x) { x, y = y, x } b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { if i <= len(y) { c += d(y[len(y)-i]) } s := d(x[len(x)-i]) + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mulDigit(x string, y byte) string { if y == '0' { return "0" } y = d(y) b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { s := d(x[len(x)-i])*y + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mul(x, y string) string { result := mulDigit(x, y[len(y)-1]) for i, zeros := 2, ""; i <= len(y); i++ { zeros += "0" result = add(result, mulDigit(x, y[len(y)-i])+zeros) } return result } const n = "18446744073709551616" func main() { fmt.Println(mul(n, n)) }
Convert the following code from Java to Go, ensuring the logic remains intact.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PellsEquation { public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } } private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } } private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b; while ( true ) { int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; } private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; } }
package main import ( "fmt" "math/big" ) var big1 = new(big.Int).SetUint64(1) func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1) e1 := new(big.Int).SetUint64(1) e2 := new(big.Int) f1 := new(big.Int) f2 := new(big.Int).SetUint64(1) t := new(big.Int) u := new(big.Int) a := new(big.Int) b := new(big.Int) for { t.Mul(r, z) y.Sub(t, y) t.Mul(y, y) t.Sub(n, t) z.Quo(t, z) t.Add(x, y) r.Quo(t, z) u.Set(e1) e1.Set(e2) t.Mul(r, e2) e2.Add(t, u) u.Set(f1) f1.Set(f2) t.Mul(r, f2) f2.Add(t, u) t.Mul(x, f2) a.Add(e2, t) b.Set(f2) t.Mul(a, a) u.Mul(n, b) u.Mul(u, b) t.Sub(t, u) if t.Cmp(big1) == 0 { return a, b } } } func main() { ns := []uint64{61, 109, 181, 277} for _, n := range ns { x, y := solvePell(n) fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y) } }
Ensure the translated Go code behaves exactly like the original Java snippet.
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); } public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
package main import ( "bufio" "bytes" "fmt" "math/rand" "os" "strings" "time" ) func main() { fmt.Println(`Cows and Bulls Guess four digit number of unique digits in the range 1 to 9. A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bull.`) pat := make([]byte, 4) rand.Seed(time.Now().Unix()) r := rand.Perm(9) for i := range pat { pat[i] = '1' + byte(r[i]) } valid := []byte("123456789") guess: for in := bufio.NewReader(os.Stdin); ; { fmt.Print("Guess: ") guess, err := in.ReadString('\n') if err != nil { fmt.Println("\nSo, bye.") return } guess = strings.TrimSpace(guess) if len(guess) != 4 { fmt.Println("Please guess a four digit number.") continue } var cows, bulls int for ig, cg := range guess { if strings.IndexRune(guess[:ig], cg) >= 0 { fmt.Printf("Repeated digit: %c\n", cg) continue guess } switch bytes.IndexByte(pat, byte(cg)) { case -1: if bytes.IndexByte(valid, byte(cg)) == -1 { fmt.Printf("Invalid digit: %c\n", cg) continue guess } default: cows++ case ig: bulls++ } } fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) if bulls == 4 { fmt.Println("You got it.") return } } }
Port the provided Java code into Go while preserving the original functionality.
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
package main import "fmt" func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) bubblesort(list) fmt.Println("sorted! ", list) } func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
Produce a language-to-language conversion: from Java to Go, same semantics.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
Write a version of this Java function in Go with identical behavior.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
Change the following Java code into Go without altering its purpose.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
Produce a language-to-language conversion: from Java to Go, same semantics.
import java.io.*; public class FileIODemo { public static void main(String[] args) { try { FileInputStream in = new FileInputStream("input.txt"); FileOutputStream out = new FileOutputStream("ouput.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } }
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
Generate a Go translation of this Java snippet without changing its computational steps.
import java.util.Scanner; public class IntegerArithmetic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int sum = a + b; int difference = a - b; int product = a * b; int division = a / b; int remainder = a % b; System.out.println("a + b = " + sum); System.out.println("a - b = " + difference); System.out.println("a * b = " + product); System.out.println("quotient of a / b = " + division); System.out.println("remainder of a / b = " + remainder); } }
package main import "fmt" func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d + %d = %d\n", a, b, a+b) fmt.Printf("%d - %d = %d\n", a, b, a-b) fmt.Printf("%d * %d = %d\n", a, b, a*b) fmt.Printf("%d / %d = %d\n", a, b, a/b) fmt.Printf("%d %% %d = %d\n", a, b, a%b) }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.Arrays; public class Transpose{ public static void main(String[] args){ double[][] m = {{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}, {5, 25, 125, 625}}; double[][] ans = new double[m[0].length][m.length]; for(int rows = 0; rows < m.length; rows++){ for(int cols = 0; cols < m[0].length; cols++){ ans[cols][rows] = m[rows][cols]; } } for(double[] i:ans){ System.out.println(Arrays.toString(i)); } } }
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { m := mat.NewDense(2, 3, []float64{ 1, 2, 3, 4, 5, 6, }) fmt.Println(mat.Formatted(m)) fmt.Println() fmt.Println(mat.Formatted(m.T())) }
Transform the following Java implementation into Go, maintaining the same output and logic.
import java.util.Arrays; public class Transpose{ public static void main(String[] args){ double[][] m = {{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}, {5, 25, 125, 625}}; double[][] ans = new double[m[0].length][m.length]; for(int rows = 0; rows < m.length; rows++){ for(int cols = 0; cols < m[0].length; cols++){ ans[cols][rows] = m[rows][cols]; } } for(double[] i:ans){ System.out.println(Arrays.toString(i)); } } }
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { m := mat.NewDense(2, 3, []float64{ 1, 2, 3, 4, 5, 6, }) fmt.Println(mat.Formatted(m)) fmt.Println() fmt.Println(mat.Formatted(m.T())) }
Produce a functionally identical Go code for the snippet given in Java.
import java.util.function.DoubleSupplier; public class ManOrBoy { static double A(int k, DoubleSupplier x1, DoubleSupplier x2, DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) { DoubleSupplier B = new DoubleSupplier() { int m = k; public double getAsDouble() { return A(--m, this, x1, x2, x3, x4); } }; return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble(); } public static void main(String[] args) { System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0)); } }
package main import "fmt" func a(k int, x1, x2, x3, x4, x5 func() int) int { var b func() int b = func() int { k-- return a(k, b, x1, x2, x3, x4) } if k <= 0 { return x4() + x5() } return b() } func main() { x := func(i int) func() int { return func() int { return i } } fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0))) }