Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class ImmutableMap {
public static void main(String[] args) {
Map<String,Integer> hashMap = getImmutableMap();
try {
hashMap.put("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put new value.");
}
try {
hashMap.clear();
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to clear map.");
}
try {
hashMap.putIfAbsent("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put if absent.");
}
for ( String key : hashMap.keySet() ) {
System.out.printf("key = %s, value = %s%n", key, hashMap.get(key));
}
}
private static Map<String,Integer> getImmutableMap() {
Map<String,Integer> hashMap = new HashMap<>();
hashMap.put("Key 1", 34);
hashMap.put("Key 2", 105);
hashMap.put("Key 3", 144);
return Collections.unmodifiableMap(hashMap);
}
}
| package romap
type Romap struct{ imap map[byte]int }
func New(m map[byte]int) *Romap {
if m == nil {
return nil
}
return &Romap{m}
}
func (rom *Romap) Get(key byte) (int, bool) {
i, ok := rom.imap[key]
return i, ok
}
func (rom *Romap) Reset(key byte) {
_, ok := rom.imap[key]
if ok {
rom.imap[key] = 0
}
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
public class Copypasta
{
public static void fatal_error(String errtext)
{
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName();
System.out.println("%" + errtext);
System.out.println("usage: " + mainClass + " [filename.cp]");
System.exit(1);
}
public static void main(String[] args)
{
String fname = null;
String source = null;
try
{
fname = args[0];
source = new String(Files.readAllBytes(new File(fname).toPath()));
}
catch(Exception e)
{
fatal_error("error while trying to read from specified file");
}
ArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split("\n")));
String clipboard = "";
int loc = 0;
while(loc < lines.size())
{
String command = lines.get(loc).trim();
try
{
if(command.equals("Copy"))
clipboard += lines.get(loc + 1);
else if(command.equals("CopyFile"))
{
if(lines.get(loc + 1).equals("TheF*ckingCode"))
clipboard += source;
else
{
String filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));
clipboard += filetext;
}
}
else if(command.equals("Duplicate"))
{
String origClipboard = clipboard;
int amount = Integer.parseInt(lines.get(loc + 1)) - 1;
for(int i = 0; i < amount; i++)
clipboard += origClipboard;
}
else if(command.equals("Pasta!"))
{
System.out.println(clipboard);
System.exit(0);
}
else
fatal_error("unknown command '" + command + "' encountered on line " + new Integer(loc + 1).toString());
}
catch(Exception e)
{
fatal_error("error while executing command '" + command + "' on line " + new Integer(loc + 1).toString());
}
loc += 2;
}
}
}
|
package main
import (
"fmt"
"github.com/atotto/clipboard"
"io/ioutil"
"log"
"os"
"runtime"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
clipboard.WriteAll("")
log.Fatal(err)
}
}
func interpret(source string) {
source2 := source
if runtime.GOOS == "windows" {
source2 = strings.ReplaceAll(source, "\r\n", "\n")
}
lines := strings.Split(source2, "\n")
le := len(lines)
for i := 0; i < le; i++ {
lines[i] = strings.TrimSpace(lines[i])
switch lines[i] {
case "Copy":
if i == le-1 {
log.Fatal("There are no lines after the Copy command.")
}
i++
err := clipboard.WriteAll(lines[i])
check(err)
case "CopyFile":
if i == le-1 {
log.Fatal("There are no lines after the CopyFile command.")
}
i++
if lines[i] == "TheF*ckingCode" {
err := clipboard.WriteAll(source)
check(err)
} else {
bytes, err := ioutil.ReadFile(lines[i])
check(err)
err = clipboard.WriteAll(string(bytes))
check(err)
}
case "Duplicate":
if i == le-1 {
log.Fatal("There are no lines after the Duplicate command.")
}
i++
times, err := strconv.Atoi(lines[i])
check(err)
if times < 0 {
log.Fatal("Can't duplicate text a negative number of times.")
}
text, err := clipboard.ReadAll()
check(err)
err = clipboard.WriteAll(strings.Repeat(text, times+1))
check(err)
case "Pasta!":
text, err := clipboard.ReadAll()
check(err)
fmt.Println(text)
return
default:
if lines[i] == "" {
continue
}
log.Fatal("Unknown command, " + lines[i])
}
}
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There should be exactly one command line argument, the CopyPasta file path.")
}
bytes, err := ioutil.ReadFile(os.Args[1])
check(err)
interpret(string(bytes))
err = clipboard.WriteAll("")
check(err)
}
|
Keep all operations the same but rewrite the snippet in Go. | 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();
}
}
| package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)
func sqrt(n float64, limit int) {
if n < 0 {
log.Fatal("Number cannot be negative")
}
count := 0
for n != math.Trunc(n) {
n *= 100
count--
}
i := big.NewInt(int64(n))
j := new(big.Int).Sqrt(i)
count += len(j.String())
k := new(big.Int).Set(j)
d := new(big.Int).Set(j)
t := new(big.Int)
digits := 0
var sb strings.Builder
for digits < limit {
sb.WriteString(d.String())
t.Mul(k, d)
i.Sub(i, t)
i.Mul(i, hundred)
k.Mul(j, twenty)
d.Set(one)
for d.Cmp(ten) <= 0 {
t.Add(k, d)
t.Mul(t, d)
if t.Cmp(i) > 0 {
d.Sub(d, one)
break
}
d.Add(d, one)
}
j.Mul(j, ten)
j.Add(j, d)
k.Add(k, d)
digits = digits + 1
}
root := strings.TrimRight(sb.String(), "0")
if len(root) == 0 {
root = "0"
}
if count > 0 {
root = root[0:count] + "." + root[count:]
} else if count == 0 {
root = "0." + root
} else {
root = "0." + strings.Repeat("0", -count) + root
}
root = strings.TrimSuffix(root, ".")
fmt.Println(root)
}
func main() {
numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
digits := []int{500, 80, 8, 8, 8}
for i, n := range numbers {
fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
sqrt(n, digits[i])
fmt.Println()
}
}
|
Change the following Java code into Go without altering its purpose. | 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();
}
}
| package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)
func sqrt(n float64, limit int) {
if n < 0 {
log.Fatal("Number cannot be negative")
}
count := 0
for n != math.Trunc(n) {
n *= 100
count--
}
i := big.NewInt(int64(n))
j := new(big.Int).Sqrt(i)
count += len(j.String())
k := new(big.Int).Set(j)
d := new(big.Int).Set(j)
t := new(big.Int)
digits := 0
var sb strings.Builder
for digits < limit {
sb.WriteString(d.String())
t.Mul(k, d)
i.Sub(i, t)
i.Mul(i, hundred)
k.Mul(j, twenty)
d.Set(one)
for d.Cmp(ten) <= 0 {
t.Add(k, d)
t.Mul(t, d)
if t.Cmp(i) > 0 {
d.Sub(d, one)
break
}
d.Add(d, one)
}
j.Mul(j, ten)
j.Add(j, d)
k.Add(k, d)
digits = digits + 1
}
root := strings.TrimRight(sb.String(), "0")
if len(root) == 0 {
root = "0"
}
if count > 0 {
root = root[0:count] + "." + root[count:]
} else if count == 0 {
root = "0." + root
} else {
root = "0." + strings.Repeat("0", -count) + root
}
root = strings.TrimSuffix(root, ".")
fmt.Println(root)
}
func main() {
numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
digits := []int{500, 80, 8, 8, 8}
for i, n := range numbers {
fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
sqrt(n, digits[i])
fmt.Println()
}
}
|
Preserve the algorithm and functionality while converting the code from Java to Go. | 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));
}
}
}
| package main
import (
"fmt"
"image"
"reflect"
)
type t struct {
X int
next *t
}
func main() {
report(t{})
report(image.Point{})
}
func report(x interface{}) {
t := reflect.TypeOf(x)
n := t.NumField()
fmt.Printf("Type %v has %d fields:\n", t, n)
fmt.Println("Name Type Exported")
for i := 0; i < n; i++ {
f := t.Field(i)
fmt.Printf("%-8s %-8v %-8t\n",
f.Name,
f.Type,
f.PkgPath == "",
)
}
fmt.Println()
}
|
Translate the given Java code snippet into Go without altering its behavior. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class 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";
}
}
}
| package main
import (
"fmt"
"strings"
)
const limit = 50000
var (
divs, subs []int
mins [][]string
)
func minsteps(n int) {
if n == 1 {
mins[1] = []string{}
return
}
min := limit
var p, q int
var op byte
for _, div := range divs {
if n%div == 0 {
d := n / div
steps := len(mins[d]) + 1
if steps < min {
min = steps
p, q, op = d, div, '/'
}
}
}
for _, sub := range subs {
if d := n - sub; d >= 1 {
steps := len(mins[d]) + 1
if steps < min {
min = steps
p, q, op = d, sub, '-'
}
}
}
mins[n] = append(mins[n], fmt.Sprintf("%c%d -> %d", op, q, p))
mins[n] = append(mins[n], mins[p]...)
}
func main() {
for r := 0; r < 2; r++ {
divs = []int{2, 3}
if r == 0 {
subs = []int{1}
} else {
subs = []int{2}
}
mins = make([][]string, limit+1)
fmt.Printf("With: Divisors: %v, Subtractors: %v =>\n", divs, subs)
fmt.Println(" Minimum number of steps to diminish the following numbers down to 1 is:")
for i := 1; i <= limit; i++ {
minsteps(i)
if i <= 10 {
steps := len(mins[i])
plural := "s"
if steps == 1 {
plural = " "
}
fmt.Printf(" %2d: %d step%s: %s\n", i, steps, plural, strings.Join(mins[i], ", "))
}
}
for _, lim := range []int{2000, 20000, 50000} {
max := 0
for _, min := range mins[0 : lim+1] {
m := len(min)
if m > max {
max = m
}
}
var maxs []int
for i, min := range mins[0 : lim+1] {
if len(min) == max {
maxs = append(maxs, i)
}
}
nums := len(maxs)
verb, verb2, plural := "are", "have", "s"
if nums == 1 {
verb, verb2, plural = "is", "has", ""
}
fmt.Printf(" There %s %d number%s in the range 1-%d ", verb, nums, plural, lim)
fmt.Printf("that %s maximum 'minimal steps' of %d:\n", verb2, max)
fmt.Println(" ", maxs)
}
fmt.Println()
}
}
|
Write a version of this Java function in Go with identical behavior. | 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;
}
}
}
| package main
import (
"fmt"
"strings"
)
const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.`
type formatter struct {
text [][]string
width []int
}
func newFormatter(text string) *formatter {
var f formatter
for _, line := range strings.Split(text, "\n") {
words := strings.Split(line, "$")
for words[len(words)-1] == "" {
words = words[:len(words)-1]
}
f.text = append(f.text, words)
for i, word := range words {
if i == len(f.width) {
f.width = append(f.width, len(word))
} else if len(word) > f.width[i] {
f.width[i] = len(word)
}
}
}
return &f
}
const (
left = iota
middle
right
)
func (f formatter) print(j int) {
for _, line := range f.text {
for i, word := range line {
fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s",
len(word)+(f.width[i]-len(word))*j/2, word))
}
fmt.Println("")
}
fmt.Println("")
}
func main() {
f := newFormatter(text)
f.print(left)
f.print(middle)
f.print(right)
}
|
Convert this Java snippet to Go and keep its semantics consistent. | 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);
}
}
}
| package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo:
"urn:example:animal:ferret:nose",
"jdbc:mysql:
"ftp:
"http:
"ldap:
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet:
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh:
"https:
"http:
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | 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);
}
}
}
| package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo:
"urn:example:animal:ferret:nose",
"jdbc:mysql:
"ftp:
"http:
"ldap:
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet:
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh:
"https:
"http:
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
}
|
Produce a language-to-language conversion: from Java to Go, same semantics. | 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);
}
}
}
| package main
import (
"fmt"
"log"
"math/big"
"strings"
)
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var big0 = new(big.Int)
var big58 = big.NewInt(58)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func convertToBase58(hash string, base int) (string, error) {
var x, ok = new(big.Int).SetString(hash, base)
if !ok {
return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base)
}
var sb strings.Builder
var rem = new(big.Int)
for x.Cmp(big0) == 1 {
x.QuoRem(x, big58, rem)
r := rem.Int64()
sb.WriteByte(alphabet[r])
}
return reverse(sb.String()), nil
}
func main() {
s := "25420294593250030202636073700053352635053786165627414518"
b, err := convertToBase58(s, 10)
if err != nil {
log.Fatal(err)
}
fmt.Println(s, "->", b)
hashes := [...]string{
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
}
for _, hash := range hashes {
b58, err := convertToBase58(hash, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-56s -> %s\n", hash, b58)
}
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | 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);
}
}
}
| package main
import (
"fmt"
"log"
"math/big"
"strings"
)
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var big0 = new(big.Int)
var big58 = big.NewInt(58)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func convertToBase58(hash string, base int) (string, error) {
var x, ok = new(big.Int).SetString(hash, base)
if !ok {
return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base)
}
var sb strings.Builder
var rem = new(big.Int)
for x.Cmp(big0) == 1 {
x.QuoRem(x, big58, rem)
r := rem.Int64()
sb.WriteByte(alphabet[r])
}
return reverse(sb.String()), nil
}
func main() {
s := "25420294593250030202636073700053352635053786165627414518"
b, err := convertToBase58(s, 10)
if err != nil {
log.Fatal(err)
}
fmt.Println(s, "->", b)
hashes := [...]string{
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
}
for _, hash := range hashes {
b58, err := convertToBase58(hash, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-56s -> %s\n", hash, b58)
}
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | 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));
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
n := 0
for n < 1 || n > 5 {
fmt.Print("How many integer variables do you want to create (max 5) : ")
scanner.Scan()
n, _ = strconv.Atoi(scanner.Text())
check(scanner.Err())
}
vars := make(map[string]int)
fmt.Println("OK, enter the variable names and their values, below")
for i := 1; i <= n; {
fmt.Println("\n Variable", i)
fmt.Print(" Name : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if _, ok := vars[name]; ok {
fmt.Println(" Sorry, you've already created a variable of that name, try again")
continue
}
var value int
var err error
for {
fmt.Print(" Value : ")
scanner.Scan()
value, err = strconv.Atoi(scanner.Text())
check(scanner.Err())
if err != nil {
fmt.Println(" Not a valid integer, try again")
} else {
break
}
}
vars[name] = value
i++
}
fmt.Println("\nEnter q to quit")
for {
fmt.Print("\nWhich variable do you want to inspect : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if s := strings.ToLower(name); s == "q" {
return
}
v, ok := vars[name]
if !ok {
fmt.Println("Sorry there's no variable of that name, try again")
} else {
fmt.Println("It's value is", v)
}
}
}
|
Change the following Java code into Go without altering its purpose. | 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));
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
n := 0
for n < 1 || n > 5 {
fmt.Print("How many integer variables do you want to create (max 5) : ")
scanner.Scan()
n, _ = strconv.Atoi(scanner.Text())
check(scanner.Err())
}
vars := make(map[string]int)
fmt.Println("OK, enter the variable names and their values, below")
for i := 1; i <= n; {
fmt.Println("\n Variable", i)
fmt.Print(" Name : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if _, ok := vars[name]; ok {
fmt.Println(" Sorry, you've already created a variable of that name, try again")
continue
}
var value int
var err error
for {
fmt.Print(" Value : ")
scanner.Scan()
value, err = strconv.Atoi(scanner.Text())
check(scanner.Err())
if err != nil {
fmt.Println(" Not a valid integer, try again")
} else {
break
}
}
vars[name] = value
i++
}
fmt.Println("\nEnter q to quit")
for {
fmt.Print("\nWhich variable do you want to inspect : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if s := strings.ToLower(name); s == "q" {
return
}
v, ok := vars[name]
if !ok {
fmt.Println("Sorry there's no variable of that name, try again")
} else {
fmt.Println("It's value is", v)
}
}
}
|
Write the same algorithm in Go as shown in this Java implementation. | 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");
}
}
| package main
import (
"crypto/des"
"encoding/hex"
"fmt"
"log"
)
func main() {
key, err := hex.DecodeString("0e329232ea6d0d73")
if err != nil {
log.Fatal(err)
}
c, err := des.NewCipher(key)
if err != nil {
log.Fatal(err)
}
src, err := hex.DecodeString("8787878787878787")
if err != nil {
log.Fatal(err)
}
dst := make([]byte, des.BlockSize)
c.Encrypt(dst, src)
fmt.Printf("%x\n", dst)
}
|
Write a version of this Java function in Go with identical behavior. | 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);
}
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
type vector = []*big.Int
type matrix []vector
var (
zero = new(big.Int)
one = big.NewInt(1)
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
temp := new(big.Int)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
result[i][j] = new(big.Int)
for k := 0; k < rows2; k++ {
temp.Mul(m1[i][k], m2[k][j])
result[i][j].Add(result[i][j], temp)
}
}
}
return result
}
func identityMatrix(n uint64) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := uint64(0); i < n; i++ {
ident[i] = make(vector, n)
for j := uint64(0); j < n; j++ {
ident[i][j] = new(big.Int)
if i == j {
ident[i][j].Set(one)
}
}
}
return ident
}
func (m matrix) pow(n *big.Int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n.Cmp(zero) == -1:
panic("Negative exponents not supported")
case n.Cmp(zero) == 0:
return identityMatrix(uint64(le))
case n.Cmp(one) == 0:
return m
}
pow := identityMatrix(uint64(le))
base := m
e := new(big.Int).Set(n)
temp := new(big.Int)
for e.Cmp(zero) > 0 {
temp.And(e, one)
if temp.Cmp(one) == 0 {
pow = pow.mul(base)
}
e.Rsh(e, 1)
base = base.mul(base)
}
return pow
}
func fibonacci(n *big.Int) *big.Int {
if n.Cmp(zero) == 0 {
return zero
}
m := matrix{{one, one}, {one, zero}}
m = m.pow(n.Sub(n, one))
return m[0][0]
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
start := time.Now()
n := new(big.Int)
for i := uint64(10); i <= 1e7; i *= 10 {
n.SetUint64(i)
s := fibonacci(n).String()
fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n",
commatize(i), commatize(uint64(len(s))))
if len(s) > 20 {
fmt.Printf(" First 20 : %s\n", s[0:20])
if len(s) < 40 {
fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:])
} else {
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
}
} else {
fmt.Printf(" All %-2d : %s\n", len(s), s)
}
fmt.Println()
}
sfxs := []string{"nd", "th"}
for i, e := range []uint{16, 32} {
n.Lsh(one, e)
s := fibonacci(n).String()
fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i],
commatize(uint64(len(s))))
fmt.Printf(" First 20 : %s\n", s[0:20])
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
fmt.Println()
}
fmt.Printf("Took %s\n\n", time.Since(start))
}
|
Convert this Java snippet to Go and keep its semantics consistent. | 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);
}
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
type vector = []*big.Int
type matrix []vector
var (
zero = new(big.Int)
one = big.NewInt(1)
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
temp := new(big.Int)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
result[i][j] = new(big.Int)
for k := 0; k < rows2; k++ {
temp.Mul(m1[i][k], m2[k][j])
result[i][j].Add(result[i][j], temp)
}
}
}
return result
}
func identityMatrix(n uint64) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := uint64(0); i < n; i++ {
ident[i] = make(vector, n)
for j := uint64(0); j < n; j++ {
ident[i][j] = new(big.Int)
if i == j {
ident[i][j].Set(one)
}
}
}
return ident
}
func (m matrix) pow(n *big.Int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n.Cmp(zero) == -1:
panic("Negative exponents not supported")
case n.Cmp(zero) == 0:
return identityMatrix(uint64(le))
case n.Cmp(one) == 0:
return m
}
pow := identityMatrix(uint64(le))
base := m
e := new(big.Int).Set(n)
temp := new(big.Int)
for e.Cmp(zero) > 0 {
temp.And(e, one)
if temp.Cmp(one) == 0 {
pow = pow.mul(base)
}
e.Rsh(e, 1)
base = base.mul(base)
}
return pow
}
func fibonacci(n *big.Int) *big.Int {
if n.Cmp(zero) == 0 {
return zero
}
m := matrix{{one, one}, {one, zero}}
m = m.pow(n.Sub(n, one))
return m[0][0]
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
start := time.Now()
n := new(big.Int)
for i := uint64(10); i <= 1e7; i *= 10 {
n.SetUint64(i)
s := fibonacci(n).String()
fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n",
commatize(i), commatize(uint64(len(s))))
if len(s) > 20 {
fmt.Printf(" First 20 : %s\n", s[0:20])
if len(s) < 40 {
fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:])
} else {
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
}
} else {
fmt.Printf(" All %-2d : %s\n", len(s), s)
}
fmt.Println()
}
sfxs := []string{"nd", "th"}
for i, e := range []uint{16, 32} {
n.Lsh(one, e)
s := fibonacci(n).String()
fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i],
commatize(uint64(len(s))))
fmt.Printf(" First 20 : %s\n", s[0:20])
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
fmt.Println()
}
fmt.Printf("Took %s\n\n", time.Since(start))
}
|
Write the same algorithm in Go as shown in this Java implementation. | 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);
}
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
type vector = []*big.Int
type matrix []vector
var (
zero = new(big.Int)
one = big.NewInt(1)
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
temp := new(big.Int)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
result[i][j] = new(big.Int)
for k := 0; k < rows2; k++ {
temp.Mul(m1[i][k], m2[k][j])
result[i][j].Add(result[i][j], temp)
}
}
}
return result
}
func identityMatrix(n uint64) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := uint64(0); i < n; i++ {
ident[i] = make(vector, n)
for j := uint64(0); j < n; j++ {
ident[i][j] = new(big.Int)
if i == j {
ident[i][j].Set(one)
}
}
}
return ident
}
func (m matrix) pow(n *big.Int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n.Cmp(zero) == -1:
panic("Negative exponents not supported")
case n.Cmp(zero) == 0:
return identityMatrix(uint64(le))
case n.Cmp(one) == 0:
return m
}
pow := identityMatrix(uint64(le))
base := m
e := new(big.Int).Set(n)
temp := new(big.Int)
for e.Cmp(zero) > 0 {
temp.And(e, one)
if temp.Cmp(one) == 0 {
pow = pow.mul(base)
}
e.Rsh(e, 1)
base = base.mul(base)
}
return pow
}
func fibonacci(n *big.Int) *big.Int {
if n.Cmp(zero) == 0 {
return zero
}
m := matrix{{one, one}, {one, zero}}
m = m.pow(n.Sub(n, one))
return m[0][0]
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
start := time.Now()
n := new(big.Int)
for i := uint64(10); i <= 1e7; i *= 10 {
n.SetUint64(i)
s := fibonacci(n).String()
fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n",
commatize(i), commatize(uint64(len(s))))
if len(s) > 20 {
fmt.Printf(" First 20 : %s\n", s[0:20])
if len(s) < 40 {
fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:])
} else {
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
}
} else {
fmt.Printf(" All %-2d : %s\n", len(s), s)
}
fmt.Println()
}
sfxs := []string{"nd", "th"}
for i, e := range []uint{16, 32} {
n.Lsh(one, e)
s := fibonacci(n).String()
fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i],
commatize(uint64(len(s))))
fmt.Printf(" First 20 : %s\n", s[0:20])
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
fmt.Println()
}
fmt.Printf("Took %s\n\n", time.Since(start))
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | 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));
}
}
| package main
import (
"fmt"
"regexp"
"strings"
)
var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func commatize(s string, startIndex, period int, sep string) string {
if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" {
return s
}
m := reg.FindString(s[startIndex:])
if m == "" {
return s
}
splits := strings.Split(m, ".")
ip := splits[0]
if len(ip) > period {
pi := reverse(ip)
for i := (len(ip) - 1) / period * period; i >= period; i -= period {
pi = pi[:i] + sep + pi[i:]
}
ip = reverse(pi)
}
if strings.Contains(m, ".") {
dp := splits[1]
if len(dp) > period {
for i := (len(dp) - 1) / period * period; i >= period; i -= period {
dp = dp[:i] + sep + dp[i:]
}
}
ip += "." + dp
}
return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)
}
func main() {
tests := [...]string{
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-in Aus$+1411.8millions",
"===US$0017440 millions=== (in 2000 dollars)",
"123.e8000 is pretty big.",
"The land area of the earth is 57268900(29% of the surface) square miles.",
"Ain't no numbers in this here words, nohow, no way, Jose.",
"James was never known as 0000000007",
"Arthur Eddington wrote: I believe there are " +
"15747724136275002577605653961181555468044717914527116709366231425076185631031296" +
" protons in the universe.",
" $-140000±100 millions.",
"6/9/1946 was a good year for some.",
}
fmt.Println(commatize(tests[0], 0, 2, "*"))
fmt.Println(commatize(tests[1], 0, 3, "-"))
fmt.Println(commatize(tests[2], 0, 4, "__"))
fmt.Println(commatize(tests[3], 0, 5, " "))
fmt.Println(commatize(tests[4], 0, 3, "."))
for _, test := range tests[5:] {
fmt.Println(commatize(test, 0, 3, ","))
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | 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!");
}
}
}
| package main
import (
"fmt"
"math/big"
)
func cumulative_freq(freq map[byte]int64) map[byte]int64 {
total := int64(0)
cf := make(map[byte]int64)
for i := 0; i < 256; i++ {
b := byte(i)
if v, ok := freq[b]; ok {
cf[b] = total
total += v
}
}
return cf
}
func arithmethic_coding(str string, radix int64) (*big.Int,
*big.Int, map[byte]int64) {
chars := []byte(str)
freq := make(map[byte]int64)
for _, c := range chars {
freq[c] += 1
}
cf := cumulative_freq(freq)
base := len(chars)
L := big.NewInt(0)
pf := big.NewInt(1)
bigBase := big.NewInt(int64(base))
for _, c := range chars {
x := big.NewInt(cf[c])
L.Mul(L, bigBase)
L.Add(L, x.Mul(x, pf))
pf.Mul(pf, big.NewInt(freq[c]))
}
U := big.NewInt(0)
U.Set(L)
U.Add(U, pf)
bigOne := big.NewInt(1)
bigZero := big.NewInt(0)
bigRadix := big.NewInt(radix)
tmp := big.NewInt(0).Set(pf)
powr := big.NewInt(0)
for {
tmp.Div(tmp, bigRadix)
if tmp.Cmp(bigZero) == 0 {
break
}
powr.Add(powr, bigOne)
}
diff := big.NewInt(0)
diff.Sub(U, bigOne)
diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))
return diff, powr, freq
}
func arithmethic_decoding(num *big.Int, radix int64,
pow *big.Int, freq map[byte]int64) string {
powr := big.NewInt(radix)
enc := big.NewInt(0).Set(num)
enc.Mul(enc, powr.Exp(powr, pow, nil))
base := int64(0)
for _, v := range freq {
base += v
}
cf := cumulative_freq(freq)
dict := make(map[int64]byte)
for k, v := range cf {
dict[v] = k
}
lchar := -1
for i := int64(0); i < base; i++ {
if v, ok := dict[i]; ok {
lchar = int(v)
} else if lchar != -1 {
dict[i] = byte(lchar)
}
}
decoded := make([]byte, base)
bigBase := big.NewInt(base)
for i := base - 1; i >= 0; i-- {
pow := big.NewInt(0)
pow.Exp(bigBase, big.NewInt(i), nil)
div := big.NewInt(0)
div.Div(enc, pow)
c := dict[div.Int64()]
fv := freq[c]
cv := cf[c]
prod := big.NewInt(0).Mul(pow, big.NewInt(cv))
diff := big.NewInt(0).Sub(enc, prod)
enc.Div(diff, big.NewInt(fv))
decoded[base-i-1] = c
}
return string(decoded)
}
func main() {
var radix = int64(10)
strSlice := []string{
`DABDDB`,
`DABDDBBDDBA`,
`ABRACADABRA`,
`TOBEORNOTTOBEORTOBEORNOT`,
}
for _, str := range strSlice {
enc, pow, freq := arithmethic_coding(str, radix)
dec := arithmethic_decoding(enc, radix, pow, freq)
fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow)
if str != dec {
panic("\tHowever that is incorrect!")
}
}
}
|
Transform the following Java implementation into Go, maintaining the same output and logic. | 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);
}
}
| package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
vis := make([]bool, len(g))
L := make([]int, len(g))
x := len(L)
t := make([][]int, len(g))
var Visit func(int)
Visit = func(u int) {
if !vis[u] {
vis[u] = true
for _, v := range g[u] {
Visit(v)
t[v] = append(t[v], u)
}
x--
L[x] = u
}
}
for u := range g {
Visit(u)
}
c := make([]int, len(g))
var Assign func(int, int)
Assign = func(u, root int) {
if vis[u] {
vis[u] = false
c[u] = root
for _, v := range t[u] {
Assign(v, root)
}
}
}
for _, u := range L {
Assign(u, u)
}
return c
}
|
Produce a functionally identical Go code for the snippet given in Java. | 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);
}
}
}
| package main
import (
"fmt"
"image"
"reflect"
)
type t int
func (r t) Twice() t { return r * 2 }
func (r t) Half() t { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}
func main() {
report(t(0))
report(image.Point{})
}
func report(x interface{}) {
v := reflect.ValueOf(x)
t := reflect.TypeOf(x)
n := t.NumMethod()
fmt.Printf("Type %v has %d exported methods:\n", t, n)
const format = "%-6s %-46s %s\n"
fmt.Printf(format, "Name", "Method expression", "Method value")
for i := 0; i < n; i++ {
fmt.Printf(format,
t.Method(i).Name,
t.Method(i).Func.Type(),
v.Method(i).Type(),
)
}
fmt.Println()
}
|
Generate a Go translation of this Java snippet without changing its computational steps. | 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);
}
}
| package main
import (
"fmt"
"reflect"
)
type example struct{}
func (example) Foo() int {
return 42
}
func main() {
var e example
m := reflect.ValueOf(e).MethodByName("Foo")
r := m.Call(nil)
fmt.Println(r[0].Int())
}
|
Generate a Go translation of this Java snippet without changing its computational steps. | import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.function.Function;
public class App {
static class Parameters {
double omega;
double phip;
double phig;
Parameters(double omega, double phip, double phig) {
this.omega = omega;
this.phip = phip;
this.phig = phig;
}
}
static class State {
int iter;
double[] gbpos;
double gbval;
double[] min;
double[] max;
Parameters parameters;
double[][] pos;
double[][] vel;
double[][] bpos;
double[] bval;
int nParticles;
int nDims;
State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) {
this.iter = iter;
this.gbpos = gbpos;
this.gbval = gbval;
this.min = min;
this.max = max;
this.parameters = parameters;
this.pos = pos;
this.vel = vel;
this.bpos = bpos;
this.bval = bval;
this.nParticles = nParticles;
this.nDims = nDims;
}
void report(String testfunc) {
System.out.printf("Test Function : %s\n", testfunc);
System.out.printf("Iterations : %d\n", iter);
System.out.printf("Global Best Position : %s\n", Arrays.toString(gbpos));
System.out.printf("Global Best value : %.15f\n", gbval);
}
}
private static State psoInit(double[] min, double[] max, Parameters parameters, int nParticles) {
int nDims = min.length;
double[][] pos = new double[nParticles][];
for (int i = 0; i < nParticles; ++i) {
pos[i] = min.clone();
}
double[][] vel = new double[nParticles][nDims];
double[][] bpos = new double[nParticles][];
for (int i = 0; i < nParticles; ++i) {
bpos[i] = min.clone();
}
double[] bval = new double[nParticles];
for (int i = 0; i < bval.length; ++i) {
bval[i] = Double.POSITIVE_INFINITY;
}
int iter = 0;
double[] gbpos = new double[nDims];
for (int i = 0; i < gbpos.length; ++i) {
gbpos[i] = Double.POSITIVE_INFINITY;
}
double gbval = Double.POSITIVE_INFINITY;
return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);
}
private static Random r = new Random();
private static State pso(Function<double[], Double> fn, State y) {
Parameters p = y.parameters;
double[] v = new double[y.nParticles];
double[][] bpos = new double[y.nParticles][];
for (int i = 0; i < y.nParticles; ++i) {
bpos[i] = y.min.clone();
}
double[] bval = new double[y.nParticles];
double[] gbpos = new double[y.nDims];
double gbval = Double.POSITIVE_INFINITY;
for (int j = 0; j < y.nParticles; ++j) {
v[j] = fn.apply(y.pos[j]);
if (v[j] < y.bval[j]) {
bpos[j] = y.pos[j];
bval[j] = v[j];
} else {
bpos[j] = y.bpos[j];
bval[j] = y.bval[j];
}
if (bval[j] < gbval) {
gbval = bval[j];
gbpos = bpos[j];
}
}
double rg = r.nextDouble();
double[][] pos = new double[y.nParticles][y.nDims];
double[][] vel = new double[y.nParticles][y.nDims];
for (int j = 0; j < y.nParticles; ++j) {
double rp = r.nextDouble();
boolean ok = true;
Arrays.fill(vel[j], 0.0);
Arrays.fill(pos[j], 0.0);
for (int k = 0; k < y.nDims; ++k) {
vel[j][k] = p.omega * y.vel[j][k] +
p.phip * rp * (bpos[j][k] - y.pos[j][k]) +
p.phig * rg * (gbpos[k] - y.pos[j][k]);
pos[j][k] = y.pos[j][k] + vel[j][k];
ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];
}
if (!ok) {
for (int k = 0; k < y.nDims; ++k) {
pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.nextDouble();
}
}
}
int iter = 1 + y.iter;
return new State(
iter, gbpos, gbval, y.min, y.max, y.parameters,
pos, vel, bpos, bval, y.nParticles, y.nDims
);
}
private static State iterate(Function<double[], Double> fn, int n, State y) {
State r = y;
if (n == Integer.MAX_VALUE) {
State old = y;
while (true) {
r = pso(fn, r);
if (Objects.equals(r, old)) break;
old = r;
}
} else {
for (int i = 0; i < n; ++i) {
r = pso(fn, r);
}
}
return r;
}
private static double mccormick(double[] x) {
double a = x[0];
double b = x[1];
return Math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;
}
private static double michalewicz(double[] x) {
int m = 10;
int d = x.length;
double sum = 0.0;
for (int i = 1; i < d; ++i) {
double j = x[i - 1];
double k = Math.sin(i * j * j / Math.PI);
sum += Math.sin(j) * Math.pow(k, 2.0 * m);
}
return -sum;
}
public static void main(String[] args) {
State state = psoInit(
new double[]{-1.5, -3.0},
new double[]{4.0, 4.0},
new Parameters(0.0, 0.6, 0.3),
100
);
state = iterate(App::mccormick, 40, state);
state.report("McCormick");
System.out.printf("f(-.54719, -1.54719) : %.15f\n", mccormick(new double[]{-.54719, -1.54719}));
System.out.println();
state = psoInit(
new double[]{0.0, 0.0},
new double[]{Math.PI, Math.PI},
new Parameters(0.3, 3.0, 0.3),
1000
);
state = iterate(App::michalewicz, 30, state);
state.report("Michalewicz (2D)");
System.out.printf("f(2.20, 1.57) : %.15f\n", michalewicz(new double[]{2.20, 1.57}));
}
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type ff = func([]float64) float64
type parameters struct{ omega, phip, phig float64 }
type state struct {
iter int
gbpos []float64
gbval float64
min []float64
max []float64
params parameters
pos [][]float64
vel [][]float64
bpos [][]float64
bval []float64
nParticles int
nDims int
}
func (s state) report(testfunc string) {
fmt.Println("Test Function :", testfunc)
fmt.Println("Iterations :", s.iter)
fmt.Println("Global Best Position :", s.gbpos)
fmt.Println("Global Best Value :", s.gbval)
}
func psoInit(min, max []float64, params parameters, nParticles int) *state {
nDims := len(min)
pos := make([][]float64, nParticles)
vel := make([][]float64, nParticles)
bpos := make([][]float64, nParticles)
bval := make([]float64, nParticles)
for i := 0; i < nParticles; i++ {
pos[i] = min
vel[i] = make([]float64, nDims)
bpos[i] = min
bval[i] = math.Inf(1)
}
iter := 0
gbpos := make([]float64, nDims)
for i := 0; i < nDims; i++ {
gbpos[i] = math.Inf(1)
}
gbval := math.Inf(1)
return &state{iter, gbpos, gbval, min, max, params,
pos, vel, bpos, bval, nParticles, nDims}
}
func pso(fn ff, y *state) *state {
p := y.params
v := make([]float64, y.nParticles)
bpos := make([][]float64, y.nParticles)
bval := make([]float64, y.nParticles)
gbpos := make([]float64, y.nDims)
gbval := math.Inf(1)
for j := 0; j < y.nParticles; j++ {
v[j] = fn(y.pos[j])
if v[j] < y.bval[j] {
bpos[j] = y.pos[j]
bval[j] = v[j]
} else {
bpos[j] = y.bpos[j]
bval[j] = y.bval[j]
}
if bval[j] < gbval {
gbval = bval[j]
gbpos = bpos[j]
}
}
rg := rand.Float64()
pos := make([][]float64, y.nParticles)
vel := make([][]float64, y.nParticles)
for j := 0; j < y.nParticles; j++ {
pos[j] = make([]float64, y.nDims)
vel[j] = make([]float64, y.nDims)
rp := rand.Float64()
ok := true
for z := 0; z < y.nDims; z++ {
pos[j][z] = 0
vel[j][z] = 0
}
for k := 0; k < y.nDims; k++ {
vel[j][k] = p.omega*y.vel[j][k] +
p.phip*rp*(bpos[j][k]-y.pos[j][k]) +
p.phig*rg*(gbpos[k]-y.pos[j][k])
pos[j][k] = y.pos[j][k] + vel[j][k]
ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]
}
if !ok {
for k := 0; k < y.nDims; k++ {
pos[j][k] = y.min[k] + (y.max[k]-y.min[k])*rand.Float64()
}
}
}
iter := 1 + y.iter
return &state{iter, gbpos, gbval, y.min, y.max, y.params,
pos, vel, bpos, bval, y.nParticles, y.nDims}
}
func iterate(fn ff, n int, y *state) *state {
r := y
for i := 0; i < n; i++ {
r = pso(fn, r)
}
return r
}
func mccormick(x []float64) float64 {
a, b := x[0], x[1]
return math.Sin(a+b) + (a-b)*(a-b) + 1.0 + 2.5*b - 1.5*a
}
func michalewicz(x []float64) float64 {
m := 10.0
sum := 0.0
for i := 1; i <= len(x); i++ {
j := x[i-1]
k := math.Sin(float64(i) * j * j / math.Pi)
sum += math.Sin(j) * math.Pow(k, 2*m)
}
return -sum
}
func main() {
rand.Seed(time.Now().UnixNano())
st := psoInit(
[]float64{-1.5, -3.0},
[]float64{4.0, 4.0},
parameters{0.0, 0.6, 0.3},
100,
)
st = iterate(mccormick, 40, st)
st.report("McCormick")
fmt.Println("f(-.54719, -1.54719) :", mccormick([]float64{-.54719, -1.54719}))
fmt.Println()
st = psoInit(
[]float64{0.0, 0.0},
[]float64{math.Pi, math.Pi},
parameters{0.3, 0.3, 0.3},
1000,
)
st = iterate(michalewicz, 30, st)
st.report("Michalewicz (2D)")
fmt.Println("f(2.20, 1.57) :", michalewicz([]float64{2.2, 1.57}))
|
Preserve the algorithm and functionality while converting the code from Java to Go. | public static void main(String[] args) {
System.out.println(concat("Rosetta", "Code", ":"));
}
public static String concat(String a, String b, String c) {
return a + c + c + b;
}
Rosetta::Code
| package main
import "fmt"
func f(s1, s2, sep string) string {
return s1 + sep + sep + s2
}
func main() {
fmt.Println(f("Rosetta", "Code", ":"))
}
|
Rewrite the snippet below in Go so it works the same as the original Java code. | import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.Collectors.*;
public class Test3 {
static BigInteger rank(int[] x) {
String s = stream(x).mapToObj(String::valueOf).collect(joining("F"));
return new BigInteger(s, 16);
}
static List<BigInteger> unrank(BigInteger n) {
BigInteger sixteen = BigInteger.valueOf(16);
String s = "";
while (!n.equals(BigInteger.ZERO)) {
s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s;
n = n.divide(sixteen);
}
return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList());
}
public static void main(String[] args) {
int[] s = {1, 2, 3, 10, 100, 987654321};
System.out.println(Arrays.toString(s));
System.out.println(rank(s));
System.out.println(unrank(rank(s)));
}
}
| package main
import (
"fmt"
"math/big"
)
func rank(l []uint) (r big.Int) {
for _, n := range l {
r.Lsh(&r, n+1)
r.SetBit(&r, int(n), 1)
}
return
}
func unrank(n big.Int) (l []uint) {
m := new(big.Int).Set(&n)
for a := m.BitLen(); a > 0; {
m.SetBit(m, a-1, 0)
b := m.BitLen()
l = append(l, uint(a-b-1))
a = b
}
return
}
func main() {
var b big.Int
for i := 0; i <= 10; i++ {
b.SetInt64(int64(i))
u := unrank(b)
r := rank(u)
fmt.Println(i, u, &r)
}
b.SetString("12345678901234567890", 10)
u := unrank(b)
r := rank(u)
fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
public class Backup {
public static void saveWithBackup(String filename, String... data)
throws IOException {
Path file = Paths.get(filename).toRealPath();
File backFile = new File(filename + ".backup");
if(!backFile.exists()) {
backFile.createNewFile();
}
Path back = Paths.get(filename + ".backup").toRealPath();
Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
try(PrintWriter out = new PrintWriter(file.toFile())){
for(int i = 0; i < data.length; i++) {
out.print(data[i]);
if(i < data.length - 1) {
out.println();
}
}
}
}
public static void main(String[] args) {
try {
saveWithBackup("original.txt", "fourth", "fifth", "sixth");
} catch (IOException e) {
System.err.println(e);
}
}
}
| package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
}
if err = os.Rename(fn, fn+bx); err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
if err != nil {
fmt.Println(err)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
public class Backup {
public static void saveWithBackup(String filename, String... data)
throws IOException {
Path file = Paths.get(filename).toRealPath();
File backFile = new File(filename + ".backup");
if(!backFile.exists()) {
backFile.createNewFile();
}
Path back = Paths.get(filename + ".backup").toRealPath();
Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
try(PrintWriter out = new PrintWriter(file.toFile())){
for(int i = 0; i < data.length; i++) {
out.print(data[i]);
if(i < data.length - 1) {
out.println();
}
}
}
}
public static void main(String[] args) {
try {
saveWithBackup("original.txt", "fourth", "fifth", "sixth");
} catch (IOException e) {
System.err.println(e);
}
}
}
| package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
}
if err = os.Rename(fn, fn+bx); err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
if err != nil {
fmt.Println(err)
}
}
|
Port the following code from Java to Go with equivalent syntax and logic. | import java.math.BigDecimal;
public class GeneralisedFloatingPointAddition {
public static void main(String[] args) {
BigDecimal oneExp72 = new BigDecimal("1E72");
for ( int i = 0 ; i <= 21+7 ; i++ ) {
String s = "12345679";
for ( int j = 0 ; j < i ; j++ ) {
s += "012345679";
}
int exp = 63 - 9*i;
s += "E" + exp;
BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal("1E" + exp));
System.out.printf("Test value (%s) equals computed value: %b. Computed = %s%n", oneExp72, num.compareTo(oneExp72) == 0 , num);
}
}
}
| package main
import (
"fmt"
"math/big"
)
func repeatedAdd(bf *big.Float, times int) *big.Float {
if times < 2 {
return bf
}
var sum big.Float
for i := 0; i < times; i++ {
sum.Add(&sum, bf)
}
return &sum
}
func main() {
s := "12345679"
t := "123456790"
e := 63
var bf, extra big.Float
for n := -7; n <= 21; n++ {
bf.SetString(fmt.Sprintf("%se%d", s, e))
extra.SetString(fmt.Sprintf("1e%d", e))
bf = *repeatedAdd(&bf, 81)
bf.Add(&bf, &extra)
fmt.Printf("%2d : %s\n", n, bf.String())
s = t + s
e -= 9
}
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | import java.math.BigDecimal;
public class GeneralisedFloatingPointAddition {
public static void main(String[] args) {
BigDecimal oneExp72 = new BigDecimal("1E72");
for ( int i = 0 ; i <= 21+7 ; i++ ) {
String s = "12345679";
for ( int j = 0 ; j < i ; j++ ) {
s += "012345679";
}
int exp = 63 - 9*i;
s += "E" + exp;
BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal("1E" + exp));
System.out.printf("Test value (%s) equals computed value: %b. Computed = %s%n", oneExp72, num.compareTo(oneExp72) == 0 , num);
}
}
}
| package main
import (
"fmt"
"math/big"
)
func repeatedAdd(bf *big.Float, times int) *big.Float {
if times < 2 {
return bf
}
var sum big.Float
for i := 0; i < times; i++ {
sum.Add(&sum, bf)
}
return &sum
}
func main() {
s := "12345679"
t := "123456790"
e := 63
var bf, extra big.Float
for n := -7; n <= 21; n++ {
bf.SetString(fmt.Sprintf("%se%d", s, e))
extra.SetString(fmt.Sprintf("1e%d", e))
bf = *repeatedAdd(&bf, 81)
bf.Add(&bf, &extra)
fmt.Printf("%2d : %s\n", n, bf.String())
s = t + s
e -= 9
}
}
|
Write a version of this Java function in Go with identical behavior. | public class ReallyLameTranslationOfJ {
public static void main(String[] args) {
String s = "She was a soul stripper. She took my heart!";
System.out.println(cheapTrick(s));
System.out.println(cheapTrick(cheapTrick(s)));
}
static String cheapTrick(String s) {
if (s.contains("She"))
return s.replaceAll("She", "He");
else if(s.contains("He"))
return s.replaceAll("He", "She");
return s;
}
}
| package main
import (
"fmt"
"strings"
)
func reverseGender(s string) string {
if strings.Contains(s, "She") {
return strings.Replace(s, "She", "He", -1)
} else if strings.Contains(s, "He") {
return strings.Replace(s, "He", "She", -1)
}
return s
}
func main() {
s := "She was a soul stripper. She took my heart!"
t := reverseGender(s)
fmt.Println(t)
fmt.Println(reverseGender(t))
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | public class ReallyLameTranslationOfJ {
public static void main(String[] args) {
String s = "She was a soul stripper. She took my heart!";
System.out.println(cheapTrick(s));
System.out.println(cheapTrick(cheapTrick(s)));
}
static String cheapTrick(String s) {
if (s.contains("She"))
return s.replaceAll("She", "He");
else if(s.contains("He"))
return s.replaceAll("He", "She");
return s;
}
}
| package main
import (
"fmt"
"strings"
)
func reverseGender(s string) string {
if strings.Contains(s, "She") {
return strings.Replace(s, "She", "He", -1)
} else if strings.Contains(s, "He") {
return strings.Replace(s, "He", "She", -1)
}
return s
}
func main() {
s := "She was a soul stripper. She took my heart!"
t := reverseGender(s)
fmt.Println(t)
fmt.Println(reverseGender(t))
}
|
Rewrite the snippet below in Go so it works the same as the original Java code. | import com.sun.javafx.application.PlatformImpl;
import java.io.File;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class AudioAlarm {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number of seconds: ");
int seconds = Integer.parseInt(input.nextLine());
System.out.print("Enter a filename (must end with .mp3 or .wav): ");
String audio = input.nextLine();
TimeUnit.SECONDS.sleep(seconds);
Media media = new Media(new File(audio).toURI().toString());
AtomicBoolean stop = new AtomicBoolean();
Runnable onEnd = () -> stop.set(true);
PlatformImpl.startup(() -> {});
MediaPlayer player = new MediaPlayer(media);
player.setOnEndOfMedia(onEnd);
player.setOnError(onEnd);
player.setOnHalted(onEnd);
player.play();
while (!stop.get()) {
Thread.sleep(100);
}
System.exit(0);
}
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
"time"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
number := 0
for number < 1 {
fmt.Print("Enter number of seconds delay > 0 : ")
scanner.Scan()
input := scanner.Text()
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
number, _ = strconv.Atoi(input)
}
filename := ""
for filename == "" {
fmt.Print("Enter name of .mp3 file to play (without extension) : ")
scanner.Scan()
filename = scanner.Text()
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
cls := "\033[2J\033[0;0H"
fmt.Printf("%sAlarm will sound in %d seconds...", cls, number)
time.Sleep(time.Duration(number) * time.Second)
fmt.Printf(cls)
cmd := exec.Command("play", filename+".mp3")
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
|
Port the provided Java code into Go while preserving the original functionality. | import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class DecimalToBinary {
public static void main(String[] args) {
for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) {
String binary = decimalToBinary(new BigDecimal(s));
System.out.printf("%s => %s%n", s, binary);
System.out.printf("%s => %s%n", binary, binaryToDecimal(binary));
}
}
private static BigDecimal binaryToDecimal(String binary) {
return binaryToDecimal(binary, 50);
}
private static BigDecimal binaryToDecimal(String binary, int digits) {
int decimalPosition = binary.indexOf(".");
String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;
String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : "";
BigDecimal result = BigDecimal.ZERO;
BigDecimal powTwo = BigDecimal.ONE;
BigDecimal two = BigDecimal.valueOf(2);
for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));
powTwo = powTwo.multiply(two);
}
MathContext mc = new MathContext(digits);
powTwo = BigDecimal.ONE;
for ( char c : fractional.toCharArray() ) {
powTwo = powTwo.divide(two);
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);
}
return result;
}
private static String decimalToBinary(BigDecimal decimal) {
return decimalToBinary(decimal, 50);
}
private static String decimalToBinary(BigDecimal decimal, int digits) {
BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);
BigDecimal fractional = decimal.subtract(integer);
StringBuilder sb = new StringBuilder();
BigDecimal two = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.ZERO;
while ( integer.compareTo(zero) > 0 ) {
BigDecimal[] result = integer.divideAndRemainder(two);
sb.append(result[1]);
integer = result[0];
}
sb.reverse();
int count = 0;
if ( fractional.compareTo(zero) != 0 ) {
sb.append(".");
}
while ( fractional.compareTo(zero) != 0 ) {
count++;
fractional = fractional.multiply(two);
sb.append(fractional.setScale(0, RoundingMode.FLOOR));
if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {
fractional = fractional.subtract(BigDecimal.ONE);
}
if ( count >= digits ) {
break;
}
}
return sb.toString();
}
}
| package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func decToBin(d float64) string {
whole := int64(math.Floor(d))
binary := strconv.FormatInt(whole, 2) + "."
dd := d - float64(whole)
for dd > 0.0 {
r := dd * 2.0
if r >= 1.0 {
binary += "1"
dd = r - 1.0
} else {
binary += "0"
dd = r
}
}
return binary
}
func binToDec(s string) float64 {
ss := strings.Replace(s, ".", "", 1)
num, _ := strconv.ParseInt(ss, 2, 64)
ss = strings.Split(s, ".")[1]
ss = strings.Replace(ss, "1", "0", -1)
den, _ := strconv.ParseInt("1" + ss, 2, 64)
return float64(num) / float64(den)
}
func main() {
f := 23.34375
fmt.Printf("%v\t => %s\n", f, decToBin(f))
s := "1011.11101"
fmt.Printf("%s\t => %v\n", s, binToDec(s))
}
|
Please provide an equivalent version of this Java code in Go. | import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class DecimalToBinary {
public static void main(String[] args) {
for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) {
String binary = decimalToBinary(new BigDecimal(s));
System.out.printf("%s => %s%n", s, binary);
System.out.printf("%s => %s%n", binary, binaryToDecimal(binary));
}
}
private static BigDecimal binaryToDecimal(String binary) {
return binaryToDecimal(binary, 50);
}
private static BigDecimal binaryToDecimal(String binary, int digits) {
int decimalPosition = binary.indexOf(".");
String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;
String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : "";
BigDecimal result = BigDecimal.ZERO;
BigDecimal powTwo = BigDecimal.ONE;
BigDecimal two = BigDecimal.valueOf(2);
for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));
powTwo = powTwo.multiply(two);
}
MathContext mc = new MathContext(digits);
powTwo = BigDecimal.ONE;
for ( char c : fractional.toCharArray() ) {
powTwo = powTwo.divide(two);
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);
}
return result;
}
private static String decimalToBinary(BigDecimal decimal) {
return decimalToBinary(decimal, 50);
}
private static String decimalToBinary(BigDecimal decimal, int digits) {
BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);
BigDecimal fractional = decimal.subtract(integer);
StringBuilder sb = new StringBuilder();
BigDecimal two = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.ZERO;
while ( integer.compareTo(zero) > 0 ) {
BigDecimal[] result = integer.divideAndRemainder(two);
sb.append(result[1]);
integer = result[0];
}
sb.reverse();
int count = 0;
if ( fractional.compareTo(zero) != 0 ) {
sb.append(".");
}
while ( fractional.compareTo(zero) != 0 ) {
count++;
fractional = fractional.multiply(two);
sb.append(fractional.setScale(0, RoundingMode.FLOOR));
if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {
fractional = fractional.subtract(BigDecimal.ONE);
}
if ( count >= digits ) {
break;
}
}
return sb.toString();
}
}
| package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func decToBin(d float64) string {
whole := int64(math.Floor(d))
binary := strconv.FormatInt(whole, 2) + "."
dd := d - float64(whole)
for dd > 0.0 {
r := dd * 2.0
if r >= 1.0 {
binary += "1"
dd = r - 1.0
} else {
binary += "0"
dd = r
}
}
return binary
}
func binToDec(s string) float64 {
ss := strings.Replace(s, ".", "", 1)
num, _ := strconv.ParseInt(ss, 2, 64)
ss = strings.Split(s, ".")[1]
ss = strings.Replace(ss, "1", "0", -1)
den, _ := strconv.ParseInt("1" + ss, 2, 64)
return float64(num) / float64(den)
}
func main() {
f := 23.34375
fmt.Printf("%v\t => %s\n", f, decToBin(f))
s := "1011.11101"
fmt.Printf("%s\t => %v\n", s, binToDec(s))
}
|
Change the following Java code into Go without altering its purpose. | import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string:
m_sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
return m_sourceCode;
}
private boolean compile() {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
null, null, null, Arrays.asList( this )
).call();
}
private double callEval( final double x )
throws Exception {
final Class<?> clarse = Class.forName( CLASS_NAME );
final Method eval = clarse.getMethod( "eval", double.class );
return ( Double ) eval.invoke( null, x );
}
}
public static double evalWithX( final String code, final double x )
throws Exception {
final StringCompiler sc = new StringCompiler(
"class "
+ CLASS_NAME
+ "{public static double eval(double x){return ("
+ code
+ ");}}"
);
if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
return sc.callEval( x );
}
public static void main( final String [] args )
throws Exception {
final String expression = args [ 0 ];
final double x1 = Double.parseDouble( args [ 1 ] );
final double x2 = Double.parseDouble( args [ 2 ] );
System.out.println(
evalWithX( expression, x1 )
- evalWithX( expression, x2 )
);
}
}
| package main
import (
"bitbucket.org/binet/go-eval/pkg/eval"
"fmt"
"go/parser"
"go/token"
)
func main() {
squareExpr := "x*x"
fset := token.NewFileSet()
squareAst, err := parser.ParseExpr(squareExpr)
if err != nil {
fmt.Println(err)
return
}
w := eval.NewWorld()
wVar := new(intV)
err = w.DefineVar("x", eval.IntType, wVar)
if err != nil {
fmt.Println(err)
return
}
squareCode, err := w.CompileExpr(fset, squareAst)
if err != nil {
fmt.Println(err)
return
}
*wVar = 5
r0, err := squareCode.Run()
if err != nil {
fmt.Println(err)
return
}
*wVar--
r1, err := squareCode.Run()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}
type intV int64
func (v *intV) String() string { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64 { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
*v = intV(o.(eval.IntValue).Get(t))
}
|
Generate an equivalent Go version of this Java code. | import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string:
m_sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
return m_sourceCode;
}
private boolean compile() {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
null, null, null, Arrays.asList( this )
).call();
}
private double callEval( final double x )
throws Exception {
final Class<?> clarse = Class.forName( CLASS_NAME );
final Method eval = clarse.getMethod( "eval", double.class );
return ( Double ) eval.invoke( null, x );
}
}
public static double evalWithX( final String code, final double x )
throws Exception {
final StringCompiler sc = new StringCompiler(
"class "
+ CLASS_NAME
+ "{public static double eval(double x){return ("
+ code
+ ");}}"
);
if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
return sc.callEval( x );
}
public static void main( final String [] args )
throws Exception {
final String expression = args [ 0 ];
final double x1 = Double.parseDouble( args [ 1 ] );
final double x2 = Double.parseDouble( args [ 2 ] );
System.out.println(
evalWithX( expression, x1 )
- evalWithX( expression, x2 )
);
}
}
| package main
import (
"bitbucket.org/binet/go-eval/pkg/eval"
"fmt"
"go/parser"
"go/token"
)
func main() {
squareExpr := "x*x"
fset := token.NewFileSet()
squareAst, err := parser.ParseExpr(squareExpr)
if err != nil {
fmt.Println(err)
return
}
w := eval.NewWorld()
wVar := new(intV)
err = w.DefineVar("x", eval.IntType, wVar)
if err != nil {
fmt.Println(err)
return
}
squareCode, err := w.CompileExpr(fset, squareAst)
if err != nil {
fmt.Println(err)
return
}
*wVar = 5
r0, err := squareCode.Run()
if err != nil {
fmt.Println(err)
return
}
*wVar--
r1, err := squareCode.Run()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}
type intV int64
func (v *intV) String() string { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64 { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
*v = intV(o.(eval.IntValue).Get(t))
}
|
Write the same code in Go as shown below in Java. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMachinFormula {
private static String FILE_NAME = "MachinFormula.txt";
public static void main(String[] args) {
try {
runPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runPrivate() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("=");
System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
}
}
}
private static String tanLeft(String formula) {
if ( formula.compareTo("pi/4") == 0 ) {
return "1";
}
throw new RuntimeException("ERROR 104: Unknown left side: " + formula);
}
private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");
private static Fraction tanRight(String formula) {
Matcher matcher = ARCTAN_PATTERN.matcher(formula);
List<Term> terms = new ArrayList<>();
while ( matcher.find() ) {
terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
}
return evaluateArctan(terms);
}
private static Fraction evaluateArctan(List<Term> terms) {
if ( terms.size() == 1 ) {
Term term = terms.get(0);
return evaluateArctan(term.coefficient, term.fraction);
}
int size = terms.size();
List<Term> left = terms.subList(0, (size+1) / 2);
List<Term> right = terms.subList((size+1) / 2, size);
return arctanFormula(evaluateArctan(left), evaluateArctan(right));
}
private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
if ( coefficient == 1 ) {
return fraction;
}
else if ( coefficient < 0 ) {
return evaluateArctan(-coefficient, fraction).negate();
}
if ( coefficient % 2 == 0 ) {
Fraction f = evaluateArctan(coefficient/2, fraction);
return arctanFormula(f, f);
}
Fraction a = evaluateArctan(coefficient/2, fraction);
Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
return arctanFormula(a, b);
}
private static Fraction arctanFormula(Fraction f1, Fraction f2) {
return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
}
private static class Fraction {
public static final Fraction ONE = new Fraction("1", "1");
private BigInteger numerator;
private BigInteger denominator;
public Fraction(String num, String den) {
numerator = new BigInteger(num);
denominator = new BigInteger(den);
}
public Fraction(BigInteger num, BigInteger den) {
numerator = num;
denominator = den;
}
public Fraction negate() {
return new Fraction(numerator.negate(), denominator);
}
public Fraction add(Fraction f) {
BigInteger gcd = denominator.gcd(f.denominator);
BigInteger first = numerator.multiply(f.denominator.divide(gcd));
BigInteger second = f.numerator.multiply(denominator.divide(gcd));
return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
}
public Fraction subtract(Fraction f) {
return add(f.negate());
}
public Fraction multiply(Fraction f) {
BigInteger num = numerator.multiply(f.numerator);
BigInteger den = denominator.multiply(f.denominator);
BigInteger gcd = num.gcd(den);
return new Fraction(num.divide(gcd), den.divide(gcd));
}
public Fraction divide(Fraction f) {
return multiply(new Fraction(f.denominator, f.numerator));
}
@Override
public String toString() {
if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
return numerator.toString();
}
return numerator + " / " + denominator;
}
}
private static class Term {
private int coefficient;
private Fraction fraction;
public Term(int c, Fraction f) {
coefficient = c;
fraction = f;
}
}
}
| package main
import (
"fmt"
"math/big"
)
type mTerm struct {
a, n, d int64
}
var testCases = [][]mTerm{
{{1, 1, 2}, {1, 1, 3}},
{{2, 1, 3}, {1, 1, 7}},
{{4, 1, 5}, {-1, 1, 239}},
{{5, 1, 7}, {2, 3, 79}},
{{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},
{{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},
{{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},
{{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},
{{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},
{{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},
{{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},
{{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},
{{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},
{{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},
}
func main() {
for _, m := range testCases {
fmt.Printf("tan %v = %v\n", m, tans(m))
}
}
var one = big.NewRat(1, 1)
func tans(m []mTerm) *big.Rat {
if len(m) == 1 {
return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))
}
half := len(m) / 2
a := tans(m[:half])
b := tans(m[half:])
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
func tanEval(coef int64, f *big.Rat) *big.Rat {
if coef == 1 {
return f
}
if coef < 0 {
r := tanEval(-coef, f)
return r.Neg(r)
}
ca := coef / 2
cb := coef - ca
a := tanEval(ca, f)
b := tanEval(cb, f)
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
|
Write the same code in Go as shown below in Java. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMachinFormula {
private static String FILE_NAME = "MachinFormula.txt";
public static void main(String[] args) {
try {
runPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runPrivate() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("=");
System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
}
}
}
private static String tanLeft(String formula) {
if ( formula.compareTo("pi/4") == 0 ) {
return "1";
}
throw new RuntimeException("ERROR 104: Unknown left side: " + formula);
}
private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");
private static Fraction tanRight(String formula) {
Matcher matcher = ARCTAN_PATTERN.matcher(formula);
List<Term> terms = new ArrayList<>();
while ( matcher.find() ) {
terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
}
return evaluateArctan(terms);
}
private static Fraction evaluateArctan(List<Term> terms) {
if ( terms.size() == 1 ) {
Term term = terms.get(0);
return evaluateArctan(term.coefficient, term.fraction);
}
int size = terms.size();
List<Term> left = terms.subList(0, (size+1) / 2);
List<Term> right = terms.subList((size+1) / 2, size);
return arctanFormula(evaluateArctan(left), evaluateArctan(right));
}
private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
if ( coefficient == 1 ) {
return fraction;
}
else if ( coefficient < 0 ) {
return evaluateArctan(-coefficient, fraction).negate();
}
if ( coefficient % 2 == 0 ) {
Fraction f = evaluateArctan(coefficient/2, fraction);
return arctanFormula(f, f);
}
Fraction a = evaluateArctan(coefficient/2, fraction);
Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
return arctanFormula(a, b);
}
private static Fraction arctanFormula(Fraction f1, Fraction f2) {
return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
}
private static class Fraction {
public static final Fraction ONE = new Fraction("1", "1");
private BigInteger numerator;
private BigInteger denominator;
public Fraction(String num, String den) {
numerator = new BigInteger(num);
denominator = new BigInteger(den);
}
public Fraction(BigInteger num, BigInteger den) {
numerator = num;
denominator = den;
}
public Fraction negate() {
return new Fraction(numerator.negate(), denominator);
}
public Fraction add(Fraction f) {
BigInteger gcd = denominator.gcd(f.denominator);
BigInteger first = numerator.multiply(f.denominator.divide(gcd));
BigInteger second = f.numerator.multiply(denominator.divide(gcd));
return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
}
public Fraction subtract(Fraction f) {
return add(f.negate());
}
public Fraction multiply(Fraction f) {
BigInteger num = numerator.multiply(f.numerator);
BigInteger den = denominator.multiply(f.denominator);
BigInteger gcd = num.gcd(den);
return new Fraction(num.divide(gcd), den.divide(gcd));
}
public Fraction divide(Fraction f) {
return multiply(new Fraction(f.denominator, f.numerator));
}
@Override
public String toString() {
if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
return numerator.toString();
}
return numerator + " / " + denominator;
}
}
private static class Term {
private int coefficient;
private Fraction fraction;
public Term(int c, Fraction f) {
coefficient = c;
fraction = f;
}
}
}
| package main
import (
"fmt"
"math/big"
)
type mTerm struct {
a, n, d int64
}
var testCases = [][]mTerm{
{{1, 1, 2}, {1, 1, 3}},
{{2, 1, 3}, {1, 1, 7}},
{{4, 1, 5}, {-1, 1, 239}},
{{5, 1, 7}, {2, 3, 79}},
{{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},
{{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},
{{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},
{{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},
{{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},
{{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},
{{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},
{{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},
{{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},
{{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},
}
func main() {
for _, m := range testCases {
fmt.Printf("tan %v = %v\n", m, tans(m))
}
}
var one = big.NewRat(1, 1)
func tans(m []mTerm) *big.Rat {
if len(m) == 1 {
return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))
}
half := len(m) / 2
a := tans(m[:half])
b := tans(m[half:])
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
func tanEval(coef int64, f *big.Rat) *big.Rat {
if coef == 1 {
return f
}
if coef < 0 {
r := tanEval(-coef, f)
return r.Neg(r)
}
ca := coef / 2
cb := coef - ca
a := tanEval(ca, f)
b := tanEval(cb, f)
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | class MD5
{
private static final int INIT_A = 0x67452301;
private static final int INIT_B = (int)0xEFCDAB89L;
private static final int INIT_C = (int)0x98BADCFEL;
private static final int INIT_D = 0x10325476;
private static final int[] SHIFT_AMTS = {
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
};
private static final int[] TABLE_T = new int[64];
static
{
for (int i = 0; i < 64; i++)
TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));
}
public static byte[] computeMD5(byte[] message)
{
int messageLenBytes = message.length;
int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
int totalLen = numBlocks << 6;
byte[] paddingBytes = new byte[totalLen - messageLenBytes];
paddingBytes[0] = (byte)0x80;
long messageLenBits = (long)messageLenBytes << 3;
for (int i = 0; i < 8; i++)
{
paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;
messageLenBits >>>= 8;
}
int a = INIT_A;
int b = INIT_B;
int c = INIT_C;
int d = INIT_D;
int[] buffer = new int[16];
for (int i = 0; i < numBlocks; i ++)
{
int index = i << 6;
for (int j = 0; j < 64; j++, index++)
buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);
int originalA = a;
int originalB = b;
int originalC = c;
int originalD = d;
for (int j = 0; j < 64; j++)
{
int div16 = j >>> 4;
int f = 0;
int bufferIndex = j;
switch (div16)
{
case 0:
f = (b & c) | (~b & d);
break;
case 1:
f = (b & d) | (c & ~d);
bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
break;
case 2:
f = b ^ c ^ d;
bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
break;
case 3:
f = c ^ (b | ~d);
bufferIndex = (bufferIndex * 7) & 0x0F;
break;
}
int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);
a = d;
d = c;
c = b;
b = temp;
}
a += originalA;
b += originalB;
c += originalC;
d += originalD;
}
byte[] md5 = new byte[16];
int count = 0;
for (int i = 0; i < 4; i++)
{
int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
for (int j = 0; j < 4; j++)
{
md5[count++] = (byte)n;
n >>>= 8;
}
}
return md5;
}
public static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
sb.append(String.format("%02X", b[i] & 0xFF));
}
return sb.toString();
}
public static void main(String[] args)
{
String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" };
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"");
return;
}
}
| package main
import (
"fmt"
"math"
"bytes"
"encoding/binary"
)
type testCase struct {
hashCode string
string
}
var testCases = []testCase{
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
{"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
{"d174ab98d277d9f5a5611c2c9f419d9f",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
{"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890"},
}
func main() {
for _, tc := range testCases {
fmt.Printf("%s\n%x\n\n", tc.hashCode, md5(tc.string))
}
}
var shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}
var table [64]uint32
func init() {
for i := range table {
table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))
}
}
func md5(s string) (r [16]byte) {
padded := bytes.NewBuffer([]byte(s))
padded.WriteByte(0x80)
for padded.Len() % 64 != 56 {
padded.WriteByte(0)
}
messageLenBits := uint64(len(s)) * 8
binary.Write(padded, binary.LittleEndian, messageLenBits)
var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476
var buffer [16]uint32
for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil {
a1, b1, c1, d1 := a, b, c, d
for j := 0; j < 64; j++ {
var f uint32
bufferIndex := j
round := j >> 4
switch round {
case 0:
f = (b1 & c1) | (^b1 & d1)
case 1:
f = (b1 & d1) | (c1 & ^d1)
bufferIndex = (bufferIndex*5 + 1) & 0x0F
case 2:
f = b1 ^ c1 ^ d1
bufferIndex = (bufferIndex*3 + 5) & 0x0F
case 3:
f = c1 ^ (b1 | ^d1)
bufferIndex = (bufferIndex * 7) & 0x0F
}
sa := shift[(round<<2)|(j&3)]
a1 += f + buffer[bufferIndex] + table[j]
a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1
}
a, b, c, d = a+a1, b+b1, c+c1, d+d1
}
binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})
return
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | import java.util.Random;
public class KMeansWithKpp{
public Point[] points;
public Point[] centroids;
Random rand;
public int n;
public int k;
private KMeansWithKpp(){
}
KMeansWithKpp(Point[] p, int clusters){
points = p;
n = p.length;
k = Math.max(1, clusters);
centroids = new Point[k];
rand = new Random();
}
private static double distance(Point a, Point b){
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
private static int nearest(Point pt, Point[] others, int len){
double minD = Double.MAX_VALUE;
int index = pt.group;
len = Math.min(others.length, len);
double dist;
for (int i = 0; i < len; i++) {
if (minD > (dist = distance(pt, others[i]))) {
minD = dist;
index = i;
}
}
return index;
}
private static double nearestDistance(Point pt, Point[] others, int len){
double minD = Double.MAX_VALUE;
len = Math.min(others.length, len);
double dist;
for (int i = 0; i < len; i++) {
if (minD > (dist = distance(pt, others[i]))) {
minD = dist;
}
}
return minD;
}
private void kpp(){
centroids[0] = points[rand.nextInt(n)];
double[] dist = new double[n];
double sum = 0;
for (int i = 1; i < k; i++) {
for (int j = 0; j < n; j++) {
dist[j] = nearestDistance(points[j], centroids, i);
sum += dist[j];
}
sum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if ((sum -= dist[j]) > 0)
continue;
centroids[i].x = points[j].x;
centroids[i].y = points[j].y;
}
}
for (int i = 0; i < n; i++) {
points[i].group = nearest(points[i], centroids, k);
}
}
public void kMeans(int maxTimes){
if (k == 1 || n <= 0) {
return;
}
if(k >= n){
for(int i =0; i < n; i++){
points[i].group = i;
}
return;
}
maxTimes = Math.max(1, maxTimes);
int changed;
int bestPercent = n/1000;
int minIndex;
kpp();
do {
for (Point c : centroids) {
c.x = 0.0;
c.y = 0.0;
c.group = 0;
}
for (Point pt : points) {
if(pt.group < 0 || pt.group > centroids.length){
pt.group = rand.nextInt(centroids.length);
}
centroids[pt.group].x += pt.x;
centroids[pt.group].y = pt.y;
centroids[pt.group].group++;
}
for (Point c : centroids) {
c.x /= c.group;
c.y /= c.group;
}
changed = 0;
for (Point pt : points) {
minIndex = nearest(pt, centroids, k);
if (k != pt.group) {
changed++;
pt.group = minIndex;
}
}
maxTimes--;
} while (changed > bestPercent && maxTimes > 0);
}
}
class Point{
public double x;
public double y;
public int group;
Point(){
x = y = 0.0;
group = 0;
}
public Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){
if (size <= 0)
return null;
double xdiff, ydiff;
xdiff = maxX - minX;
ydiff = maxY - minY;
if (minX > maxX) {
xdiff = minX - maxX;
minX = maxX;
}
if (maxY < minY) {
ydiff = minY - maxY;
minY = maxY;
}
Point[] data = new Point[size];
Random rand = new Random();
for (int i = 0; i < size; i++) {
data[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
data[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
}
return data;
}
public Point[] getRandomPolarData(double radius, int size){
if (size <= 0) {
return null;
}
Point[] data = new Point[size];
double radi, arg;
Random rand = new Random();
for (int i = 0; i < size; i++) {
radi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
arg = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
data[i].x = radi * Math.cos(arg);
data[i].y = radi * Math.sin(arg);
}
return data;
}
}
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"math/rand"
"os"
"time"
)
type r2 struct {
x, y float64
}
type r2c struct {
r2
c int
}
func kmpp(k int, data []r2c) {
kMeans(data, kmppSeeds(k, data))
}
func kmppSeeds(k int, data []r2c) []r2 {
s := make([]r2, k)
s[0] = data[rand.Intn(len(data))].r2
d2 := make([]float64, len(data))
for i := 1; i < k; i++ {
var sum float64
for j, p := range data {
_, dMin := nearest(p, s[:i])
d2[j] = dMin * dMin
sum += d2[j]
}
target := rand.Float64() * sum
j := 0
for sum = d2[0]; sum < target; sum += d2[j] {
j++
}
s[i] = data[j].r2
}
return s
}
func nearest(p r2c, mean []r2) (int, float64) {
iMin := 0
dMin := math.Hypot(p.x-mean[0].x, p.y-mean[0].y)
for i := 1; i < len(mean); i++ {
d := math.Hypot(p.x-mean[i].x, p.y-mean[i].y)
if d < dMin {
dMin = d
iMin = i
}
}
return iMin, dMin
}
func kMeans(data []r2c, mean []r2) {
for i, p := range data {
cMin, _ := nearest(p, mean)
data[i].c = cMin
}
mLen := make([]int, len(mean))
for {
for i := range mean {
mean[i] = r2{}
mLen[i] = 0
}
for _, p := range data {
mean[p.c].x += p.x
mean[p.c].y += p.y
mLen[p.c]++
}
for i := range mean {
inv := 1 / float64(mLen[i])
mean[i].x *= inv
mean[i].y *= inv
}
var changes int
for i, p := range data {
if cMin, _ := nearest(p, mean); cMin != p.c {
changes++
data[i].c = cMin
}
}
if changes == 0 {
return
}
}
}
type ecParam struct {
k int
nPoints int
xBox, yBox int
stdv int
}
func main() {
ec := &ecParam{6, 30000, 300, 200, 30}
origin, data := genECData(ec)
vis(ec, data, "origin")
fmt.Println("Data set origins:")
fmt.Println(" x y")
for _, o := range origin {
fmt.Printf("%5.1f %5.1f\n", o.x, o.y)
}
kmpp(ec.k, data)
fmt.Println(
"\nCluster centroids, mean distance from centroid, number of points:")
fmt.Println(" x y distance points")
cent := make([]r2, ec.k)
cLen := make([]int, ec.k)
inv := make([]float64, ec.k)
for _, p := range data {
cent[p.c].x += p.x
cent[p.c].y += p.y
cLen[p.c]++
}
for i, iLen := range cLen {
inv[i] = 1 / float64(iLen)
cent[i].x *= inv[i]
cent[i].y *= inv[i]
}
dist := make([]float64, ec.k)
for _, p := range data {
dist[p.c] += math.Hypot(p.x-cent[p.c].x, p.y-cent[p.c].y)
}
for i, iLen := range cLen {
fmt.Printf("%5.1f %5.1f %8.1f %6d\n",
cent[i].x, cent[i].y, dist[i]*inv[i], iLen)
}
vis(ec, data, "clusters")
}
func genECData(ec *ecParam) (orig []r2, data []r2c) {
rand.Seed(time.Now().UnixNano())
orig = make([]r2, ec.k)
data = make([]r2c, ec.nPoints)
for i, n := 0, 0; i < ec.k; i++ {
x := rand.Float64() * float64(ec.xBox)
y := rand.Float64() * float64(ec.yBox)
orig[i] = r2{x, y}
for j := ec.nPoints / ec.k; j > 0; j-- {
data[n].x = rand.NormFloat64()*float64(ec.stdv) + x
data[n].y = rand.NormFloat64()*float64(ec.stdv) + y
data[n].c = i
n++
}
}
return
}
func vis(ec *ecParam, data []r2c, fn string) {
colors := make([]color.NRGBA, ec.k)
for i := range colors {
i3 := i * 3
third := i3 / ec.k
frac := uint8((i3 % ec.k) * 255 / ec.k)
switch third {
case 0:
colors[i] = color.NRGBA{frac, 255 - frac, 0, 255}
case 1:
colors[i] = color.NRGBA{0, frac, 255 - frac, 255}
case 2:
colors[i] = color.NRGBA{255 - frac, 0, frac, 255}
}
}
bounds := image.Rect(-ec.stdv, -ec.stdv, ec.xBox+ec.stdv, ec.yBox+ec.stdv)
im := image.NewNRGBA(bounds)
draw.Draw(im, bounds, image.NewUniform(color.White), image.ZP, draw.Src)
fMinX := float64(bounds.Min.X)
fMaxX := float64(bounds.Max.X)
fMinY := float64(bounds.Min.Y)
fMaxY := float64(bounds.Max.Y)
for _, p := range data {
imx := math.Floor(p.x)
imy := math.Floor(float64(ec.yBox) - p.y)
if imx >= fMinX && imx < fMaxX && imy >= fMinY && imy < fMaxY {
im.SetNRGBA(int(imx), int(imy), colors[p.c])
}
}
f, err := os.Create(fn + ".png")
if err != nil {
fmt.Println(err)
return
}
err = png.Encode(f, im)
if err != nil {
fmt.Println(err)
}
err = f.Close()
if err != nil {
fmt.Println(err)
}
}
|
Change the following Java code into Go without altering its purpose. | import java.io.*;
import java.util.*;
public class MazeSolver
{
private static String[] readLines (InputStream f) throws IOException
{
BufferedReader r =
new BufferedReader (new InputStreamReader (f, "US-ASCII"));
ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = r.readLine()) != null)
lines.add (line);
return lines.toArray(new String[0]);
}
private static char[][] decimateHorizontally (String[] lines)
{
final int width = (lines[0].length() + 1) / 2;
char[][] c = new char[lines.length][width];
for (int i = 0 ; i < lines.length ; i++)
for (int j = 0 ; j < width ; j++)
c[i][j] = lines[i].charAt (j * 2);
return c;
}
private static boolean solveMazeRecursively (char[][] maze,
int x, int y, int d)
{
boolean ok = false;
for (int i = 0 ; i < 4 && !ok ; i++)
if (i != d)
switch (i)
{
case 0:
if (maze[y-1][x] == ' ')
ok = solveMazeRecursively (maze, x, y - 2, 2);
break;
case 1:
if (maze[y][x+1] == ' ')
ok = solveMazeRecursively (maze, x + 2, y, 3);
break;
case 2:
if (maze[y+1][x] == ' ')
ok = solveMazeRecursively (maze, x, y + 2, 0);
break;
case 3:
if (maze[y][x-1] == ' ')
ok = solveMazeRecursively (maze, x - 2, y, 1);
break;
}
if (x == 1 && y == 1)
ok = true;
if (ok)
{
maze[y][x] = '*';
switch (d)
{
case 0:
maze[y-1][x] = '*';
break;
case 1:
maze[y][x+1] = '*';
break;
case 2:
maze[y+1][x] = '*';
break;
case 3:
maze[y][x-1] = '*';
break;
}
}
return ok;
}
private static void solveMaze (char[][] maze)
{
solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1);
}
private static String[] expandHorizontally (char[][] maze)
{
char[] tmp = new char[3];
String[] lines = new String[maze.length];
for (int i = 0 ; i < maze.length ; i++)
{
StringBuilder sb = new StringBuilder(maze[i].length * 2);
for (int j = 0 ; j < maze[i].length ; j++)
if (j % 2 == 0)
sb.append (maze[i][j]);
else
{
tmp[0] = tmp[1] = tmp[2] = maze[i][j];
if (tmp[1] == '*')
tmp[0] = tmp[2] = ' ';
sb.append (tmp);
}
lines[i] = sb.toString();
}
return lines;
}
public static void main (String[] args) throws IOException
{
InputStream f = (args.length > 0
? new FileInputStream (args[0])
: System.in);
String[] lines = readLines (f);
char[][] maze = decimateHorizontally (lines);
solveMaze (maze);
String[] solvedLines = expandHorizontally (maze);
for (int i = 0 ; i < solvedLines.length ; i++)
System.out.println (solvedLines[i]);
}
}
| package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
type maze struct {
c2 [][]byte
h2 [][]byte
v2 [][]byte
}
func newMaze(rows, cols int) *maze {
c := make([]byte, rows*cols)
h := bytes.Repeat([]byte{'-'}, rows*cols)
v := bytes.Repeat([]byte{'|'}, rows*cols)
c2 := make([][]byte, rows)
h2 := make([][]byte, rows)
v2 := make([][]byte, rows)
for i := range h2 {
c2[i] = c[i*cols : (i+1)*cols]
h2[i] = h[i*cols : (i+1)*cols]
v2[i] = v[i*cols : (i+1)*cols]
}
return &maze{c2, h2, v2}
}
func (m *maze) String() string {
hWall := []byte("+---")
hOpen := []byte("+ ")
vWall := []byte("| ")
vOpen := []byte(" ")
rightCorner := []byte("+\n")
rightWall := []byte("|\n")
var b []byte
for r, hw := range m.h2 {
for _, h := range hw {
if h == '-' || r == 0 {
b = append(b, hWall...)
} else {
b = append(b, hOpen...)
if h != '-' && h != 0 {
b[len(b)-2] = h
}
}
}
b = append(b, rightCorner...)
for c, vw := range m.v2[r] {
if vw == '|' || c == 0 {
b = append(b, vWall...)
} else {
b = append(b, vOpen...)
if vw != '|' && vw != 0 {
b[len(b)-4] = vw
}
}
if m.c2[r][c] != 0 {
b[len(b)-2] = m.c2[r][c]
}
}
b = append(b, rightWall...)
}
for _ = range m.h2[0] {
b = append(b, hWall...)
}
b = append(b, rightCorner...)
return string(b)
}
func (m *maze) gen() {
m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0])))
}
const (
up = iota
dn
rt
lf
)
func (m *maze) g2(r, c int) {
m.c2[r][c] = ' '
for _, dir := range rand.Perm(4) {
switch dir {
case up:
if r > 0 && m.c2[r-1][c] == 0 {
m.h2[r][c] = 0
m.g2(r-1, c)
}
case lf:
if c > 0 && m.c2[r][c-1] == 0 {
m.v2[r][c] = 0
m.g2(r, c-1)
}
case dn:
if r < len(m.c2)-1 && m.c2[r+1][c] == 0 {
m.h2[r+1][c] = 0
m.g2(r+1, c)
}
case rt:
if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 {
m.v2[r][c+1] = 0
m.g2(r, c+1)
}
}
}
}
func main() {
rand.Seed(time.Now().UnixNano())
const height = 4
const width = 7
m := newMaze(height, width)
m.gen()
m.solve(
rand.Intn(height), rand.Intn(width),
rand.Intn(height), rand.Intn(width))
fmt.Print(m)
}
func (m *maze) solve(ra, ca, rz, cz int) {
var rSolve func(ra, ca, dir int) bool
rSolve = func(r, c, dir int) bool {
if r == rz && c == cz {
m.c2[r][c] = 'F'
return true
}
if dir != dn && m.h2[r][c] == 0 {
if rSolve(r-1, c, up) {
m.c2[r][c] = '^'
m.h2[r][c] = '^'
return true
}
}
if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 {
if rSolve(r+1, c, dn) {
m.c2[r][c] = 'v'
m.h2[r+1][c] = 'v'
return true
}
}
if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 {
if rSolve(r, c+1, rt) {
m.c2[r][c] = '>'
m.v2[r][c+1] = '>'
return true
}
}
if dir != rt && m.v2[r][c] == 0 {
if rSolve(r, c-1, lf) {
m.c2[r][c] = '<'
m.v2[r][c] = '<'
return true
}
}
return false
}
rSolve(ra, ca, -1)
m.c2[ra][ca] = 'S'
}
|
Keep all operations the same but rewrite the snippet in Go. | import java.util.*;
public class RandomShuffle {
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
for (int j = 1; j <= 20; ++j)
list.add(j);
Collections.shuffle(list, rand);
System.out.println(list);
}
}
| package main
import (
"fmt"
"log"
"math/rand"
"time"
)
func generate(from, to int64) {
if to < from || from < 0 {
log.Fatal("Invalid range.")
}
span := to - from + 1
generated := make([]bool, span)
count := span
for count > 0 {
n := from + rand.Int63n(span)
if !generated[n-from] {
generated[n-from] = true
fmt.Printf("%2d ", n)
count--
}
}
fmt.Println()
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := 1; i <= 5; i++ {
generate(1, 20)
}
}
|
Write a version of this Java function in Go with identical behavior. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class IQPuzzle {
public static void main(String[] args) {
System.out.printf(" ");
for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {
System.out.printf(" %,6d", start);
}
System.out.printf("%n");
for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {
System.out.printf("%2d", start);
Map<Integer,Integer> solutions = solve(start);
for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {
System.out.printf(" %,6d", solutions.containsKey(end) ? solutions.get(end) : 0);
}
System.out.printf("%n");
}
int moveNum = 0;
System.out.printf("%nOne Solution:%n");
for ( Move m : oneSolution ) {
moveNum++;
System.out.printf("Move %d = %s%n", moveNum, m);
}
}
private static List<Move> oneSolution = null;
private static Map<Integer, Integer> solve(int emptyPeg) {
Puzzle puzzle = new Puzzle(emptyPeg);
Map<Integer,Integer> solutions = new HashMap<>();
Stack<Puzzle> stack = new Stack<Puzzle>();
stack.push(puzzle);
while ( ! stack.isEmpty() ) {
Puzzle p = stack.pop();
if ( p.solved() ) {
solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);
if ( oneSolution == null ) {
oneSolution = p.moves;
}
continue;
}
for ( Move move : p.getValidMoves() ) {
Puzzle pMove = p.move(move);
stack.add(pMove);
}
}
return solutions;
}
private static class Puzzle {
public static int MAX_PEGS = 16;
private boolean[] pegs = new boolean[MAX_PEGS];
private List<Move> moves;
public Puzzle(int emptyPeg) {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
pegs[i] = true;
}
pegs[emptyPeg] = false;
moves = new ArrayList<>();
}
public Puzzle() {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
pegs[i] = true;
}
moves = new ArrayList<>();
}
private static Map<Integer,List<Move>> validMoves = new HashMap<>();
static {
validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));
validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));
validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));
validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));
validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));
validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));
validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));
validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));
validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));
validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));
validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));
validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));
validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));
validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));
validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));
}
public List<Move> getValidMoves() {
List<Move> moves = new ArrayList<Move>();
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
for ( Move testMove : validMoves.get(i) ) {
if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {
moves.add(testMove);
}
}
}
}
return moves;
}
public boolean solved() {
boolean foundFirstPeg = false;
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
if ( foundFirstPeg ) {
return false;
}
foundFirstPeg = true;
}
}
return true;
}
public Puzzle move(Move move) {
Puzzle p = new Puzzle();
if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {
throw new RuntimeException("Invalid move.");
}
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
p.pegs[i] = pegs[i];
}
p.pegs[move.start] = false;
p.pegs[move.jump] = false;
p.pegs[move.end] = true;
for ( Move m : moves ) {
p.moves.add(new Move(m.start, m.jump, m.end));
}
p.moves.add(new Move(move.start, move.jump, move.end));
return p;
}
public int getLastPeg() {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
return i;
}
}
throw new RuntimeException("ERROR: Illegal position.");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
sb.append(pegs[i] ? 1 : 0);
sb.append(",");
}
sb.setLength(sb.length()-1);
sb.append("]");
return sb.toString();
}
}
private static class Move {
int start;
int jump;
int end;
public Move(int s, int j, int e) {
start = s; jump = j; end = e;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("s=" + start);
sb.append(", j=" + jump);
sb.append(", e=" + end);
sb.append("}");
return sb.toString();
}
}
}
| package main
import "fmt"
type solution struct{ peg, over, land int }
type move struct{ from, to int }
var emptyStart = 1
var board [16]bool
var jumpMoves = [16][]move{
{},
{{2, 4}, {3, 6}},
{{4, 7}, {5, 9}},
{{5, 8}, {6, 10}},
{{2, 1}, {5, 6}, {7, 11}, {8, 13}},
{{8, 12}, {9, 14}},
{{3, 1}, {5, 4}, {9, 13}, {10, 15}},
{{4, 2}, {8, 9}},
{{5, 3}, {9, 10}},
{{5, 2}, {8, 7}},
{{9, 8}},
{{12, 13}},
{{8, 5}, {13, 14}},
{{8, 4}, {9, 6}, {12, 11}, {14, 15}},
{{9, 5}, {13, 12}},
{{10, 6}, {14, 13}},
}
var solutions []solution
func initBoard() {
for i := 1; i < 16; i++ {
board[i] = true
}
board[emptyStart] = false
}
func (sol solution) split() (int, int, int) {
return sol.peg, sol.over, sol.land
}
func (mv move) split() (int, int) {
return mv.from, mv.to
}
func drawBoard() {
var pegs [16]byte
for i := 1; i < 16; i++ {
if board[i] {
pegs[i] = fmt.Sprintf("%X", i)[0]
} else {
pegs[i] = '-'
}
}
fmt.Printf(" %c\n", pegs[1])
fmt.Printf(" %c %c\n", pegs[2], pegs[3])
fmt.Printf(" %c %c %c\n", pegs[4], pegs[5], pegs[6])
fmt.Printf(" %c %c %c %c\n", pegs[7], pegs[8], pegs[9], pegs[10])
fmt.Printf(" %c %c %c %c %c\n", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])
}
func solved() bool {
count := 0
for _, b := range board {
if b {
count++
}
}
return count == 1
}
func solve() {
if solved() {
return
}
for peg := 1; peg < 16; peg++ {
if board[peg] {
for _, mv := range jumpMoves[peg] {
over, land := mv.split()
if board[over] && !board[land] {
saveBoard := board
board[peg] = false
board[over] = false
board[land] = true
solutions = append(solutions, solution{peg, over, land})
solve()
if solved() {
return
}
board = saveBoard
solutions = solutions[:len(solutions)-1]
}
}
}
}
}
func main() {
initBoard()
solve()
initBoard()
drawBoard()
fmt.Printf("Starting with peg %X removed\n\n", emptyStart)
for _, solution := range solutions {
peg, over, land := solution.split()
board[peg] = false
board[over] = false
board[land] = true
drawBoard()
fmt.Printf("Peg %X jumped over %X to land on %X\n\n", peg, over, land)
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
import java.util.Scanner;
public class csprngBBS {
public static Scanner input = new Scanner(System.in);
private static final String fileformat = "png";
private static String bitsStri = "";
private static String parityEven = "";
private static String leastSig = "";
private static String randomJavaUtil = "";
private static int width = 0;
private static int BIT_LENGTH = 0;
private static final Random rand = new SecureRandom();
private static BigInteger p = null;
private static BigInteger q = null;
private static BigInteger m = null;
private static BigInteger seed = null;
private static BigInteger seedFinal = null;
private static final Random randMathUtil = new SecureRandom();
public static void main(String[] args) throws IOException {
System.out.print("Width: ");
width = input.nextInt();
System.out.print("Bit-Length: ");
BIT_LENGTH = input.nextInt();
System.out.print("Generator format: ");
String useGenerator = input.next();
p = BigInteger.probablePrime(BIT_LENGTH, rand);
q = BigInteger.probablePrime(BIT_LENGTH, rand);
m = p.multiply(q);
seed = BigInteger.probablePrime(BIT_LENGTH,rand);
seedFinal = seed.add(BigInteger.ZERO);
if(useGenerator.contains("parity") && useGenerator.contains("significant")) {
findLeastSignificant();
findBitParityEven();
createImage(parityEven, "parityEven");
createImage(leastSig, "significant");
}
if(useGenerator.contains("parity") && !useGenerator.contains("significant")){
findBitParityEven();
}
if(useGenerator.contains("significant") && !useGenerator.contains("parity")){
findLeastSignificant();
createImage(leastSig, "significant");
}
if(useGenerator.contains("util")){
findRandomJava(randMathUtil);
createImage(randomJavaUtil, "randomUtilJava");
}
}
public static void findRandomJava(Random random){
for(int x = 1; x <= Math.pow(width, 2); x++){
randomJavaUtil += random.nextInt(2);
}
}
public static void findBitParityEven(){
for(int x = 1; x <= Math.pow(width, 2); x++) {
seed = seed.pow(2).mod(m);
bitsStri = convertBinary(seed);
char[] bits = bitsStri.toCharArray();
int counter = 0;
for (char bit : bits) {
if (bit == '1') {
counter++;
}
}
if (counter % 2 != 0) {
parityEven += "1";
} else {
parityEven += "0";
}
}
}
public static void findLeastSignificant(){
seed = seedFinal;
for(int x = 1; x <= Math.pow(width, 2); x++){
seed = seed.pow(2).mod(m);
leastSig += bitsStri.substring(bitsStri.length() - 1);
}
}
public static String convertBinary(BigInteger value){
StringBuilder total = new StringBuilder();
BigInteger two = BigInteger.TWO;
while(value.compareTo(BigInteger.ZERO) > 0){
total.append(value.mod(two));
value = value.divide(two);
}
return total.reverse().toString();
}
public static void createImage(String useThis, String fileName) throws IOException {
int length = csprngBBS.width;
BufferedImage bufferedImage = new BufferedImage(length, length, 1);
Graphics2D g2d = bufferedImage.createGraphics();
for (int y = 1; y <= length; y++) {
for (int x = 1; x <= length; x++) {
if (useThis.startsWith("1")) {
useThis = useThis.substring(1);
g2d.setColor(Color.BLACK);
g2d.fillRect(x, y, 1, 1);
} else if (useThis.startsWith("0")) {
useThis = useThis.substring(1);
g2d.setColor(Color.WHITE);
g2d.fillRect(x, y, 1, 1);
}
}
System.out.print(y + "\t");
}
g2d.dispose();
File file = new File("REPLACEFILEPATHHERE" + fileName + "." + fileformat);
ImageIO.write(bufferedImage, fileformat, file);
}
}
| package main
import (
"image"
"image/color"
"image/png"
"log"
"math/rand"
"os"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
img := image.NewNRGBA(image.Rect(0, 0, 1000, 1000))
for x := 0; x < 1000; x++ {
for y := 0; y < 1000; y++ {
col := color.RGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256)), 255}
img.Set(x, y, col)
}
}
fileName := "pseudorandom_number_generator.png"
imgFile, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer imgFile.Close()
if err := png.Encode(imgFile, img); err != nil {
imgFile.Close()
log.Fatal(err)
}
}
|
Produce a functionally identical Go code for the snippet given in Java. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
private static List<List<Integer>> fourFaceCombos() {
List<List<Integer>> res = new ArrayList<>();
Set<Integer> found = new HashSet<>();
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
for (int k = 1; k <= 4; k++) {
for (int l = 1; l <= 4; l++) {
List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());
int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);
if (found.add(key)) {
res.add(c);
}
}
}
}
}
return res;
}
private static int cmp(List<Integer> x, List<Integer> y) {
int xw = 0;
int yw = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (x.get(i) > y.get(j)) {
xw++;
} else if (x.get(i) < y.get(j)) {
yw++;
}
}
}
return Integer.compare(xw, yw);
}
private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {
int c = cs.size();
List<List<List<Integer>>> res = new ArrayList<>();
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
if (cmp(cs.get(i), cs.get(j)) == -1) {
for (List<Integer> kl : cs) {
if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {
res.add(List.of(cs.get(i), cs.get(j), kl));
}
}
}
}
}
return res;
}
private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {
int c = cs.size();
List<List<List<Integer>>> res = new ArrayList<>();
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
if (cmp(cs.get(i), cs.get(j)) == -1) {
for (int k = 0; k < cs.size(); k++) {
if (cmp(cs.get(j), cs.get(k)) == -1) {
for (List<Integer> ll : cs) {
if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {
res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));
}
}
}
}
}
}
}
return res;
}
public static void main(String[] args) {
List<List<Integer>> combos = fourFaceCombos();
System.out.printf("Number of eligible 4-faced dice: %d%n", combos.size());
System.out.println();
List<List<List<Integer>>> it3 = findIntransitive3(combos);
System.out.printf("%d ordered lists of 3 non-transitive dice found, namely:%n", it3.size());
for (List<List<Integer>> a : it3) {
System.out.println(a);
}
System.out.println();
List<List<List<Integer>>> it4 = findIntransitive4(combos);
System.out.printf("%d ordered lists of 4 non-transitive dice found, namely:%n", it4.size());
for (List<List<Integer>> a : it4) {
System.out.println(a);
}
}
}
| package main
import (
"fmt"
"sort"
)
func fourFaceCombs() (res [][4]int) {
found := make([]bool, 256)
for i := 1; i <= 4; i++ {
for j := 1; j <= 4; j++ {
for k := 1; k <= 4; k++ {
for l := 1; l <= 4; l++ {
c := [4]int{i, j, k, l}
sort.Ints(c[:])
key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)
if !found[key] {
found[key] = true
res = append(res, c)
}
}
}
}
}
return
}
func cmp(x, y [4]int) int {
xw := 0
yw := 0
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
if x[i] > y[j] {
xw++
} else if y[j] > x[i] {
yw++
}
}
}
if xw < yw {
return -1
} else if xw > yw {
return 1
}
return 0
}
func findIntransitive3(cs [][4]int) (res [][3][4]int) {
var c = len(cs)
for i := 0; i < c; i++ {
for j := 0; j < c; j++ {
for k := 0; k < c; k++ {
first := cmp(cs[i], cs[j])
if first == -1 {
second := cmp(cs[j], cs[k])
if second == -1 {
third := cmp(cs[i], cs[k])
if third == 1 {
res = append(res, [3][4]int{cs[i], cs[j], cs[k]})
}
}
}
}
}
}
return
}
func findIntransitive4(cs [][4]int) (res [][4][4]int) {
c := len(cs)
for i := 0; i < c; i++ {
for j := 0; j < c; j++ {
for k := 0; k < c; k++ {
for l := 0; l < c; l++ {
first := cmp(cs[i], cs[j])
if first == -1 {
second := cmp(cs[j], cs[k])
if second == -1 {
third := cmp(cs[k], cs[l])
if third == -1 {
fourth := cmp(cs[i], cs[l])
if fourth == 1 {
res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})
}
}
}
}
}
}
}
}
return
}
func main() {
combs := fourFaceCombs()
fmt.Println("Number of eligible 4-faced dice", len(combs))
it3 := findIntransitive3(combs)
fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3))
for _, a := range it3 {
fmt.Println(a)
}
it4 := findIntransitive4(combs)
fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4))
for _, a := range it4 {
fmt.Println(a)
}
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | public class HistoryVariable
{
private Object value;
public HistoryVariable(Object v)
{
value = v;
}
public void update(Object v)
{
value = v;
}
public Object undo()
{
return value;
}
@Override
public String toString()
{
return value.toString();
}
public void dispose()
{
}
}
| package main
import (
"fmt"
"sort"
"sync"
"time"
)
type history struct {
timestamp tsFunc
hs []hset
}
type tsFunc func() time.Time
type hset struct {
int
t time.Time
}
func newHistory(ts tsFunc) history {
return history{ts, []hset{{t: ts()}}}
}
func (h history) int() int {
return h.hs[len(h.hs)-1].int
}
func (h *history) set(x int) time.Time {
t := h.timestamp()
h.hs = append(h.hs, hset{x, t})
return t
}
func (h history) dump() {
for _, hs := range h.hs {
fmt.Println(hs.t.Format(time.StampNano), hs.int)
}
}
func (h history) recall(t time.Time) (int, bool) {
i := sort.Search(len(h.hs), func(i int) bool {
return h.hs[i].t.After(t)
})
if i > 0 {
return h.hs[i-1].int, true
}
return 0, false
}
func newTimestamper() tsFunc {
var last time.Time
return func() time.Time {
if t := time.Now(); t.After(last) {
last = t
} else {
last.Add(1)
}
return last
}
}
func newProtectedTimestamper() tsFunc {
var last time.Time
var m sync.Mutex
return func() (t time.Time) {
t = time.Now()
m.Lock()
if t.After(last) {
last = t
} else {
last.Add(1)
t = last
}
m.Unlock()
return
}
}
func main() {
ts := newTimestamper()
h := newHistory(ts)
ref := []time.Time{h.set(3), h.set(1), h.set(4)}
fmt.Println("History of variable h:")
h.dump()
fmt.Println("Recalling values:")
for _, t := range ref {
rv, _ := h.recall(t)
fmt.Println(rv)
}
}
|
Change the following Java code into Go without altering its purpose. | import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class Perceptron extends JPanel {
class Trainer {
double[] inputs;
int answer;
Trainer(double x, double y, int a) {
inputs = new double[]{x, y, 1};
answer = a;
}
}
Trainer[] training = new Trainer[2000];
double[] weights;
double c = 0.00001;
int count;
public Perceptron(int n) {
Random r = new Random();
Dimension dim = new Dimension(640, 360);
setPreferredSize(dim);
setBackground(Color.white);
weights = new double[n];
for (int i = 0; i < weights.length; i++) {
weights[i] = r.nextDouble() * 2 - 1;
}
for (int i = 0; i < training.length; i++) {
double x = r.nextDouble() * dim.width;
double y = r.nextDouble() * dim.height;
int answer = y < f(x) ? -1 : 1;
training[i] = new Trainer(x, y, answer);
}
new Timer(10, (ActionEvent e) -> {
repaint();
}).start();
}
private double f(double x) {
return x * 0.7 + 40;
}
int feedForward(double[] inputs) {
assert inputs.length == weights.length : "weights and input length mismatch";
double sum = 0;
for (int i = 0; i < weights.length; i++) {
sum += inputs[i] * weights[i];
}
return activate(sum);
}
int activate(double s) {
return s > 0 ? 1 : -1;
}
void train(double[] inputs, int desired) {
int guess = feedForward(inputs);
double error = desired - guess;
for (int i = 0; i < weights.length; i++) {
weights[i] += c * error * inputs[i];
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int x = getWidth();
int y = (int) f(x);
g.setStroke(new BasicStroke(2));
g.setColor(Color.orange);
g.drawLine(0, (int) f(0), x, y);
train(training[count].inputs, training[count].answer);
count = (count + 1) % training.length;
g.setStroke(new BasicStroke(1));
g.setColor(Color.black);
for (int i = 0; i < count; i++) {
int guess = feedForward(training[i].inputs);
x = (int) training[i].inputs[0] - 4;
y = (int) training[i].inputs[1] - 4;
if (guess > 0)
g.drawOval(x, y, 8, 8);
else
g.fillOval(x, y, 8, 8);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Perceptron");
f.setResizable(false);
f.add(new Perceptron(3), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| package main
import (
"github.com/fogleman/gg"
"math/rand"
"time"
)
const c = 0.00001
func linear(x float64) float64 {
return x*0.7 + 40
}
type trainer struct {
inputs []float64
answer int
}
func newTrainer(x, y float64, a int) *trainer {
return &trainer{[]float64{x, y, 1}, a}
}
type perceptron struct {
weights []float64
training []*trainer
}
func newPerceptron(n, w, h int) *perceptron {
weights := make([]float64, n)
for i := 0; i < n; i++ {
weights[i] = rand.Float64()*2 - 1
}
training := make([]*trainer, 2000)
for i := 0; i < 2000; i++ {
x := rand.Float64() * float64(w)
y := rand.Float64() * float64(h)
answer := 1
if y < linear(x) {
answer = -1
}
training[i] = newTrainer(x, y, answer)
}
return &perceptron{weights, training}
}
func (p *perceptron) feedForward(inputs []float64) int {
if len(inputs) != len(p.weights) {
panic("weights and input length mismatch, program terminated")
}
sum := 0.0
for i, w := range p.weights {
sum += inputs[i] * w
}
if sum > 0 {
return 1
}
return -1
}
func (p *perceptron) train(inputs []float64, desired int) {
guess := p.feedForward(inputs)
err := float64(desired - guess)
for i := range p.weights {
p.weights[i] += c * err * inputs[i]
}
}
func (p *perceptron) draw(dc *gg.Context, iterations int) {
le := len(p.training)
for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le {
p.train(p.training[count].inputs, p.training[count].answer)
}
x := float64(dc.Width())
y := linear(x)
dc.SetLineWidth(2)
dc.SetRGB255(0, 0, 0)
dc.DrawLine(0, linear(0), x, y)
dc.Stroke()
dc.SetLineWidth(1)
for i := 0; i < le; i++ {
guess := p.feedForward(p.training[i].inputs)
x := p.training[i].inputs[0] - 4
y := p.training[i].inputs[1] - 4
if guess > 0 {
dc.SetRGB(0, 0, 1)
} else {
dc.SetRGB(1, 0, 0)
}
dc.DrawCircle(x, y, 8)
dc.Stroke()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
w, h := 640, 360
perc := newPerceptron(3, w, h)
dc := gg.NewContext(w, h)
dc.SetRGB(1, 1, 1)
dc.Clear()
perc.draw(dc, 2000)
dc.SavePNG("perceptron.png")
}
|
Convert this Java snippet to Go and keep its semantics consistent. | import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
}
| package main
import (
"fmt"
"bitbucket.org/binet/go-eval/pkg/eval"
"go/token"
)
func main() {
w := eval.NewWorld();
fset := token.NewFileSet();
code, err := w.Compile(fset, "1 + 2")
if err != nil {
fmt.Println("Compile error");
return
}
val, err := code.Run();
if err != nil {
fmt.Println("Run time error");
return;
}
fmt.Println("Return value:", val)
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
}
| package main
import (
"fmt"
"bitbucket.org/binet/go-eval/pkg/eval"
"go/token"
)
func main() {
w := eval.NewWorld();
fset := token.NewFileSet();
code, err := w.Compile(fset, "1 + 2")
if err != nil {
fmt.Println("Compile error");
return
}
val, err := code.Run();
if err != nil {
fmt.Println("Run time error");
return;
}
fmt.Println("Return value:", val)
}
|
Change the following Java code into Go without altering its purpose. | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class PisanoPeriod {
public static void main(String[] args) {
System.out.printf("Print pisano(p^2) for every prime p lower than 15%n");
for ( long i = 2 ; i < 15 ; i++ ) {
if ( isPrime(i) ) {
long n = i*i;
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(p) for every prime p lower than 180%n");
for ( long n = 2 ; n < 180 ; n++ ) {
if ( isPrime(n) ) {
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(n) for every integer from 1 to 180%n");
for ( long n = 1 ; n <= 180 ; n++ ) {
System.out.printf("%3d ", pisano(n));
if ( n % 10 == 0 ) {
System.out.printf("%n");
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) {
return false;
}
for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
if ( test % i == 0 ) {
return false;
}
}
return true;
}
private static Map<Long,Long> PERIOD_MEMO = new HashMap<>();
static {
PERIOD_MEMO.put(2L, 3L);
PERIOD_MEMO.put(3L, 8L);
PERIOD_MEMO.put(5L, 20L);
}
private static long pisano(long n) {
if ( PERIOD_MEMO.containsKey(n) ) {
return PERIOD_MEMO.get(n);
}
if ( n == 1 ) {
return 1;
}
Map<Long,Long> factors = getFactors(n);
if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {
long result = 3 * n / 2;
PERIOD_MEMO.put(n, result);
return result;
}
if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 4*n;
PERIOD_MEMO.put(n, result);
return result;
}
if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 6*n;
PERIOD_MEMO.put(n, result);
return result;
}
List<Long> primes = new ArrayList<>(factors.keySet());
long prime = primes.get(0);
if ( factors.size() == 1 && factors.get(prime) == 1 ) {
List<Long> divisors = new ArrayList<>();
if ( n % 10 == 1 || n % 10 == 9 ) {
for ( long divisor : getDivisors(prime-1) ) {
if ( divisor % 2 == 0 ) {
divisors.add(divisor);
}
}
}
else {
List<Long> pPlus1Divisors = getDivisors(prime+1);
for ( long divisor : getDivisors(2*prime+2) ) {
if ( ! pPlus1Divisors.contains(divisor) ) {
divisors.add(divisor);
}
}
}
Collections.sort(divisors);
for ( long divisor : divisors ) {
if ( fibModIdentity(divisor, prime) ) {
PERIOD_MEMO.put(prime, divisor);
return divisor;
}
}
throw new RuntimeException("ERROR 144: Divisor not found.");
}
long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);
for ( int i = 1 ; i < primes.size() ; i++ ) {
prime = primes.get(i);
period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));
}
PERIOD_MEMO.put(n, period);
return period;
}
private static boolean fibModIdentity(long n, long mod) {
long aRes = 0;
long bRes = 1;
long cRes = 1;
long aBase = 0;
long bBase = 1;
long cBase = 1;
while ( n > 0 ) {
if ( n % 2 == 1 ) {
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {
temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;
temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;
temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;
}
else {
temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;
temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;
temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;
}
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
n >>= 1L;
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {
temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;
temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;
temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;
}
else {
temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;
temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;
temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;
}
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
private static final List<Long> getDivisors(long number) {
List<Long> divisors = new ArrayList<>();
long sqrt = (long) Math.sqrt(number);
for ( long i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
long div = number / i;
if ( div != i ) {
divisors.add(div);
}
}
}
return divisors;
}
public static long lcm(long a, long b) {
return a*b/gcd(a,b);
}
public static long gcd(long a, long b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
private static final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();
static {
Map<Long,Long> factors = new TreeMap<Long,Long>();
factors.put(2L, 1L);
allFactors.put(2L, factors);
}
public static Long MAX_ALL_FACTORS = 100000L;
public static final Map<Long,Long> getFactors(Long number) {
if ( allFactors.containsKey(number) ) {
return allFactors.get(number);
}
Map<Long,Long> factors = new TreeMap<Long,Long>();
if ( number % 2 == 0 ) {
Map<Long,Long> factorsdDivTwo = getFactors(number/2);
factors.putAll(factorsdDivTwo);
factors.merge(2L, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
boolean prime = true;
long sqrt = (long) Math.sqrt(number);
for ( long i = 3 ; i <= sqrt ; i += 2 ) {
if ( number % i == 0 ) {
prime = false;
factors.putAll(getFactors(number/i));
factors.merge(i, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
}
if ( prime ) {
factors.put(number, 1L);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
}
return factors;
}
}
| package main
import "fmt"
func gcd(a, b uint) uint {
if b == 0 {
return a
}
return gcd(b, a%b)
}
func lcm(a, b uint) uint {
return a / gcd(a, b) * b
}
func ipow(x, p uint) uint {
prod := uint(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func getPrimes(n uint) []uint {
var primes []uint
for i := uint(2); i <= n; i++ {
div := n / i
mod := n % i
for mod == 0 {
primes = append(primes, i)
n = div
div = n / i
mod = n % i
}
}
return primes
}
func isPrime(n uint) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func pisanoPeriod(m uint) uint {
var p, c uint = 0, 1
for i := uint(0); i < m*m; i++ {
p, c = c, (p+c)%m
if p == 0 && c == 1 {
return i + 1
}
}
return 1
}
func pisanoPrime(p uint, k uint) uint {
if !isPrime(p) || k == 0 {
return 0
}
return ipow(p, k-1) * pisanoPeriod(p)
}
func pisano(m uint) uint {
primes := getPrimes(m)
primePowers := make(map[uint]uint)
for _, p := range primes {
primePowers[p]++
}
var pps []uint
for k, v := range primePowers {
pps = append(pps, pisanoPrime(k, v))
}
if len(pps) == 0 {
return 1
}
if len(pps) == 1 {
return pps[0]
}
f := pps[0]
for i := 1; i < len(pps); i++ {
f = lcm(f, pps[i])
}
return f
}
func main() {
for p := uint(2); p < 15; p++ {
pp := pisanoPrime(p, 2)
if pp > 0 {
fmt.Printf("pisanoPrime(%2d: 2) = %d\n", p, pp)
}
}
fmt.Println()
for p := uint(2); p < 180; p++ {
pp := pisanoPrime(p, 1)
if pp > 0 {
fmt.Printf("pisanoPrime(%3d: 1) = %d\n", p, pp)
}
}
fmt.Println()
fmt.Println("pisano(n) for integers 'n' from 1 to 180 are:")
for n := uint(1); n <= 180; n++ {
fmt.Printf("%3d ", pisano(n))
if n != 1 && n%15 == 0 {
fmt.Println()
}
}
fmt.Println()
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | package railwaycircuit;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.IntStream.range;
public class RailwayCircuit {
final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0;
static String normalize(int[] tracks) {
char[] a = new char[tracks.length];
for (int i = 0; i < a.length; i++)
a[i] = "abc".charAt(tracks[i] + 1);
String norm = new String(a);
for (int i = 0, len = a.length; i < len; i++) {
String s = new String(a);
if (s.compareTo(norm) < 0)
norm = s;
char tmp = a[0];
for (int j = 1; j < a.length; j++)
a[j - 1] = a[j];
a[len - 1] = tmp;
}
return norm;
}
static boolean fullCircleStraight(int[] tracks, int nStraight) {
if (nStraight == 0)
return true;
if (stream(tracks).filter(i -> i == STRAIGHT).count() != nStraight)
return false;
int[] straight = new int[12];
for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {
if (tracks[i] == STRAIGHT)
straight[idx % 12]++;
idx += tracks[i];
}
return !(range(0, 6).anyMatch(i -> straight[i] != straight[i + 6])
&& range(0, 8).anyMatch(i -> straight[i] != straight[i + 4]));
}
static boolean fullCircleRight(int[] tracks) {
if (stream(tracks).map(i -> i * 30).sum() % 360 != 0)
return false;
int[] rTurns = new int[12];
for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {
if (tracks[i] == RIGHT)
rTurns[idx % 12]++;
idx += tracks[i];
}
return !(range(0, 6).anyMatch(i -> rTurns[i] != rTurns[i + 6])
&& range(0, 8).anyMatch(i -> rTurns[i] != rTurns[i + 4]));
}
static void circuits(int nCurved, int nStraight) {
Map<String, int[]> solutions = new HashMap<>();
PermutationsGen gen = getPermutationsGen(nCurved, nStraight);
while (gen.hasNext()) {
int[] tracks = gen.next();
if (!fullCircleStraight(tracks, nStraight))
continue;
if (!fullCircleRight(tracks))
continue;
solutions.put(normalize(tracks), tracks.clone());
}
report(solutions, nCurved, nStraight);
}
static PermutationsGen getPermutationsGen(int nCurved, int nStraight) {
assert (nCurved + nStraight - 12) % 4 == 0 : "input must be 12 + k * 4";
int[] trackTypes = new int[]{RIGHT, LEFT};
if (nStraight != 0) {
if (nCurved == 12)
trackTypes = new int[]{RIGHT, STRAIGHT};
else
trackTypes = new int[]{RIGHT, LEFT, STRAIGHT};
}
return new PermutationsGen(nCurved + nStraight, trackTypes);
}
static void report(Map<String, int[]> sol, int numC, int numS) {
int size = sol.size();
System.out.printf("%n%d solution(s) for C%d,%d %n", size, numC, numS);
if (size < 10)
sol.values().stream().forEach(tracks -> {
stream(tracks).forEach(i -> System.out.printf("%2d ", i));
System.out.println();
});
}
public static void main(String[] args) {
circuits(12, 0);
circuits(16, 0);
circuits(20, 0);
circuits(24, 0);
circuits(12, 4);
}
}
class PermutationsGen {
private int[] indices;
private int[] choices;
private int[] sequence;
private int carry;
PermutationsGen(int numPositions, int[] choices) {
indices = new int[numPositions];
sequence = new int[numPositions];
this.choices = choices;
}
int[] next() {
carry = 1;
for (int i = 1; i < indices.length && carry > 0; i++) {
indices[i] += carry;
carry = 0;
if (indices[i] == choices.length) {
carry = 1;
indices[i] = 0;
}
}
for (int i = 0; i < indices.length; i++)
sequence[i] = choices[indices[i]];
return sequence;
}
boolean hasNext() {
return carry != 1;
}
}
| package main
import "fmt"
const (
right = 1
left = -1
straight = 0
)
func normalize(tracks []int) string {
size := len(tracks)
a := make([]byte, size)
for i := 0; i < size; i++ {
a[i] = "abc"[tracks[i]+1]
}
norm := string(a)
for i := 0; i < size; i++ {
s := string(a)
if s < norm {
norm = s
}
tmp := a[0]
copy(a, a[1:])
a[size-1] = tmp
}
return norm
}
func fullCircleStraight(tracks []int, nStraight int) bool {
if nStraight == 0 {
return true
}
count := 0
for _, track := range tracks {
if track == straight {
count++
}
}
if count != nStraight {
return false
}
var straightTracks [12]int
for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {
if tracks[i] == straight {
straightTracks[idx%12]++
}
idx += tracks[i]
}
any1, any2 := false, false
for i := 0; i <= 5; i++ {
if straightTracks[i] != straightTracks[i+6] {
any1 = true
break
}
}
for i := 0; i <= 7; i++ {
if straightTracks[i] != straightTracks[i+4] {
any2 = true
break
}
}
return !any1 || !any2
}
func fullCircleRight(tracks []int) bool {
sum := 0
for _, track := range tracks {
sum += track * 30
}
if sum%360 != 0 {
return false
}
var rTurns [12]int
for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {
if tracks[i] == right {
rTurns[idx%12]++
}
idx += tracks[i]
}
any1, any2 := false, false
for i := 0; i <= 5; i++ {
if rTurns[i] != rTurns[i+6] {
any1 = true
break
}
}
for i := 0; i <= 7; i++ {
if rTurns[i] != rTurns[i+4] {
any2 = true
break
}
}
return !any1 || !any2
}
func circuits(nCurved, nStraight int) {
solutions := make(map[string][]int)
gen := getPermutationsGen(nCurved, nStraight)
for gen.hasNext() {
tracks := gen.next()
if !fullCircleStraight(tracks, nStraight) {
continue
}
if !fullCircleRight(tracks) {
continue
}
tracks2 := make([]int, len(tracks))
copy(tracks2, tracks)
solutions[normalize(tracks)] = tracks2
}
report(solutions, nCurved, nStraight)
}
func getPermutationsGen(nCurved, nStraight int) PermutationsGen {
if (nCurved+nStraight-12)%4 != 0 {
panic("input must be 12 + k * 4")
}
var trackTypes []int
switch nStraight {
case 0:
trackTypes = []int{right, left}
case 12:
trackTypes = []int{right, straight}
default:
trackTypes = []int{right, left, straight}
}
return NewPermutationsGen(nCurved+nStraight, trackTypes)
}
func report(sol map[string][]int, numC, numS int) {
size := len(sol)
fmt.Printf("\n%d solution(s) for C%d,%d \n", size, numC, numS)
if numC <= 20 {
for _, tracks := range sol {
for _, track := range tracks {
fmt.Printf("%2d ", track)
}
fmt.Println()
}
}
}
type PermutationsGen struct {
NumPositions int
choices []int
indices []int
sequence []int
carry int
}
func NewPermutationsGen(numPositions int, choices []int) PermutationsGen {
indices := make([]int, numPositions)
sequence := make([]int, numPositions)
carry := 0
return PermutationsGen{numPositions, choices, indices, sequence, carry}
}
func (p *PermutationsGen) next() []int {
p.carry = 1
for i := 1; i < len(p.indices) && p.carry > 0; i++ {
p.indices[i] += p.carry
p.carry = 0
if p.indices[i] == len(p.choices) {
p.carry = 1
p.indices[i] = 0
}
}
for j := 0; j < len(p.indices); j++ {
p.sequence[j] = p.choices[p.indices[j]]
}
return p.sequence
}
func (p *PermutationsGen) hasNext() bool {
return p.carry != 1
}
func main() {
for n := 12; n <= 28; n += 4 {
circuits(n, 0)
}
circuits(12, 4)
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | import java.awt.Point;
import java.util.*;
import static java.util.Arrays.asList;
import java.util.function.Function;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
public class FreePolyominoesEnum {
static final List<Function<Point, Point>> transforms = new ArrayList<>();
static {
transforms.add(p -> new Point(p.y, -p.x));
transforms.add(p -> new Point(-p.x, -p.y));
transforms.add(p -> new Point(-p.y, p.x));
transforms.add(p -> new Point(-p.x, p.y));
transforms.add(p -> new Point(-p.y, -p.x));
transforms.add(p -> new Point(p.x, -p.y));
transforms.add(p -> new Point(p.y, p.x));
}
static Point findMinima(List<Point> poly) {
return new Point(
poly.stream().mapToInt(a -> a.x).min().getAsInt(),
poly.stream().mapToInt(a -> a.y).min().getAsInt());
}
static List<Point> translateToOrigin(List<Point> poly) {
final Point min = findMinima(poly);
poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y));
return poly;
}
static List<List<Point>> rotationsAndReflections(List<Point> poly) {
List<List<Point>> lst = new ArrayList<>();
lst.add(poly);
for (Function<Point, Point> t : transforms)
lst.add(poly.stream().map(t).collect(toList()));
return lst;
}
static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x)
.thenComparingInt(p -> p.y);
static List<Point> normalize(List<Point> poly) {
return rotationsAndReflections(poly).stream()
.map(lst -> translateToOrigin(lst))
.map(lst -> lst.stream().sorted(byCoords).collect(toList()))
.min(comparing(Object::toString))
.get();
}
static List<Point> neighborhoods(Point p) {
return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y),
new Point(p.x, p.y - 1), new Point(p.x, p.y + 1));
}
static List<Point> concat(List<Point> lst, Point pt) {
List<Point> r = new ArrayList<>();
r.addAll(lst);
r.add(pt);
return r;
}
static List<Point> newPoints(List<Point> poly) {
return poly.stream()
.flatMap(p -> neighborhoods(p).stream())
.filter(p -> !poly.contains(p))
.distinct()
.collect(toList());
}
static List<List<Point>> constructNextRank(List<Point> poly) {
return newPoints(poly).stream()
.map(p -> normalize(concat(poly, p)))
.distinct()
.collect(toList());
}
static List<List<Point>> rank(int n) {
if (n < 0)
throw new IllegalArgumentException("n cannot be negative");
if (n < 2) {
List<List<Point>> r = new ArrayList<>();
if (n == 1)
r.add(asList(new Point(0, 0)));
return r;
}
return rank(n - 1).stream()
.parallel()
.flatMap(lst -> constructNextRank(lst).stream())
.distinct()
.collect(toList());
}
public static void main(String[] args) {
for (List<Point> poly : rank(5)) {
for (Point p : poly)
System.out.printf("(%d,%d) ", p.x, p.y);
System.out.println();
}
}
}
| package main
import (
"fmt"
"sort"
)
type point struct{ x, y int }
type polyomino []point
type pointset map[point]bool
func (p point) rotate90() point { return point{p.y, -p.x} }
func (p point) rotate180() point { return point{-p.x, -p.y} }
func (p point) rotate270() point { return point{-p.y, p.x} }
func (p point) reflect() point { return point{-p.x, p.y} }
func (p point) String() string { return fmt.Sprintf("(%d, %d)", p.x, p.y) }
func (p point) contiguous() polyomino {
return polyomino{point{p.x - 1, p.y}, point{p.x + 1, p.y},
point{p.x, p.y - 1}, point{p.x, p.y + 1}}
}
func (po polyomino) minima() (int, int) {
minx := po[0].x
miny := po[0].y
for i := 1; i < len(po); i++ {
if po[i].x < minx {
minx = po[i].x
}
if po[i].y < miny {
miny = po[i].y
}
}
return minx, miny
}
func (po polyomino) translateToOrigin() polyomino {
minx, miny := po.minima()
res := make(polyomino, len(po))
for i, p := range po {
res[i] = point{p.x - minx, p.y - miny}
}
sort.Slice(res, func(i, j int) bool {
return res[i].x < res[j].x || (res[i].x == res[j].x && res[i].y < res[j].y)
})
return res
}
func (po polyomino) rotationsAndReflections() []polyomino {
rr := make([]polyomino, 8)
for i := 0; i < 8; i++ {
rr[i] = make(polyomino, len(po))
}
copy(rr[0], po)
for j := 0; j < len(po); j++ {
rr[1][j] = po[j].rotate90()
rr[2][j] = po[j].rotate180()
rr[3][j] = po[j].rotate270()
rr[4][j] = po[j].reflect()
rr[5][j] = po[j].rotate90().reflect()
rr[6][j] = po[j].rotate180().reflect()
rr[7][j] = po[j].rotate270().reflect()
}
return rr
}
func (po polyomino) canonical() polyomino {
rr := po.rotationsAndReflections()
minr := rr[0].translateToOrigin()
mins := minr.String()
for i := 1; i < 8; i++ {
r := rr[i].translateToOrigin()
s := r.String()
if s < mins {
minr = r
mins = s
}
}
return minr
}
func (po polyomino) String() string {
return fmt.Sprintf("%v", []point(po))
}
func (po polyomino) toPointset() pointset {
pset := make(pointset, len(po))
for _, p := range po {
pset[p] = true
}
return pset
}
func (po polyomino) newPoints() polyomino {
pset := po.toPointset()
m := make(pointset)
for _, p := range po {
pts := p.contiguous()
for _, pt := range pts {
if !pset[pt] {
m[pt] = true
}
}
}
poly := make(polyomino, 0, len(m))
for k := range m {
poly = append(poly, k)
}
return poly
}
func (po polyomino) newPolys() []polyomino {
pts := po.newPoints()
res := make([]polyomino, len(pts))
for i, pt := range pts {
poly := make(polyomino, len(po))
copy(poly, po)
poly = append(poly, pt)
res[i] = poly.canonical()
}
return res
}
var monomino = polyomino{point{0, 0}}
var monominoes = []polyomino{monomino}
func rank(n int) []polyomino {
switch {
case n < 0:
panic("n cannot be negative. Program terminated.")
case n == 0:
return []polyomino{}
case n == 1:
return monominoes
default:
r := rank(n - 1)
m := make(map[string]bool)
var polys []polyomino
for _, po := range r {
for _, po2 := range po.newPolys() {
if s := po2.String(); !m[s] {
polys = append(polys, po2)
m[s] = true
}
}
}
sort.Slice(polys, func(i, j int) bool {
return polys[i].String() < polys[j].String()
})
return polys
}
}
func main() {
const n = 5
fmt.Printf("All free polyominoes of rank %d:\n\n", n)
for _, poly := range rank(n) {
for _, pt := range poly {
fmt.Printf("%s ", pt)
}
fmt.Println()
}
const k = 10
fmt.Printf("\nNumber of free polyominoes of ranks 1 to %d:\n", k)
for i := 1; i <= k; i++ {
fmt.Printf("%d ", len(rank(i)))
}
fmt.Println()
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | package src;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URI;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class EventGetter {
String city = "";
String topic = "";
public String getEvent(String path_code,String key) throws Exception{
String responseString = "";
URI request = new URIBuilder()
.setScheme("http")
.setHost("api.meetup.com")
.setPath(path_code)
.setParameter("topic", topic)
.setParameter("city", city)
.setParameter("key", key)
.build();
HttpGet get = new HttpGet(request);
System.out.println("Get request : "+get.toString());
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(get);
responseString = EntityUtils.toString(response.getEntity());
return responseString;
}
public String getApiKey(String key_path){
String key = "";
try{
BufferedReader reader = new BufferedReader(new FileReader(key_path));
key = reader.readLine().toString();
reader.close();
}
catch(Exception e){System.out.println(e.toString());}
return key;
}
}
| package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var key string
func init() {
const keyFile = "api_key.txt"
f, err := os.Open(keyFile)
if err != nil {
log.Fatal(err)
}
keydata, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
key = strings.TrimSpace(string(keydata))
}
type EventResponse struct {
Results []Result
}
type Result struct {
ID string
Status string
Name string
EventURL string `json:"event_url"`
Description string
Time EventTime
}
type EventTime struct{ time.Time }
func (et *EventTime) UnmarshalJSON(data []byte) error {
var msec int64
if err := json.Unmarshal(data, &msec); err != nil {
return err
}
et.Time = time.Unix(0, msec*int64(time.Millisecond))
return nil
}
func (et EventTime) MarshalJSON() ([]byte, error) {
msec := et.UnixNano() / int64(time.Millisecond)
return json.Marshal(msec)
}
func (r *Result) String() string {
var b bytes.Buffer
fmt.Fprintln(&b, "ID:", r.ID)
fmt.Fprintln(&b, "URL:", r.EventURL)
fmt.Fprintln(&b, "Time:", r.Time.Format(time.UnixDate))
d := r.Description
const limit = 65
if len(d) > limit {
d = d[:limit-1] + "…"
}
fmt.Fprintln(&b, "Description:", d)
return b.String()
}
func main() {
v := url.Values{
"topic": []string{"photo"},
"time": []string{",1w"},
"key": []string{key},
}
u := url.URL{
Scheme: "http",
Host: "api.meetup.com",
Path: "2/open_events.json",
RawQuery: v.Encode(),
}
resp, err := http.Get(u.String())
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
log.Println("HTTP Status:", resp.Status)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
if err = json.Indent(&buf, body, "", " "); err != nil {
log.Fatal(err)
}
var evresp EventResponse
json.Unmarshal(body, &evresp)
fmt.Println("Got", len(evresp.Results), "events")
if len(evresp.Results) > 0 {
fmt.Println("First event:\n", &evresp.Results[0])
}
}
|
Port the provided Java code into Go while preserving the original functionality. | 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.");
}
}
| package main
import "fmt"
var solution = make(chan int)
var nearMiss = make(chan int)
var done = make(chan bool)
func main() {
for i := 0; i < 4096; i++ {
go checkPerm(i)
}
var ms []int
for i := 0; i < 4096; {
select {
case <-done:
i++
case s := <-solution:
print12("solution", s)
case m := <-nearMiss:
ms = append(ms, m)
}
}
for _, m := range ms {
print12("near miss", m)
}
}
func print12(label string, bits int) {
fmt.Print(label, ":")
for i := 1; i <= 12; i++ {
if bits&1 == 1 {
fmt.Print(" ", i)
}
bits >>= 1
}
fmt.Println()
}
func checkPerm(tz int) {
ts := func(n uint) bool {
return tz>>(n-1)&1 == 1
}
ntrue := func(xs ...uint) int {
nt := 0
for _, x := range xs {
if ts(x) {
nt++
}
}
return nt
}
var con bool
test := func(statement uint, b bool) {
switch {
case ts(statement) == b:
case con:
panic("bail")
default:
con = true
}
}
defer func() {
if x := recover(); x != nil {
if msg, ok := x.(string); !ok && msg != "bail" {
panic(x)
}
}
done <- true
}()
test(1, true)
test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)
test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)
test(4, !ts(5) || ts(6) && ts(7))
test(5, !ts(4) && !ts(3) && !ts(2))
test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)
test(7, ts(2) != ts(3))
test(8, !ts(7) || ts(5) && ts(6))
test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)
test(10, ts(11) && ts(12))
test(11, ntrue(7, 8, 9) == 1)
test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)
if con {
nearMiss <- tz
} else {
solution <- tz
}
}
|
Convert the following code from Java to Go, ensuring the logic remains intact. | 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.");
}
}
| package main
import "fmt"
var solution = make(chan int)
var nearMiss = make(chan int)
var done = make(chan bool)
func main() {
for i := 0; i < 4096; i++ {
go checkPerm(i)
}
var ms []int
for i := 0; i < 4096; {
select {
case <-done:
i++
case s := <-solution:
print12("solution", s)
case m := <-nearMiss:
ms = append(ms, m)
}
}
for _, m := range ms {
print12("near miss", m)
}
}
func print12(label string, bits int) {
fmt.Print(label, ":")
for i := 1; i <= 12; i++ {
if bits&1 == 1 {
fmt.Print(" ", i)
}
bits >>= 1
}
fmt.Println()
}
func checkPerm(tz int) {
ts := func(n uint) bool {
return tz>>(n-1)&1 == 1
}
ntrue := func(xs ...uint) int {
nt := 0
for _, x := range xs {
if ts(x) {
nt++
}
}
return nt
}
var con bool
test := func(statement uint, b bool) {
switch {
case ts(statement) == b:
case con:
panic("bail")
default:
con = true
}
}
defer func() {
if x := recover(); x != nil {
if msg, ok := x.(string); !ok && msg != "bail" {
panic(x)
}
}
done <- true
}()
test(1, true)
test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)
test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)
test(4, !ts(5) || ts(6) && ts(7))
test(5, !ts(4) && !ts(3) && !ts(2))
test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)
test(7, ts(2) != ts(3))
test(8, !ts(7) || ts(5) && ts(6))
test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)
test(10, ts(11) && ts(12))
test(11, ntrue(7, 8, 9) == 1)
test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)
if con {
nearMiss <- tz
} else {
solution <- tz
}
}
|
Write the same code in Go as shown below in Java. | import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] dxs = {
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
}
| package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
}
var dys = []float64{
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
}
func funnel(fa []float64, r rule) []float64 {
x := 0.0
result := make([]float64, len(fa))
for i, f := range fa {
result[i] = x + f
x = r(x, f)
}
return result
}
func mean(fa []float64) float64 {
sum := 0.0
for _, f := range fa {
sum += f
}
return sum / float64(len(fa))
}
func stdDev(fa []float64) float64 {
m := mean(fa)
sum := 0.0
for _, f := range fa {
sum += (f - m) * (f - m)
}
return math.Sqrt(sum / float64(len(fa)))
}
func experiment(label string, r rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
fmt.Println(label, " : x y")
fmt.Printf("Mean : %7.4f, %7.4f\n", mean(rxs), mean(rys))
fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
fmt.Println()
}
func main() {
experiment("Rule 1", func(_, _ float64) float64 {
return 0.0
})
experiment("Rule 2", func(_, dz float64) float64 {
return -dz
})
experiment("Rule 3", func(z, dz float64) float64 {
return -(z + dz)
})
experiment("Rule 4", func(z, dz float64) float64 {
return z + dz
})
}
|
Rewrite the snippet below in Go so it works the same as the original Java code. | import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] dxs = {
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
}
| package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
}
var dys = []float64{
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
}
func funnel(fa []float64, r rule) []float64 {
x := 0.0
result := make([]float64, len(fa))
for i, f := range fa {
result[i] = x + f
x = r(x, f)
}
return result
}
func mean(fa []float64) float64 {
sum := 0.0
for _, f := range fa {
sum += f
}
return sum / float64(len(fa))
}
func stdDev(fa []float64) float64 {
m := mean(fa)
sum := 0.0
for _, f := range fa {
sum += (f - m) * (f - m)
}
return math.Sqrt(sum / float64(len(fa)))
}
func experiment(label string, r rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
fmt.Println(label, " : x y")
fmt.Printf("Mean : %7.4f, %7.4f\n", mean(rxs), mean(rys))
fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
fmt.Println()
}
func main() {
experiment("Rule 1", func(_, _ float64) float64 {
return 0.0
})
experiment("Rule 2", func(_, dz float64) float64 {
return -dz
})
experiment("Rule 3", func(z, dz float64) float64 {
return -(z + dz)
})
experiment("Rule 4", func(z, dz float64) float64 {
return z + dz
})
}
|
Keep all operations the same but rewrite the snippet in Go. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class FixCodeTags
{
public static void main(String[] args)
{
String sourcefile=args[0];
String convertedfile=args[1];
convert(sourcefile,convertedfile);
}
static String[] languages = {"abap", "actionscript", "actionscript3",
"ada", "apache", "applescript", "apt_sources", "asm", "asp",
"autoit", "avisynth", "bar", "bash", "basic4gl", "bf",
"blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg",
"cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css",
"d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email",
"foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml",
"gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict",
"idl", "ini", "inno", "intercal", "io", "java", "java5",
"javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
"lolcode", "lotusformulas", "lotusscript", "lscript", "lua",
"m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml",
"mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas",
"oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief",
"pic16", "pixelbender", "plsql", "povray", "powershell",
"progress", "prolog", "providex", "python", "qbasic", "rails",
"reg", "robots", "ruby", "sas", "scala", "scheme", "scilab",
"sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet",
"verilog", "vhdl", "vim", "visualfoxpro", "visualprolog",
"whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"};
static void convert(String sourcefile,String convertedfile)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(sourcefile));
StringBuffer sb=new StringBuffer("");
String line;
while((line=br.readLine())!=null)
{
for(int i=0;i<languages.length;i++)
{
String lang=languages[i];
line=line.replaceAll("<"+lang+">", "<lang "+lang+">");
line=line.replaceAll("</"+lang+">", "</"+"lang>");
line=line.replaceAll("<code "+lang+">", "<lang "+lang+">");
line=line.replaceAll("</code>", "</"+"lang>");
}
sb.append(line);
}
br.close();
FileWriter fw=new FileWriter(new File(convertedfile));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
| package main
import "fmt"
import "io/ioutil"
import "log"
import "os"
import "regexp"
import "strings"
func main() {
err := fix()
if err != nil {
log.Fatalln(err)
}
}
func fix() (err error) {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
out, err := Lang(string(buf))
if err != nil {
return err
}
fmt.Println(out)
return nil
}
func Lang(in string) (out string, err error) {
reg := regexp.MustCompile("<[^>]+>")
out = reg.ReplaceAllStringFunc(in, repl)
return out, nil
}
func repl(in string) (out string) {
if in == "</code>" {
return "</"+"lang>"
}
mid := in[1 : len(in)-1]
var langs = []string{
"abap", "actionscript", "actionscript3", "ada", "apache", "applescript",
"apt_sources", "asm", "asp", "autoit", "avisynth", "bash", "basic4gl",
"bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm",
"cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi",
"diff", "_div", "dos", "dot", "eiffel", "email", "fortran", "freebasic",
"genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell",
"hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java",
"java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
"lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k",
"make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis",
"objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal",
"per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql",
"povray", "powershell", "progress", "prolog", "providex", "python",
"qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme",
"scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog",
"vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch",
"xml", "xorg_conf", "xpp", "z80",
}
for _, lang := range langs {
if mid == lang {
return fmt.Sprintf("<lang %s>", lang)
}
if strings.HasPrefix(mid, "/") {
if mid[len("/"):] == lang {
return "</"+"lang>"
}
}
if strings.HasPrefix(mid, "code ") {
if mid[len("code "):] == lang {
return fmt.Sprintf("<lang %s>", lang)
}
}
}
return in
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
| package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
|
Please provide an equivalent version of this Java code in Go. | import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
| package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
|
Rewrite the snippet below in Go so it works the same as the original Java code. | import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
| package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
|
Convert this Java snippet to Go and keep its semantics consistent. | import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class CopysJ {
public static void main(String[] args) {
String ddname_IN = "copys.in.txt";
String ddname_OUT = "copys.out.txt";
if (args.length >= 1) { ddname_IN = args[0].length() > 0 ? args[0] : ddname_IN; }
if (args.length >= 2) { ddname_OUT = args[1].length() > 0 ? args[1] : ddname_OUT; }
File dd_IN = new File(ddname_IN);
File dd_OUT = new File(ddname_OUT);
try (
Scanner scanner_IN = new Scanner(dd_IN);
BufferedWriter writer_OUT = new BufferedWriter(new FileWriter(dd_OUT))
) {
String a;
String b;
String c;
String d;
String c1;
String x = "XXXXX";
String data_IN;
String data_OUT;
int ib;
while (scanner_IN.hasNextLine()) {
data_IN = scanner_IN.nextLine();
ib = 0;
a = data_IN.substring(ib, ib += 5);
b = data_IN.substring(ib, ib += 5);
c = data_IN.substring(ib, ib += 4);
c1=Integer.toHexString(new Byte((c.getBytes())[0]).intValue());
if (c1.length()<2) { c1="0" + c1; }
data_OUT = a + c1 + x;
writer_OUT.write(data_OUT);
writer_OUT.newLine();
System.out.println(data_IN);
System.out.println(data_OUT);
System.out.println();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return;
}
}
| package main
import (
"encoding/json"
"log"
"os"
"bytes"
"errors"
"strings"
)
type s1 struct {
A string
B string
C int
D string
}
type s2 struct {
A string
C intString
X string
}
type intString string
func (i *intString) UnmarshalJSON(b []byte) error {
if len(b) == 0 || bytes.IndexByte([]byte("0123456789-"), b[0]) < 0 {
return errors.New("Unmarshal intString expected JSON number")
}
*i = intString(b)
return nil
}
func NewS2() *s2 {
return &s2{X: "XXXXX"}
}
func main() {
o1, err := os.Create("o1.json")
if err != nil {
log.Fatal(err)
}
e := json.NewEncoder(o1)
for i := 1; i <= 5; i++ {
err := e.Encode(s1{
strings.Repeat("A", i),
strings.Repeat("B", i),
i,
strings.Repeat("D", i),
})
if err != nil {
log.Fatal(err)
}
}
o1.Close()
in, err := os.Open("o1.json")
if err != nil {
log.Fatal(err)
}
out, err := os.Create("out.json")
if err != nil {
log.Fatal(err)
}
d := json.NewDecoder(in)
e = json.NewEncoder(out)
for d.More() {
s := NewS2()
if err = d.Decode(s); err != nil {
log.Fatal(err)
}
if err = e.Encode(s); err != nil {
log.Fatal(err)
}
}
}
|
Translate this program into Go but keep the logic exactly as in Java. | import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws Exception {
print("Java Identifier start: ", 0, 0x10FFFF, 72,
Character::isJavaIdentifierStart, "%c");
print("Java Identifier part: ", 0, 0x10FFFF, 25,
Character::isJavaIdentifierPart, "[%d]");
print("Identifier ignorable: ", 0, 0x10FFFF, 25,
Character::isIdentifierIgnorable, "[%d]");
print("Unicode Identifier start: ", 0, 0x10FFFF, 72,
Character::isUnicodeIdentifierStart, "%c");
print("Unicode Identifier part : ", 0, 0x10FFFF, 25,
Character::isUnicodeIdentifierPart, "[%d]");
}
static void print(String msg, int start, int end, int limit,
IntPredicate p, String fmt) {
System.out.print(msg);
IntStream.rangeClosed(start, end)
.filter(p)
.limit(limit)
.forEach(cp -> System.out.printf(fmt, cp));
System.out.println("...");
}
}
| package main
import (
"fmt"
"go/ast"
"go/parser"
"strings"
"unicode"
)
func isValidIdentifier(identifier string) bool {
node, err := parser.ParseExpr(identifier)
if err != nil {
return false
}
ident, ok := node.(*ast.Ident)
return ok && ident.Name == identifier
}
type runeRanges struct {
ranges []string
hasStart bool
start rune
end rune
}
func (r *runeRanges) add(cp rune) {
if !r.hasStart {
r.hasStart = true
r.start = cp
r.end = cp
return
}
if cp == r.end+1 {
r.end = cp
return
}
r.writeTo(&r.ranges)
r.start = cp
r.end = cp
}
func (r *runeRanges) writeTo(ranges *[]string) {
if r.hasStart {
if r.start == r.end {
*ranges = append(*ranges, fmt.Sprintf("%U", r.end))
} else {
*ranges = append(*ranges, fmt.Sprintf("%U-%U", r.start, r.end))
}
}
}
func (r *runeRanges) String() string {
ranges := r.ranges
r.writeTo(&ranges)
return strings.Join(ranges, ", ")
}
func main() {
var validFirst runeRanges
var validFollow runeRanges
var validOnlyFollow runeRanges
for r := rune(0); r <= unicode.MaxRune; r++ {
first := isValidIdentifier(string([]rune{r}))
follow := isValidIdentifier(string([]rune{'_', r}))
if first {
validFirst.add(r)
}
if follow {
validFollow.add(r)
}
if follow && !first {
validOnlyFollow.add(r)
}
}
_, _ = fmt.Println("Valid first:", validFirst.String())
_, _ = fmt.Println("Valid follow:", validFollow.String())
_, _ = fmt.Println("Only follow:", validOnlyFollow.String())
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | (...)
int feedForward(double[] inputs) {
assert inputs.length == weights.length : "weights and input length mismatch";
double sum = 0;
for (int i = 0; i < weights.length; i++) {
sum += inputs[i] * weights[i];
}
return activate(sum);
}
(...)
| func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
|
Convert the following code from Java to Go, ensuring the logic remains intact. | (...)
int feedForward(double[] inputs) {
assert inputs.length == weights.length : "weights and input length mismatch";
double sum = 0;
for (int i = 0; i < weights.length; i++) {
sum += inputs[i] * weights[i];
}
return activate(sum);
}
(...)
| func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
|
Translate the given Java code snippet into Go without altering its behavior. | module test
{
@Inject Console console;
void run()
{
Char ch = 'x';
console.print( $"ch={ch.quoted()}");
String greeting = "Hello";
console.print( $"greeting={greeting.quoted()}");
String lines = \|first line
|second line\
| continued
;
console.print($|lines=
|{lines}
);
String name = "Bob";
String msg = $|{greeting} {name},
|Have a nice day!
|{ch}{ch}{ch}
;
console.print($|msg=
|{msg}
);
}
}
| package main
import (
"fmt"
"os"
"regexp"
"strconv"
)
var (
rl1 = 'a'
rl2 = '\''
)
var (
is1 = "abc"
is2 = "\"ab\tc\""
)
var (
rs1 = `
first"
second'
third"
`
rs2 = `This is one way of including a ` + "`" + ` in a raw string literal.`
rs3 = `\d+`
)
func main() {
fmt.Println(rl1, rl2)
fmt.Println(is1, is2)
fmt.Println(rs1)
fmt.Println(rs2)
re := regexp.MustCompile(rs3)
fmt.Println(re.FindString("abcd1234efgh"))
n := 3
fmt.Printf("\nThere are %d quoting constructs in Go.\n", n)
s := "constructs"
fmt.Println("There are", n, "quoting", s, "in Go.")
mapper := func(placeholder string) string {
switch placeholder {
case "NUMBER":
return strconv.Itoa(n)
case "TYPES":
return s
}
return ""
}
fmt.Println(os.Expand("There are ${NUMBER} quoting ${TYPES} in Go.", mapper))
}
|
Write the same code in Python as shown below in C#. | using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
|
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a)
|
Change the programming language of this snippet from C# to Python without modifying what it does. | using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
| def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0
|
Maintain the same structure and functionality when rewriting this code in Python. | using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
| def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0
|
Rewrite the snippet below in Python so it works the same as the original C# code. | using System;
static class YCombinator<T, TResult>
{
private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);
public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}
static class Program
{
static void Main()
{
var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));
Console.WriteLine(fac(10));
Console.WriteLine(fib(10));
}
}
| >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
Convert this C# snippet to Python and keep its semantics consistent. | using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
| def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
|
Change the following C# code into Python without altering its purpose. | using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
| def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
|
Write a version of this C# function in Python with identical behavior. | using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
| for i in range(1, 11):
if i % 5 == 0:
print(i)
continue
print(i, end=', ')
|
Write the same code in Python as shown below in C#. | using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
| def genfizzbuzz(factorwords, numbers):
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
|
Transform the following C# implementation into Python, maintaining the same output and logic. | using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Maintain the same structure and functionality when rewriting this code in Python. | namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
| def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
answer = '0'*(len(_sep)-1) + answer
else:
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
return answer
def tovlq(n):
return tobits(n, _group=7, _sep='1_', _pad=True)
def toint(vlq):
return int(''.join(vlq.split('_1')), 2)
def vlqsend(vlq):
for i, byte in enumerate(vlq.split('_')[::-1]):
print('Sent byte {0:3}: {1:
|
Change the programming language of this snippet from C# to Python without modifying what it does. | using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
| s = "alphaBETA"
print s.upper()
print s.lower()
print s.swapcase()
print "fOo bAR".capitalize()
print "fOo bAR".title()
import string
print string.capwords("fOo bAR")
|
Preserve the algorithm and functionality while converting the code from C# to Python. | using System.Text;
using System.Security.Cryptography;
byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
| >>> import hashlib
>>>
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>>
|
Transform the following C# implementation into Python, maintaining the same output and logic. | class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
| import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
|
Produce a functionally identical Python code for the snippet given in C#. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
}
| from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v: mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
if sleepsort(x) == sorted(x):
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)
|
Convert this C# block to Python, preserving its control flow and logic. | using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
}
| from random import randint
def do_scan(mat):
for row in mat:
for item in row:
print item,
if item == 20:
print
return
print
print
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
|
Please provide an equivalent version of this C# code in Python. | int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
| items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
|
Write a version of this C# function in Python with identical behavior. | int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
| items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
|
Keep all operations the same but rewrite the snippet in Python. | using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
| def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
|
Convert this C# snippet to Python and keep its semantics consistent. |
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek();
top = stack.Pop();
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek();
top = stack.Pop();
| from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
|
Convert this C# block to Python, preserving its control flow and logic. | using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
| from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
|
Translate the given C# code snippet into Python without altering its behavior. | using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
| from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
|
Translate the given C# code snippet into Python without altering its behavior. | if (condition)
{
}
if (condition)
{
}
else if (condition2)
{
}
else
{
}
| if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
|
Produce a language-to-language conversion: from C# to Python, same semantics. | using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
| strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
|
Produce a language-to-language conversion: from C# to Python, same semantics. | using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
| strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
|
Write the same code in Python as shown below in C#. | using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
}
| txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
|
Ensure the translated Python code behaves exactly like the original C# snippet. | using System;
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move)
old[i-j] = old[i];
else
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
|
from math import log
def getDigit(num, base, digit_num):
return (num // base ** digit_num) % base
def makeBlanks(size):
return [ [] for i in range(size) ]
def split(a_list, base, digit_num):
buckets = makeBlanks(base)
for num in a_list:
buckets[getDigit(num, base, digit_num)].append(num)
return buckets
def merge(a_list):
new_list = []
for sublist in a_list:
new_list.extend(sublist)
return new_list
def maxAbs(a_list):
return max(abs(num) for num in a_list)
def split_by_sign(a_list):
buckets = [[], []]
for num in a_list:
if num < 0:
buckets[0].append(num)
else:
buckets[1].append(num)
return buckets
def radixSort(a_list, base):
passes = int(round(log(maxAbs(a_list), base)) + 1)
new_list = list(a_list)
for digit_num in range(passes):
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list))
|
Change the programming language of this snippet from C# to Python without modifying what it does. | using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Transform the following C# implementation into Python, maintaining the same output and logic. | class SelectionSort<T> where T : IComparable {
public T[] Sort(T[] list) {
int k;
T temp;
for (int i = 0; i < list.Length; i++) {
k = i;
for (int j=i + 1; j < list.Length; j++) {
if (list[j].CompareTo(list[k]) < 0) {
k = j;
}
}
temp = list[i];
list[i] = list[k];
list[k] = temp;
}
return list;
}
}
| def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
|
Keep all operations the same but rewrite the snippet in Python. | int[] intArray = { 1, 2, 3, 4, 5 };
int[] squares1 = intArray.Select(x => x * x).ToArray();
int[] squares2 = (from x in intArray
select x * x).ToArray();
foreach (var i in intArray)
Console.WriteLine(i * i);
| def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
|
Transform the following C# implementation into Python, maintaining the same output and logic. | public sealed class Singleton1
{
private static Singleton1 instance;
private static readonly object lockObj = new object();
public static Singleton1 Instance {
get {
lock(lockObj) {
if (instance == null) {
instance = new Singleton1();
}
}
return instance;
}
}
}
| >>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>>
|
Can you help me rewrite this code in Python instead of C#, keeping it the same logically? | using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl++;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static float NextDown(float d) {
if (d == 0.0) return -float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl--;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static Tuple<float, float> SafeAdd(float a, float b) {
return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
}
static void Main(string[] args) {
float a = 1.20f;
float b = 0.03f;
Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
}
}
}
| >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
|
Keep all operations the same but rewrite the snippet in Python. | for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}
| for i in xrange(10, -1, -1):
print i
|
Rewrite this program in Python while keeping its functionality equivalent to the C# version. | System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
| with open(filename, 'w') as f:
f.write(data)
|
Transform the following C# implementation into Python, maintaining the same output and logic. | using System;
class Program {
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
| for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.