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", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
}
h := map[string][]int{}
for i, r := range tableA {
h[r.key] = append(h[r.key], i)
}
for _, x := range tableB {
for _, a := range h[x.key] {
fmt.Println(tableA[a], x)
}
}
}
| import java.util.*;
public class HashJoin {
public static void main(String[] args) {
String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
{"18", "Popeye"}, {"28", "Alan"}};
String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
{"Bob", "foo"}};
hashJoin(table1, 1, table2, 0).stream()
.forEach(r -> System.out.println(Arrays.deepToString(r)));
}
static List<String[][]> hashJoin(String[][] records1, int idx1,
String[][] records2, int idx2) {
List<String[][]> result = new ArrayList<>();
Map<String, List<String[]>> map = new HashMap<>();
for (String[] record : records1) {
List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
v.add(record);
map.put(record[idx1], v);
}
for (String[] record : records2) {
List<String[]> lst = map.get(record[idx2]);
if (lst != null) {
lst.stream().forEach(r -> {
result.add(new String[][]{r, record});
});
}
}
return result;
}
}
|
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 < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
| import java.util.Arrays;
public class RamanujanPrimes {
public static void main(String[] args) {
long start = System.nanoTime();
System.out.println("First 100 Ramanujan primes:");
PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));
for (int i = 1; i <= 100; ++i) {
int p = ramanujanPrime(pc, i);
System.out.printf("%,5d%c", p, i % 10 == 0 ? '\n' : ' ');
}
System.out.println();
for (int i = 1000; i <= 100000; i *= 10) {
int p = ramanujanPrime(pc, i);
System.out.printf("The %,dth Ramanujan prime is %,d.\n", i, p);
}
long end = System.nanoTime();
System.out.printf("\nElapsed time: %.1f milliseconds\n", (end - start) / 1e6);
}
private static int ramanujanMax(int n) {
return (int)Math.ceil(4 * n * Math.log(4 * n));
}
private static int ramanujanPrime(PrimeCounter pc, int n) {
for (int i = ramanujanMax(n); i >= 0; --i) {
if (pc.primeCount(i) - pc.primeCount(i / 2) < n)
return i + 1;
}
return 0;
}
private static class PrimeCounter {
private PrimeCounter(int limit) {
count = new int[limit];
Arrays.fill(count, 1);
if (limit > 0)
count[0] = 0;
if (limit > 1)
count[1] = 0;
for (int i = 4; i < limit; i += 2)
count[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count[p] != 0) {
for (int q = sq; q < limit; q += p << 1)
count[q] = 0;
}
sq += (p + 1) << 2;
}
Arrays.parallelPrefix(count, (x, y) -> x + y);
}
private int primeCount(int n) {
return n < 1 ? 0 : count[n];
}
private int[] count;
}
}
|
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 < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
| import java.util.Arrays;
public class RamanujanPrimes {
public static void main(String[] args) {
long start = System.nanoTime();
System.out.println("First 100 Ramanujan primes:");
PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));
for (int i = 1; i <= 100; ++i) {
int p = ramanujanPrime(pc, i);
System.out.printf("%,5d%c", p, i % 10 == 0 ? '\n' : ' ');
}
System.out.println();
for (int i = 1000; i <= 100000; i *= 10) {
int p = ramanujanPrime(pc, i);
System.out.printf("The %,dth Ramanujan prime is %,d.\n", i, p);
}
long end = System.nanoTime();
System.out.printf("\nElapsed time: %.1f milliseconds\n", (end - start) / 1e6);
}
private static int ramanujanMax(int n) {
return (int)Math.ceil(4 * n * Math.log(4 * n));
}
private static int ramanujanPrime(PrimeCounter pc, int n) {
for (int i = ramanujanMax(n); i >= 0; --i) {
if (pc.primeCount(i) - pc.primeCount(i / 2) < n)
return i + 1;
}
return 0;
}
private static class PrimeCounter {
private PrimeCounter(int limit) {
count = new int[limit];
Arrays.fill(count, 1);
if (limit > 0)
count[0] = 0;
if (limit > 1)
count[1] = 0;
for (int i = 4; i < limit; i += 2)
count[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count[p] != 0) {
for (int q = sq; q < limit; q += p << 1)
count[q] = 0;
}
sq += (p + 1) << 2;
}
Arrays.parallelPrefix(count, (x, y) -> x + y);
}
private int primeCount(int n) {
return n < 1 ? 0 : count[n];
}
private int[] count;
}
}
|
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, cy-2*h) }
func lineS() { lineTo(cx, cy+2*h) }
func lineE() { lineTo(cx+2*h, cy) }
func lineW() { lineTo(cx-2*h, cy) }
func lineNW() { lineTo(cx-h, cy-h) }
func lineNE() { lineTo(cx+h, cy-h) }
func lineSE() { lineTo(cx+h, cy+h) }
func lineSW() { lineTo(cx-h, cy+h) }
func sierN(level int) {
if level == 1 {
lineNE()
lineN()
lineNW()
} else {
sierN(level - 1)
lineNE()
sierE(level - 1)
lineN()
sierW(level - 1)
lineNW()
sierN(level - 1)
}
}
func sierE(level int) {
if level == 1 {
lineSE()
lineE()
lineNE()
} else {
sierE(level - 1)
lineSE()
sierS(level - 1)
lineE()
sierN(level - 1)
lineNE()
sierE(level - 1)
}
}
func sierS(level int) {
if level == 1 {
lineSW()
lineS()
lineSE()
} else {
sierS(level - 1)
lineSW()
sierW(level - 1)
lineS()
sierE(level - 1)
lineSE()
sierS(level - 1)
}
}
func sierW(level int) {
if level == 1 {
lineNW()
lineW()
lineSW()
} else {
sierW(level - 1)
lineNW()
sierN(level - 1)
lineW()
sierS(level - 1)
lineSW()
sierW(level - 1)
}
}
func squareCurve(level int) {
sierN(level)
lineNE()
sierE(level)
lineSE()
sierS(level)
lineSW()
sierW(level)
lineNW()
lineNE()
}
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
level := 5
cx, cy = width/2, height
h = cx / math.Pow(2, float64(level+1))
squareCurve(level)
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_curve.png")
}
| import java.io.*;
public class SierpinskiCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
SierpinskiCurve s = new SierpinskiCurve(writer);
s.currentAngle = 45;
s.currentX = 5;
s.currentY = 10;
s.lineLength = 7;
s.begin(545);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
case 'G':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY -= length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F--XF--F--XF";
private static final String PRODUCTION = "XF+G+XF--F--XF+G+X";
private static final int ANGLE = 45;
}
|
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, cy-2*h) }
func lineS() { lineTo(cx, cy+2*h) }
func lineE() { lineTo(cx+2*h, cy) }
func lineW() { lineTo(cx-2*h, cy) }
func lineNW() { lineTo(cx-h, cy-h) }
func lineNE() { lineTo(cx+h, cy-h) }
func lineSE() { lineTo(cx+h, cy+h) }
func lineSW() { lineTo(cx-h, cy+h) }
func sierN(level int) {
if level == 1 {
lineNE()
lineN()
lineNW()
} else {
sierN(level - 1)
lineNE()
sierE(level - 1)
lineN()
sierW(level - 1)
lineNW()
sierN(level - 1)
}
}
func sierE(level int) {
if level == 1 {
lineSE()
lineE()
lineNE()
} else {
sierE(level - 1)
lineSE()
sierS(level - 1)
lineE()
sierN(level - 1)
lineNE()
sierE(level - 1)
}
}
func sierS(level int) {
if level == 1 {
lineSW()
lineS()
lineSE()
} else {
sierS(level - 1)
lineSW()
sierW(level - 1)
lineS()
sierE(level - 1)
lineSE()
sierS(level - 1)
}
}
func sierW(level int) {
if level == 1 {
lineNW()
lineW()
lineSW()
} else {
sierW(level - 1)
lineNW()
sierN(level - 1)
lineW()
sierS(level - 1)
lineSW()
sierW(level - 1)
}
}
func squareCurve(level int) {
sierN(level)
lineNE()
sierE(level)
lineSE()
sierS(level)
lineSW()
sierW(level)
lineNW()
lineNE()
}
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
level := 5
cx, cy = width/2, height
h = cx / math.Pow(2, float64(level+1))
squareCurve(level)
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_curve.png")
}
| import java.io.*;
public class SierpinskiCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
SierpinskiCurve s = new SierpinskiCurve(writer);
s.currentAngle = 45;
s.currentX = 5;
s.currentY = 10;
s.lineLength = 7;
s.begin(545);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
case 'G':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY -= length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F--XF--F--XF";
private static final String PRODUCTION = "XF+G+XF--F--XF+G+X";
private static final int ANGLE = 45;
}
|
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, cy-2*h) }
func lineS() { lineTo(cx, cy+2*h) }
func lineE() { lineTo(cx+2*h, cy) }
func lineW() { lineTo(cx-2*h, cy) }
func lineNW() { lineTo(cx-h, cy-h) }
func lineNE() { lineTo(cx+h, cy-h) }
func lineSE() { lineTo(cx+h, cy+h) }
func lineSW() { lineTo(cx-h, cy+h) }
func sierN(level int) {
if level == 1 {
lineNE()
lineN()
lineNW()
} else {
sierN(level - 1)
lineNE()
sierE(level - 1)
lineN()
sierW(level - 1)
lineNW()
sierN(level - 1)
}
}
func sierE(level int) {
if level == 1 {
lineSE()
lineE()
lineNE()
} else {
sierE(level - 1)
lineSE()
sierS(level - 1)
lineE()
sierN(level - 1)
lineNE()
sierE(level - 1)
}
}
func sierS(level int) {
if level == 1 {
lineSW()
lineS()
lineSE()
} else {
sierS(level - 1)
lineSW()
sierW(level - 1)
lineS()
sierE(level - 1)
lineSE()
sierS(level - 1)
}
}
func sierW(level int) {
if level == 1 {
lineNW()
lineW()
lineSW()
} else {
sierW(level - 1)
lineNW()
sierN(level - 1)
lineW()
sierS(level - 1)
lineSW()
sierW(level - 1)
}
}
func squareCurve(level int) {
sierN(level)
lineNE()
sierE(level)
lineSE()
sierS(level)
lineSW()
sierW(level)
lineNW()
lineNE()
}
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
level := 5
cx, cy = width/2, height
h = cx / math.Pow(2, float64(level+1))
squareCurve(level)
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_curve.png")
}
| import java.io.*;
public class SierpinskiCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
SierpinskiCurve s = new SierpinskiCurve(writer);
s.currentAngle = 45;
s.currentX = 5;
s.currentY = 10;
s.lineLength = 7;
s.begin(545);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
case 'G':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY -= length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F--XF--F--XF";
private static final String PRODUCTION = "XF+G+XF--F--XF+G+X";
private static final int ANGLE = 45;
}
|
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) int {
for i, cf := range cfs {
if cf.c == r {
return i
}
}
return -1
}
func minOf(i, j int) int {
if i < j {
return i
}
return j
}
func mostFreqKHashing(input string, k int) string {
var cfs []cf
for _, r := range input {
ix := indexOfCf(cfs, r)
if ix >= 0 {
cfs[ix].f++
} else {
cfs = append(cfs, cf{r, 1})
}
}
sort.SliceStable(cfs, func(i, j int) bool {
return cfs[i].f > cfs[j].f
})
acc := ""
min := minOf(len(cfs), k)
for _, cf := range cfs[:min] {
acc += fmt.Sprintf("%c%c", cf.c, cf.f)
}
return acc
}
func mostFreqKSimilarity(input1, input2 string) int {
similarity := 0
runes1, runes2 := []rune(input1), []rune(input2)
for i := 0; i < len(runes1); i += 2 {
for j := 0; j < len(runes2); j += 2 {
if runes1[i] == runes2[j] {
freq1, freq2 := runes1[i+1], runes2[j+1]
if freq1 != freq2 {
continue
}
similarity += int(freq1)
}
}
}
return similarity
}
func mostFreqKSDF(input1, input2 string, k, maxDistance int) {
fmt.Println("input1 :", input1)
fmt.Println("input2 :", input2)
s1 := mostFreqKHashing(input1, k)
s2 := mostFreqKHashing(input2, k)
fmt.Printf("mfkh(input1, %d) = ", k)
for i, c := range s1 {
if i%2 == 0 {
fmt.Printf("%c", c)
} else {
fmt.Printf("%d", c)
}
}
fmt.Printf("\nmfkh(input2, %d) = ", k)
for i, c := range s2 {
if i%2 == 0 {
fmt.Printf("%c", c)
} else {
fmt.Printf("%d", c)
}
}
result := maxDistance - mostFreqKSimilarity(s1, s2)
fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result)
}
func main() {
pairs := [][2]string{
{"research", "seeking"},
{"night", "nacht"},
{"my", "a"},
{"research", "research"},
{"aaaaabbbb", "ababababa"},
{"significant", "capabilities"},
}
for _, pair := range pairs {
mostFreqKSDF(pair[0], pair[1], 2, 10)
}
s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"
s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"
mostFreqKSDF(s1, s2, 2, 100)
s1 = "abracadabra12121212121abracadabra12121212121"
s2 = reverseStr(s1)
mostFreqKSDF(s1, s2, 2, 100)
}
| import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SDF {
public static HashMap<Character, Integer> countElementOcurrences(char[] array) {
HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();
for (char element : array) {
Integer count = countMap.get(element);
count = (count == null) ? 1 : count + 1;
countMap.put(element, count);
}
return countMap;
}
private static <K, V extends Comparable<? super V>>
HashMap<K, V> descendingSortByValues(HashMap<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
HashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
public static String mostOcurrencesElement(char[] array, int k) {
HashMap<Character, Integer> countMap = countElementOcurrences(array);
System.out.println(countMap);
Map<Character, Integer> map = descendingSortByValues(countMap);
System.out.println(map);
int i = 0;
String output = "";
for (Map.Entry<Character, Integer> pairs : map.entrySet()) {
if (i++ >= k)
break;
output += "" + pairs.getKey() + pairs.getValue();
}
return output;
}
public static int getDiff(String str1, String str2, int limit) {
int similarity = 0;
int k = 0;
for (int i = 0; i < str1.length() ; i = k) {
k ++;
if (Character.isLetter(str1.charAt(i))) {
int pos = str2.indexOf(str1.charAt(i));
if (pos >= 0) {
String digitStr1 = "";
while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {
digitStr1 += str1.charAt(k);
k++;
}
int k2 = pos+1;
String digitStr2 = "";
while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {
digitStr2 += str2.charAt(k2);
k2++;
}
similarity += Integer.parseInt(digitStr2)
+ Integer.parseInt(digitStr1);
}
}
}
return Math.abs(limit - similarity);
}
public static int SDFfunc(String str1, String str2, int limit) {
return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);
}
public static void main(String[] args) {
String input1 = "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV";
String input2 = "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG";
System.out.println(SDF.SDFfunc(input1,input2,100));
}
}
|
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 := 1; j <= len(t); j++ {
for i := 1; i <= len(s); i++ {
if s[i-1] == t[j-1] {
d[i][j] = d[i-1][j-1]
} else {
min := d[i-1][j]
if d[i][j-1] < min {
min = d[i][j-1]
}
if d[i-1][j-1] < min {
min = d[i-1][j-1]
}
d[i][j] = min + 1
}
}
}
return d[len(s)][len(t)]
}
func main() {
search := "complition"
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
words := bytes.Fields(b)
var lev [4][]string
for _, word := range words {
s := string(word)
ld := levenshtein(search, s)
if ld < 4 {
lev[ld] = append(lev[ld], s)
}
}
fmt.Printf("Input word: %s\n\n", search)
for i := 1; i < 4; i++ {
length := float64(len(search))
similarity := (length - float64(i)) * 100 / length
fmt.Printf("Words which are %4.1f%% similar:\n", similarity)
fmt.Println(lev[i])
fmt.Println()
}
}
| import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Scanner;
public class textCompletionConcept {
public static int correct = 0;
public static ArrayList<String> listed = new ArrayList<>();
public static void main(String[]args) throws IOException, URISyntaxException {
Scanner input = new Scanner(System.in);
System.out.println("Input word: ");
String errorRode = input.next();
File file = new File(new
File(textCompletionConcept.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath() + File.separator + "words.txt");
Scanner reader = new Scanner(file);
while(reader.hasNext()){
double percent;
String compareToThis = reader.nextLine();
char[] s1 = errorRode.toCharArray();
char[] s2 = compareToThis.toCharArray();
int maxlen = Math.min(s1.length, s2.length);
for (int index = 0; index < maxlen; index++) {
String x = String.valueOf(s1[index]);
String y = String.valueOf(s2[index]);
if (x.equals(y)) {
correct++;
}
}
double length = Math.max(s1.length, s2.length);
percent = correct / length;
percent *= 100;
boolean perfect = false;
if (percent >= 80 && compareToThis.charAt(0) == errorRode.charAt(0)) {
if(String.valueOf(percent).equals("100.00")){
perfect = true;
}
String addtoit = compareToThis + " : " + String.format("%.2f", percent) + "% similar.";
listed.add(addtoit);
}
if(compareToThis.contains(errorRode) && !perfect && errorRode.length() * 2 > compareToThis.length()){
String addtoit = compareToThis + " : 80.00% similar.";
listed.add(addtoit);
}
correct = 0;
}
for(String x : listed){
if(x.contains("100.00% similar.")){
System.out.println(x);
listed.clear();
break;
}
}
for(String x : listed){
System.out.println(x);
}
}
}
|
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
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
| import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
|
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
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
| import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
|
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
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
| import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
|
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
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
| import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
|
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(v.String())
result.SetString(s, 10)
} else {
v := new(big.Int).Set(v)
digit := new(big.Int)
result.SetUint64(0)
for v.BitLen() > 0 {
v.QuoRem(v, ten, digit)
result.Mul(result, ten)
result.Add(result, digit)
}
}
}
return result
}
func reverseUint64(v uint64) uint64 {
var r uint64
for v > 0 {
r *= 10
r += v % 10
v /= 10
}
return r
}
func reverseString(s string) string {
b := make([]byte, len(s))
for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {
b[i] = s[j]
}
return string(b)
}
var known = make(map[string]bool)
func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {
v, r := new(big.Int).SetUint64(n), new(big.Int)
reverseInt(v, r)
seen := make(map[string]bool)
isLychrel = true
isSeed = true
for i := iter; i > 0; i-- {
str := v.String()
if seen[str] {
isLychrel = true
break
}
if ans, ok := known[str]; ok {
isLychrel = ans
isSeed = false
break
}
seen[str] = true
v = v.Add(v, r)
reverseInt(v, r)
if v.Cmp(r) == 0 {
isLychrel = false
isSeed = false
break
}
}
for k := range seen {
known[k] = isLychrel
}
return isLychrel, isSeed
}
func main() {
max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive")
iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter)
var seeds []uint64
var related int
var pals []uint64
for i := uint64(1); i <= *max; i++ {
if l, s := Lychrel(i, *iter); l {
if s {
seeds = append(seeds, i)
} else {
related++
}
if i == reverseUint64(i) {
pals = append(pals, i)
}
}
}
fmt.Println(" Number of Lychrel seeds:", len(seeds))
fmt.Println(" Lychrel seeds:", seeds)
fmt.Println(" Number of related:", related)
fmt.Println("Number of Lychrel palindromes:", len(pals))
fmt.Println(" Lychrel palindromes:", pals)
}
| import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
|
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(v.String())
result.SetString(s, 10)
} else {
v := new(big.Int).Set(v)
digit := new(big.Int)
result.SetUint64(0)
for v.BitLen() > 0 {
v.QuoRem(v, ten, digit)
result.Mul(result, ten)
result.Add(result, digit)
}
}
}
return result
}
func reverseUint64(v uint64) uint64 {
var r uint64
for v > 0 {
r *= 10
r += v % 10
v /= 10
}
return r
}
func reverseString(s string) string {
b := make([]byte, len(s))
for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {
b[i] = s[j]
}
return string(b)
}
var known = make(map[string]bool)
func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {
v, r := new(big.Int).SetUint64(n), new(big.Int)
reverseInt(v, r)
seen := make(map[string]bool)
isLychrel = true
isSeed = true
for i := iter; i > 0; i-- {
str := v.String()
if seen[str] {
isLychrel = true
break
}
if ans, ok := known[str]; ok {
isLychrel = ans
isSeed = false
break
}
seen[str] = true
v = v.Add(v, r)
reverseInt(v, r)
if v.Cmp(r) == 0 {
isLychrel = false
isSeed = false
break
}
}
for k := range seen {
known[k] = isLychrel
}
return isLychrel, isSeed
}
func main() {
max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive")
iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter)
var seeds []uint64
var related int
var pals []uint64
for i := uint64(1); i <= *max; i++ {
if l, s := Lychrel(i, *iter); l {
if s {
seeds = append(seeds, i)
} else {
related++
}
if i == reverseUint64(i) {
pals = append(pals, i)
}
}
}
fmt.Println(" Number of Lychrel seeds:", len(seeds))
fmt.Println(" Lychrel seeds:", seeds)
fmt.Println(" Number of related:", related)
fmt.Println("Number of Lychrel palindromes:", len(pals))
fmt.Println(" Lychrel palindromes:", pals)
}
| import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
|
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 {
if f != 2 && f != 3 {
all = false
break
}
}
if all {
return 1
}
if p > 2 {
len := len(pf)
for i := len - 1; i >= 1; i-- {
if pf[i-1] == pf[i] {
pf = append(pf[:i], pf[i+1:]...)
}
}
}
for c := 2; c <= 11; c++ {
all := true
for _, f := range pf {
if cat(f) >= c {
all = false
break
}
}
if all {
prevCats[p] = c
return c
}
}
return 12
}
func main() {
es := make([][]int, 12)
fmt.Println("First 200 primes:\n")
for _, p := range primes[0:200] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 6; c++ {
if len(es[c-1]) > 0 {
fmt.Println("Category", c, "\b:")
fmt.Println(es[c-1])
fmt.Println()
}
}
fmt.Println("First million primes:\n")
for _, p := range primes[200:1e6] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 12; c++ {
e := es[c-1]
if len(e) > 0 {
format := "Category %-2d: First = %7d Last = %8d Count = %6d\n"
fmt.Printf(format, c, e[0], e[len(e)-1], len(e))
}
}
}
| import java.util.*;
public class ErdosSelfridge {
private int[] primes;
private int[] category;
public static void main(String[] args) {
ErdosSelfridge es = new ErdosSelfridge(1000000);
System.out.println("First 200 primes:");
for (var e : es.getPrimesByCategory(200).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %d:\n", category);
for (int i = 0, n = primes.size(); i != n; ++i)
System.out.printf("%4d%c", primes.get(i), (i + 1) % 15 == 0 ? '\n' : ' ');
System.out.printf("\n\n");
}
System.out.println("First 1,000,000 primes:");
for (var e : es.getPrimesByCategory(1000000).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %2d: first = %7d last = %8d count = %d\n", category,
primes.get(0), primes.get(primes.size() - 1), primes.size());
}
}
private ErdosSelfridge(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);
List<Integer> primeList = new ArrayList<>();
for (int i = 0; i < limit; ++i)
primeList.add(primeGen.nextPrime());
primes = new int[primeList.size()];
for (int i = 0; i < primes.length; ++i)
primes[i] = primeList.get(i);
category = new int[primes.length];
}
private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {
Map<Integer, List<Integer>> result = new TreeMap<>();
for (int i = 0; i < limit; ++i) {
var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());
p.add(primes[i]);
}
return result;
}
private int getCategory(int index) {
if (category[index] != 0)
return category[index];
int maxCategory = 0;
int n = primes[index] + 1;
for (int i = 0; n > 1; ++i) {
int p = primes[i];
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + getCategory(i);
maxCategory = Math.max(maxCategory, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));
maxCategory = Math.max(maxCategory, category);
}
category[index] = maxCategory;
return maxCategory;
}
private int getIndex(int prime) {
return Arrays.binarySearch(primes, prime);
}
}
|
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.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2,
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
operations['+']()
operations['F']()
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
}
| import java.io.*;
public class SierpinskiSquareCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) {
SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);
int size = 635, length = 5;
s.currentAngle = 0;
s.currentX = (size - length)/2;
s.currentY = length;
s.lineLength = length;
s.begin(size);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiSquareCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY += length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F+XF+F+XF";
private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X";
private static final int ANGLE = 90;
}
|
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.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2,
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
operations['+']()
operations['F']()
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
}
| import java.io.*;
public class SierpinskiSquareCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) {
SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);
int size = 635, length = 5;
s.currentAngle = 0;
s.currentX = (size - length)/2;
s.currentY = length;
s.lineLength = length;
s.begin(size);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiSquareCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY += length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F+XF+F+XF";
private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X";
private static final int ANGLE = 90;
}
|
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 uint64) bool {
for _, p := range primes {
p2 := p * p
if p2 > x {
break
}
if x%p2 == 0 {
return false
}
}
return true
}
func iroot(x, p uint64) uint64 {
return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)
}
func ipow(x, p uint64) uint64 {
prod := uint64(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func powerful(n, k uint64) []uint64 {
set := make(map[uint64]bool)
var f func(m, r uint64)
f = func(m, r uint64) {
if r < k {
set[m] = true
return
}
for v := uint64(1); v <= iroot(n/m, r); v++ {
if r > k {
if !isSquareFree(v) || gcd(m, v) != 1 {
continue
}
}
f(m*ipow(v, r), r-1)
}
}
f(1, (1<<k)-1)
list := make([]uint64, 0, len(set))
for key := range set {
list = append(list, key)
}
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list
}
func main() {
power := uint64(10)
for k := uint64(2); k <= 10; k++ {
power *= 10
a := powerful(power, k)
le := len(a)
h, t := a[0:5], a[le-5:]
fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t)
}
fmt.Println()
for k := uint64(2); k <= 10; k++ {
power := uint64(1)
var counts []int
for j := uint64(0); j < k+10; j++ {
a := powerful(power, k)
counts = append(counts, len(a))
power *= 10
}
j := k + 10
fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts)
}
}
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
|
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 uint64) bool {
for _, p := range primes {
p2 := p * p
if p2 > x {
break
}
if x%p2 == 0 {
return false
}
}
return true
}
func iroot(x, p uint64) uint64 {
return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)
}
func ipow(x, p uint64) uint64 {
prod := uint64(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func powerful(n, k uint64) []uint64 {
set := make(map[uint64]bool)
var f func(m, r uint64)
f = func(m, r uint64) {
if r < k {
set[m] = true
return
}
for v := uint64(1); v <= iroot(n/m, r); v++ {
if r > k {
if !isSquareFree(v) || gcd(m, v) != 1 {
continue
}
}
f(m*ipow(v, r), r-1)
}
}
f(1, (1<<k)-1)
list := make([]uint64, 0, len(set))
for key := range set {
list = append(list, key)
}
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list
}
func main() {
power := uint64(10)
for k := uint64(2); k <= 10; k++ {
power *= 10
a := powerful(power, k)
le := len(a)
h, t := a[0:5], a[le-5:]
fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t)
}
fmt.Println()
for k := uint64(2); k <= 10; k++ {
power := uint64(1)
var counts []int
for j := uint64(0); j < k+10; j++ {
a := powerful(power, k)
counts = append(counts, len(a))
power *= 10
}
j := k + 10
fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts)
}
}
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
|
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(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
| import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
|
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(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
| import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
|
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))
for i, bword := range bwords {
words[i] = string(bword)
}
count := 0
fmt.Println("The odd words with length > 4 in", wordList, "are:")
for _, word := range words {
rword := []rune(word)
if len(rword) > 8 {
var sb strings.Builder
for i := 0; i < len(rword); i += 2 {
sb.WriteRune(rword[i])
}
s := sb.String()
idx := sort.SearchStrings(words, s)
if idx < len(words) && words[idx] == s {
count = count + 1
fmt.Printf("%2d: %-12s -> %s\n", count, word, s)
}
}
}
}
| import java.io.*;
import java.util.*;
public class OddWords {
public static void main(String[] args) {
try {
Set<String> dictionary = new TreeSet<>();
final int minLength = 5;
String fileName = "unixdict.txt";
if (args.length != 0)
fileName = args[0];
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() >= minLength)
dictionary.add(line);
}
}
StringBuilder word1 = new StringBuilder();
StringBuilder word2 = new StringBuilder();
List<StringPair> evenWords = new ArrayList<>();
List<StringPair> oddWords = new ArrayList<>();
for (String word : dictionary) {
int length = word.length();
if (length < minLength + 2 * (minLength/2))
continue;
word1.setLength(0);
word2.setLength(0);
for (int i = 0; i < length; ++i) {
if ((i & 1) == 0)
word1.append(word.charAt(i));
else
word2.append(word.charAt(i));
}
String oddWord = word1.toString();
String evenWord = word2.toString();
if (dictionary.contains(oddWord))
oddWords.add(new StringPair(word, oddWord));
if (dictionary.contains(evenWord))
evenWords.add(new StringPair(word, evenWord));
}
System.out.println("Odd words:");
printWords(oddWords);
System.out.println("\nEven words:");
printWords(evenWords);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printWords(List<StringPair> strings) {
int n = 1;
for (StringPair pair : strings) {
System.out.printf("%2d: %-14s%s\n", n++,
pair.string1, pair.string2);
}
}
private static class StringPair {
private String string1;
private String string2;
private StringPair(String s1, String s2) {
string1 = s1;
string2 = s2;
}
}
}
|
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).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
|
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).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
|
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
}
type prefix struct {
length int
broken []string
}
bp := []prefix{{0, nil}}
for end := 1; end <= len(s); end++ {
for i := len(bp) - 1; i >= 0; i-- {
w := s[bp[i].length:end]
if d[w] {
b := append(bp[i].broken, w)
if end == len(s) {
return b, true
}
bp = append(bp, prefix{end, b})
break
}
}
}
return nil, false
}
func main() {
d := newDict("a", "bc", "abc", "cd", "b")
for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} {
if b, ok := d.wordBreak(s); ok {
fmt.Printf("%s: %s\n", s, strings.Join(b, " "))
} else {
fmt.Println("can't break")
}
}
}
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class WordBreak {
public static void main(String[] args) {
List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab");
for ( String testString : Arrays.asList("aab", "aa b") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d");
for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
}
private static List<List<String>> wordBreak(String s, List<String> dictionary) {
List<List<String>> matches = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(s));
while ( ! queue.isEmpty() ) {
Node node = queue.remove();
if ( node.val.length() == 0 ) {
matches.add(node.parsed);
}
else {
for ( String word : dictionary ) {
if ( node.val.startsWith(word) ) {
String valNew = node.val.substring(word.length(), node.val.length());
List<String> parsedNew = new ArrayList<>();
parsedNew.addAll(node.parsed);
parsedNew.add(word);
queue.add(new Node(valNew, parsedNew));
}
}
}
}
return matches;
}
private static class Node {
private String val;
private List<String> parsed;
public Node(String initial) {
val = initial;
parsed = new ArrayList<>();
}
public Node(String s, List<String> p) {
val = s;
parsed = p;
}
}
}
|
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; k++ {
var s []int
for _, p := range primes {
if p >= pow*10 {
break
}
if p > pow {
s = append(s, p)
}
}
for i := 0; i < len(s); i++ {
for j := i; j < len(s); j++ {
prod := s[i] * s[j]
if prod < limit {
if countOnly {
count++
} else {
brilliant = append(brilliant, prod)
}
} else {
if next > prod {
next = prod
}
break
}
}
}
pow *= 10
}
if countOnly {
return res{count, next}
}
return res{brilliant, next}
}
func main() {
fmt.Println("First 100 brilliant numbers:")
brilliant := getBrilliant(2, 10000, false).bc.([]int)
sort.Ints(brilliant)
brilliant = brilliant[0:100]
for i := 0; i < len(brilliant); i++ {
fmt.Printf("%4d ", brilliant[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
for k := 1; k <= 13; k++ {
limit := int(math.Pow(10, float64(k)))
r := getBrilliant(k, limit, true)
total := r.bc.(int)
next := r.next
climit := rcu.Commatize(limit)
ctotal := rcu.Commatize(total + 1)
cnext := rcu.Commatize(next)
fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
}
}
| import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
}
|
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; k++ {
var s []int
for _, p := range primes {
if p >= pow*10 {
break
}
if p > pow {
s = append(s, p)
}
}
for i := 0; i < len(s); i++ {
for j := i; j < len(s); j++ {
prod := s[i] * s[j]
if prod < limit {
if countOnly {
count++
} else {
brilliant = append(brilliant, prod)
}
} else {
if next > prod {
next = prod
}
break
}
}
}
pow *= 10
}
if countOnly {
return res{count, next}
}
return res{brilliant, next}
}
func main() {
fmt.Println("First 100 brilliant numbers:")
brilliant := getBrilliant(2, 10000, false).bc.([]int)
sort.Ints(brilliant)
brilliant = brilliant[0:100]
for i := 0; i < len(brilliant); i++ {
fmt.Printf("%4d ", brilliant[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
for k := 1; k <= 13; k++ {
limit := int(math.Pow(10, float64(k)))
r := getBrilliant(k, limit, true)
total := r.bc.(int)
next := r.next
climit := rcu.Commatize(limit)
ctotal := rcu.Commatize(total + 1)
cnext := rcu.Commatize(next)
fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
}
}
| import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
}
|
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++ {
if a[i] != b[i] {
sum++
}
}
return sum == 1
}
func wordLadder(words []string, a, b string) {
l := len(a)
var poss []string
for _, word := range words {
if len(word) == l {
poss = append(poss, word)
}
}
todo := [][]string{{a}}
for len(todo) > 0 {
curr := todo[0]
todo = todo[1:]
var next []string
for _, word := range poss {
if oneAway(word, curr[len(curr)-1]) {
next = append(next, word)
}
}
if contains(next, b) {
curr = append(curr, b)
fmt.Println(strings.Join(curr, " -> "))
return
}
for i := len(poss) - 1; i >= 0; i-- {
if contains(next, poss[i]) {
copy(poss[i:], poss[i+1:])
poss[len(poss)-1] = ""
poss = poss[:len(poss)-1]
}
}
for _, s := range next {
temp := make([]string, len(curr))
copy(temp, curr)
temp = append(temp, s)
todo = append(todo, temp)
}
}
fmt.Println(a, "into", b, "cannot be done.")
}
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
pairs := [][]string{
{"boy", "man"},
{"girl", "lady"},
{"john", "jane"},
{"child", "adult"},
}
for _, pair := range pairs {
wordLadder(words, pair[0], pair[1])
}
}
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
}
|
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++ {
if a[i] != b[i] {
sum++
}
}
return sum == 1
}
func wordLadder(words []string, a, b string) {
l := len(a)
var poss []string
for _, word := range words {
if len(word) == l {
poss = append(poss, word)
}
}
todo := [][]string{{a}}
for len(todo) > 0 {
curr := todo[0]
todo = todo[1:]
var next []string
for _, word := range poss {
if oneAway(word, curr[len(curr)-1]) {
next = append(next, word)
}
}
if contains(next, b) {
curr = append(curr, b)
fmt.Println(strings.Join(curr, " -> "))
return
}
for i := len(poss) - 1; i >= 0; i-- {
if contains(next, poss[i]) {
copy(poss[i:], poss[i+1:])
poss[len(poss)-1] = ""
poss = poss[:len(poss)-1]
}
}
for _, s := range next {
temp := make([]string, len(curr))
copy(temp, curr)
temp = append(temp, s)
todo = append(todo, temp)
}
}
fmt.Println(a, "into", b, "cannot be done.")
}
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
pairs := [][]string{
{"boy", "man"},
{"girl", "lady"},
{"john", "jane"},
{"child", "adult"},
}
for _, pair := range pairs {
wordLadder(words, pair[0], pair[1])
}
}
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
}
|
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]
}
}
pm := 10
gap1 := 2
for {
for _, ok := gapStarts[gap1]; !ok; {
gap1 += 2
}
start1 := gapStarts[gap1]
gap2 := gap1 + 2
if _, ok := gapStarts[gap2]; !ok {
gap1 = gap2 + 2
continue
}
start2 := gapStarts[gap2]
diff := start2 - start1
if diff < 0 {
diff = -diff
}
if diff > pm {
cpm := rcu.Commatize(pm)
cst1 := rcu.Commatize(start1)
cst2 := rcu.Commatize(start2)
cd := rcu.Commatize(diff)
fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm)
fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd)
if pm == limit {
break
}
pm *= 10
} else {
gap1 = gap2
}
}
}
| import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 100000000;
PrimeGaps pg = new PrimeGaps();
for (int pm = 10, gap1 = 2;;) {
int start1 = pg.findGapStart(gap1);
int gap2 = gap1 + 2;
int start2 = pg.findGapStart(gap2);
int diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
System.out.printf(
"Earliest difference > %,d between adjacent prime gap starting primes:\n"
+ "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n",
pm, gap1, start1, gap2, start2, diff);
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
private int findGapStart(int gap) {
Integer start = gapStarts.get(gap);
if (start != null)
return start;
for (;;) {
int prev = lastPrime;
lastPrime = primeGenerator.nextPrime();
int diff = lastPrime - prev;
gapStarts.putIfAbsent(diff, prev);
if (diff == gap)
return prev;
}
}
}
|
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]
}
}
pm := 10
gap1 := 2
for {
for _, ok := gapStarts[gap1]; !ok; {
gap1 += 2
}
start1 := gapStarts[gap1]
gap2 := gap1 + 2
if _, ok := gapStarts[gap2]; !ok {
gap1 = gap2 + 2
continue
}
start2 := gapStarts[gap2]
diff := start2 - start1
if diff < 0 {
diff = -diff
}
if diff > pm {
cpm := rcu.Commatize(pm)
cst1 := rcu.Commatize(start1)
cst2 := rcu.Commatize(start2)
cd := rcu.Commatize(diff)
fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm)
fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd)
if pm == limit {
break
}
pm *= 10
} else {
gap1 = gap2
}
}
}
| import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 100000000;
PrimeGaps pg = new PrimeGaps();
for (int pm = 10, gap1 = 2;;) {
int start1 = pg.findGapStart(gap1);
int gap2 = gap1 + 2;
int start2 = pg.findGapStart(gap2);
int diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
System.out.printf(
"Earliest difference > %,d between adjacent prime gap starting primes:\n"
+ "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n",
pm, gap1, start1, gap2, start2, diff);
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
private int findGapStart(int gap) {
Integer start = gapStarts.get(gap);
if (start != null)
return start;
for (;;) {
int prev = lastPrime;
lastPrime = primeGenerator.nextPrime();
int diff = lastPrime - prev;
gapStarts.putIfAbsent(diff, prev);
if (diff == gap)
return prev;
}
}
}
|
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(last int) {
if last == first {
for j, v := range a[1:] {
if j+1 == v {
return
}
}
b := make([]int, n)
copy(b, a)
for i := range b {
b[i]++
}
r = append(r, b)
return
}
for i := last; i >= 1; i-- {
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
}
}
recurse(n - 1)
return
}
func reducedLatinSquare(n int, echo bool) uint64 {
if n <= 0 {
if echo {
fmt.Println("[]\n")
}
return 0
} else if n == 1 {
if echo {
fmt.Println("[1]\n")
}
return 1
}
rlatin := make(matrix, n)
for i := 0; i < n; i++ {
rlatin[i] = make([]int, n)
}
for j := 0; j < n; j++ {
rlatin[0][j] = j + 1
}
count := uint64(0)
var recurse func(i int)
recurse = func(i int) {
rows := dList(n, i)
outer:
for r := 0; r < len(rows); r++ {
copy(rlatin[i-1], rows[r])
for k := 0; k < i-1; k++ {
for j := 1; j < n; j++ {
if rlatin[k][j] == rlatin[i-1][j] {
if r < len(rows)-1 {
continue outer
} else if i > 2 {
return
}
}
}
}
if i < n {
recurse(i + 1)
} else {
count++
if echo {
printSquare(rlatin, n)
}
}
}
return
}
recurse(2)
return count
}
func printSquare(latin matrix, n int) {
for i := 0; i < n; i++ {
fmt.Println(latin[i])
}
fmt.Println()
}
func factorial(n uint64) uint64 {
if n == 0 {
return 1
}
prod := uint64(1)
for i := uint64(2); i <= n; i++ {
prod *= i
}
return prod
}
func main() {
fmt.Println("The four reduced latin squares of order 4 are:\n")
reducedLatinSquare(4, true)
fmt.Println("The size of the set of reduced latin squares for the following orders")
fmt.Println("and hence the total number of latin squares of these orders are:\n")
for n := uint64(1); n <= 6; n++ {
size := reducedLatinSquare(int(n), false)
f := factorial(n - 1)
f *= f * n * size
fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f)
}
}
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LatinSquaresInReducedForm {
public static void main(String[] args) {
System.out.printf("Reduced latin squares of order 4:%n");
for ( LatinSquare square : getReducedLatinSquares(4) ) {
System.out.printf("%s%n", square);
}
System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n");
for ( int n = 1 ; n <= 6 ; n++ ) {
List<LatinSquare> list = getReducedLatinSquares(n);
System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));
}
}
private static long fact(int n) {
if ( n == 0 ) {
return 1;
}
int prod = 1;
for ( int i = 1 ; i <= n ; i++ ) {
prod *= i;
}
return prod;
}
private static List<LatinSquare> getReducedLatinSquares(int n) {
List<LatinSquare> squares = new ArrayList<>();
squares.add(new LatinSquare(n));
PermutationGenerator permGen = new PermutationGenerator(n);
for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {
List<LatinSquare> squaresNext = new ArrayList<>();
for ( LatinSquare square : squares ) {
while ( permGen.hasMore() ) {
int[] perm = permGen.getNext();
if ( (perm[0]+1) != (fillRow+1) ) {
continue;
}
boolean permOk = true;
done:
for ( int row = 0 ; row < fillRow ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
if ( square.get(row, col) == (perm[col]+1) ) {
permOk = false;
break done;
}
}
}
if ( permOk ) {
LatinSquare newSquare = new LatinSquare(square);
for ( int col = 0 ; col < n ; col++ ) {
newSquare.set(fillRow, col, perm[col]+1);
}
squaresNext.add(newSquare);
}
}
permGen.reset();
}
squares = squaresNext;
}
return squares;
}
@SuppressWarnings("unused")
private static int[] display(int[] in) {
int [] out = new int[in.length];
for ( int i = 0 ; i < in.length ; i++ ) {
out[i] = in[i] + 1;
}
return out;
}
private static class LatinSquare {
int[][] square;
int size;
public LatinSquare(int n) {
square = new int[n][n];
size = n;
for ( int col = 0 ; col < n ; col++ ) {
set(0, col, col + 1);
}
}
public LatinSquare(LatinSquare ls) {
int n = ls.size;
square = new int[n][n];
size = n;
for ( int row = 0 ; row < n ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
set(row, col, ls.get(row, col));
}
}
}
public void set(int row, int col, int value) {
square[row][col] = value;
}
public int get(int row, int col) {
return square[row][col];
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for ( int row = 0 ; row < size ; row++ ) {
sb.append(Arrays.toString(square[row]));
sb.append("\n");
}
return sb.toString();
}
}
private static class PermutationGenerator {
private int[] a;
private BigInteger numLeft;
private BigInteger total;
public PermutationGenerator (int n) {
if (n < 1) {
throw new IllegalArgumentException ("Min 1");
}
a = new int[n];
total = getFactorial(n);
reset();
}
private void reset () {
for ( int i = 0 ; i < a.length ; i++ ) {
a[i] = i;
}
numLeft = new BigInteger(total.toString());
}
public boolean hasMore() {
return numLeft.compareTo(BigInteger.ZERO) == 1;
}
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for ( int i = n ; i > 1 ; i-- ) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
return fact;
}
public int[] getNext() {
if ( numLeft.equals(total) ) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
int j = a.length - 2;
while ( a[j] > a[j+1] ) {
j--;
}
int k = a.length - 1;
while ( a[j] > a[k] ) {
k--;
}
int temp = a[k];
a[k] = a[j];
a[j] = temp;
int r = a.length - 1;
int s = j + 1;
while (r > s) {
int temp2 = a[s];
a[s] = a[r];
a[r] = temp2;
r--;
s++;
}
numLeft = numLeft.subtract(BigInteger.ONE);
return a;
}
}
}
|
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[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
}
expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
rx := regexp.MustCompile(expr)
fmt.Println("UPC-A barcodes:")
for i, bc := range barcodes {
for j := 0; j <= 1; j++ {
if !rx.MatchString(bc) {
fmt.Printf("%2d: Invalid format\n", i+1)
break
}
codes := rx.FindStringSubmatch(bc)
digits := make([]int, 12)
var invalid, ok bool
for i := 1; i <= 6; i++ {
digits[i-1], ok = lhs[codes[i]]
if !ok {
invalid = true
}
digits[i+5], ok = rhs[codes[i+6]]
if !ok {
invalid = true
}
}
if invalid {
if j == 0 {
bc = reverse(bc)
continue
} else {
fmt.Printf("%2d: Invalid digit(s)\n", i+1)
break
}
}
sum := 0
for i, d := range digits {
sum += weights[i] * d
}
if sum%10 != 0 {
fmt.Printf("%2d: Checksum error\n", i+1)
break
} else {
ud := ""
if j == 1 {
ud = "(upside down)"
}
fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
break
}
}
}
}
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
}
|
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[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
}
expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
rx := regexp.MustCompile(expr)
fmt.Println("UPC-A barcodes:")
for i, bc := range barcodes {
for j := 0; j <= 1; j++ {
if !rx.MatchString(bc) {
fmt.Printf("%2d: Invalid format\n", i+1)
break
}
codes := rx.FindStringSubmatch(bc)
digits := make([]int, 12)
var invalid, ok bool
for i := 1; i <= 6; i++ {
digits[i-1], ok = lhs[codes[i]]
if !ok {
invalid = true
}
digits[i+5], ok = rhs[codes[i+6]]
if !ok {
invalid = true
}
}
if invalid {
if j == 0 {
bc = reverse(bc)
continue
} else {
fmt.Printf("%2d: Invalid digit(s)\n", i+1)
break
}
}
sum := 0
for i, d := range digits {
sum += weights[i] * d
}
if sum%10 != 0 {
fmt.Printf("%2d: Checksum error\n", i+1)
break
} else {
ud := ""
if j == 1 {
ud = "(upside down)"
}
fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
break
}
}
}
}
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
}
|
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 {
used[16] = true
} else {
used[9] = true
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
plainText = strings.ToUpper(plainText)
var cleanText strings.Builder
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}
| import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
|
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 {
used[16] = true
} else {
used[9] = true
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
plainText = strings.ToUpper(plainText)
var cleanText strings.Builder
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}
| import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
|
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 {
used[16] = true
} else {
used[9] = true
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
plainText = strings.ToUpper(plainText)
var cleanText strings.Builder
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}
| import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
|
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 points {
points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
}
p1, p2 := closestPair(points)
fmt.Println(p1, p2)
fmt.Println("distance:", d(p1, p2))
}
func closestPair(points []xy) (p1, p2 xy) {
if len(points) < 2 {
panic("at least two points expected")
}
min := 2 * scale
for i, q1 := range points[:len(points)-1] {
for _, q2 := range points[i+1:] {
if dq := d(q1, q2); dq < min {
p1, p2 = q1, q2
min = dq
}
}
}
return
}
| import java.util.*;
public class ClosestPair
{
public static class Point
{
public final double x;
public final double y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public String toString()
{ return "(" + x + ", " + y + ")"; }
}
public static class Pair
{
public Point point1 = null;
public Point point2 = null;
public double distance = 0.0;
public Pair()
{ }
public Pair(Point point1, Point point2)
{
this.point1 = point1;
this.point2 = point2;
calcDistance();
}
public void update(Point point1, Point point2, double distance)
{
this.point1 = point1;
this.point2 = point2;
this.distance = distance;
}
public void calcDistance()
{ this.distance = distance(point1, point2); }
public String toString()
{ return point1 + "-" + point2 + " : " + distance; }
}
public static double distance(Point p1, Point p2)
{
double xdist = p2.x - p1.x;
double ydist = p2.y - p1.y;
return Math.hypot(xdist, ydist);
}
public static Pair bruteForce(List<? extends Point> points)
{
int numPoints = points.size();
if (numPoints < 2)
return null;
Pair pair = new Pair(points.get(0), points.get(1));
if (numPoints > 2)
{
for (int i = 0; i < numPoints - 1; i++)
{
Point point1 = points.get(i);
for (int j = i + 1; j < numPoints; j++)
{
Point point2 = points.get(j);
double distance = distance(point1, point2);
if (distance < pair.distance)
pair.update(point1, point2, distance);
}
}
}
return pair;
}
public static void sortByX(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.x < point2.x)
return -1;
if (point1.x > point2.x)
return 1;
return 0;
}
}
);
}
public static void sortByY(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.y < point2.y)
return -1;
if (point1.y > point2.y)
return 1;
return 0;
}
}
);
}
public static Pair divideAndConquer(List<? extends Point> points)
{
List<Point> pointsSortedByX = new ArrayList<Point>(points);
sortByX(pointsSortedByX);
List<Point> pointsSortedByY = new ArrayList<Point>(points);
sortByY(pointsSortedByY);
return divideAndConquer(pointsSortedByX, pointsSortedByY);
}
private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)
{
int numPoints = pointsSortedByX.size();
if (numPoints <= 3)
return bruteForce(pointsSortedByX);
int dividingIndex = numPoints >>> 1;
List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);
List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);
List<Point> tempList = new ArrayList<Point>(leftOfCenter);
sortByY(tempList);
Pair closestPair = divideAndConquer(leftOfCenter, tempList);
tempList.clear();
tempList.addAll(rightOfCenter);
sortByY(tempList);
Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);
if (closestPairRight.distance < closestPair.distance)
closestPair = closestPairRight;
tempList.clear();
double shortestDistance =closestPair.distance;
double centerX = rightOfCenter.get(0).x;
for (Point point : pointsSortedByY)
if (Math.abs(centerX - point.x) < shortestDistance)
tempList.add(point);
for (int i = 0; i < tempList.size() - 1; i++)
{
Point point1 = tempList.get(i);
for (int j = i + 1; j < tempList.size(); j++)
{
Point point2 = tempList.get(j);
if ((point2.y - point1.y) >= shortestDistance)
break;
double distance = distance(point1, point2);
if (distance < closestPair.distance)
{
closestPair.update(point1, point2, distance);
shortestDistance = distance;
}
}
}
return closestPair;
}
public static void main(String[] args)
{
int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);
List<Point> points = new ArrayList<Point>();
Random r = new Random();
for (int i = 0; i < numPoints; i++)
points.add(new Point(r.nextDouble(), r.nextDouble()));
System.out.println("Generated " + numPoints + " random points");
long startTime = System.currentTimeMillis();
Pair bruteForceClosestPair = bruteForce(points);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair);
startTime = System.currentTimeMillis();
Pair dqClosestPair = divideAndConquer(points);
elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair);
if (bruteForceClosestPair.distance != dqClosestPair.distance)
System.out.println("MISMATCH");
}
}
|
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 = true
pet.obedienceTrained = false
pet.color = "yellow"
}
| 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))
}
sign := int64(1)
f := new(big.Int)
zero := new(big.Int)
fmt.Println(" n: Wilson primes")
fmt.Println("--------------------")
for n := 1; n < 12; n++ {
fmt.Printf("%2d: ", n)
sign = -sign
for _, p := range primes {
if p < n {
continue
}
f.Mul(facts[n-1], facts[p-n])
f.Sub(f, big.NewInt(sign))
p2 := int64(p * p)
bp2 := big.NewInt(p2)
if f.Rem(f, bp2).Cmp(zero) == 0 {
fmt.Printf("%d ", p)
}
}
fmt.Println()
}
}
| import java.math.BigInteger;
import java.util.*;
public class WilsonPrimes {
public static void main(String[] args) {
final int limit = 11000;
BigInteger[] f = new BigInteger[limit];
f[0] = BigInteger.ONE;
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i < limit; ++i) {
factorial = factorial.multiply(BigInteger.valueOf(i));
f[i] = factorial;
}
List<Integer> primes = generatePrimes(limit);
System.out.printf(" n | Wilson primes\n--------------------\n");
BigInteger s = BigInteger.valueOf(-1);
for (int n = 1; n <= 11; ++n) {
System.out.printf("%2d |", n);
for (int p : primes) {
if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)
.mod(BigInteger.valueOf(p * p))
.equals(BigInteger.ZERO))
System.out.printf(" %d", p);
}
s = s.negate();
System.out.println();
}
}
private static List<Integer> generatePrimes(int limit) {
boolean[] sieve = new boolean[limit >> 1];
Arrays.fill(sieve, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
List<Integer> primes = new ArrayList<>();
if (limit > 2)
primes.add(2);
for (int i = 1; i < sieve.length; ++i) {
if (sieve[i])
primes.add((i << 1) + 1);
}
return primes;
}
}
|
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*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func colorWheel(dc *gg.Context) {
width, height := dc.Width(), dc.Height()
centerX, centerY := width/2, height/2
radius := centerX
if centerY < radius {
radius = centerY
}
for y := 0; y < height; y++ {
dy := float64(y - centerY)
for x := 0; x < width; x++ {
dx := float64(x - centerX)
dist := math.Sqrt(dx*dx + dy*dy)
if dist <= float64(radius) {
theta := math.Atan2(dy, dx)
hue := (theta + math.Pi) / tau
r, g, b := hsb2rgb(hue, 1, 1)
dc.SetRGB255(r, g, b)
dc.SetPixel(x, y)
}
}
}
}
func main() {
const width, height = 480, 480
dc := gg.NewContext(width, height)
dc.SetRGB(1, 1, 1)
dc.Clear()
colorWheel(dc)
dc.SavePNG("color_wheel.png")
}
| import java.awt.*;
import javax.swing.*;
public class ColorWheel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorWheelFrame frame = new ColorWheelFrame();
frame.setVisible(true);
}
});
}
private static class ColorWheelFrame extends JFrame {
private ColorWheelFrame() {
super("Color Wheel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ColorWheelPanel());
pack();
}
}
private static class ColorWheelPanel extends JComponent {
private ColorWheelPanel() {
setPreferredSize(new Dimension(400, 400));
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int margin = 10;
int radius = (Math.min(w, h) - 2 * margin)/2;
int cx = w/2;
int cy = h/2;
float[] dist = {0.F, 1.0F};
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, w, h);
for (int angle = 0; angle < 360; ++angle) {
Color color = hsvToRgb(angle, 1.0, 1.0);
Color[] colors = {Color.WHITE, color};
RadialGradientPaint paint = new RadialGradientPaint(cx, cy,
radius, dist, colors);
g2.setPaint(paint);
g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,
angle, 1);
}
}
}
private static Color hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - Math.abs(hp % 2.0 - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
}
|
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 float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func main() {
const degToRad = math.Pi / 180
const nframes = 100
const delay = 4
w, h := 640, 640
anim := gif.GIF{LoopCount: nframes}
rect := image.Rect(0, 0, w, h)
palette := make([]color.Color, nframes+1)
palette[0] = color.White
for i := 1; i <= nframes; i++ {
r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)
palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}
}
for f := 1; f <= nframes; f++ {
img := image.NewPaletted(rect, palette)
setBackgroundColor(img, w, h, 0)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
fx, fy := float64(x), float64(y)
value := math.Sin(fx / 16)
value += math.Sin(fy / 8)
value += math.Sin((fx + fy) / 16)
value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)
value += 4
value /= 8
_, rem := math.Modf(value + float64(f)/float64(nframes))
ci := uint8(nframes*rem) + 1
img.SetColorIndex(x, y, ci)
}
}
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
file, err := os.Create("plasma.gif")
if err != nil {
log.Fatal(err)
}
defer file.Close()
if err2 := gif.EncodeAll(file, &anim); err != nil {
log.Fatal(err2)
}
}
| import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;
public class PlasmaEffect extends JPanel {
float[][] plasma;
float hueShift = 0;
BufferedImage img;
public PlasmaEffect() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
plasma = createPlasma(dim.height, dim.width);
new Timer(42, (ActionEvent e) -> {
hueShift = (hueShift + 0.02f) % 1;
repaint();
}).start();
}
float[][] createPlasma(int w, int h) {
float[][] buffer = new float[h][w];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
double value = sin(x / 16.0);
value += sin(y / 8.0);
value += sin((x + y) / 16.0);
value += sin(sqrt(x * x + y * y) / 8.0);
value += 4;
value /= 8;
assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";
buffer[y][x] = (float) value;
}
return buffer;
}
void drawPlasma(Graphics2D g) {
int h = plasma.length;
int w = plasma[0].length;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
float hue = hueShift + plasma[y][x] % 1;
img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
}
g.drawImage(img, 0, 0, null);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPlasma(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Plasma Effect");
f.setResizable(false);
f.add(new PlasmaEffect(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
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 := 0
var rhonda []int
for n := 1; count < 15; n++ {
digits := rcu.Digits(n, b)
if !contains(digits, 0) {
var anyEven = false
for _, d := range digits {
if d%2 == 0 {
anyEven = true
break
}
}
if b != 10 || (contains(digits, 5) && anyEven) {
calc1 := 1
for _, d := range digits {
calc1 *= d
}
calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))
if calc1 == calc2 {
rhonda = append(rhonda, n)
count++
}
}
}
}
if len(rhonda) > 0 {
fmt.Printf("\nFirst 15 Rhonda numbers in base %d:\n", b)
rhonda2 := make([]string, len(rhonda))
counts2 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda2[i] = fmt.Sprintf("%d", r)
counts2[i] = len(rhonda2[i])
}
rhonda3 := make([]string, len(rhonda))
counts3 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda3[i] = strconv.FormatInt(int64(r), b)
counts3[i] = len(rhonda3[i])
}
maxLen2 := rcu.MaxInts(counts2)
maxLen3 := rcu.MaxInts(counts3)
maxLen := maxLen2
if maxLen3 > maxLen {
maxLen = maxLen3
}
maxLen++
fmt.Printf("In base 10: %*s\n", maxLen, rhonda2)
fmt.Printf("In base %-2d: %*s\n", b, maxLen, rhonda3)
}
}
}
| public class RhondaNumbers {
public static void main(String[] args) {
final int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (isPrime(base))
continue;
System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base);
int numbers[] = new int[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (isRhonda(base, n))
numbers[count++] = n;
}
System.out.printf("In base 10:");
for (int i = 0; i < limit; ++i)
System.out.printf(" %d", numbers[i]);
System.out.printf("\nIn base %d:", base);
for (int i = 0; i < limit; ++i)
System.out.printf(" %s", Integer.toString(numbers[i], base));
System.out.printf("\n\n");
}
}
private static int digitProduct(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
private static int primeFactorSum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static boolean isRhonda(int base, int n) {
return digitProduct(base, n) == base * primeFactorSum(n);
}
}
|
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 = newPoint(3, 4)
i.print()
i = newCircle(5, 12, 13)
i.print()
}
func (p *point) getX() float64 { return p.x }
func (p *point) getY() float64 { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }
func (c *circle) getX() float64 { return c.x }
func (c *circle) getY() float64 { return c.y }
func (c *circle) getR() float64 { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }
func (p *point) clone() *point { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }
func (p *point) set(q *point) { *p = *q }
func (c *circle) set(d *circle) { *c = *d }
func newPoint(x, y float64) *point {
return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
return &circle{x, y, r}
}
| class Point {
protected int x, y;
public Point() { this(0); }
public Point(int x) { this(x, 0); }
public Point(int x, int y) { this.x = x; this.y = y; }
public Point(Point p) { this(p.x, p.y); }
public int getX() { return this.x; }
public int getY() { return this.y; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); }
}
class Circle extends Point {
private int r;
public Circle(Point p) { this(p, 0); }
public Circle(Point p, int r) { super(p); this.r = r; }
public Circle() { this(0); }
public Circle(int x) { this(x, 0); }
public Circle(int x, int y) { this(x, y, 0); }
public Circle(int x, int y, int r) { super(x, y); this.r = r; }
public Circle(Circle c) { this(c.x, c.y, c.r); }
public int getR() { return this.r; }
public void setR(int r) { this.r = r; }
public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); }
}
public class test {
public static void main(String args[]) {
Point p = new Point();
Point c = new Circle();
p.print();
c.print();
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | 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
}
}
| 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);
}
}
|
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 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)
}
| 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;
}
}
}
|
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 *= 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()
}
}
| 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();
}
}
|
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 *= 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()
}
}
| import java.math.BigInteger;
public class SquareRoot {
public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);
public static final BigInteger TWENTY = BigInteger.valueOf(20);
public static void main(String[] args) {
var i = BigInteger.TWO;
var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));
var k = j;
var d = j;
int n = 500;
int n0 = n;
do {
System.out.print(d);
i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);
k = TWENTY.multiply(j);
for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {
if (k.add(d).multiply(d).compareTo(i) > 0) {
d = d.subtract(BigInteger.ONE);
break;
}
}
j = j.multiply(BigInteger.TEN).add(d);
k = k.add(d);
if (n0 > 0) {
n--;
}
} while (n > 0);
System.out.println();
}
}
|
Rewrite 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 < n; i++ {
f := t.Field(i)
fmt.Printf("%-8s %-8v %-8t\n",
f.Name,
f.Type,
f.PkgPath == "",
)
}
fmt.Println()
}
| 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));
}
}
}
|
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 {
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()
}
}
| 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";
}
}
}
|
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$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)
}
| 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;
}
}
}
|
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: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)
}
}
| 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);
}
}
}
|
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: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)
}
}
| 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);
}
}
}
|
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 {
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)
}
}
| 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);
}
}
}
|
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 {
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)
}
}
| 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);
}
}
}
|
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 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)
}
}
}
| 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));
}
|
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 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)
}
}
}
| public static void main(String... args){
HashMap<String, Integer> vars = new HashMap<String, Integer>();
vars.put("Variable name", 3);
vars.put("Next variable name", 5);
Scanner sc = new Scanner(System.in);
String str = sc.next();
vars.put(str, sc.nextInt());
System.out.println(vars.get("Variable name"));
System.out.println(vars.get(str));
}
|
Translate 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("8787878787878787")
if err != nil {
log.Fatal(err)
}
dst := make([]byte, des.BlockSize)
c.Encrypt(dst, src)
fmt.Printf("%x\n", dst)
}
| 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");
}
}
|
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 != 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))
}
| 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);
}
}
|
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 != 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))
}
| 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);
}
}
|
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 != 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))
}
| 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);
}
}
|
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 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, ","))
}
}
| 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));
}
}
|
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
}
}
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!")
}
}
}
| 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!");
}
}
}
|
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(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
}
| 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);
}
}
|
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 := 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()
}
| 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);
}
}
}
|
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(name, int.class);
Object result = meth.invoke(example, 5);
System.out.println(result);
}
}
|
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 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}))
| 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}));
}
}
|
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)
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)
}
| 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)));
}
}
|
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
}
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)
}
}
| 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);
}
}
}
|
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
}
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)
}
}
| 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);
}
}
}
|
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 := 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
}
}
| 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);
}
}
}
|
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 := 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
}
}
| 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);
}
}
}
|
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 was a soul stripper. She took my heart!"
t := reverseGender(s)
fmt.Println(t)
fmt.Println(reverseGender(t))
}
| 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;
}
}
|
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 was a soul stripper. She took my heart!"
t := reverseGender(s)
fmt.Println(t)
fmt.Println(reverseGender(t))
}
| 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;
}
}
|
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()
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)
}
}
| 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);
}
}
|
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"
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))
}
| 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();
}
}
|
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"
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))
}
| 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();
}
}
|
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 := 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))
}
| 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 )
);
}
}
|
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 := 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))
}
| 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 )
);
}
}
|
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}},
{{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)))
}
| 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;
}
}
}
|
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}},
{{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)))
}
| 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;
}
}
}
|
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"},
{"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
}
| 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;
}
}
|
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, 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)
}
}
| 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;
}
}
|
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*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'
}
| 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]);
}
}
|
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)
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)
}
}
| 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}},
{{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)
}
}
| 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();
}
}
}
|
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.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)
}
}
| 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);
}
}
|
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}
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)
}
}
| 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);
}
}
}
|
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()}}}
}
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)
}
}
| 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()
{
}
}
|
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 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")
}
| 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);
});
}
}
|
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 error");
return;
}
fmt.Println("Return value:", val)
}
| 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);
}
}
}
|
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 error");
return;
}
fmt.Println("Return value:", val)
}
| 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);
}
}
}
|
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
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()
}
| 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;
}
}
|
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++ {
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)
}
| 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;
}
}
|
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 (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()
}
| 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();
}
}
}
|
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(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])
}
}
| 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;
}
}
|
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 := <-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
}
}
| 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.");
}
}
|
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 := <-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
}
}
| 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.");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.