Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the following Go code into Java without altering its purpose.
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah"...
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan...
Translate the given Go code snippet into Java without altering its behavior.
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < l...
import java.util.Arrays; public class RamanujanPrimes { public static void main(String[] args) { long start = System.nanoTime(); System.out.println("First 100 Ramanujan primes:"); PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000)); for (int i = 1; i <= 100; ++i) { ...
Maintain the same structure and functionality when rewriting this code in Java.
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < l...
import java.util.Arrays; public class RamanujanPrimes { public static void main(String[] args) { long start = System.nanoTime(); System.out.println("First 100 Ramanujan primes:"); PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000)); for (int i = 1; i <= 100; ++i) { ...
Preserve the algorithm and functionality while converting the code from Go to Java.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; ...
Can you help me rewrite this code in Java instead of Go, keeping it the same logically?
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; ...
Convert the following code from Go to Java, ensuring the logic remains intact.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; ...
Convert this Go block to Java, preserving its control flow and logic.
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) i...
import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SDF { public static HashMap<Character, Integer> countElementOcurrences(char[] array) { HashMap<C...
Can you help me rewrite this code in Java instead of Go, keeping it the same logically?
package main import ( "bytes" "fmt" "io/ioutil" "log" ) func levenshtein(s, t string) int { d := make([][]int, len(s)+1) for i := range d { d[i] = make([]int, len(t)+1) } for i := range d { d[i][0] = i } for j := range d[0] { d[0][j] = j } for j ...
import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Scanner; public class textCompletionConcept { public static int correct = 0; public static ArrayList<String> listed = new ArrayList<>(); public static void main(String[]args) ...
Change the following Go code into Java without altering its purpose.
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan...
Generate a Java translation of this Go snippet without changing its computational steps.
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan...
Change the following Go code into Java without altering its purpose.
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan...
Translate this program into Java but keep the logic exactly as in Go.
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan...
Translate this program into Java but keep the logic exactly as in Go.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } ...
Convert this Go snippet to Java and keep its semantics consistent.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } ...
Generate an equivalent Java version of this Go code.
package main import ( "fmt" "math" "rcu" ) var limit = int(math.Log(1e6) * 1e6 * 1.2) var primes = rcu.Primes(limit) var prevCats = make(map[int]int) func cat(p int) int { if v, ok := prevCats[p]; ok { return v } pf := rcu.PrimeFactors(p + 1) all := true for _, f := range pf...
import java.util.*; public class ErdosSelfridge { private int[] primes; private int[] category; public static void main(String[] args) { ErdosSelfridge es = new ErdosSelfridge(1000000); System.out.println("First 200 primes:"); for (var e : es.getPrimesByCategory(200).entrySet()) {...
Translate this program into Java but keep the logic exactly as in Go.
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.C...
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; ...
Please provide an equivalent version of this Go code in Java.
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.C...
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; ...
Convert this Go block to Java, preserving its control flow and logic.
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x ui...
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numb...
Write a version of this Go function in Java with identical behavior.
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x ui...
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numb...
Port the provided Go code into Java while preserving the original functionality.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSynthe...
Write the same code in Java as shown below in Go.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSynthe...
Generate a Java translation of this Go snippet without changing its computational steps.
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords))...
import java.io.*; import java.util.*; public class OddWords { public static void main(String[] args) { try { Set<String> dictionary = new TreeSet<>(); final int minLength = 5; String fileName = "unixdict.txt"; if (args.length != 0) fileName = ...
Translate the given Go code snippet into Java without altering its behavior.
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec)....
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Hee...
Produce a language-to-language conversion: from Go to Java, same semantics.
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec)....
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Hee...
Rewrite this program in Java while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "strings" ) type dict map[string]bool func newDict(words ...string) dict { d := dict{} for _, w := range words { d[w] = true } return d } func (d dict) wordBreak(s string) (broken []string, ok bool) { if s == "" { return nil, true } typ...
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList...
Translate this program into Java but keep the logic exactly as in Go.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) {...
Port the provided Go code into Java while preserving the original functionality.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) {...
Please provide an equivalent version of this Go code in Java.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { ...
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadde...
Translate this program into Java but keep the logic exactly as in Go.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { ...
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadde...
Write a version of this Go function in Java with identical behavior.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] ...
import java.util.HashMap; import java.util.Map; public class PrimeGaps { private Map<Integer, Integer> gapStarts = new HashMap<>(); private int lastPrime; private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000); public static void main(String[] args) { final int limit = 100000...
Change the following Go code into Java without altering its purpose.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] ...
import java.util.HashMap; import java.util.Map; public class PrimeGaps { private Map<Integer, Integer> gapStarts = new HashMap<>(); private int lastPrime; private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000); public static void main(String[] args) { final int limit = 100000...
Translate the given Go code snippet into Java without altering its behavior.
package main import ( "fmt" "sort" ) type matrix [][]int func dList(n, start int) (r matrix) { start-- a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] sort.Ints(a[1:]) first := a[1] var recurse func(last int) recurse = func(las...
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LatinSquaresInReducedForm { public static void main(String[] args) { System.out.printf("Reduced latin squares of order 4:%n"); for ( LatinSquare square : getReducedLatinSquares(4) ...
Write the same code in Java as shown below in Go.
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[st...
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ...
Convert this Go block to Java, preserving its control flow and logic.
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[st...
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ...
Convert the following code from Go to Java, ensuring the logic remains intact.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ",...
Ensure the translated Java code behaves exactly like the original Go snippet.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ",...
Rewrite this program in Java while keeping its functionality equivalent to the Go version.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ",...
Port the provided Go code into Java while preserving the original functionality.
package main import ( "fmt" "math" "math/rand" "time" ) type xy struct { x, y float64 } const n = 1000 const scale = 100. func d(p1, p2 xy) float64 { return math.Hypot(p2.x-p1.x, p2.y-p1.y) } func main() { rand.Seed(time.Now().Unix()) points := make([]xy, n) for i := range point...
import java.util.*; public class ClosestPair { public static class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } } public sta...
Write a version of this Go function in Java with identical behavior.
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = tru...
public class Animal{ }
Write the same algorithm in Java as shown in this Go implementation.
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
Map<String, Int> map = new HashMap(); map["foo"] = 5; map["bar"] = 10; map["baz"] = 15; map["foo"] = 6;
Convert this Go snippet to Java and keep its semantics consistent.
package main import ( "fmt" "math/big" "rcu" ) func main() { const LIMIT = 11000 primes := rcu.Primes(LIMIT) facts := make([]*big.Int, LIMIT) facts[0] = big.NewInt(1) for i := int64(1); i < LIMIT; i++ { facts[i] = new(big.Int) facts[i].Mul(facts[i-1], big.NewInt(i)) ...
import java.math.BigInteger; import java.util.*; public class WilsonPrimes { public static void main(String[] args) { final int limit = 11000; BigInteger[] f = new BigInteger[limit]; f[0] = BigInteger.ONE; BigInteger factorial = BigInteger.ONE; for (int i = 1; i < limit; ++i...
Write the same code in Java as shown below in Go.
package main import ( "github.com/fogleman/gg" "math" ) const tau = 2 * math.Pi func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri...
import java.awt.*; import javax.swing.*; public class ColorWheel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ColorWheelFrame frame = new ColorWheelFrame(); frame.setVisible(true); } ...
Ensure the translated Java code behaves exactly like the original Go snippet.
package main import ( "image" "image/color" "image/gif" "log" "math" "os" ) func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func hsb2rgb(hue, sat, bri flo...
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { D...
Port the provided Go code into Java while preserving the original functionality.
package main import ( "fmt" "rcu" "strconv" ) func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false } func main() { for b := 2; b <= 36; b++ { if rcu.IsPrime(b) { continue } count...
public class RhondaNumbers { public static void main(String[] args) { final int limit = 15; for (int base = 2; base <= 36; ++base) { if (isPrime(base)) continue; System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base); int numbers[]...
Write the same algorithm in Java as shown in this Go implementation.
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = ...
class Point { protected int x, y; public Point() { this(0); } public Point(int x) { this(x, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point p) { this(p.x, p.y); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { t...
Maintain the same structure and functionality when rewriting this code in Java.
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] i...
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)...
Keep all operations the same but rewrite the snippet in Java.
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 run...
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 mainClas...
Translate this program into Java but keep the logic exactly as in Go.
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 *= 10...
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) Ma...
Maintain the same structure and functionality when rewriting this code in Java.
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 *= 10...
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) Ma...
Rewrite the snippet below in Java so it works the same as the original Go code.
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...
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(); Sys...
Generate an equivalent Java version of this Go code.
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 ...
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 vo...
Port the following code from Go to Java with equivalent syntax and logic.
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$eac...
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 ...
Translate this program into Java but keep the logic exactly as in Go.
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:s...
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{ ...
Ensure the translated Java code behaves exactly like the original Go snippet.
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:s...
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{ ...
Convert this Go block to Java, preserving its control flow and logic.
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 { ...
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);...
Generate a Java translation of this Go snippet without changing its computational steps.
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 { ...
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);...
Convert this Go snippet to Java and keep its semantics consistent.
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...
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,...
Port the following code from Go to Java with equivalent syntax and logic.
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...
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,...
Translate this program into Java but keep the logic exactly as in Go.
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("878787...
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.sub...
Please provide an equivalent version of this Go code in Java.
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 != ro...
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, fi...
Change the following Go code into Java without altering its purpose.
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 != ro...
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, fi...
Ensure the translated Java code behaves exactly like the original Go snippet.
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 != ro...
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, fi...
Generate an equivalent Java version of this Go code.
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 commatiz...
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...
Generate an equivalent Java version of this Go code.
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 } } re...
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 = ...
Write the same code in Java as shown below in Go.
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(...
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; } ...
Maintain the same structure and functionality when rewriting this code in Java.
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 := ...
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 = ListMethod...
Write the same code in Java as shown below in Go.
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()) }
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(na...
Write the same code in Java as shown below in Go.
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 parame...
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; ...
Rewrite the snippet below in Java so it works the same as the original Go code.
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
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
Write the same code in Java as shown below in Go.
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) ...
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); } ...
Produce a functionally identical Java code for the snippet given in Go.
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 ...
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...
Write a version of this Go function in Java with identical behavior.
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 ...
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...
Convert this Go block to Java, preserving its control flow and logic.
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 := ...
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++ ) { ...
Please provide an equivalent version of this Go code in Java.
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 := ...
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++ ) { ...
Translate the given Go code snippet into Java without altering its behavior.
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 wa...
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...
Write the same code in Java as shown below in Go.
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 wa...
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...
Rewrite the snippet below in Java so it works the same as the original Go code.
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() ...
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[] ...
Preserve the algorithm and functionality while converting the code from Go to Java.
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" ...
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)); ...
Write the same code in Java as shown below in Go.
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" ...
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)); ...
Generate a Java translation of this Go snippet without changing its computational steps.
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 :=...
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...
Convert the following code from Go to Java, ensuring the logic remains intact.
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 :=...
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...
Write a version of this Go function in Java with identical behavior.
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}}, ...
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 FIL...
Produce a functionally identical Java code for the snippet given in Go.
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}}, ...
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 FIL...
Preserve the algorithm and functionality while converting the code from Go to Java.
package main import ( "fmt" "math" "bytes" "encoding/binary" ) type testCase struct { hashCode string string } var testCases = []testCase{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b69...
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,...
Port the provided Go code into Java while preserving the original functionality.
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, da...
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 ...
Please provide an equivalent version of this Go code in Java.
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...
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>(); Strin...
Rewrite this program in Java while keeping its functionality equivalent to the Go version.
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) ...
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); ...
Port the provided Go code into Java while preserving the original functionality.
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}}, {{...
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++ ) { ...
Transform the following Go implementation into Java, maintaining the same output and logic.
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.RG...
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 Scann...
Port the following code from Go to Java with equivalent syntax and logic.
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} ...
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<Intege...
Port the provided Go code into Java while preserving the original functionality.
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()}}} } ...
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 valu...
Please provide an equivalent version of this Go code in Java.
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 p...
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}; ...
Translate the given Go code snippet into Java without altering its behavior.
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 er...
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.Fo...
Write a version of this Go function in Java with identical behavior.
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 er...
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.Fo...
Ensure the translated Java code behaves exactly like the original Go snippet.
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 ...
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"); ...
Produce a functionally identical Java code for the snippet given in Go.
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++ { ...
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...
Transform the following Go implementation into Java, maintaining the same output and logic.
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 (...
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 ArrayLi...
Can you help me rewrite this code in Java instead of Go, keeping it the same logically?
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...
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.apa...
Produce a functionally identical Java code for the snippet given in Go.
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 := ...
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; f...
Keep all operations the same but rewrite the snippet in Java.
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 := ...
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; f...