Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"log"
"math/big"
"strings"
)
type result struct {
name string
size int
start int
end int
}
func (r result) String() string {
return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end)
}
func validate(diagram string) []string {
var lines []string
for _, line := range strings.Split(diagram, "\n") {
line = strings.Trim(line, " \t")
if line != "" {
lines = append(lines, line)
}
}
if len(lines) == 0 {
log.Fatal("diagram has no non-empty lines!")
}
width := len(lines[0])
cols := (width - 1) / 3
if cols != 8 && cols != 16 && cols != 32 && cols != 64 {
log.Fatal("number of columns should be 8, 16, 32 or 64")
}
if len(lines)%2 == 0 {
log.Fatal("number of non-empty lines should be odd")
}
if lines[0] != strings.Repeat("+--", cols)+"+" {
log.Fatal("incorrect header line")
}
for i, line := range lines {
if i == 0 {
continue
} else if i%2 == 0 {
if line != lines[0] {
log.Fatal("incorrect separator line")
}
} else if len(line) != width {
log.Fatal("inconsistent line widths")
} else if line[0] != '|' || line[width-1] != '|' {
log.Fatal("non-separator lines must begin and end with '|'")
}
}
return lines
}
func decode(lines []string) []result {
fmt.Println("Name Bits Start End")
fmt.Println("======= ==== ===== ===")
start := 0
width := len(lines[0])
var results []result
for i, line := range lines {
if i%2 == 0 {
continue
}
line := line[1 : width-1]
for _, name := range strings.Split(line, "|") {
size := (len(name) + 1) / 3
name = strings.TrimSpace(name)
res := result{name, size, start, start + size - 1}
results = append(results, res)
fmt.Println(res)
start += size
}
}
return results
}
func unpack(results []result, hex string) {
fmt.Println("\nTest string in hex:")
fmt.Println(hex)
fmt.Println("\nTest string in binary:")
bin := hex2bin(hex)
fmt.Println(bin)
fmt.Println("\nUnpacked:\n")
fmt.Println("Name Size Bit pattern")
fmt.Println("======= ==== ================")
for _, res := range results {
fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1])
}
}
func hex2bin(hex string) string {
z := new(big.Int)
z.SetString(hex, 16)
return fmt.Sprintf("%0*b", 4*len(hex), z)
}
func main() {
const diagram = `
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
`
lines := validate(diagram)
fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n")
for _, line := range lines {
fmt.Println(line)
}
fmt.Println("\nDecoded:\n")
results := decode(lines)
hex := "78477bbf5496e12e1bf169a4"
unpack(results, hex)
}
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class AsciiArtDiagramConverter {
private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ID |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| QDCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ANCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| NSCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ARCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+";
public static void main(String[] args) {
validate(TEST);
display(TEST);
Map<String,List<Integer>> asciiMap = decode(TEST);
displayMap(asciiMap);
displayCode(asciiMap, "78477bbf5496e12e1bf169a4");
}
private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {
System.out.printf("%nTest string in hex:%n%s%n%n", hex);
String bin = new BigInteger(hex,16).toString(2);
int length = 0;
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
length += pos.get(1) - pos.get(0) + 1;
}
while ( length > bin.length() ) {
bin = "0" + bin;
}
System.out.printf("Test string in binary:%n%s%n%n", bin);
System.out.printf("Name Size Bit Pattern%n");
System.out.printf("-------- ----- -----------%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
int start = pos.get(0);
int end = pos.get(1);
System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1));
}
}
private static void display(String ascii) {
System.out.printf("%nDiagram:%n%n");
for ( String s : TEST.split("\\r\\n") ) {
System.out.println(s);
}
}
private static void displayMap(Map<String,List<Integer>> asciiMap) {
System.out.printf("%nDecode:%n%n");
System.out.printf("Name Size Start End%n");
System.out.printf("-------- ----- ----- -----%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));
}
}
private static Map<String,List<Integer>> decode(String ascii) {
Map<String,List<Integer>> map = new LinkedHashMap<>();
String[] split = TEST.split("\\r\\n");
int size = split[0].indexOf("+", 1) - split[0].indexOf("+");
int length = split[0].length() - 1;
for ( int i = 1 ; i < split.length ; i += 2 ) {
int barIndex = 1;
String test = split[i];
int next;
while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) {
List<Integer> startEnd = new ArrayList<>();
startEnd.add((barIndex/size) + (i/2)*(length/size));
startEnd.add(((next-1)/size) + (i/2)*(length/size));
String code = test.substring(barIndex, next).replace(" ", "");
map.put(code, startEnd);
barIndex = next + 1;
}
}
return map;
}
private static void validate(String ascii) {
String[] split = TEST.split("\\r\\n");
if ( split.length % 2 != 1 ) {
throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length);
}
int size = 0;
for ( int i = 0 ; i < split.length ; i++ ) {
String test = split[i];
if ( i % 2 == 0 ) {
if ( ! test.matches("^\\+([-]+\\+)+$") ) {
throw new RuntimeException("ERROR 2: Improper line format. Line = " + test);
}
if ( size == 0 ) {
int firstPlus = test.indexOf("+");
int secondPlus = test.indexOf("+", 1);
size = secondPlus - firstPlus;
}
if ( ((test.length()-1) % size) != 0 ) {
throw new RuntimeException("ERROR 3: Improper line format. Line = " + test);
}
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
if ( test.charAt(j) != '+' ) {
throw new RuntimeException("ERROR 4: Improper line format. Line = " + test);
}
for ( int k = j+1 ; k < j + size ; k++ ) {
if ( test.charAt(k) != '-' ) {
throw new RuntimeException("ERROR 5: Improper line format. Line = " + test);
}
}
}
}
else {
if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) {
throw new RuntimeException("ERROR 6: Improper line format. Line = " + test);
}
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
for ( int k = j+1 ; k < j + size ; k++ ) {
if ( test.charAt(k) == '|' ) {
throw new RuntimeException("ERROR 7: Improper line format. Line = " + test);
}
}
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"github.com/biogo/biogo/align"
ab "github.com/biogo/biogo/alphabet"
"github.com/biogo/biogo/feat"
"github.com/biogo/biogo/seq/linear"
)
func main() {
lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz",
feat.Undefined, '-', 0, true))
nw := make(align.NW, lc.Len())
for i := range nw {
r := make([]int, lc.Len())
nw[i] = r
for j := range r {
if j != i {
r[j] = -1
}
}
}
a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))}
a.Alpha = lc
b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))}
b.Alpha = lc
aln, err := nw.Align(a, b)
if err != nil {
fmt.Println(err)
return
}
fa := align.Format(a, b, aln, '-')
fmt.Printf("%s\n%s\n", fa[0], fa[1])
aa := fmt.Sprint(fa[0])
ba := fmt.Sprint(fa[1])
ma := make([]byte, len(aa))
for i := range ma {
if aa[i] == ba[i] {
ma[i] = ' '
} else {
ma[i] = '|'
}
}
fmt.Println(string(ma))
}
| public class LevenshteinAlignment {
public static String[] alignment(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
int[][] costs = new int[a.length()+1][b.length()+1];
for (int j = 0; j <= b.length(); j++)
costs[0][j] = j;
for (int i = 1; i <= a.length(); i++) {
costs[i][0] = i;
for (int j = 1; j <= b.length(); j++) {
costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);
}
}
StringBuilder aPathRev = new StringBuilder();
StringBuilder bPathRev = new StringBuilder();
for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {
if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {
aPathRev.append(a.charAt(--i));
bPathRev.append(b.charAt(--j));
} else if (costs[i][j] == 1 + costs[i-1][j]) {
aPathRev.append(a.charAt(--i));
bPathRev.append('-');
} else if (costs[i][j] == 1 + costs[i][j-1]) {
aPathRev.append('-');
bPathRev.append(b.charAt(--j));
}
}
return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};
}
public static void main(String[] args) {
String[] result = alignment("rosettacode", "raisethysword");
System.out.println(result[0]);
System.out.println(result[1]);
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
type node struct {
int
left, right *node
}
func leaves(t *node) chan int {
ch := make(chan int)
var f func(*node)
f = func(n *node) {
if n == nil {
return
}
if n.left == nil && n.right == nil {
ch <- n.int
} else {
f(n.left)
f(n.right)
}
}
go func() {
f(t)
close(ch)
}()
return ch
}
func sameFringe(t1, t2 *node) bool {
f1 := leaves(t1)
f2 := leaves(t2)
for l1 := range f1 {
if l2, ok := <-f2; !ok || l1 != l2 {
return false
}
}
_, ok := <-f2
return !ok
}
func main() {
t1 := &node{3,
&node{1,
&node{int: 1},
&node{int: 2}},
&node{8,
&node{int: 5},
&node{int: 13}}}
t2 := &node{-8,
&node{-3,
&node{-1,
&node{int: 1},
&node{int: 2}},
&node{int: 5}},
&node{int: 13}}
fmt.Println(sameFringe(t1, t2))
}
| import java.util.*;
class SameFringe
{
public interface Node<T extends Comparable<? super T>>
{
Node<T> getLeft();
Node<T> getRight();
boolean isLeaf();
T getData();
}
public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>
{
private final T data;
public SimpleNode<T> left;
public SimpleNode<T> right;
public SimpleNode(T data)
{ this(data, null, null); }
public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public Node<T> getLeft()
{ return left; }
public Node<T> getRight()
{ return right; }
public boolean isLeaf()
{ return ((left == null) && (right == null)); }
public T getData()
{ return data; }
public SimpleNode<T> addToTree(T data)
{
int cmp = data.compareTo(this.data);
if (cmp == 0)
throw new IllegalArgumentException("Same data!");
if (cmp < 0)
{
if (left == null)
return (left = new SimpleNode<T>(data));
return left.addToTree(data);
}
if (right == null)
return (right = new SimpleNode<T>(data));
return right.addToTree(data);
}
}
public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)
{
Stack<Node<T>> stack1 = new Stack<Node<T>>();
Stack<Node<T>> stack2 = new Stack<Node<T>>();
stack1.push(node1);
stack2.push(node2);
while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))
if (!node1.getData().equals(node2.getData()))
return false;
return (node1 == null) && (node2 == null);
}
private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)
{
while (!stack.isEmpty())
{
Node<T> node = stack.pop();
if (node.isLeaf())
return node;
Node<T> rightNode = node.getRight();
if (rightNode != null)
stack.push(rightNode);
Node<T> leftNode = node.getLeft();
if (leftNode != null)
stack.push(leftNode);
}
return null;
}
public static void main(String[] args)
{
SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));
SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));
SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));
System.out.print("Leaves for set 1: ");
simpleWalk(headNode1);
System.out.println();
System.out.print("Leaves for set 2: ");
simpleWalk(headNode2);
System.out.println();
System.out.print("Leaves for set 3: ");
simpleWalk(headNode3);
System.out.println();
System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2));
System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3));
}
public static void simpleWalk(Node<Integer> node)
{
if (node.isLeaf())
System.out.print(node.getData() + " ");
else
{
Node<Integer> left = node.getLeft();
if (left != null)
simpleWalk(left);
Node<Integer> right = node.getRight();
if (right != null)
simpleWalk(right);
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"github.com/micmonay/keybd_event"
"log"
"runtime"
"time"
)
func main() {
kb, err := keybd_event.NewKeyBonding()
if err != nil {
log.Fatal(err)
}
if runtime.GOOS == "linux" {
time.Sleep(2 * time.Second)
}
kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)
err = kb.Launching()
if err != nil {
log.Fatal(err)
}
}
| import java.awt.Robot
public static void type(String str){
Robot robot = new Robot();
for(char ch:str.toCharArray()){
if(Character.isUpperCase(ch)){
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress((int)ch);
robot.keyRelease((int)ch);
robot.keyRelease(KeyEvent.VK_SHIFT);
}else{
char upCh = Character.toUpperCase(ch);
robot.keyPress((int)upCh);
robot.keyRelease((int)upCh);
}
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import "fmt"
const (
empty = iota
black
white
)
const (
bqueen = 'B'
wqueen = 'W'
bbullet = '•'
wbullet = '◦'
)
type position struct{ i, j int }
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {
if m == 0 {
return true
}
placingBlack := true
for i := 0; i < n; i++ {
inner:
for j := 0; j < n; j++ {
pos := position{i, j}
for _, queen := range *pBlackQueens {
if queen == pos || !placingBlack && isAttacking(queen, pos) {
continue inner
}
}
for _, queen := range *pWhiteQueens {
if queen == pos || placingBlack && isAttacking(queen, pos) {
continue inner
}
}
if placingBlack {
*pBlackQueens = append(*pBlackQueens, pos)
placingBlack = false
} else {
*pWhiteQueens = append(*pWhiteQueens, pos)
if place(m-1, n, pBlackQueens, pWhiteQueens) {
return true
}
*pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
*pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]
placingBlack = true
}
}
}
if !placingBlack {
*pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
}
return false
}
func isAttacking(queen, pos position) bool {
if queen.i == pos.i {
return true
}
if queen.j == pos.j {
return true
}
if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {
return true
}
return false
}
func printBoard(n int, blackQueens, whiteQueens []position) {
board := make([]int, n*n)
for _, queen := range blackQueens {
board[queen.i*n+queen.j] = black
}
for _, queen := range whiteQueens {
board[queen.i*n+queen.j] = white
}
for i, b := range board {
if i != 0 && i%n == 0 {
fmt.Println()
}
switch b {
case black:
fmt.Printf("%c ", bqueen)
case white:
fmt.Printf("%c ", wqueen)
case empty:
if i%2 == 0 {
fmt.Printf("%c ", bbullet)
} else {
fmt.Printf("%c ", wbullet)
}
}
}
fmt.Println("\n")
}
func main() {
nms := [][2]int{
{2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
{5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
{6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
{7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
}
for _, nm := range nms {
n, m := nm[0], nm[1]
fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n)
var blackQueens, whiteQueens []position
if place(m, n, &blackQueens, &whiteQueens) {
printBoard(n, blackQueens, whiteQueens)
} else {
fmt.Println("No solution exists.\n")
}
}
}
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Peaceful {
enum Piece {
Empty,
Black,
White,
}
public static class Position {
public int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Position) {
Position pos = (Position) obj;
return pos.x == x && pos.y == y;
}
return false;
}
}
private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
boolean placingBlack = true;
for (int i = 0; i < n; ++i) {
inner:
for (int j = 0; j < n; ++j) {
Position pos = new Position(i, j);
for (Position queen : pBlackQueens) {
if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
for (Position queen : pWhiteQueens) {
if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
if (placingBlack) {
pBlackQueens.add(pos);
placingBlack = false;
} else {
pWhiteQueens.add(pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.remove(pBlackQueens.size() - 1);
pWhiteQueens.remove(pWhiteQueens.size() - 1);
placingBlack = true;
}
}
}
if (!placingBlack) {
pBlackQueens.remove(pBlackQueens.size() - 1);
}
return false;
}
private static boolean isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);
}
private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
Piece[] board = new Piece[n * n];
Arrays.fill(board, Piece.Empty);
for (Position queen : blackQueens) {
board[queen.x + n * queen.y] = Piece.Black;
}
for (Position queen : whiteQueens) {
board[queen.x + n * queen.y] = Piece.White;
}
for (int i = 0; i < board.length; ++i) {
if ((i != 0) && i % n == 0) {
System.out.println();
}
Piece b = board[i];
if (b == Piece.Black) {
System.out.print("B ");
} else if (b == Piece.White) {
System.out.print("W ");
} else {
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
System.out.print("• ");
} else {
System.out.print("◦ ");
}
}
}
System.out.println('\n');
}
public static void main(String[] args) {
List<Position> nms = List.of(
new Position(2, 1),
new Position(3, 1),
new Position(3, 2),
new Position(4, 1),
new Position(4, 2),
new Position(4, 3),
new Position(5, 1),
new Position(5, 2),
new Position(5, 3),
new Position(5, 4),
new Position(5, 5),
new Position(6, 1),
new Position(6, 2),
new Position(6, 3),
new Position(6, 4),
new Position(6, 5),
new Position(6, 6),
new Position(7, 1),
new Position(7, 2),
new Position(7, 3),
new Position(7, 4),
new Position(7, 5),
new Position(7, 6),
new Position(7, 7)
);
for (Position nm : nms) {
int m = nm.y;
int n = nm.x;
System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n);
List<Position> blackQueens = new ArrayList<>();
List<Position> whiteQueens = new ArrayList<>();
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens);
} else {
System.out.println("No solution exists.\n");
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
| while (true) {
System.out.println("SPAM");
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"bytes"
"fmt"
)
type symbolTable string
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
}
func (symbols symbolTable) decode(seq []byte) string {
chars := make([]byte, len(seq))
pad := []byte(symbols)
for i, x := range seq {
c := pad[x]
chars[i] = c
copy(pad[1:], pad[:x])
pad[0] = c
}
return string(chars)
}
func main() {
m := symbolTable("abcdefghijklmnopqrstuvwxyz")
for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
enc := m.encode(s)
dec := m.decode(enc)
fmt.Println(s, enc, dec)
if dec != s {
panic("Whoops!")
}
}
}
| import java.util.LinkedList;
import java.util.List;
public class MTF{
public static List<Integer> encode(String msg, String symTable){
List<Integer> output = new LinkedList<Integer>();
StringBuilder s = new StringBuilder(symTable);
for(char c : msg.toCharArray()){
int idx = s.indexOf("" + c);
output.add(idx);
s = s.deleteCharAt(idx).insert(0, c);
}
return output;
}
public static String decode(List<Integer> idxs, String symTable){
StringBuilder output = new StringBuilder();
StringBuilder s = new StringBuilder(symTable);
for(int idx : idxs){
char c = s.charAt(idx);
output = output.append(c);
s = s.deleteCharAt(idx).insert(0, c);
}
return output.toString();
}
private static void test(String toEncode, String symTable){
List<Integer> encoded = encode(toEncode, symTable);
System.out.println(toEncode + ": " + encoded);
String decoded = decode(encoded, symTable);
System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
}
public static void main(String[] args){
String symTable = "abcdefghijklmnopqrstuvwxyz";
test("broood", symTable);
test("bananaaa", symTable);
test("hiphophiphop", symTable);
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"log"
"github.com/jtblin/go-ldap-client"
)
func main() {
client := &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.example.com",
Port: 389,
GroupFilter: "(memberUid=%s)",
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect : %+v", err)
}
groups, err := client.GetGroupsOfUser("username")
if err != nil {
log.Fatalf("Error getting groups for user %s: %+v", "username", err)
}
log.Printf("Groups: %+v", groups)
}
| import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapSearchDemo {
public static void main(String[] args) throws IOException, LdapException, CursorException {
new LdapSearchDemo().demonstrateSearch();
}
private void demonstrateSearch() throws IOException, LdapException, CursorException {
try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) {
conn.bind("uid=admin,ou=system", "********");
search(conn, "*mil*");
conn.unBind();
}
}
private void search(LdapConnection connection, String uid) throws LdapException, CursorException {
String baseDn = "ou=users,o=mojo";
String filter = "(&(objectClass=person)(&(uid=" + uid + ")))";
SearchScope scope = SearchScope.SUBTREE;
String[] attributes = {"dn", "cn", "sn", "uid"};
int ksearch = 0;
EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);
while (cursor.next()) {
ksearch++;
Entry entry = cursor.get();
System.out.printf("Search entry %d = %s%n", ksearch, entry);
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | <package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
"log"
)
func matPrint(m mat.Matrix) {
fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze())
fmt.Printf("%13.10f\n", fa)
}
func main() {
var svd mat.SVD
a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})
ok := svd.Factorize(a, mat.SVDFull)
if !ok {
log.Fatal("Something went wrong!")
}
u := mat.NewDense(2, 2, nil)
svd.UTo(u)
fmt.Println("U:")
matPrint(u)
values := svd.Values(nil)
sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})
fmt.Println("\nΣ:")
matPrint(sigma)
vt := mat.NewDense(2, 2, nil)
svd.VTo(vt)
fmt.Println("\nVT:")
matPrint(vt)
}
| import Jama.Matrix;
public class SingularValueDecomposition {
public static void main(String[] args) {
double[][] matrixArray = {{3, 0}, {4, 5}};
var matrix = new Matrix(matrixArray);
var svd = matrix.svd();
svd.getU().print(0, 10);
svd.getS().print(0, 10);
svd.getV().print(0, 10);
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
)
func Float64IsInt(f float64) bool {
_, frac := math.Modf(f)
return frac == 0
}
func Float32IsInt(f float32) bool {
return Float64IsInt(float64(f))
}
func Complex128IsInt(c complex128) bool {
return imag(c) == 0 && Float64IsInt(real(c))
}
func Complex64IsInt(c complex64) bool {
return imag(c) == 0 && Float64IsInt(float64(real(c)))
}
type hasIsInt interface {
IsInt() bool
}
var bigIntT = reflect.TypeOf((*big.Int)(nil))
func IsInt(i interface{}) bool {
if ci, ok := i.(hasIsInt); ok {
return ci.IsInt()
}
switch v := reflect.ValueOf(i); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return true
case reflect.Float32, reflect.Float64:
return Float64IsInt(v.Float())
case reflect.Complex64, reflect.Complex128:
return Complex128IsInt(v.Complex())
case reflect.String:
if r, ok := new(big.Rat).SetString(v.String()); ok {
return r.IsInt()
}
case reflect.Ptr:
if v.Type() == bigIntT {
return true
}
}
return false
}
type intbased int16
type complexbased complex64
type customIntegerType struct {
}
func (customIntegerType) IsInt() bool { return true }
func (customIntegerType) String() string { return "<…>" }
func main() {
hdr := fmt.Sprintf("%27s %-6s %s\n", "Input", "IsInt", "Type")
show2 := func(t bool, i interface{}, args ...interface{}) {
istr := fmt.Sprint(i)
fmt.Printf("%27s %-6t %T ", istr, t, i)
fmt.Println(args...)
}
show := func(i interface{}, args ...interface{}) {
show2(IsInt(i), i, args...)
}
fmt.Print("Using Float64IsInt with float64:\n", hdr)
neg1 := -1.
for _, f := range []float64{
0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,
math.Pi,
math.MinInt64, math.MaxUint64,
math.SmallestNonzeroFloat64, math.MaxFloat64,
math.NaN(), math.Inf(1), math.Inf(-1),
} {
show2(Float64IsInt(f), f)
}
fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr)
for _, c := range []complex128{
3, 1i, 0i, 3.4,
} {
show2(Complex128IsInt(c), c)
}
fmt.Println("\nUsing reflection:")
fmt.Print(hdr)
show("hello")
show(math.MaxFloat64)
show("9e100")
f := new(big.Float)
show(f)
f.SetString("1e-3000")
show(f)
show("(4+0i)", "(complex strings not parsed)")
show(4 + 0i)
show(rune('§'), "or rune")
show(byte('A'), "or byte")
var t1 intbased = 5200
var t2a, t2b complexbased = 5 + 0i, 5 + 1i
show(t1)
show(t2a)
show(t2b)
x := uintptr(unsafe.Pointer(&t2b))
show(x)
show(math.MinInt32)
show(uint64(math.MaxUint64))
b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0)
show(b)
r := new(big.Rat)
show(r)
r.SetString("2/3")
show(r)
show(r.SetFrac(b, new(big.Int).SetInt64(9)))
show("12345/5")
show(new(customIntegerType))
}
| import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isBigInteger(BigDecimal bd) {
try {
bd.toBigIntegerExact();
return true;
} catch (ArithmeticException ex) {
return false;
}
}
private static class Rational {
long num;
long denom;
Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
boolean isLong() {
return num % denom == 0;
}
@Override
public String toString() {
return String.format("%s/%s", num, denom);
}
}
private static class Complex {
double real;
double imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
boolean isLong() {
return TestIntegerness.isLong(real) && imag == 0.0;
}
@Override
public String toString() {
if (imag >= 0.0) {
return String.format("%s + %si", real, imag);
}
return String.format("%s - %si", real, imag);
}
}
public static void main(String[] args) {
List<Double> da = List.of(25.000000, 24.999999, 25.000100);
for (Double d : da) {
boolean exact = isLong(d);
System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an");
}
System.out.println();
double tolerance = 0.00001;
System.out.printf("With a tolerance of %.5f:%n", tolerance);
for (Double d : da) {
boolean fuzzy = isLong(d, tolerance);
System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an");
}
System.out.println();
List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
for (Double f : fa) {
boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an");
}
System.out.println();
List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
for (Complex c : ca) {
boolean exact = c.isLong();
System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an");
}
System.out.println();
List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
for (Rational r : ra) {
boolean exact = r.isLong();
System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an");
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
| import java.util.Scanner;
import java.io.*;
public class Program {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");
Scanner sc = new Scanner(p.getInputStream());
while (sc.hasNext()) System.out.println(sc.nextLine());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"fmt"
"math"
)
type vector [3]float64
type matrix [3]vector
func norm(v vector) float64 {
return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
}
func normalize(v vector) vector {
length := norm(v)
return vector{v[0] / length, v[1] / length, v[2] / length}
}
func dotProduct(v1, v2 vector) float64 {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}
func crossProduct(v1, v2 vector) vector {
return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}
}
func getAngle(v1, v2 vector) float64 {
return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))
}
func matrixMultiply(m matrix, v vector) vector {
return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}
}
func aRotate(p, v vector, a float64) vector {
ca, sa := math.Cos(a), math.Sin(a)
t := 1 - ca
x, y, z := v[0], v[1], v[2]
r := matrix{
{ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},
{x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},
{z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},
}
return matrixMultiply(r, p)
}
func main() {
v1 := vector{5, -6, 4}
v2 := vector{8, 5, -30}
a := getAngle(v1, v2)
cp := crossProduct(v1, v2)
ncp := normalize(cp)
np := aRotate(v1, ncp, a)
fmt.Println(np)
}
|
class Vector{
private double x, y, z;
public Vector(double x1,double y1,double z1){
x = x1;
y = y1;
z = z1;
}
void printVector(int x,int y){
text("( " + this.x + " ) \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y);
}
public double norm() {
return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
}
public Vector normalize(){
double length = this.norm();
return new Vector(this.x / length, this.y / length, this.z / length);
}
public double dotProduct(Vector v2) {
return this.x*v2.x + this.y*v2.y + this.z*v2.z;
}
public Vector crossProduct(Vector v2) {
return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);
}
public double getAngle(Vector v2) {
return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));
}
public Vector aRotate(Vector v, double a) {
double ca = Math.cos(a), sa = Math.sin(a);
double t = 1.0 - ca;
double x = v.x, y = v.y, z = v.z;
Vector[] r = {
new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),
new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),
new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)
};
return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));
}
}
void setup(){
Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);
double a = v1.getAngle(v2);
Vector cp = v1.crossProduct(v2);
Vector normCP = cp.normalize();
Vector np = v1.aRotate(normCP,a);
size(1200,600);
fill(#000000);
textSize(30);
text("v1 = ",10,100);
v1.printVector(60,100);
text("v2 = ",10,150);
v2.printVector(60,150);
text("rV = ",10,200);
np.printVector(60,200);
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"math"
)
type vector [3]float64
type matrix [3]vector
func norm(v vector) float64 {
return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
}
func normalize(v vector) vector {
length := norm(v)
return vector{v[0] / length, v[1] / length, v[2] / length}
}
func dotProduct(v1, v2 vector) float64 {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}
func crossProduct(v1, v2 vector) vector {
return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}
}
func getAngle(v1, v2 vector) float64 {
return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))
}
func matrixMultiply(m matrix, v vector) vector {
return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}
}
func aRotate(p, v vector, a float64) vector {
ca, sa := math.Cos(a), math.Sin(a)
t := 1 - ca
x, y, z := v[0], v[1], v[2]
r := matrix{
{ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},
{x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},
{z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},
}
return matrixMultiply(r, p)
}
func main() {
v1 := vector{5, -6, 4}
v2 := vector{8, 5, -30}
a := getAngle(v1, v2)
cp := crossProduct(v1, v2)
ncp := normalize(cp)
np := aRotate(v1, ncp, a)
fmt.Println(np)
}
|
class Vector{
private double x, y, z;
public Vector(double x1,double y1,double z1){
x = x1;
y = y1;
z = z1;
}
void printVector(int x,int y){
text("( " + this.x + " ) \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y);
}
public double norm() {
return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
}
public Vector normalize(){
double length = this.norm();
return new Vector(this.x / length, this.y / length, this.z / length);
}
public double dotProduct(Vector v2) {
return this.x*v2.x + this.y*v2.y + this.z*v2.z;
}
public Vector crossProduct(Vector v2) {
return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);
}
public double getAngle(Vector v2) {
return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));
}
public Vector aRotate(Vector v, double a) {
double ca = Math.cos(a), sa = Math.sin(a);
double t = 1.0 - ca;
double x = v.x, y = v.y, z = v.z;
Vector[] r = {
new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),
new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),
new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)
};
return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));
}
}
void setup(){
Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);
double a = v1.getAngle(v2);
Vector cp = v1.crossProduct(v2);
Vector normCP = cp.normalize();
Vector np = v1.aRotate(normCP,a);
size(1200,600);
fill(#000000);
textSize(30);
text("v1 = ",10,100);
v1.printVector(60,100);
text("v2 = ",10,150);
v2.printVector(60,150);
text("rV = ",10,200);
np.printVector(60,200);
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/xsd"
"io/ioutil"
"log"
"os"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
xsdfile := "shiporder.xsd"
f, err := os.Open(xsdfile)
check(err)
defer f.Close()
buf, err := ioutil.ReadAll(f)
check(err)
s, err := xsd.Parse(buf)
check(err)
defer s.Free()
xmlfile := "shiporder.xml"
f2, err := os.Open(xmlfile)
check(err)
defer f2.Close()
buf2, err := ioutil.ReadAll(f2)
check(err)
d, err := libxml2.Parse(buf2)
check(err)
if err := s.Validate(d); err != nil {
for _, e := range err.(xsd.SchemaValidationError).Errors() {
log.Printf("error: %s", e.Error())
}
return
}
fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!")
}
| import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.ws.Holder;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XmlValidation {
public static void main(String... args) throws MalformedURLException {
URL schemaLocation = new URL("http:
URL documentLocation = new URL("http:
if (validate(schemaLocation, documentLocation)) {
System.out.println("document is valid");
} else {
System.out.println("document is invalid");
}
}
public static boolean minimalValidate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.validate(new StreamSource(documentLocation.toString()));
return true;
} catch (Exception e) {
return false;
}
}
public static boolean validate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
final Holder<Boolean> valid = new Holder<>(true);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.setErrorHandler(new ErrorHandler(){
@Override
public void warning(SAXParseException exception) {
System.out.println("warning: " + exception.getMessage());
}
@Override
public void error(SAXParseException exception) {
System.out.println("error: " + exception.getMessage());
valid.value = false;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatal error: " + exception.getMessage());
throw exception;
}});
validator.validate(new StreamSource(documentLocation.toString()));
return valid.value;
} catch (SAXException e) {
return false;
} catch (Exception e) {
System.err.println(e);
return false;
}
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"sort"
)
type Node struct {
val int
back *Node
}
func lis (n []int) (result []int) {
var pileTops []*Node
for _, x := range n {
j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
node := &Node{ x, nil }
if j != 0 { node.back = pileTops[j-1] }
if j != len(pileTops) {
pileTops[j] = node
} else {
pileTops = append(pileTops, node)
}
}
if len(pileTops) == 0 { return []int{} }
for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
result = append(result, node.val)
}
for i := 0; i < len(result)/2; i++ {
result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
}
return
}
func main() {
for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
}
}
| import java.util.*;
public class LIS {
public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {
List<Node<E>> pileTops = new ArrayList<Node<E>>();
for (E x : n) {
Node<E> node = new Node<E>();
node.value = x;
int i = Collections.binarySearch(pileTops, node);
if (i < 0) i = ~i;
if (i != 0)
node.pointer = pileTops.get(i-1);
if (i != pileTops.size())
pileTops.set(i, node);
else
pileTops.add(node);
}
List<E> result = new ArrayList<E>();
for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);
node != null; node = node.pointer)
result.add(node.value);
Collections.reverse(result);
return result;
}
private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {
public E value;
public Node<E> pointer;
public int compareTo(Node<E> y) { return value.compareTo(y.value); }
}
public static void main(String[] args) {
List<Integer> d = Arrays.asList(3,2,6,4,5,1);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func (v *vector) normalize() {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
type sphere struct {
cx, cy, cz int
r int
}
func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {
x -= s.cx
y -= s.cy
if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {
zsqrt := math.Sqrt(float64(zsq))
return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true
}
return 0, 0, false
}
func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {
w, h := pos.r*4, pos.r*3
bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)
img := image.NewGray(bounds)
vec := new(vector)
for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {
for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {
zb1, zb2, hit := pos.hit(x, y)
if !hit {
continue
}
zs1, zs2, hit := neg.hit(x, y)
if hit {
if zs1 > zb1 {
hit = false
} else if zs2 > zb2 {
continue
}
}
if hit {
vec[0] = float64(neg.cx - x)
vec[1] = float64(neg.cy - y)
vec[2] = float64(neg.cz) - zs2
} else {
vec[0] = float64(x - pos.cx)
vec[1] = float64(y - pos.cy)
vec[2] = zb1 - float64(pos.cz)
}
vec.normalize()
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
return img
}
func main() {
dir := &vector{20, -40, -10}
dir.normalize()
pos := &sphere{0, 0, 0, 120}
neg := &sphere{-90, -90, -30, 100}
img := deathStar(pos, neg, 1.5, .2, dir)
f, err := os.Create("dstar.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.shape.MeshView;
import javafx.scene.shape.TriangleMesh;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class DeathStar extends Application {
private static final int DIVISION = 200;
float radius = 300;
@Override
public void start(Stage primaryStage) throws Exception {
Point3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);
final TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);
MeshView a = new MeshView(triangleMesh);
a.setTranslateY(radius);
a.setTranslateX(radius);
a.setRotationAxis(Rotate.Y_AXIS);
Scene scene = new Scene(new Group(a));
primaryStage.setScene(scene);
primaryStage.show();
}
static TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {
Rotate rotate = new Rotate(180, centerOtherSphere);
final int div2 = division / 2;
final int nPoints = division * (div2 - 1) + 2;
final int nTPoints = (division + 1) * (div2 - 1) + division * 2;
final int nFaces = division * (div2 - 2) * 2 + division * 2;
final float rDiv = 1.f / division;
float points[] = new float[nPoints * 3];
float tPoints[] = new float[nTPoints * 2];
int faces[] = new int[nFaces * 6];
int pPos = 0, tPos = 0;
for (int y = 0; y < div2 - 1; ++y) {
float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;
float sin_va = (float) Math.sin(va);
float cos_va = (float) Math.cos(va);
float ty = 0.5f + sin_va * 0.5f;
for (int i = 0; i < division; ++i) {
double a = rDiv * i * 2 * (float) Math.PI;
float hSin = (float) Math.sin(a);
float hCos = (float) Math.cos(a);
points[pPos + 0] = hSin * cos_va * radius;
points[pPos + 2] = hCos * cos_va * radius;
points[pPos + 1] = sin_va * radius;
final Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);
double distance = centerOtherSphere.distance(point3D);
if (distance <= radius) {
Point3D subtract = centerOtherSphere.subtract(point3D);
Point3D transform = rotate.transform(subtract);
points[pPos + 0] = (float) transform.getX();
points[pPos + 1] = (float) transform.getY();
points[pPos + 2] = (float) transform.getZ();
}
tPoints[tPos + 0] = 1 - rDiv * i;
tPoints[tPos + 1] = ty;
pPos += 3;
tPos += 2;
}
tPoints[tPos + 0] = 0;
tPoints[tPos + 1] = ty;
tPos += 2;
}
points[pPos + 0] = 0;
points[pPos + 1] = -radius;
points[pPos + 2] = 0;
points[pPos + 3] = 0;
points[pPos + 4] = radius;
points[pPos + 5] = 0;
pPos += 6;
int pS = (div2 - 1) * division;
float textureDelta = 1.f / 256;
for (int i = 0; i < division; ++i) {
tPoints[tPos + 0] = rDiv * (0.5f + i);
tPoints[tPos + 1] = textureDelta;
tPos += 2;
}
for (int i = 0; i < division; ++i) {
tPoints[tPos + 0] = rDiv * (0.5f + i);
tPoints[tPos + 1] = 1 - textureDelta;
tPos += 2;
}
int fIndex = 0;
for (int y = 0; y < div2 - 2; ++y) {
for (int x = 0; x < division; ++x) {
int p0 = y * division + x;
int p1 = p0 + 1;
int p2 = p0 + division;
int p3 = p1 + division;
int t0 = p0 + y;
int t1 = t0 + 1;
int t2 = t0 + division + 1;
int t3 = t1 + division + 1;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;
faces[fIndex + 3] = t1;
faces[fIndex + 4] = p2;
faces[fIndex + 5] = t2;
fIndex += 6;
faces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;
faces[fIndex + 1] = t3;
faces[fIndex + 2] = p2;
faces[fIndex + 3] = t2;
faces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;
faces[fIndex + 5] = t1;
fIndex += 6;
}
}
int p0 = pS;
int tB = (div2 - 1) * (division + 1);
for (int x = 0; x < division; ++x) {
int p2 = x, p1 = x + 1, t0 = tB + x;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1 == division ? 0 : p1;
faces[fIndex + 3] = p1;
faces[fIndex + 4] = p2;
faces[fIndex + 5] = p2;
fIndex += 6;
}
p0 = p0 + 1;
tB = tB + division;
int pB = (div2 - 2) * division;
for (int x = 0; x < division; ++x) {
int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;
int t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1;
faces[fIndex + 3] = t1;
faces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;
faces[fIndex + 5] = t2;
fIndex += 6;
}
TriangleMesh m = new TriangleMesh();
m.getPoints().setAll(points);
m.getTexCoords().setAll(tPoints);
m.getFaces().setAll(faces);
return m;
}
public static void main(String[] args) {
launch(args);
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
)
const luckySize = 60000
var luckyOdd = make([]int, luckySize)
var luckyEven = make([]int, luckySize)
func init() {
for i := 0; i < luckySize; i++ {
luckyOdd[i] = i*2 + 1
luckyEven[i] = i*2 + 2
}
}
func filterLuckyOdd() {
for n := 2; n < len(luckyOdd); n++ {
m := luckyOdd[n-1]
end := (len(luckyOdd)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyOdd[j:], luckyOdd[j+1:])
luckyOdd = luckyOdd[:len(luckyOdd)-1]
}
}
}
func filterLuckyEven() {
for n := 2; n < len(luckyEven); n++ {
m := luckyEven[n-1]
end := (len(luckyEven)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyEven[j:], luckyEven[j+1:])
luckyEven = luckyEven[:len(luckyEven)-1]
}
}
}
func printSingle(j int, odd bool) error {
if odd {
if j >= len(luckyOdd) {
return fmt.Errorf("the argument, %d, is too big", j)
}
fmt.Println("Lucky number", j, "=", luckyOdd[j-1])
} else {
if j >= len(luckyEven) {
return fmt.Errorf("the argument, %d, is too big", j)
}
fmt.Println("Lucky even number", j, "=", luckyEven[j-1])
}
return nil
}
func printRange(j, k int, odd bool) error {
if odd {
if k >= len(luckyOdd) {
return fmt.Errorf("the argument, %d, is too big", k)
}
fmt.Println("Lucky numbers", j, "to", k, "are:")
fmt.Println(luckyOdd[j-1 : k])
} else {
if k >= len(luckyEven) {
return fmt.Errorf("the argument, %d, is too big", k)
}
fmt.Println("Lucky even numbers", j, "to", k, "are:")
fmt.Println(luckyEven[j-1 : k])
}
return nil
}
func printBetween(j, k int, odd bool) error {
var r []int
if odd {
max := luckyOdd[len(luckyOdd)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument, %d or %d, is too big", j, k)
}
for _, num := range luckyOdd {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky numbers between", j, "and", k, "are:")
fmt.Println(r)
} else {
max := luckyEven[len(luckyEven)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument, %d or %d, is too big", j, k)
}
for _, num := range luckyEven {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky even numbers between", j, "and", k, "are:")
fmt.Println(r)
}
return nil
}
func main() {
nargs := len(os.Args)
if nargs < 2 || nargs > 4 {
log.Fatal("there must be between 1 and 3 command line arguments")
}
filterLuckyOdd()
filterLuckyEven()
j, err := strconv.Atoi(os.Args[1])
if err != nil || j < 1 {
log.Fatalf("first argument, %s, must be a positive integer", os.Args[1])
}
if nargs == 2 {
if err := printSingle(j, true); err != nil {
log.Fatal(err)
}
return
}
if nargs == 3 {
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatalf("second argument, %s, must be an integer", os.Args[2])
}
if k >= 0 {
if j > k {
log.Fatalf("second argument, %d, can't be less than first, %d", k, j)
}
if err := printRange(j, k, true); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j)
}
if err := printBetween(j, l, true); err != nil {
log.Fatal(err)
}
}
return
}
var odd bool
switch lucky := strings.ToLower(os.Args[3]); lucky {
case "lucky":
odd = true
case "evenlucky":
odd = false
default:
log.Fatalf("third argument, %s, is invalid", os.Args[3])
}
if os.Args[2] == "," {
if err := printSingle(j, odd); err != nil {
log.Fatal(err)
}
return
}
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatal("second argument must be an integer or a comma")
}
if k >= 0 {
if j > k {
log.Fatalf("second argument, %d, can't be less than first, %d", k, j)
}
if err := printRange(j, k, odd); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j)
}
if err := printBetween(j, l, odd); err != nil {
log.Fatal(err)
}
}
}
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LuckyNumbers {
private static int MAX = 200000;
private static List<Integer> luckyEven = luckyNumbers(MAX, true);
private static List<Integer> luckyOdd = luckyNumbers(MAX, false);
public static void main(String[] args) {
if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) {
int n = Integer.parseInt(args[0]);
System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1));
}
else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) {
int n = Integer.parseInt(args[0]);
System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1));
}
else if ( args.length == 2 || args.length == 3 ) {
int j = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) {
System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k));
}
else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) {
System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k));
}
else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) {
int n = Collections.binarySearch(luckyOdd, j);
int m = Collections.binarySearch(luckyOdd, -k);
System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) {
int n = Collections.binarySearch(luckyEven, j);
int m = Collections.binarySearch(luckyEven, -k);
System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
}
}
private static List<Integer> luckyNumbers(int max, boolean even) {
List<Integer> luckyList = new ArrayList<>();
for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {
luckyList.add(i);
}
int start = 1;
boolean removed = true;
while ( removed ) {
removed = false;
int increment = luckyList.get(start);
List<Integer> remove = new ArrayList<>();
for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {
remove.add(0, i);
removed = true;
}
for ( int i : remove ) {
luckyList.remove(i);
}
start++;
}
return luckyList;
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import (
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strings"
"time"
"unicode"
)
type Item struct {
Stamp time.Time
Name string
Tags []string `json:",omitempty"`
Notes string `json:",omitempty"`
}
func (i *Item) String() string {
s := i.Stamp.Format(time.ANSIC) + "\n Name: " + i.Name
if len(i.Tags) > 0 {
s = fmt.Sprintf("%s\n Tags: %v", s, i.Tags)
}
if i.Notes > "" {
s += "\n Notes: " + i.Notes
}
return s
}
type db []*Item
func (d db) Len() int { return len(d) }
func (d db) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) }
const fn = "sdb.json"
func main() {
if len(os.Args) == 1 {
latest()
return
}
switch os.Args[1] {
case "add":
add()
case "latest":
latest()
case "tags":
tags()
case "all":
all()
case "help":
help()
default:
usage("unrecognized command")
}
}
func usage(err string) {
if err > "" {
fmt.Println(err)
}
fmt.Println(`usage: sdb [command] [data]
where command is one of add, latest, tags, all, or help.`)
}
func help() {
usage("")
fmt.Println(`
Commands must be in lower case.
If no command is specified, the default command is latest.
Latest prints the latest item.
All prints all items in chronological order.
Tags prints the lastest item for each tag.
Help prints this message.
Add adds data as a new record. The format is,
name [tags] [notes]
Name is the name of the item and is required for the add command.
Tags are optional. A tag is a single word.
A single tag can be specified without enclosing brackets.
Multiple tags can be specified by enclosing them in square brackets.
Text remaining after tags is taken as notes. Notes do not have to be
enclosed in quotes or brackets. The brackets above are only showing
that notes are optional.
Quotes may be useful however--as recognized by your operating system shell
or command line--to allow entry of arbitrary text. In particular, quotes
or escape characters may be needed to prevent the shell from trying to
interpret brackets or other special characters.
Examples:
sdb add Bookends
sdb add Bookends rock my favorite
sdb add Bookends [rock folk]
sdb add Bookends [] "Simon & Garfunkel"
sdb add "Simon&Garfunkel [artist]"
As shown in the last example, if you use features of your shell to pass
all data as a single string, the item name and tags will still be identified
by separating whitespace.
The database is stored in JSON format in the file "sdb.json"
`)
}
func load() (db, bool) {
d, f, ok := open()
if ok {
f.Close()
if len(d) == 0 {
fmt.Println("no items")
ok = false
}
}
return d, ok
}
func open() (d db, f *os.File, ok bool) {
var err error
f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
fmt.Println("cant open??")
fmt.Println(err)
return
}
jd := json.NewDecoder(f)
err = jd.Decode(&d)
if err != nil && err != io.EOF {
fmt.Println(err)
f.Close()
return
}
ok = true
return
}
func latest() {
d, ok := load()
if !ok {
return
}
sort.Sort(d)
fmt.Println(d[len(d)-1])
}
func all() {
d, ok := load()
if !ok {
return
}
sort.Sort(d)
for _, i := range d {
fmt.Println("-----------------------------------")
fmt.Println(i)
}
fmt.Println("-----------------------------------")
}
func tags() {
d, ok := load()
if !ok {
return
}
latest := make(map[string]*Item)
for _, item := range d {
for _, tag := range item.Tags {
li, ok := latest[tag]
if !ok || item.Stamp.After(li.Stamp) {
latest[tag] = item
}
}
}
type itemTags struct {
item *Item
tags []string
}
inv := make(map[*Item][]string)
for tag, item := range latest {
inv[item] = append(inv[item], tag)
}
li := make(db, len(inv))
i := 0
for item := range inv {
li[i] = item
i++
}
sort.Sort(li)
for _, item := range li {
tags := inv[item]
fmt.Println("-----------------------------------")
fmt.Println("Latest item with tags", tags)
fmt.Println(item)
}
fmt.Println("-----------------------------------")
}
func add() {
if len(os.Args) < 3 {
usage("add command requires data")
return
} else if len(os.Args) == 3 {
add1()
} else {
add4()
}
}
func add1() {
data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace)
if data == "" {
usage("invalid name")
return
}
sep := strings.IndexFunc(data, unicode.IsSpace)
if sep < 0 {
addItem(data, nil, "")
return
}
name := data[:sep]
data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace)
if data == "" {
addItem(name, nil, "")
return
}
if data[0] == '[' {
sep = strings.Index(data, "]")
if sep < 0 {
addItem(name, strings.Fields(data[1:]), "")
} else {
addItem(name, strings.Fields(data[1:sep]),
strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))
}
return
}
sep = strings.IndexFunc(data, unicode.IsSpace)
if sep < 0 {
addItem(name, []string{data}, "")
} else {
addItem(name, []string{data[:sep]},
strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))
}
}
func add4() {
name := os.Args[2]
tag1 := os.Args[3]
if tag1[0] != '[' {
addItem(name, []string{tag1}, strings.Join(os.Args[4:], " "))
return
}
if tag1[len(tag1)-1] == ']' {
addItem(name, strings.Fields(tag1[1:len(tag1)-1]),
strings.Join(os.Args[4:], " "))
return
}
var tags []string
if tag1 > "[" {
tags = []string{tag1[1:]}
}
for x, tag := range os.Args[4:] {
if tag[len(tag)-1] != ']' {
tags = append(tags, tag)
} else {
if tag > "]" {
tags = append(tags, tag[:len(tag)-1])
}
addItem(name, tags, strings.Join(os.Args[5+x:], " "))
return
}
}
addItem(name, tags, "")
}
func addItem(name string, tags []string, notes string) {
db, f, ok := open()
if !ok {
return
}
defer f.Close()
db = append(db, &Item{time.Now(), name, tags, notes})
sort.Sort(db)
js, err := json.MarshalIndent(db, "", " ")
if err != nil {
fmt.Println(err)
return
}
if _, err = f.Seek(0, 0); err != nil {
fmt.Println(err)
return
}
f.Truncate(0)
if _, err = f.Write(js); err != nil {
fmt.Println(err)
}
}
| import java.io.*;
import java.text.*;
import java.util.*;
public class SimpleDatabase {
final static String filename = "simdb.csv";
public static void main(String[] args) {
if (args.length < 1 || args.length > 3) {
printUsage();
return;
}
switch (args[0].toLowerCase()) {
case "add":
addItem(args);
break;
case "latest":
printLatest(args);
break;
case "all":
printAll();
break;
default:
printUsage();
break;
}
}
private static class Item implements Comparable<Item>{
final String name;
final String date;
final String category;
Item(String n, String d, String c) {
name = n;
date = d;
category = c;
}
@Override
public int compareTo(Item item){
return date.compareTo(item.date);
}
@Override
public String toString() {
return String.format("%s,%s,%s%n", name, date, category);
}
}
private static void addItem(String[] input) {
if (input.length < 2) {
printUsage();
return;
}
List<Item> db = load();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
String cat = (input.length == 3) ? input[2] : "none";
db.add(new Item(input[1], date, cat));
store(db);
}
private static void printLatest(String[] a) {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
if (a.length == 2) {
for (Item item : db)
if (item.category.equals(a[1]))
System.out.println(item);
} else {
System.out.println(db.get(0));
}
}
private static void printAll() {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
for (Item item : db)
System.out.println(item);
}
private static List<Item> load() {
List<Item> db = new ArrayList<>();
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNext()) {
String[] item = sc.nextLine().split(",");
db.add(new Item(item[0], item[1], item[2]));
}
} catch (IOException e) {
System.out.println(e);
}
return db;
}
private static void store(List<Item> db) {
try (FileWriter fw = new FileWriter(filename)) {
for (Item item : db)
fw.write(item.toString());
} catch (IOException e) {
System.out.println(e);
}
}
private static void printUsage() {
System.out.println("Usage:");
System.out.println(" simdb cmd [categoryName]");
System.out.println(" add add item, followed by optional category");
System.out.println(" latest print last added item(s), followed by "
+ "optional category");
System.out.println(" all print all");
System.out.println(" For instance: add \"some item name\" "
+ "\"some category name\"");
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
)
func hough(im image.Image, ntx, mry int) draw.Image {
nimx := im.Bounds().Max.X
mimy := im.Bounds().Max.Y
him := image.NewGray(image.Rect(0, 0, ntx, mry))
draw.Draw(him, him.Bounds(), image.NewUniform(color.White),
image.Point{}, draw.Src)
rmax := math.Hypot(float64(nimx), float64(mimy))
dr := rmax / float64(mry/2)
dth := math.Pi / float64(ntx)
for jx := 0; jx < nimx; jx++ {
for iy := 0; iy < mimy; iy++ {
col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)
if col.Y == 255 {
continue
}
for jtx := 0; jtx < ntx; jtx++ {
th := dth * float64(jtx)
r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)
iry := mry/2 - int(math.Floor(r/dr+.5))
col = him.At(jtx, iry).(color.Gray)
if col.Y > 0 {
col.Y--
him.SetGray(jtx, iry, col)
}
}
}
}
return him
}
func main() {
f, err := os.Open("Pentagon.png")
if err != nil {
fmt.Println(err)
return
}
pent, err := png.Decode(f)
if err != nil {
fmt.Println(err)
return
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
h := hough(pent, 460, 360)
if f, err = os.Create("hough.png"); err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, h); err != nil {
fmt.Println(err)
}
if cErr := f.Close(); cErr != nil && err == nil {
fmt.Println(err)
}
}
| import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
public class HoughTransform
{
public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)
{
int width = inputData.width;
int height = inputData.height;
int maxRadius = (int)Math.ceil(Math.hypot(width, height));
int halfRAxisSize = rAxisSize >>> 1;
ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);
double[] sinTable = new double[thetaAxisSize];
double[] cosTable = new double[thetaAxisSize];
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double thetaRadians = theta * Math.PI / thetaAxisSize;
sinTable[theta] = Math.sin(thetaRadians);
cosTable[theta] = Math.cos(thetaRadians);
}
for (int y = height - 1; y >= 0; y--)
{
for (int x = width - 1; x >= 0; x--)
{
if (inputData.contrast(x, y, minContrast))
{
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double r = cosTable[theta] * x + sinTable[theta] * y;
int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;
outputData.accumulate(theta, rScaled, 1);
}
}
}
}
return outputData;
}
public static class ArrayData
{
public final int[] dataArray;
public final int width;
public final int height;
public ArrayData(int width, int height)
{
this(new int[width * height], width, height);
}
public ArrayData(int[] dataArray, int width, int height)
{
this.dataArray = dataArray;
this.width = width;
this.height = height;
}
public int get(int x, int y)
{ return dataArray[y * width + x]; }
public void set(int x, int y, int value)
{ dataArray[y * width + x] = value; }
public void accumulate(int x, int y, int delta)
{ set(x, y, get(x, y) + delta); }
public boolean contrast(int x, int y, int minContrast)
{
int centerValue = get(x, y);
for (int i = 8; i >= 0; i--)
{
if (i == 4)
continue;
int newx = x + (i % 3) - 1;
int newy = y + (i / 3) - 1;
if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))
continue;
if (Math.abs(get(newx, newy) - centerValue) >= minContrast)
return true;
}
return false;
}
public int getMax()
{
int max = dataArray[0];
for (int i = width * height - 1; i > 0; i--)
if (dataArray[i] > max)
max = dataArray[i];
return max;
}
}
public static ArrayData getArrayDataFromImage(String filename) throws IOException
{
BufferedImage inputImage = ImageIO.read(new File(filename));
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
ArrayData arrayData = new ArrayData(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgbValue = rgbData[y * width + x];
rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
arrayData.set(x, height - 1 - y, rgbValue);
}
}
return arrayData;
}
public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException
{
int max = arrayData.getMax();
BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < arrayData.height; y++)
{
for (int x = 0; x < arrayData.width; x++)
{
int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);
outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);
}
}
ImageIO.write(outputImage, "PNG", new File(filename));
return;
}
public static void main(String[] args) throws IOException
{
ArrayData inputData = getArrayDataFromImage(args[0]);
int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);
ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);
writeOutputImage(args[1], outputData);
return;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
)
func hough(im image.Image, ntx, mry int) draw.Image {
nimx := im.Bounds().Max.X
mimy := im.Bounds().Max.Y
him := image.NewGray(image.Rect(0, 0, ntx, mry))
draw.Draw(him, him.Bounds(), image.NewUniform(color.White),
image.Point{}, draw.Src)
rmax := math.Hypot(float64(nimx), float64(mimy))
dr := rmax / float64(mry/2)
dth := math.Pi / float64(ntx)
for jx := 0; jx < nimx; jx++ {
for iy := 0; iy < mimy; iy++ {
col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)
if col.Y == 255 {
continue
}
for jtx := 0; jtx < ntx; jtx++ {
th := dth * float64(jtx)
r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)
iry := mry/2 - int(math.Floor(r/dr+.5))
col = him.At(jtx, iry).(color.Gray)
if col.Y > 0 {
col.Y--
him.SetGray(jtx, iry, col)
}
}
}
}
return him
}
func main() {
f, err := os.Open("Pentagon.png")
if err != nil {
fmt.Println(err)
return
}
pent, err := png.Decode(f)
if err != nil {
fmt.Println(err)
return
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
h := hough(pent, 460, 360)
if f, err = os.Create("hough.png"); err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, h); err != nil {
fmt.Println(err)
}
if cErr := f.Close(); cErr != nil && err == nil {
fmt.Println(err)
}
}
| import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
public class HoughTransform
{
public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)
{
int width = inputData.width;
int height = inputData.height;
int maxRadius = (int)Math.ceil(Math.hypot(width, height));
int halfRAxisSize = rAxisSize >>> 1;
ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);
double[] sinTable = new double[thetaAxisSize];
double[] cosTable = new double[thetaAxisSize];
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double thetaRadians = theta * Math.PI / thetaAxisSize;
sinTable[theta] = Math.sin(thetaRadians);
cosTable[theta] = Math.cos(thetaRadians);
}
for (int y = height - 1; y >= 0; y--)
{
for (int x = width - 1; x >= 0; x--)
{
if (inputData.contrast(x, y, minContrast))
{
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double r = cosTable[theta] * x + sinTable[theta] * y;
int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;
outputData.accumulate(theta, rScaled, 1);
}
}
}
}
return outputData;
}
public static class ArrayData
{
public final int[] dataArray;
public final int width;
public final int height;
public ArrayData(int width, int height)
{
this(new int[width * height], width, height);
}
public ArrayData(int[] dataArray, int width, int height)
{
this.dataArray = dataArray;
this.width = width;
this.height = height;
}
public int get(int x, int y)
{ return dataArray[y * width + x]; }
public void set(int x, int y, int value)
{ dataArray[y * width + x] = value; }
public void accumulate(int x, int y, int delta)
{ set(x, y, get(x, y) + delta); }
public boolean contrast(int x, int y, int minContrast)
{
int centerValue = get(x, y);
for (int i = 8; i >= 0; i--)
{
if (i == 4)
continue;
int newx = x + (i % 3) - 1;
int newy = y + (i / 3) - 1;
if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))
continue;
if (Math.abs(get(newx, newy) - centerValue) >= minContrast)
return true;
}
return false;
}
public int getMax()
{
int max = dataArray[0];
for (int i = width * height - 1; i > 0; i--)
if (dataArray[i] > max)
max = dataArray[i];
return max;
}
}
public static ArrayData getArrayDataFromImage(String filename) throws IOException
{
BufferedImage inputImage = ImageIO.read(new File(filename));
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
ArrayData arrayData = new ArrayData(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgbValue = rgbData[y * width + x];
rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
arrayData.set(x, height - 1 - y, rgbValue);
}
}
return arrayData;
}
public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException
{
int max = arrayData.getMax();
BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < arrayData.height; y++)
{
for (int x = 0; x < arrayData.width; x++)
{
int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);
outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);
}
}
ImageIO.write(outputImage, "PNG", new File(filename));
return;
}
public static void main(String[] args) throws IOException
{
ArrayData inputData = getArrayDataFromImage(args[0]);
int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);
ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);
writeOutputImage(args[1], outputData);
return;
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math"
)
type ifctn func(float64) float64
func simpson38(f ifctn, a, b float64, n int) float64 {
h := (b - a) / float64(n)
h1 := h / 3
sum := f(a) + f(b)
for j := 3*n - 1; j > 0; j-- {
if j%3 == 0 {
sum += 2 * f(a+h1*float64(j))
} else {
sum += 3 * f(a+h1*float64(j))
}
}
return h * sum / 8
}
func gammaIncQ(a, x float64) float64 {
aa1 := a - 1
var f ifctn = func(t float64) float64 {
return math.Pow(t, aa1) * math.Exp(-t)
}
y := aa1
h := 1.5e-2
for f(y)*(x-y) > 2e-8 && y < x {
y += .4
}
if y > x {
y = x
}
return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))
}
func chi2ud(ds []int) float64 {
var sum, expected float64
for _, d := range ds {
expected += float64(d)
}
expected /= float64(len(ds))
for _, d := range ds {
x := float64(d) - expected
sum += x * x
}
return sum / expected
}
func chi2p(dof int, distance float64) float64 {
return gammaIncQ(.5*float64(dof), .5*distance)
}
const sigLevel = .05
func main() {
for _, dset := range [][]int{
{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461},
} {
utest(dset)
}
}
func utest(dset []int) {
fmt.Println("Uniform distribution test")
var sum int
for _, c := range dset {
sum += c
}
fmt.Println(" dataset:", dset)
fmt.Println(" samples: ", sum)
fmt.Println(" categories: ", len(dset))
dof := len(dset) - 1
fmt.Println(" degrees of freedom: ", dof)
dist := chi2ud(dset)
fmt.Println(" chi square test statistic: ", dist)
p := chi2p(dof, dist)
fmt.Println(" p-value of test statistic: ", p)
sig := p < sigLevel
fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig)
fmt.Println(" uniform? ", !sig, "\n")
}
| import static java.lang.Math.pow;
import java.util.Arrays;
import static java.util.Arrays.stream;
import org.apache.commons.math3.special.Gamma;
public class Test {
static double x2Dist(double[] data) {
double avg = stream(data).sum() / data.length;
double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));
return sqs / avg;
}
static double x2Prob(double dof, double distance) {
return Gamma.regularizedGammaQ(dof / 2, distance / 2);
}
static boolean x2IsUniform(double[] data, double significance) {
return x2Prob(data.length - 1.0, x2Dist(data)) > significance;
}
public static void main(String[] a) {
double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461}};
System.out.printf(" %4s %12s %12s %8s %s%n",
"dof", "distance", "probability", "Uniform?", "dataset");
for (double[] ds : dataSets) {
int dof = ds.length - 1;
double dist = x2Dist(ds);
double prob = x2Prob(dof, dist);
System.out.printf("%4d %12.3f %12.8f %5s %6s%n",
dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO",
Arrays.toString(ds));
}
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
var (
d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,
23.1, 19.6, 19.0, 21.7, 21.4}
d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,
21.9, 22.1, 22.9, 20.5, 24.4}
d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}
d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,
20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}
d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}
d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,
23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}
d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}
d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}
x = []float64{3.0, 4.0, 1.0, 2.1}
y = []float64{490.2, 340.0, 433.9}
)
func main() {
fmt.Printf("%.6f\n", pValue(d1, d2))
fmt.Printf("%.6f\n", pValue(d3, d4))
fmt.Printf("%.6f\n", pValue(d5, d6))
fmt.Printf("%.6f\n", pValue(d7, d8))
fmt.Printf("%.6f\n", pValue(x, y))
}
func mean(a []float64) float64 {
sum := 0.
for _, x := range a {
sum += x
}
return sum / float64(len(a))
}
func sv(a []float64) float64 {
m := mean(a)
sum := 0.
for _, x := range a {
d := x - m
sum += d * d
}
return sum / float64(len(a)-1)
}
func welch(a, b []float64) float64 {
return (mean(a) - mean(b)) /
math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))
}
func dof(a, b []float64) float64 {
sva := sv(a)
svb := sv(b)
n := sva/float64(len(a)) + svb/float64(len(b))
return n * n /
(sva*sva/float64(len(a)*len(a)*(len(a)-1)) +
svb*svb/float64(len(b)*len(b)*(len(b)-1)))
}
func simpson0(n int, upper float64, f func(float64) float64) float64 {
sum := 0.
nf := float64(n)
dx0 := upper / nf
sum += f(0) * dx0
sum += f(dx0*.5) * dx0 * 4
x0 := dx0
for i := 1; i < n; i++ {
x1 := float64(i+1) * upper / nf
xmid := (x0 + x1) * .5
dx := x1 - x0
sum += f(x0) * dx * 2
sum += f(xmid) * dx * 4
x0 = x1
}
return (sum + f(upper)*dx0) / 6
}
func pValue(a, b []float64) float64 {
ν := dof(a, b)
t := welch(a, b)
g1, _ := math.Lgamma(ν / 2)
g2, _ := math.Lgamma(.5)
g3, _ := math.Lgamma(ν/2 + .5)
return simpson0(2000, ν/(t*t+ν),
func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /
math.Exp(g1+g2-g3)
}
| import org.apache.commons.math3.distribution.TDistribution;
public class WelchTTest {
public static double[] meanvar(double[] a) {
double m = 0.0, v = 0.0;
int n = a.length;
for (double x: a) {
m += x;
}
m /= n;
for (double x: a) {
v += (x - m) * (x - m);
}
v /= (n - 1);
return new double[] {m, v};
}
public static double[] welch_ttest(double[] x, double[] y) {
double mx, my, vx, vy, t, df, p;
double[] res;
int nx = x.length, ny = y.length;
res = meanvar(x);
mx = res[0];
vx = res[1];
res = meanvar(y);
my = res[0];
vy = res[1];
t = (mx-my)/Math.sqrt(vx/nx+vy/ny);
df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));
TDistribution dist = new TDistribution(df);
p = 2.0*dist.cumulativeProbability(-Math.abs(t));
return new double[] {t, df, p};
}
public static void main(String[] args) {
double x[] = {3.0, 4.0, 1.0, 2.1};
double y[] = {490.2, 340.0, 433.9};
double res[] = welch_ttest(x, y);
System.out.println("t = " + res[0]);
System.out.println("df = " + res[1]);
System.out.println("p = " + res[2]);
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math"
)
var (
d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,
23.1, 19.6, 19.0, 21.7, 21.4}
d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,
21.9, 22.1, 22.9, 20.5, 24.4}
d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}
d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,
20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}
d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}
d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,
23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}
d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}
d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}
x = []float64{3.0, 4.0, 1.0, 2.1}
y = []float64{490.2, 340.0, 433.9}
)
func main() {
fmt.Printf("%.6f\n", pValue(d1, d2))
fmt.Printf("%.6f\n", pValue(d3, d4))
fmt.Printf("%.6f\n", pValue(d5, d6))
fmt.Printf("%.6f\n", pValue(d7, d8))
fmt.Printf("%.6f\n", pValue(x, y))
}
func mean(a []float64) float64 {
sum := 0.
for _, x := range a {
sum += x
}
return sum / float64(len(a))
}
func sv(a []float64) float64 {
m := mean(a)
sum := 0.
for _, x := range a {
d := x - m
sum += d * d
}
return sum / float64(len(a)-1)
}
func welch(a, b []float64) float64 {
return (mean(a) - mean(b)) /
math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))
}
func dof(a, b []float64) float64 {
sva := sv(a)
svb := sv(b)
n := sva/float64(len(a)) + svb/float64(len(b))
return n * n /
(sva*sva/float64(len(a)*len(a)*(len(a)-1)) +
svb*svb/float64(len(b)*len(b)*(len(b)-1)))
}
func simpson0(n int, upper float64, f func(float64) float64) float64 {
sum := 0.
nf := float64(n)
dx0 := upper / nf
sum += f(0) * dx0
sum += f(dx0*.5) * dx0 * 4
x0 := dx0
for i := 1; i < n; i++ {
x1 := float64(i+1) * upper / nf
xmid := (x0 + x1) * .5
dx := x1 - x0
sum += f(x0) * dx * 2
sum += f(xmid) * dx * 4
x0 = x1
}
return (sum + f(upper)*dx0) / 6
}
func pValue(a, b []float64) float64 {
ν := dof(a, b)
t := welch(a, b)
g1, _ := math.Lgamma(ν / 2)
g2, _ := math.Lgamma(.5)
g3, _ := math.Lgamma(ν/2 + .5)
return simpson0(2000, ν/(t*t+ν),
func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /
math.Exp(g1+g2-g3)
}
| import org.apache.commons.math3.distribution.TDistribution;
public class WelchTTest {
public static double[] meanvar(double[] a) {
double m = 0.0, v = 0.0;
int n = a.length;
for (double x: a) {
m += x;
}
m /= n;
for (double x: a) {
v += (x - m) * (x - m);
}
v /= (n - 1);
return new double[] {m, v};
}
public static double[] welch_ttest(double[] x, double[] y) {
double mx, my, vx, vy, t, df, p;
double[] res;
int nx = x.length, ny = y.length;
res = meanvar(x);
mx = res[0];
vx = res[1];
res = meanvar(y);
my = res[0];
vy = res[1];
t = (mx-my)/Math.sqrt(vx/nx+vy/ny);
df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));
TDistribution dist = new TDistribution(df);
p = 2.0*dist.cumulativeProbability(-Math.abs(t));
return new double[] {t, df, p};
}
public static void main(String[] args) {
double x[] = {3.0, 4.0, 1.0, 2.1};
double y[] = {490.2, 340.0, 433.9};
double res[] = welch_ttest(x, y);
System.out.println("t = " + res[0]);
System.out.println("df = " + res[1]);
System.out.println("p = " + res[2]);
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"strings"
)
var data = `
FILE FILE DEPENDENCIES
==== =================
top1 des1 ip1 ip2
top2 des1 ip2 ip3
ip1 extra1 ip1a ipcommon
ip2 ip2a ip2b ip2c ipcommon
des1 des1a des1b des1c
des1a des1a1 des1a2
des1c des1c1 extra1`
func main() {
g, dep, err := parseLibDep(data)
if err != nil {
fmt.Println(err)
return
}
var tops []string
for n := range g {
if !dep[n] {
tops = append(tops, n)
}
}
fmt.Println("Top levels:", tops)
showOrder(g, "top1")
showOrder(g, "top2")
showOrder(g, "top1", "top2")
fmt.Println("Cycle examples:")
g, _, err = parseLibDep(data + `
des1a1 des1`)
if err != nil {
fmt.Println(err)
return
}
showOrder(g, "top1")
showOrder(g, "ip1", "ip2")
}
func showOrder(g graph, target ...string) {
order, cyclic := g.orderFrom(target...)
if cyclic == nil {
reverse(order)
fmt.Println("Target", target, "order:", order)
} else {
fmt.Println("Target", target, "cyclic dependencies:", cyclic)
}
}
func reverse(s []string) {
last := len(s) - 1
for i, e := range s[:len(s)/2] {
s[i], s[last-i] = s[last-i], e
}
}
type graph map[string][]string
type depList map[string]bool
func parseLibDep(data string) (g graph, d depList, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
d = depList{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
var deps []string
for _, dep := range libs[1:] {
g[dep] = g[dep]
if dep == lib {
continue
}
for i := 0; ; i++ {
if i == len(deps) {
deps = append(deps, dep)
d[dep] = true
break
}
if dep == deps[i] {
break
}
}
}
g[lib] = deps
}
return g, d, nil
}
func (g graph) orderFrom(start ...string) (order, cyclic []string) {
L := make([]string, len(g))
i := len(L)
temp := map[string]bool{}
perm := map[string]bool{}
var cycleFound bool
var cycleStart string
var visit func(string)
visit = func(n string) {
switch {
case temp[n]:
cycleFound = true
cycleStart = n
return
case perm[n]:
return
}
temp[n] = true
for _, m := range g[n] {
visit(m)
if cycleFound {
if cycleStart > "" {
cyclic = append(cyclic, n)
if n == cycleStart {
cycleStart = ""
}
}
return
}
}
delete(temp, n)
perm[n] = true
i--
L[i] = n
}
for _, n := range start {
if perm[n] {
continue
}
visit(n)
if cycleFound {
return nil, cyclic
}
}
return L[i:], nil
}
| import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
public class TopologicalSort2 {
public static void main(String[] args) {
String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,"
+ "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1";
Graph g = new Graph(s, new int[][]{
{0, 10}, {0, 2}, {0, 3},
{1, 10}, {1, 3}, {1, 4},
{2, 17}, {2, 5}, {2, 9},
{3, 6}, {3, 7}, {3, 8}, {3, 9},
{10, 11}, {10, 12}, {10, 13},
{11, 14}, {11, 15},
{13, 16}, {13, 17},});
System.out.println("Top levels: " + g.toplevels());
String[] files = {"top1", "top2", "ip1"};
for (String f : files)
System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f));
}
}
class Graph {
List<String> vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = asList(s.split(","));
numVertices = vertices.size();
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> toplevels() {
List<String> result = new ArrayList<>();
outer:
for (int c = 0; c < numVertices; c++) {
for (int r = 0; r < numVertices; r++) {
if (adjacency[r][c])
continue outer;
}
result.add(vertices.get(c));
}
return result;
}
List<String> compileOrder(String item) {
LinkedList<String> result = new LinkedList<>();
LinkedList<Integer> queue = new LinkedList<>();
queue.add(vertices.indexOf(item));
while (!queue.isEmpty()) {
int r = queue.poll();
for (int c = 0; c < numVertices; c++) {
if (adjacency[r][c] && !queue.contains(c)) {
queue.add(c);
}
}
result.addFirst(vertices.get(r));
}
return result.stream().distinct().collect(toList());
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"fmt"
"strings"
)
var data = `
FILE FILE DEPENDENCIES
==== =================
top1 des1 ip1 ip2
top2 des1 ip2 ip3
ip1 extra1 ip1a ipcommon
ip2 ip2a ip2b ip2c ipcommon
des1 des1a des1b des1c
des1a des1a1 des1a2
des1c des1c1 extra1`
func main() {
g, dep, err := parseLibDep(data)
if err != nil {
fmt.Println(err)
return
}
var tops []string
for n := range g {
if !dep[n] {
tops = append(tops, n)
}
}
fmt.Println("Top levels:", tops)
showOrder(g, "top1")
showOrder(g, "top2")
showOrder(g, "top1", "top2")
fmt.Println("Cycle examples:")
g, _, err = parseLibDep(data + `
des1a1 des1`)
if err != nil {
fmt.Println(err)
return
}
showOrder(g, "top1")
showOrder(g, "ip1", "ip2")
}
func showOrder(g graph, target ...string) {
order, cyclic := g.orderFrom(target...)
if cyclic == nil {
reverse(order)
fmt.Println("Target", target, "order:", order)
} else {
fmt.Println("Target", target, "cyclic dependencies:", cyclic)
}
}
func reverse(s []string) {
last := len(s) - 1
for i, e := range s[:len(s)/2] {
s[i], s[last-i] = s[last-i], e
}
}
type graph map[string][]string
type depList map[string]bool
func parseLibDep(data string) (g graph, d depList, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
d = depList{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
var deps []string
for _, dep := range libs[1:] {
g[dep] = g[dep]
if dep == lib {
continue
}
for i := 0; ; i++ {
if i == len(deps) {
deps = append(deps, dep)
d[dep] = true
break
}
if dep == deps[i] {
break
}
}
}
g[lib] = deps
}
return g, d, nil
}
func (g graph) orderFrom(start ...string) (order, cyclic []string) {
L := make([]string, len(g))
i := len(L)
temp := map[string]bool{}
perm := map[string]bool{}
var cycleFound bool
var cycleStart string
var visit func(string)
visit = func(n string) {
switch {
case temp[n]:
cycleFound = true
cycleStart = n
return
case perm[n]:
return
}
temp[n] = true
for _, m := range g[n] {
visit(m)
if cycleFound {
if cycleStart > "" {
cyclic = append(cyclic, n)
if n == cycleStart {
cycleStart = ""
}
}
return
}
}
delete(temp, n)
perm[n] = true
i--
L[i] = n
}
for _, n := range start {
if perm[n] {
continue
}
visit(n)
if cycleFound {
return nil, cyclic
}
}
return L[i:], nil
}
| import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
public class TopologicalSort2 {
public static void main(String[] args) {
String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,"
+ "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1";
Graph g = new Graph(s, new int[][]{
{0, 10}, {0, 2}, {0, 3},
{1, 10}, {1, 3}, {1, 4},
{2, 17}, {2, 5}, {2, 9},
{3, 6}, {3, 7}, {3, 8}, {3, 9},
{10, 11}, {10, 12}, {10, 13},
{11, 14}, {11, 15},
{13, 16}, {13, 17},});
System.out.println("Top levels: " + g.toplevels());
String[] files = {"top1", "top2", "ip1"};
for (String f : files)
System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f));
}
}
class Graph {
List<String> vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = asList(s.split(","));
numVertices = vertices.size();
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> toplevels() {
List<String> result = new ArrayList<>();
outer:
for (int c = 0; c < numVertices; c++) {
for (int r = 0; r < numVertices; r++) {
if (adjacency[r][c])
continue outer;
}
result.add(vertices.get(c));
}
return result;
}
List<String> compileOrder(String item) {
LinkedList<String> result = new LinkedList<>();
LinkedList<Integer> queue = new LinkedList<>();
queue.add(vertices.indexOf(item));
while (!queue.isEmpty()) {
int r = queue.poll();
for (int c = 0; c < numVertices; c++) {
if (adjacency[r][c] && !queue.contains(c)) {
queue.add(c);
}
}
result.addFirst(vertices.get(r));
}
return result.stream().distinct().collect(toList());
}
}
|
Write the same code in Java as shown below in Go. | package expand
type Expander interface {
Expand() []string
}
type Text string
func (t Text) Expand() []string { return []string{string(t)} }
type Alternation []Expander
func (alt Alternation) Expand() []string {
var out []string
for _, e := range alt {
out = append(out, e.Expand()...)
}
return out
}
type Sequence []Expander
func (seq Sequence) Expand() []string {
if len(seq) == 0 {
return nil
}
out := seq[0].Expand()
for _, e := range seq[1:] {
out = combine(out, e.Expand())
}
return out
}
func combine(al, bl []string) []string {
out := make([]string, 0, len(al)*len(bl))
for _, a := range al {
for _, b := range bl {
out = append(out, a+b)
}
}
return out
}
const (
escape = '\\'
altStart = '{'
altEnd = '}'
altSep = ','
)
type piT struct{ pos, cnt, depth int }
type Brace string
func Expand(s string) []string { return Brace(s).Expand() }
func (b Brace) Expand() []string { return b.Expander().Expand() }
func (b Brace) Expander() Expander {
s := string(b)
var posInfo []piT
var stack []int
removePosInfo := func(i int) {
end := len(posInfo) - 1
copy(posInfo[i:end], posInfo[i+1:])
posInfo = posInfo[:end]
}
inEscape := false
for i, r := range s {
if inEscape {
inEscape = false
continue
}
switch r {
case escape:
inEscape = true
case altStart:
stack = append(stack, len(posInfo))
posInfo = append(posInfo, piT{i, 0, len(stack)})
case altEnd:
if len(stack) == 0 {
continue
}
si := len(stack) - 1
pi := stack[si]
if posInfo[pi].cnt == 0 {
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == len(stack) {
removePosInfo(pi)
} else {
pi++
}
}
} else {
posInfo = append(posInfo, piT{i, -2, len(stack)})
}
stack = stack[:si]
case altSep:
if len(stack) == 0 {
continue
}
posInfo = append(posInfo, piT{i, -1, len(stack)})
posInfo[stack[len(stack)-1]].cnt++
}
}
for len(stack) > 0 {
si := len(stack) - 1
pi := stack[si]
depth := posInfo[pi].depth
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == depth {
removePosInfo(pi)
} else {
pi++
}
}
stack = stack[:si]
}
return buildExp(s, 0, posInfo)
}
func buildExp(s string, off int, info []piT) Expander {
if len(info) == 0 {
return Text(s)
}
var seq Sequence
i := 0
var dj, j, depth int
for dk, piK := range info {
k := piK.pos - off
switch s[k] {
case altStart:
if depth == 0 {
dj = dk
j = k
depth = piK.depth
}
case altEnd:
if piK.depth != depth {
continue
}
if j > i {
seq = append(seq, Text(s[i:j]))
}
alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])
seq = append(seq, alt)
i = k + 1
depth = 0
}
}
if j := len(s); j > i {
seq = append(seq, Text(s[i:j]))
}
if len(seq) == 1 {
return seq[0]
}
return seq
}
func buildAlt(s string, depth, off int, info []piT) Alternation {
var alt Alternation
i := 0
var di int
for dk, piK := range info {
if piK.depth != depth {
continue
}
if k := piK.pos - off; s[k] == altSep {
sub := buildExp(s[i:k], i+off, info[di:dk])
alt = append(alt, sub)
i = k + 1
di = dk + 1
}
}
sub := buildExp(s[i:], i+off, info[di:])
alt = append(alt, sub)
return alt
}
| public class BraceExpansion {
public static void main(String[] args) {
for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) {
System.out.println();
expand(s);
}
}
public static void expand(String s) {
expandR("", s, "");
}
private static void expandR(String pre, String s, String suf) {
int i1 = -1, i2 = 0;
String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " ");
StringBuilder sb = null;
outer:
while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
i2 = i1 + 1;
sb = new StringBuilder(s);
for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
char c = noEscape.charAt(i2);
depth = (c == '{') ? ++depth : depth;
depth = (c == '}') ? --depth : depth;
if (c == ',' && depth == 1) {
sb.setCharAt(i2, '\u0000');
} else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1)
break outer;
}
}
if (i1 == -1) {
if (suf.length() > 0)
expandR(pre + s, suf, "");
else
System.out.printf("%s%s%s%n", pre, s, suf);
} else {
for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1))
expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
| foo();
Int x = bar();
|
Convert the following code from Go to Java, ensuring the logic remains intact. | import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
| foo();
Int x = bar();
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
)
func factSum(n int) int {
s := 0
for x, f := 0, 1; x < n; {
x++
f *= x
s += f
}
return s
}
func r(n int) bool {
if n == 0 {
return false
}
c := super[pos-n]
cnt[n]--
if cnt[n] == 0 {
cnt[n] = n
if !r(n - 1) {
return false
}
}
super[pos] = c
pos++
return true
}
func superperm(n int) {
pos = n
le := factSum(n)
super = make([]byte, le)
for i := 0; i <= n; i++ {
cnt[i] = i
}
for i := 1; i <= n; i++ {
super[i-1] = byte(i) + '0'
}
for r(n) {
}
}
func main() {
for n := 0; n < max; n++ {
fmt.Printf("superperm(%2d) ", n)
superperm(n)
fmt.Printf("len = %d\n", len(super))
}
}
| import static java.util.stream.IntStream.rangeClosed;
public class Test {
final static int nMax = 12;
static char[] superperm;
static int pos;
static int[] count = new int[nMax];
static int factSum(int n) {
return rangeClosed(1, n)
.map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();
}
static boolean r(int n) {
if (n == 0)
return false;
char c = superperm[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1))
return false;
}
superperm[pos++] = c;
return true;
}
static void superPerm(int n) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pos = n;
superperm = new char[factSum(n)];
for (int i = 0; i < n + 1; i++)
count[i] = i;
for (int i = 1; i < n + 1; i++)
superperm[i - 1] = chars.charAt(i);
while (r(n)) {
}
}
public static void main(String[] args) {
for (int n = 0; n < nMax; n++) {
superPerm(n);
System.out.printf("superPerm(%2d) len = %d", n, superperm.length);
System.out.println();
}
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0")
entry.Connect("activate", func() {
str, _ := entry.GetText()
validateInput(window, str)
})
ib, err := gtk.ButtonNewWithLabel("Increment")
check(err, "Unable to create increment button:")
ib.Connect("clicked", func() {
str, _ := entry.GetText()
if i, ok := validateInput(window, str); ok {
entry.SetText(strconv.FormatInt(i+1, 10))
}
})
rb, err := gtk.ButtonNewWithLabel("Random")
check(err, "Unable to create random button:")
rb.Connect("clicked", func() {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO,
"Set random value",
)
answer := dialog.Run()
dialog.Destroy()
if answer == gtk.RESPONSE_YES {
entry.SetText(strconv.Itoa(rand.Intn(10000)))
}
})
box.PackStart(label, false, false, 2)
box.PackStart(entry, false, false, 2)
box.PackStart(ib, false, false, 2)
box.PackStart(rb, false, false, 2)
window.Add(box)
window.ShowAll()
gtk.Main()
}
| import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Interact extends JFrame{
final JTextField numberField;
final JButton incButton, randButton;
public Interact(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
numberField = new JTextField();
incButton = new JButton("Increment");
randButton = new JButton("Random");
numberField.setText("0");
numberField.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {
if(!Character.isDigit(e.getKeyChar())){
e.consume();
}
}
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyPressed(KeyEvent e){}
});
incButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String text = numberField.getText();
if(text.isEmpty()){
numberField.setText("1");
}else{
numberField.setText((Long.valueOf(text) + 1) + "");
}
}
});
randButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(JOptionPane.showConfirmDialog(null, "Are you sure?") ==
JOptionPane.YES_OPTION){
numberField.setText(Long.toString((long)(Math.random()
* Long.MAX_VALUE)));
}
}
});
setLayout(new GridLayout(2, 1));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.add(incButton);
buttonPanel.add(randButton);
add(numberField);
add(buttonPanel);
pack();
}
public static void main(String[] args){
new Interact().setVisible(true);
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"bufio"
"fmt"
"io"
"math/rand"
"time"
)
func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
br := bufio.NewReader(r)
s, err = br.ReadString('\n')
if err != nil {
return
}
ln = 1
lnLast := 1.
var sLast string
for {
sLast, err = br.ReadString('\n')
if err == io.EOF {
return s, ln, nil
}
if err != nil {
break
}
lnLast++
if rand.Float64() < 1/lnLast {
s = sLast
ln = int(lnLast)
}
}
return
}
func oneOfN(n int, file io.Reader) int {
_, ln, err := choseLineRandomly(file)
if err != nil {
panic(err)
}
return ln
}
type simReader int
func (r *simReader) Read(b []byte) (int, error) {
if *r <= 0 {
return 0, io.EOF
}
b[0] = '\n'
*r--
return 1, nil
}
func main() {
n := 10
freq := make([]int, n)
rand.Seed(time.Now().UnixNano())
for times := 0; times < 1e6; times++ {
sr := simReader(n)
freq[oneOfN(n, &sr)-1]++
}
fmt.Println(freq)
}
| import java.util.Arrays;
import java.util.Random;
public class OneOfNLines {
static Random rand;
public static int oneOfN(int n) {
int choice = 0;
for(int i = 1; i < n; i++) {
if(rand.nextInt(i+1) == 0)
choice = i;
}
return choice;
}
public static void main(String[] args) {
int n = 10;
int trials = 1000000;
int[] bins = new int[n];
rand = new Random();
for(int i = 0; i < trials; i++)
bins[oneOfN(n)]++;
System.out.println(Arrays.toString(bins));
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
seqMaxLen = [][]string{s}
}
}
fmt.Println("Max sequence length:", maxLen)
fmt.Println("Sequences:", len(seqMaxLen))
for _, seq := range seqMaxLen {
fmt.Println("Sequence:")
for _, t := range seq {
fmt.Println(t)
}
}
}
func seq(n int) []string {
s := strconv.Itoa(n)
ss := []string{s}
for {
dSeq := sortD(s)
d := dSeq[0]
nd := 1
s = ""
for i := 1; ; i++ {
if i == len(dSeq) {
s = fmt.Sprintf("%s%d%c", s, nd, d)
break
}
if dSeq[i] == d {
nd++
} else {
s = fmt.Sprintf("%s%d%c", s, nd, d)
d = dSeq[i]
nd = 1
}
}
for _, s0 := range ss {
if s == s0 {
return ss
}
}
ss = append(ss, s)
}
panic("unreachable")
}
func sortD(s string) []rune {
r := make([]rune, len(s))
for i, d := range s {
j := 0
for ; j < i; j++ {
if d > r[j] {
copy(r[j+1:], r[j:i])
break
}
}
r[j] = d
}
return r
}
| import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
.parallel()
.mapToObj(n -> summarize(n, false))
.collect(Seeds::new, Seeds::accept, Seeds::combine);
System.out.println("Seeds:");
res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));
System.out.println("\nSequence:");
summarize(res.seeds.get(0)[0], true);
}
static int[] summarize(int seed, boolean display) {
String n = String.valueOf(seed);
String k = Arrays.toString(n.chars().sorted().toArray());
if (!display && cache.get(k) != null)
return new int[]{seed, cache.get(k)};
Set<String> seen = new HashSet<>();
StringBuilder sb = new StringBuilder();
int[] freq = new int[10];
while (!seen.contains(n)) {
seen.add(n);
int len = n.length();
for (int i = 0; i < len; i++)
freq[n.charAt(i) - '0']++;
sb.setLength(0);
for (int i = 9; i >= 0; i--) {
if (freq[i] != 0) {
sb.append(freq[i]).append(i);
freq[i] = 0;
}
}
if (display)
System.out.println(n);
n = sb.toString();
}
cache.put(k, seen.size());
return new int[]{seed, seen.size()};
}
static class Seeds {
int largest = Integer.MIN_VALUE;
List<int[]> seeds = new ArrayList<>();
void accept(int[] s) {
int size = s[1];
if (size >= largest) {
if (size > largest) {
largest = size;
seeds.clear();
}
seeds.add(s);
}
}
void combine(Seeds acc) {
acc.seeds.forEach(this::accept);
}
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
seqMaxLen = [][]string{s}
}
}
fmt.Println("Max sequence length:", maxLen)
fmt.Println("Sequences:", len(seqMaxLen))
for _, seq := range seqMaxLen {
fmt.Println("Sequence:")
for _, t := range seq {
fmt.Println(t)
}
}
}
func seq(n int) []string {
s := strconv.Itoa(n)
ss := []string{s}
for {
dSeq := sortD(s)
d := dSeq[0]
nd := 1
s = ""
for i := 1; ; i++ {
if i == len(dSeq) {
s = fmt.Sprintf("%s%d%c", s, nd, d)
break
}
if dSeq[i] == d {
nd++
} else {
s = fmt.Sprintf("%s%d%c", s, nd, d)
d = dSeq[i]
nd = 1
}
}
for _, s0 := range ss {
if s == s0 {
return ss
}
}
ss = append(ss, s)
}
panic("unreachable")
}
func sortD(s string) []rune {
r := make([]rune, len(s))
for i, d := range s {
j := 0
for ; j < i; j++ {
if d > r[j] {
copy(r[j+1:], r[j:i])
break
}
}
r[j] = d
}
return r
}
| import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
.parallel()
.mapToObj(n -> summarize(n, false))
.collect(Seeds::new, Seeds::accept, Seeds::combine);
System.out.println("Seeds:");
res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));
System.out.println("\nSequence:");
summarize(res.seeds.get(0)[0], true);
}
static int[] summarize(int seed, boolean display) {
String n = String.valueOf(seed);
String k = Arrays.toString(n.chars().sorted().toArray());
if (!display && cache.get(k) != null)
return new int[]{seed, cache.get(k)};
Set<String> seen = new HashSet<>();
StringBuilder sb = new StringBuilder();
int[] freq = new int[10];
while (!seen.contains(n)) {
seen.add(n);
int len = n.length();
for (int i = 0; i < len; i++)
freq[n.charAt(i) - '0']++;
sb.setLength(0);
for (int i = 9; i >= 0; i--) {
if (freq[i] != 0) {
sb.append(freq[i]).append(i);
freq[i] = 0;
}
}
if (display)
System.out.println(n);
n = sb.toString();
}
cache.put(k, seen.size());
return new int[]{seed, seen.size()};
}
static class Seeds {
int largest = Integer.MIN_VALUE;
List<int[]> seeds = new ArrayList<>();
void accept(int[] s) {
int size = s[1];
if (size >= largest) {
if (size > largest) {
largest = size;
seeds.clear();
}
seeds.add(s);
}
}
void combine(Seeds acc) {
acc.seeds.forEach(this::accept);
}
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | import (
"fmt"
"strings"
)
func main() {
for _, n := range []int64{
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
} {
fmt.Println(sayOrdinal(n))
}
}
var irregularOrdinals = map[string]string{
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
func sayOrdinal(n int64) string {
s := say(n)
i := strings.LastIndexAny(s, " -")
i++
if x, ok := irregularOrdinals[s[i:]]; ok {
s = s[:i] + x
} else if s[len(s)-1] == 'y' {
s = s[:i] + s[i:len(s)-1] + "ieth"
} else {
s = s[:i] + s[i:] + "th"
}
return s
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
| import java.util.HashMap;
import java.util.Map;
public class SpellingOfOrdinalNumbers {
public static void main(String[] args) {
for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) {
System.out.printf("%d = %s%n", test, toOrdinal(test));
}
}
private static Map<String,String> ordinalMap = new HashMap<>();
static {
ordinalMap.put("one", "first");
ordinalMap.put("two", "second");
ordinalMap.put("three", "third");
ordinalMap.put("five", "fifth");
ordinalMap.put("eight", "eighth");
ordinalMap.put("nine", "ninth");
ordinalMap.put("twelve", "twelfth");
}
private static String toOrdinal(long n) {
String spelling = numToString(n);
String[] split = spelling.split(" ");
String last = split[split.length - 1];
String replace = "";
if ( last.contains("-") ) {
String[] lastSplit = last.split("-");
String lastWithDash = lastSplit[1];
String lastReplace = "";
if ( ordinalMap.containsKey(lastWithDash) ) {
lastReplace = ordinalMap.get(lastWithDash);
}
else if ( lastWithDash.endsWith("y") ) {
lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth";
}
else {
lastReplace = lastWithDash + "th";
}
replace = lastSplit[0] + "-" + lastReplace;
}
else {
if ( ordinalMap.containsKey(last) ) {
replace = ordinalMap.get(last);
}
else if ( last.endsWith("y") ) {
replace = last.substring(0, last.length() - 1) + "ieth";
}
else {
replace = last + "th";
}
}
split[split.length - 1] = replace;
return String.join(" ", split);
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String numToString(long n) {
return numToStringHelper(n);
}
private static final String numToStringHelper(long n) {
if ( n < 0 ) {
return "negative " + numToStringHelper(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : "");
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"strconv"
"strings"
)
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}
| public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0);
int count = 0;
for(int j = 0; j < s.length(); j++){
int temp = Integer.parseInt(s.charAt(j) + "");
if(temp == i){
count++;
}
if (count > b) return false;
}
if(count != b) return false;
}
return true;
}
public static void main(String[] args){
for(int i = 0; i < 100000000; i++){
if(isSelfDescribing(i)){
System.out.println(i);
}
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import "fmt"
var example []int
func reverse(s []int) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func checkSeq(pos, n, minLen int, seq []int) (int, int) {
switch {
case pos > minLen || seq[0] > n:
return minLen, 0
case seq[0] == n:
example = seq
return pos, 1
case pos < minLen:
return tryPerm(0, pos, n, minLen, seq)
default:
return minLen, 0
}
}
func tryPerm(i, pos, n, minLen int, seq []int) (int, int) {
if i > pos {
return minLen, 0
}
seq2 := make([]int, len(seq)+1)
copy(seq2[1:], seq)
seq2[0] = seq[0] + seq[i]
res11, res12 := checkSeq(pos+1, n, minLen, seq2)
res21, res22 := tryPerm(i+1, pos, n, res11, seq)
switch {
case res21 < res11:
return res21, res22
case res21 == res11:
return res21, res12 + res22
default:
fmt.Println("Error in tryPerm")
return 0, 0
}
}
func initTryPerm(x, minLen int) (int, int) {
return tryPerm(0, 0, x, minLen, []int{1})
}
func findBrauer(num, minLen, nbLimit int) {
actualMin, brauer := initTryPerm(num, minLen)
fmt.Println("\nN =", num)
fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin)
fmt.Println("Number of minimum length Brauer chains :", brauer)
if brauer > 0 {
reverse(example)
fmt.Println("Brauer example :", example)
}
example = nil
if num <= nbLimit {
nonBrauer := findNonBrauer(num, actualMin+1, brauer)
fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer)
if nonBrauer > 0 {
fmt.Println("Non-Brauer example :", example)
}
example = nil
} else {
println("Non-Brauer analysis suppressed")
}
}
func isAdditionChain(a []int) bool {
for i := 2; i < len(a); i++ {
if a[i] > a[i-1]*2 {
return false
}
ok := false
jloop:
for j := i - 1; j >= 0; j-- {
for k := j; k >= 0; k-- {
if a[j]+a[k] == a[i] {
ok = true
break jloop
}
}
}
if !ok {
return false
}
}
if example == nil && !isBrauer(a) {
example = make([]int, len(a))
copy(example, a)
}
return true
}
func isBrauer(a []int) bool {
for i := 2; i < len(a); i++ {
ok := false
for j := i - 1; j >= 0; j-- {
if a[i-1]+a[j] == a[i] {
ok = true
break
}
}
if !ok {
return false
}
}
return true
}
func nextChains(index, le int, seq []int, pcount *int) {
for {
if index < le-1 {
nextChains(index+1, le, seq, pcount)
}
if seq[index]+le-1-index >= seq[le-1] {
return
}
seq[index]++
for i := index + 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
if isAdditionChain(seq) {
(*pcount)++
}
}
}
func findNonBrauer(num, le, brauer int) int {
seq := make([]int, le)
seq[0] = 1
seq[le-1] = num
for i := 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
count := 0
if isAdditionChain(seq) {
count = 1
}
nextChains(2, le, seq, &count)
return count - brauer
}
func main() {
nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
fmt.Println("Searching for Brauer chains up to a minimum length of 12:")
for _, num := range nums {
findBrauer(num, 12, 79)
}
}
| public class AdditionChains {
private static class Pair {
int f, s;
Pair(int f, int s) {
this.f = f;
this.s = s;
}
}
private static int[] prepend(int n, int[] seq) {
int[] result = new int[seq.length + 1];
result[0] = n;
System.arraycopy(seq, 0, result, 1, seq.length);
return result;
}
private static Pair check_seq(int pos, int[] seq, int n, int min_len) {
if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);
else if (seq[0] == n) return new Pair(pos, 1);
else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);
else return new Pair(min_len, 0);
}
private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {
if (i > pos) return new Pair(min_len, 0);
Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);
Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);
if (res2.f < res1.f) return res2;
else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);
else throw new RuntimeException("Try_perm exception");
}
private static Pair init_try_perm(int x) {
return try_perm(0, 0, new int[]{1}, x, 12);
}
private static void find_brauer(int num) {
Pair res = init_try_perm(num);
System.out.println();
System.out.println("N = " + num);
System.out.println("Minimum length of chains: L(n)= " + res.f);
System.out.println("Number of minimum length Brauer chains: " + res.s);
}
public static void main(String[] args) {
int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};
for (int i : nums) {
find_brauer(i);
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
func main() {
integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}
for _, integer := range integers {
fmt.Printf("%d ", integer)
}
floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}
for _, float := range floats {
fmt.Printf("%g ", float)
}
fmt.Println()
}
| public class NumericSeparatorSyntax {
public static void main(String[] args) {
runTask("Underscore allowed as seperator", 1_000);
runTask("Multiple consecutive underscores allowed:", 1__0_0_0);
runTask("Many multiple consecutive underscores allowed:", 1________________________00);
runTask("Underscores allowed in multiple positions", 1__4__4);
runTask("Underscores allowed in negative number", -1__4__4);
runTask("Underscores allowed in floating point number", 1__4__4e-5);
runTask("Underscores allowed in floating point exponent", 1__4__440000e-1_2);
}
private static void runTask(String description, long n) {
runTask(description, n, "%d");
}
private static void runTask(String description, double n) {
runTask(description, n, "%3.7f");
}
private static void runTask(String description, Number n, String format) {
System.out.printf("%s: " + format + "%n", description, n);
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
}
| import java.util.function.Consumer;
import java.util.stream.IntStream;
public class Repeat {
public static void main(String[] args) {
repeat(3, (x) -> System.out.println("Example " + x));
}
static void repeat (int n, Consumer<Integer> fun) {
IntStream.range(0, n).forEach(i -> fun.accept(i + 1));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"bufio"
"errors"
"fmt"
"math"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
fmt.Println("Numbers please separated by space/commas:")
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s, n, min, max, err := spark(sc.Text())
if err != nil {
fmt.Println(err)
return
}
if n == 1 {
fmt.Println("1 value =", min)
} else {
fmt.Println(n, "values. Min:", min, "Max:", max)
}
fmt.Println(s)
}
var sep = regexp.MustCompile(`[\s,]+`)
func spark(s0 string) (sp string, n int, min, max float64, err error) {
ss := sep.Split(s0, -1)
n = len(ss)
vs := make([]float64, n)
var v float64
min = math.Inf(1)
max = math.Inf(-1)
for i, s := range ss {
switch v, err = strconv.ParseFloat(s, 64); {
case err != nil:
case math.IsNaN(v):
err = errors.New("NaN not supported.")
case math.IsInf(v, 0):
err = errors.New("Inf not supported.")
default:
if v < min {
min = v
}
if v > max {
max = v
}
vs[i] = v
continue
}
return
}
if min == max {
sp = strings.Repeat("▄", n)
} else {
rs := make([]rune, n)
f := 8 / (max - min)
for j, v := range vs {
i := rune(f * (v - min))
if i > 7 {
i = 7
}
rs[j] = '▁' + i
}
sp = string(rs)
}
return
}
| public class Sparkline
{
String bars="▁▂▃▄▅▆▇█";
public static void main(String[] args)
{
Sparkline now=new Sparkline();
float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
now.display1D(arr);
System.out.println(now.getSparkline(arr));
float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};
now.display1D(arr1);
System.out.println(now.getSparkline(arr1));
}
public void display1D(float[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public String getSparkline(float[] arr)
{
float min=Integer.MAX_VALUE;
float max=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++)
{
if(arr[i]<min)
min=arr[i];
if(arr[i]>max)
max=arr[i];
}
float range=max-min;
int num=bars.length()-1;
String line="";
for(int i=0;i<arr.length;i++)
{
line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));
}
return line;
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewInt(42)
m := big.NewInt(2017)
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
}
| System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import "github.com/go-vgo/robotgo"
func main() {
robotgo.MouseClick("left", false)
robotgo.MouseClick("right", true)
}
| Point p = component.getLocation();
Robot robot = new Robot();
robot.mouseMove(p.getX(), p.getY());
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "Goodbye, World!")
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
| import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloWorld{
public static void main(String[] args) throws IOException{
ServerSocket listener = new ServerSocket(8080);
while(true){
Socket sock = listener.accept();
new PrintWriter(sock.getOutputStream(), true).
println("Goodbye, World!");
sock.close();
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | cls
| public class Clear
{
public static void main (String[] args)
{
System.out.print("\033[2J");
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import (
"github.com/fogleman/gg"
"math"
)
func main() {
dc := gg.NewContext(400, 400)
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetRGB(0, 0, 1)
c := (math.Sqrt(5) + 1) / 2
numberOfSeeds := 3000
for i := 0; i <= numberOfSeeds; i++ {
fi := float64(i)
fn := float64(numberOfSeeds)
r := math.Pow(fi, c) / fn
angle := 2 * math.Pi * c * fi
x := r*math.Sin(angle) + 200
y := r*math.Cos(angle) + 200
fi /= fn / 5
dc.DrawCircle(x, y, fi)
}
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("sunflower_fractal.png")
}
|
size(1000,1000);
surface.setTitle("Sunflower...");
int iter = 3000;
float factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;
float x = width/2.0, y = height/2.0;
double maxRad = pow(iter,factor)/iter;
int i;
background(#add8e6);
for(i=0;i<=iter;i++){
r = pow(i,factor)/iter;
if(r/maxRad < diskRatio){
stroke(#000000);
}
else
stroke(#ffff00);
theta = 2*PI*factor*i;
ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | #include <stdio.h>
#include <limits.h>
#define TRUE 1
#define FALSE 0
#define N_ROWS 5
#define N_COLS 5
typedef int bool;
int supply[N_ROWS] = { 461, 277, 356, 488, 393 };
int demand[N_COLS] = { 278, 60, 461, 116, 1060 };
int costs[N_ROWS][N_COLS] = {
{ 46, 74, 9, 28, 99 },
{ 12, 75, 6, 36, 48 },
{ 35, 199, 4, 5, 71 },
{ 61, 81, 44, 88, 9 },
{ 85, 60, 14, 25, 79 }
};
int main() {
printf(" A B C D E\n");
for (i = 0; i < N_ROWS; ++i) {
printf("%c", 'V' + i);
for (j = 0; j < N_COLS; ++j) printf(" %3d", results[i][j]);
printf("\n");
}
printf("\nTotal cost = %d\n", total_cost);
return 0;
}
| import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;
public class VogelsApproximationMethod {
final static int[] demand = {30, 20, 70, 30, 60};
final static int[] supply = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
{19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};
final static int nRows = supply.length;
final static int nCols = demand.length;
static boolean[] rowDone = new boolean[nRows];
static boolean[] colDone = new boolean[nCols];
static int[][] result = new int[nRows][nCols];
static ExecutorService es = Executors.newFixedThreadPool(2);
public static void main(String[] args) throws Exception {
int supplyLeft = stream(supply).sum();
int totalCost = 0;
while (supplyLeft > 0) {
int[] cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = Math.min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0)
colDone[c] = true;
supply[r] -= quantity;
if (supply[r] == 0)
rowDone[r] = true;
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
System.out.println("Total cost: " + totalCost);
es.shutdown();
}
static int[] nextCell() throws Exception {
Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));
Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));
int[] res1 = f1.get();
int[] res2 = f2.get();
if (res1[3] == res2[3])
return res1[2] < res2[2] ? res1 : res2;
return (res1[3] > res2[3]) ? res2 : res1;
}
static int[] diff(int j, int len, boolean isRow) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
int minP = -1;
for (int i = 0; i < len; i++) {
if (isRow ? colDone[i] : rowDone[i])
continue;
int c = isRow ? costs[j][i] : costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
minP = i;
} else if (c < min2)
min2 = c;
}
return new int[]{min2 - min1, min1, minP};
}
static int[] maxPenalty(int len1, int len2, boolean isRow) {
int md = Integer.MIN_VALUE;
int pc = -1, pm = -1, mc = -1;
for (int i = 0; i < len1; i++) {
if (isRow ? rowDone[i] : colDone[i])
continue;
int[] res = diff(i, len2, isRow);
if (res[0] > md) {
md = res[0];
pm = i;
mc = res[1];
pc = res[2];
}
}
return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"math"
)
const (
RE = 6371000
DD = 0.001
FIN = 1e7
)
func rho(a float64) float64 { return math.Exp(-a / 8500) }
func radians(degrees float64) float64 { return degrees * math.Pi / 180 }
func height(a, z, d float64) float64 {
aa := RE + a
hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))
return hh - RE
}
func columnDensity(a, z float64) float64 {
sum := 0.0
d := 0.0
for d < FIN {
delta := math.Max(DD, DD*d)
sum += rho(height(a, z, d+0.5*delta)) * delta
d += delta
}
return sum
}
func airmass(a, z float64) float64 {
return columnDensity(a, z) / columnDensity(a, 0)
}
func main() {
fmt.Println("Angle 0 m 13700 m")
fmt.Println("------------------------------------")
for z := 0; z <= 90; z += 5 {
fz := float64(z)
fmt.Printf("%2d %11.8f %11.8f\n", z, airmass(0, fz), airmass(13700, fz))
}
}
| public class AirMass {
public static void main(String[] args) {
System.out.println("Angle 0 m 13700 m");
System.out.println("------------------------------------");
for (double z = 0; z <= 90; z+= 5) {
System.out.printf("%2.0f %11.8f %11.8f\n",
z, airmass(0.0, z), airmass(13700.0, z));
}
}
private static double rho(double a) {
return Math.exp(-a / 8500.0);
}
private static double height(double a, double z, double d) {
double aa = RE + a;
double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));
return hh - RE;
}
private static double columnDensity(double a, double z) {
double sum = 0.0, d = 0.0;
while (d < FIN) {
double delta = Math.max(DD * d, DD);
sum += rho(height(a, z, d + 0.5 * delta)) * delta;
d += delta;
}
return sum;
}
private static double airmass(double a, double z) {
return columnDensity(a, z) / columnDensity(a, 0.0);
}
private static final double RE = 6371000.0;
private static final double DD = 0.001;
private static final double FIN = 10000000.0;
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import "fmt"
func main() {
list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
list.sort()
fmt.Println("sorted! ", list)
}
type pancake []int
func (a pancake) sort() {
for uns := len(a) - 1; uns > 0; uns-- {
lx, lg := 0, a[0]
for i := 1; i <= uns; i++ {
if a[i] > lg {
lx, lg = i, a[i]
}
}
a.flip(lx)
a.flip(uns)
}
}
func (a pancake) flip(r int) {
for l := 0; l < r; l, r = l+1, r-1 {
a[l], a[r] = a[r], a[l]
}
}
| public class PancakeSort
{
int[] heap;
public String toString() {
String info = "";
for (int x: heap)
info += x + " ";
return info;
}
public void flip(int n) {
for (int i = 0; i < (n+1) / 2; ++i) {
int tmp = heap[i];
heap[i] = heap[n-i];
heap[n-i] = tmp;
}
System.out.println("flip(0.." + n + "): " + toString());
}
public int[] minmax(int n) {
int xm, xM;
xm = xM = heap[0];
int posm = 0, posM = 0;
for (int i = 1; i < n; ++i) {
if (heap[i] < xm) {
xm = heap[i];
posm = i;
}
else if (heap[i] > xM) {
xM = heap[i];
posM = i;
}
}
return new int[] {posm, posM};
}
public void sort(int n, int dir) {
if (n == 0) return;
int[] mM = minmax(n);
int bestXPos = mM[dir];
int altXPos = mM[1-dir];
boolean flipped = false;
if (bestXPos == n-1) {
--n;
}
else if (bestXPos == 0) {
flip(n-1);
--n;
}
else if (altXPos == n-1) {
dir = 1-dir;
--n;
flipped = true;
}
else {
flip(bestXPos);
}
sort(n, dir);
if (flipped) {
flip(n);
}
}
PancakeSort(int[] numbers) {
heap = numbers;
sort(numbers.length, 1);
}
public static void main(String[] args) {
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; ++i)
numbers[i] = Integer.valueOf(args[i]);
PancakeSort pancakes = new PancakeSort(numbers);
System.out.println(pancakes);
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"strconv"
"strings"
)
var atomicMass = map[string]float64{
"H": 1.008,
"He": 4.002602,
"Li": 6.94,
"Be": 9.0121831,
"B": 10.81,
"C": 12.011,
"N": 14.007,
"O": 15.999,
"F": 18.998403163,
"Ne": 20.1797,
"Na": 22.98976928,
"Mg": 24.305,
"Al": 26.9815385,
"Si": 28.085,
"P": 30.973761998,
"S": 32.06,
"Cl": 35.45,
"Ar": 39.948,
"K": 39.0983,
"Ca": 40.078,
"Sc": 44.955908,
"Ti": 47.867,
"V": 50.9415,
"Cr": 51.9961,
"Mn": 54.938044,
"Fe": 55.845,
"Co": 58.933194,
"Ni": 58.6934,
"Cu": 63.546,
"Zn": 65.38,
"Ga": 69.723,
"Ge": 72.630,
"As": 74.921595,
"Se": 78.971,
"Br": 79.904,
"Kr": 83.798,
"Rb": 85.4678,
"Sr": 87.62,
"Y": 88.90584,
"Zr": 91.224,
"Nb": 92.90637,
"Mo": 95.95,
"Ru": 101.07,
"Rh": 102.90550,
"Pd": 106.42,
"Ag": 107.8682,
"Cd": 112.414,
"In": 114.818,
"Sn": 118.710,
"Sb": 121.760,
"Te": 127.60,
"I": 126.90447,
"Xe": 131.293,
"Cs": 132.90545196,
"Ba": 137.327,
"La": 138.90547,
"Ce": 140.116,
"Pr": 140.90766,
"Nd": 144.242,
"Pm": 145,
"Sm": 150.36,
"Eu": 151.964,
"Gd": 157.25,
"Tb": 158.92535,
"Dy": 162.500,
"Ho": 164.93033,
"Er": 167.259,
"Tm": 168.93422,
"Yb": 173.054,
"Lu": 174.9668,
"Hf": 178.49,
"Ta": 180.94788,
"W": 183.84,
"Re": 186.207,
"Os": 190.23,
"Ir": 192.217,
"Pt": 195.084,
"Au": 196.966569,
"Hg": 200.592,
"Tl": 204.38,
"Pb": 207.2,
"Bi": 208.98040,
"Po": 209,
"At": 210,
"Rn": 222,
"Fr": 223,
"Ra": 226,
"Ac": 227,
"Th": 232.0377,
"Pa": 231.03588,
"U": 238.02891,
"Np": 237,
"Pu": 244,
"Am": 243,
"Cm": 247,
"Bk": 247,
"Cf": 251,
"Es": 252,
"Fm": 257,
"Uue": 315,
"Ubn": 299,
}
func replaceParens(s string) string {
var letter byte = 'a'
for {
start := strings.IndexByte(s, '(')
if start == -1 {
break
}
restart:
for i := start + 1; i < len(s); i++ {
if s[i] == ')' {
expr := s[start+1 : i]
symbol := fmt.Sprintf("@%c", letter)
s = strings.Replace(s, s[start:i+1], symbol, 1)
atomicMass[symbol] = evaluate(expr)
letter++
break
}
if s[i] == '(' {
start = i
goto restart
}
}
}
return s
}
func evaluate(s string) float64 {
s += string('[')
var symbol, number string
sum := 0.0
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c >= '@' && c <= '[':
n := 1
if number != "" {
n, _ = strconv.Atoi(number)
}
if symbol != "" {
sum += atomicMass[symbol] * float64(n)
}
if c == '[' {
break
}
symbol = string(c)
number = ""
case c >= 'a' && c <= 'z':
symbol += string(c)
case c >= '0' && c <= '9':
number += string(c)
default:
panic(fmt.Sprintf("Unexpected symbol %c in molecule", c))
}
}
return sum
}
func main() {
molecules := []string{
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3",
"C6H4O2(OH)4", "C27H46O", "Uue",
}
for _, molecule := range molecules {
mass := evaluate(replaceParens(molecule))
fmt.Printf("%17s -> %7.3f\n", molecule, mass)
}
}
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class ChemicalCalculator {
private static final Map<String, Double> atomicMass = new HashMap<>();
static {
atomicMass.put("H", 1.008);
atomicMass.put("He", 4.002602);
atomicMass.put("Li", 6.94);
atomicMass.put("Be", 9.0121831);
atomicMass.put("B", 10.81);
atomicMass.put("C", 12.011);
atomicMass.put("N", 14.007);
atomicMass.put("O", 15.999);
atomicMass.put("F", 18.998403163);
atomicMass.put("Ne", 20.1797);
atomicMass.put("Na", 22.98976928);
atomicMass.put("Mg", 24.305);
atomicMass.put("Al", 26.9815385);
atomicMass.put("Si", 28.085);
atomicMass.put("P", 30.973761998);
atomicMass.put("S", 32.06);
atomicMass.put("Cl", 35.45);
atomicMass.put("Ar", 39.948);
atomicMass.put("K", 39.0983);
atomicMass.put("Ca", 40.078);
atomicMass.put("Sc", 44.955908);
atomicMass.put("Ti", 47.867);
atomicMass.put("V", 50.9415);
atomicMass.put("Cr", 51.9961);
atomicMass.put("Mn", 54.938044);
atomicMass.put("Fe", 55.845);
atomicMass.put("Co", 58.933194);
atomicMass.put("Ni", 58.6934);
atomicMass.put("Cu", 63.546);
atomicMass.put("Zn", 65.38);
atomicMass.put("Ga", 69.723);
atomicMass.put("Ge", 72.630);
atomicMass.put("As", 74.921595);
atomicMass.put("Se", 78.971);
atomicMass.put("Br", 79.904);
atomicMass.put("Kr", 83.798);
atomicMass.put("Rb", 85.4678);
atomicMass.put("Sr", 87.62);
atomicMass.put("Y", 88.90584);
atomicMass.put("Zr", 91.224);
atomicMass.put("Nb", 92.90637);
atomicMass.put("Mo", 95.95);
atomicMass.put("Ru", 101.07);
atomicMass.put("Rh", 102.90550);
atomicMass.put("Pd", 106.42);
atomicMass.put("Ag", 107.8682);
atomicMass.put("Cd", 112.414);
atomicMass.put("In", 114.818);
atomicMass.put("Sn", 118.710);
atomicMass.put("Sb", 121.760);
atomicMass.put("Te", 127.60);
atomicMass.put("I", 126.90447);
atomicMass.put("Xe", 131.293);
atomicMass.put("Cs", 132.90545196);
atomicMass.put("Ba", 137.327);
atomicMass.put("La", 138.90547);
atomicMass.put("Ce", 140.116);
atomicMass.put("Pr", 140.90766);
atomicMass.put("Nd", 144.242);
atomicMass.put("Pm", 145.0);
atomicMass.put("Sm", 150.36);
atomicMass.put("Eu", 151.964);
atomicMass.put("Gd", 157.25);
atomicMass.put("Tb", 158.92535);
atomicMass.put("Dy", 162.500);
atomicMass.put("Ho", 164.93033);
atomicMass.put("Er", 167.259);
atomicMass.put("Tm", 168.93422);
atomicMass.put("Yb", 173.054);
atomicMass.put("Lu", 174.9668);
atomicMass.put("Hf", 178.49);
atomicMass.put("Ta", 180.94788);
atomicMass.put("W", 183.84);
atomicMass.put("Re", 186.207);
atomicMass.put("Os", 190.23);
atomicMass.put("Ir", 192.217);
atomicMass.put("Pt", 195.084);
atomicMass.put("Au", 196.966569);
atomicMass.put("Hg", 200.592);
atomicMass.put("Tl", 204.38);
atomicMass.put("Pb", 207.2);
atomicMass.put("Bi", 208.98040);
atomicMass.put("Po", 209.0);
atomicMass.put("At", 210.0);
atomicMass.put("Rn", 222.0);
atomicMass.put("Fr", 223.0);
atomicMass.put("Ra", 226.0);
atomicMass.put("Ac", 227.0);
atomicMass.put("Th", 232.0377);
atomicMass.put("Pa", 231.03588);
atomicMass.put("U", 238.02891);
atomicMass.put("Np", 237.0);
atomicMass.put("Pu", 244.0);
atomicMass.put("Am", 243.0);
atomicMass.put("Cm", 247.0);
atomicMass.put("Bk", 247.0);
atomicMass.put("Cf", 251.0);
atomicMass.put("Es", 252.0);
atomicMass.put("Fm", 257.0);
atomicMass.put("Uue", 315.0);
atomicMass.put("Ubn", 299.0);
}
private static double evaluate(String s) {
String sym = s + "[";
double sum = 0.0;
StringBuilder symbol = new StringBuilder();
String number = "";
for (int i = 0; i < sym.length(); ++i) {
char c = sym.charAt(i);
if ('@' <= c && c <= '[') {
int n = 1;
if (!number.isEmpty()) {
n = Integer.parseInt(number);
}
if (symbol.length() > 0) {
sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;
}
if (c == '[') {
break;
}
symbol = new StringBuilder(String.valueOf(c));
number = "";
} else if ('a' <= c && c <= 'z') {
symbol.append(c);
} else if ('0' <= c && c <= '9') {
number += c;
} else {
throw new RuntimeException("Unexpected symbol " + c + " in molecule");
}
}
return sum;
}
private static String replaceParens(String s) {
char letter = 'a';
String si = s;
while (true) {
int start = si.indexOf('(');
if (start == -1) {
break;
}
for (int i = start + 1; i < si.length(); ++i) {
if (si.charAt(i) == ')') {
String expr = si.substring(start + 1, i);
String symbol = "@" + letter;
String pattern = Pattern.quote(si.substring(start, i + 1));
si = si.replaceFirst(pattern, symbol);
atomicMass.put(symbol, evaluate(expr));
letter++;
break;
}
if (si.charAt(i) == '(') {
start = i;
}
}
}
return si;
}
public static void main(String[] args) {
List<String> molecules = List.of(
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
);
for (String molecule : molecules) {
double mass = evaluate(replaceParens(molecule));
System.out.printf("%17s -> %7.3f\n", molecule, mass);
}
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"log"
"github.com/jtblin/go-ldap-client"
)
func main() {
client := &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.example.com",
Port: 389,
UseSSL: false,
BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com",
BindPassword: "readonlypassword",
UserFilter: "(uid=%s)",
GroupFilter: "(memberUid=%s)",
Attributes: []string{"givenName", "sn", "mail", "uid"},
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect : %+v", err)
}
}
| import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapConnectionDemo {
public static void main(String[] args) throws LdapException, IOException {
try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
connection.bind();
connection.unBind();
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package permute
func Iter(p []int) func() int {
f := pf(len(p))
return func() int {
return f(p)
}
}
func pf(n int) func([]int) int {
sign := 1
switch n {
case 0, 1:
return func([]int) (s int) {
s = sign
sign = 0
return
}
default:
p0 := pf(n - 1)
i := n
var d int
return func(p []int) int {
switch {
case sign == 0:
case i == n:
i--
sign = p0(p[:i])
d = -1
case i == 0:
i++
sign *= p0(p[1:])
d = 1
if sign == 0 {
p[0], p[1] = p[1], p[0]
}
default:
p[i], p[i-1] = p[i-1], p[i]
sign = -sign
i += d
}
return sign
}
}
}
| package org.rosettacode.java;
import java.util.Arrays;
import java.util.stream.IntStream;
public class HeapsAlgorithm {
public static void main(String[] args) {
Object[] array = IntStream.range(0, 4)
.boxed()
.toArray();
HeapsAlgorithm algorithm = new HeapsAlgorithm();
algorithm.recursive(array);
System.out.println();
algorithm.loop(array);
}
void recursive(Object[] array) {
recursive(array, array.length, true);
}
void recursive(Object[] array, int n, boolean plus) {
if (n == 1) {
output(array, plus);
} else {
for (int i = 0; i < n; i++) {
recursive(array, n - 1, i == 0);
swap(array, n % 2 == 0 ? i : 0, n - 1);
}
}
}
void output(Object[] array, boolean plus) {
System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1"));
}
void swap(Object[] array, int a, int b) {
Object o = array[a];
array[a] = array[b];
array[b] = o;
}
void loop(Object[] array) {
loop(array, array.length);
}
void loop(Object[] array, int n) {
int[] c = new int[n];
output(array, true);
boolean plus = false;
for (int i = 0; i < n; ) {
if (c[i] < i) {
if (i % 2 == 0) {
swap(array, 0, i);
} else {
swap(array, c[i], i);
}
output(array, plus);
plus = !plus;
c[i]++;
i = 0;
} else {
c[i] = 0;
i++;
}
}
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import "fmt"
const (
N = 2200
N2 = N * N * 2
)
func main() {
s := 3
var s1, s2 int
var r [N + 1]bool
var ab [N2 + 1]bool
for a := 1; a <= N; a++ {
a2 := a * a
for b := a; b <= N; b++ {
ab[a2 + b * b] = true
}
}
for c := 1; c <= N; c++ {
s1 = s
s += 2
s2 = s
for d := c + 1; d <= N; d++ {
if ab[s1] {
r[d] = true
}
s1 += s2
s2 += 2
}
}
for d := 1; d <= N; d++ {
if !r[d] {
fmt.Printf("%d ", d)
}
}
fmt.Println()
}
| import java.util.ArrayList;
import java.util.List;
public class PythagoreanQuadruples {
public static void main(String[] args) {
long d = 2200;
System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
}
private static List<Long> getPythagoreanQuadruples(long max) {
List<Long> list = new ArrayList<>();
long n = -1;
long m = -1;
while ( true ) {
long nTest = (long) Math.pow(2, n+1);
long mTest = (long) (5L * Math.pow(2, m+1));
long test = 0;
if ( nTest > mTest ) {
test = mTest;
m++;
}
else {
test = nTest;
n++;
}
if ( test < max ) {
list.add(test);
}
else {
break;
}
}
return list;
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
type line struct {
kind lineKind
option string
value string
disabled bool
}
type lineKind int
const (
_ lineKind = iota
ignore
parseError
comment
blank
value
)
func (l line) String() string {
switch l.kind {
case ignore, parseError, comment, blank:
return l.value
case value:
s := l.option
if l.disabled {
s = "; " + s
}
if l.value != "" {
s += " " + l.value
}
return s
}
panic("unexpected line kind")
}
func removeDross(s string) string {
return strings.Map(func(r rune) rune {
if r < 32 || r > 0x7f || unicode.IsControl(r) {
return -1
}
return r
}, s)
}
func parseLine(s string) line {
if s == "" {
return line{kind: blank}
}
if s[0] == '#' {
return line{kind: comment, value: s}
}
s = removeDross(s)
fields := strings.Fields(s)
if len(fields) == 0 {
return line{kind: blank}
}
semi := false
for len(fields[0]) > 0 && fields[0][0] == ';' {
semi = true
fields[0] = fields[0][1:]
}
if fields[0] == "" {
fields = fields[1:]
}
switch len(fields) {
case 0:
return line{kind: ignore}
case 1:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
disabled: semi,
}
case 2:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
value: fields[1],
disabled: semi,
}
}
return line{kind: parseError, value: s}
}
type Config struct {
options map[string]int
lines []line
}
func (c *Config) index(option string) int {
if i, ok := c.options[option]; ok {
return i
}
return -1
}
func (c *Config) addLine(l line) {
switch l.kind {
case ignore:
return
case value:
if c.index(l.option) >= 0 {
return
}
c.options[l.option] = len(c.lines)
c.lines = append(c.lines, l)
default:
c.lines = append(c.lines, l)
}
}
func ReadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
c := &Config{options: make(map[string]int)}
for {
s, err := r.ReadString('\n')
if s != "" {
if err == nil {
s = s[:len(s)-1]
}
c.addLine(parseLine(s))
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
return c, nil
}
func (c *Config) Set(option string, val string) {
if i := c.index(option); i >= 0 {
line := &c.lines[i]
line.disabled = false
line.value = val
return
}
c.addLine(line{
kind: value,
option: option,
value: val,
})
}
func (c *Config) Enable(option string, enabled bool) {
if i := c.index(option); i >= 0 {
c.lines[i].disabled = !enabled
}
}
func (c *Config) Write(w io.Writer) {
for _, line := range c.lines {
fmt.Println(line)
}
}
func main() {
c, err := ReadConfig("/tmp/cfg")
if err != nil {
log.Fatalln(err)
}
c.Enable("NEEDSPEELING", false)
c.Set("SEEDSREMOVED", "")
c.Set("NUMBEROFBANANAS", "1024")
c.Set("NUMBEROFSTRAWBERRIES", "62000")
c.Write(os.Stdout)
}
| import java.io.*;
import java.util.*;
import java.util.regex.*;
public class UpdateConfig {
public static void main(String[] args) {
if (args[0] == null) {
System.out.println("filename required");
} else if (readConfig(args[0])) {
enableOption("seedsremoved");
disableOption("needspeeling");
setOption("numberofbananas", "1024");
addOption("numberofstrawberries", "62000");
store();
}
}
private enum EntryType {
EMPTY, ENABLED, DISABLED, COMMENT
}
private static class Entry {
EntryType type;
String name, value;
Entry(EntryType t, String n, String v) {
type = t;
name = n;
value = v;
}
}
private static Map<String, Entry> entries = new LinkedHashMap<>();
private static String path;
private static boolean readConfig(String p) {
path = p;
File f = new File(path);
if (!f.exists() || f.isDirectory())
return false;
String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)";
Pattern regex = Pattern.compile(regexString);
try (Scanner sc = new Scanner(new FileReader(f))){
int emptyLines = 0;
String line;
while (sc.hasNext()) {
line = sc.nextLine().trim();
if (line.isEmpty()) {
addOption("" + emptyLines++, null, EntryType.EMPTY);
} else if (line.charAt(0) == '#') {
entries.put(line, new Entry(EntryType.COMMENT, line, null));
} else {
line = line.replaceAll("[^a-zA-Z0-9\\x20;]", "");
Matcher m = regex.matcher(line);
if (m.find() && !m.group(2).isEmpty()) {
EntryType t = EntryType.ENABLED;
if (!m.group(1).isEmpty())
t = EntryType.DISABLED;
addOption(m.group(2), m.group(3), t);
}
}
}
} catch (IOException e) {
System.out.println(e);
}
return true;
}
private static void addOption(String name, String value) {
addOption(name, value, EntryType.ENABLED);
}
private static void addOption(String name, String value, EntryType t) {
name = name.toUpperCase();
entries.put(name, new Entry(t, name, value));
}
private static void enableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.ENABLED;
}
private static void disableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.DISABLED;
}
private static void setOption(String name, String value) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.value = value;
}
private static void store() {
try (PrintWriter pw = new PrintWriter(path)) {
for (Entry e : entries.values()) {
switch (e.type) {
case EMPTY:
pw.println();
break;
case ENABLED:
pw.format("%s %s%n", e.name, e.value);
break;
case DISABLED:
pw.format("; %s %s%n", e.name, e.value);
break;
case COMMENT:
pw.println(e.name);
break;
default:
break;
}
}
if (pw.checkError()) {
throw new IOException("writing to file failed");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"image"
"image/color"
"image/jpeg"
"math"
"os"
)
func kf3(k *[9]float64, src, dst *image.Gray) {
for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {
for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {
var sum float64
var i int
for yo := y - 1; yo <= y+1; yo++ {
for xo := x - 1; xo <= x+1; xo++ {
if (image.Point{xo, yo}).In(src.Rect) {
sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)
} else {
sum += k[i] * float64(src.At(x, y).(color.Gray).Y)
}
i++
}
}
dst.SetGray(x, y,
color.Gray{uint8(math.Min(255, math.Max(0, sum)))})
}
}
}
var blur = [9]float64{
1. / 9, 1. / 9, 1. / 9,
1. / 9, 1. / 9, 1. / 9,
1. / 9, 1. / 9, 1. / 9}
func blurY(src *image.YCbCr) *image.YCbCr {
dst := *src
if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {
return &dst
}
srcGray := image.Gray{src.Y, src.YStride, src.Rect}
dstGray := srcGray
dstGray.Pix = make([]uint8, len(src.Y))
kf3(&blur, &srcGray, &dstGray)
dst.Y = dstGray.Pix
dst.Cb = append([]uint8{}, src.Cb...)
dst.Cr = append([]uint8{}, src.Cr...)
return &dst
}
func main() {
f, err := os.Open("Lenna100.jpg")
if err != nil {
fmt.Println(err)
return
}
img, err := jpeg.Decode(f)
if err != nil {
fmt.Println(err)
return
}
f.Close()
y, ok := img.(*image.YCbCr)
if !ok {
fmt.Println("expected color jpeg")
return
}
f, err = os.Create("blur.jpg")
if err != nil {
fmt.Println(err)
return
}
err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})
if err != nil {
fmt.Println(err)
}
}
| import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
public class ImageConvolution
{
public static class ArrayData
{
public final int[] dataArray;
public final int width;
public final int height;
public ArrayData(int width, int height)
{
this(new int[width * height], width, height);
}
public ArrayData(int[] dataArray, int width, int height)
{
this.dataArray = dataArray;
this.width = width;
this.height = height;
}
public int get(int x, int y)
{ return dataArray[y * width + x]; }
public void set(int x, int y, int value)
{ dataArray[y * width + x] = value; }
}
private static int bound(int value, int endIndex)
{
if (value < 0)
return 0;
if (value < endIndex)
return value;
return endIndex - 1;
}
public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)
{
int inputWidth = inputData.width;
int inputHeight = inputData.height;
int kernelWidth = kernel.width;
int kernelHeight = kernel.height;
if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))
throw new IllegalArgumentException("Kernel must have odd width");
if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))
throw new IllegalArgumentException("Kernel must have odd height");
int kernelWidthRadius = kernelWidth >>> 1;
int kernelHeightRadius = kernelHeight >>> 1;
ArrayData outputData = new ArrayData(inputWidth, inputHeight);
for (int i = inputWidth - 1; i >= 0; i--)
{
for (int j = inputHeight - 1; j >= 0; j--)
{
double newValue = 0.0;
for (int kw = kernelWidth - 1; kw >= 0; kw--)
for (int kh = kernelHeight - 1; kh >= 0; kh--)
newValue += kernel.get(kw, kh) * inputData.get(
bound(i + kw - kernelWidthRadius, inputWidth),
bound(j + kh - kernelHeightRadius, inputHeight));
outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));
}
}
return outputData;
}
public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException
{
BufferedImage inputImage = ImageIO.read(new File(filename));
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
ArrayData reds = new ArrayData(width, height);
ArrayData greens = new ArrayData(width, height);
ArrayData blues = new ArrayData(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgbValue = rgbData[y * width + x];
reds.set(x, y, (rgbValue >>> 16) & 0xFF);
greens.set(x, y, (rgbValue >>> 8) & 0xFF);
blues.set(x, y, rgbValue & 0xFF);
}
}
return new ArrayData[] { reds, greens, blues };
}
public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException
{
ArrayData reds = redGreenBlue[0];
ArrayData greens = redGreenBlue[1];
ArrayData blues = redGreenBlue[2];
BufferedImage outputImage = new BufferedImage(reds.width, reds.height,
BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < reds.height; y++)
{
for (int x = 0; x < reds.width; x++)
{
int red = bound(reds.get(x, y), 256);
int green = bound(greens.get(x, y), 256);
int blue = bound(blues.get(x, y), 256);
outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);
}
}
ImageIO.write(outputImage, "PNG", new File(filename));
return;
}
public static void main(String[] args) throws IOException
{
int kernelWidth = Integer.parseInt(args[2]);
int kernelHeight = Integer.parseInt(args[3]);
int kernelDivisor = Integer.parseInt(args[4]);
System.out.println("Kernel size: " + kernelWidth + "x" + kernelHeight +
", divisor=" + kernelDivisor);
int y = 5;
ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);
for (int i = 0; i < kernelHeight; i++)
{
System.out.print("[");
for (int j = 0; j < kernelWidth; j++)
{
kernel.set(j, i, Integer.parseInt(args[y++]));
System.out.print(" " + kernel.get(j, i) + " ");
}
System.out.println("]");
}
ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);
for (int i = 0; i < dataArrays.length; i++)
dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);
writeOutputImage(args[1], dataArrays);
return;
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import(
"math"
"fmt"
)
func minOf(x, y uint) uint {
if x < y {
return x
}
return y
}
func throwDie(nSides, nDice, s uint, counts []uint) {
if nDice == 0 {
counts[s]++
return
}
for i := uint(1); i <= nSides; i++ {
throwDie(nSides, nDice - 1, s + i, counts)
}
}
func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
len1 := (nSides1 + 1) * nDice1
c1 := make([]uint, len1)
throwDie(nSides1, nDice1, 0, c1)
len2 := (nSides2 + 1) * nDice2
c2 := make([]uint, len2)
throwDie(nSides2, nDice2, 0, c2)
p12 := math.Pow(float64(nSides1), float64(nDice1)) *
math.Pow(float64(nSides2), float64(nDice2))
tot := 0.0
for i := uint(0); i < len1; i++ {
for j := uint(0); j < minOf(i, len2); j++ {
tot += float64(c1[i] * c2[j]) / p12
}
}
return tot
}
func main() {
fmt.Println(beatingProbability(4, 9, 6, 6))
fmt.Println(beatingProbability(10, 5, 7, 6))
}
| import java.util.Random;
public class Dice{
private static int roll(int nDice, int nSides){
int sum = 0;
Random rand = new Random();
for(int i = 0; i < nDice; i++){
sum += rand.nextInt(nSides) + 1;
}
return sum;
}
private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){
int p1Wins = 0;
for(int i = 0; i < rolls; i++){
int p1Roll = roll(p1Dice, p1Sides);
int p2Roll = roll(p2Dice, p2Sides);
if(p1Roll > p2Roll) p1Wins++;
}
return p1Wins;
}
public static void main(String[] args){
int p1Dice = 9; int p1Sides = 4;
int p2Dice = 6; int p2Sides = 6;
int rolls = 10000;
int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 10000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 9; p1Sides = 4;
p2Dice = 6; p2Sides = 6;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"strings"
)
func main() {
level := `
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######`
fmt.Printf("level:%s\n", level)
fmt.Printf("solution:\n%s\n", solve(level))
}
func solve(board string) string {
buffer = make([]byte, len(board))
width := strings.Index(board[1:], "\n") + 1
dirs := []struct {
move, push string
dPos int
}{
{"u", "U", -width},
{"r", "R", 1},
{"d", "D", width},
{"l", "L", -1},
}
visited := map[string]bool{board: true}
open := []state{state{board, "", strings.Index(board, "@")}}
for len(open) > 0 {
s1 := &open[0]
open = open[1:]
for _, dir := range dirs {
var newBoard, newSol string
newPos := s1.pos + dir.dPos
switch s1.board[newPos] {
case '$', '*':
newBoard = s1.push(dir.dPos)
if newBoard == "" || visited[newBoard] {
continue
}
newSol = s1.cSol + dir.push
if strings.IndexAny(newBoard, ".+") < 0 {
return newSol
}
case ' ', '.':
newBoard = s1.move(dir.dPos)
if visited[newBoard] {
continue
}
newSol = s1.cSol + dir.move
default:
continue
}
open = append(open, state{newBoard, newSol, newPos})
visited[newBoard] = true
}
}
return "No solution"
}
type state struct {
board string
cSol string
pos int
}
var buffer []byte
func (s *state) move(dPos int) string {
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
newPos := s.pos + dPos
if buffer[newPos] == ' ' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
return string(buffer)
}
func (s *state) push(dPos int) string {
newPos := s.pos + dPos
boxPos := newPos + dPos
switch s.board[boxPos] {
case ' ', '.':
default:
return ""
}
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
if buffer[newPos] == '$' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
if buffer[boxPos] == ' ' {
buffer[boxPos] = '$'
} else {
buffer[boxPos] = '*'
}
return string(buffer)
}
| import java.util.*;
public class Sokoban {
String destBoard, currBoard;
int playerX, playerY, nCols;
Sokoban(String[] board) {
nCols = board[0].length();
StringBuilder destBuf = new StringBuilder();
StringBuilder currBuf = new StringBuilder();
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < nCols; c++) {
char ch = board[r].charAt(c);
destBuf.append(ch != '$' && ch != '@' ? ch : ' ');
currBuf.append(ch != '.' ? ch : ' ');
if (ch == '@') {
this.playerX = c;
this.playerY = r;
}
}
}
destBoard = destBuf.toString();
currBoard = currBuf.toString();
}
String move(int x, int y, int dx, int dy, String trialBoard) {
int newPlayerPos = (y + dy) * nCols + x + dx;
if (trialBoard.charAt(newPlayerPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[newPlayerPos] = '@';
return new String(trial);
}
String push(int x, int y, int dx, int dy, String trialBoard) {
int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;
if (trialBoard.charAt(newBoxPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[(y + dy) * nCols + x + dx] = '@';
trial[newBoxPos] = '$';
return new String(trial);
}
boolean isSolved(String trialBoard) {
for (int i = 0; i < trialBoard.length(); i++)
if ((destBoard.charAt(i) == '.')
!= (trialBoard.charAt(i) == '$'))
return false;
return true;
}
String solve() {
class Board {
String cur, sol;
int x, y;
Board(String s1, String s2, int px, int py) {
cur = s1;
sol = s2;
x = px;
y = py;
}
}
char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};
int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
Set<String> history = new HashSet<>();
LinkedList<Board> open = new LinkedList<>();
history.add(currBoard);
open.add(new Board(currBoard, "", playerX, playerY));
while (!open.isEmpty()) {
Board item = open.poll();
String cur = item.cur;
String sol = item.sol;
int x = item.x;
int y = item.y;
for (int i = 0; i < dirs.length; i++) {
String trial = cur;
int dx = dirs[i][0];
int dy = dirs[i][1];
if (trial.charAt((y + dy) * nCols + x + dx) == '$') {
if ((trial = push(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][1];
if (isSolved(trial))
return newSol;
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
} else if ((trial = move(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][0];
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
}
}
return "No solution";
}
public static void main(String[] a) {
String level = "#######,# #,# #,#. # #,#. $$ #,"
+ "#.$$ #,#.# @#,#######";
System.out.println(new Sokoban(level.split(",")).solve());
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"rcu"
)
func powerset(set []int) [][]int {
if len(set) == 0 {
return [][]int{{}}
}
head := set[0]
tail := set[1:]
p1 := powerset(tail)
var p2 [][]int
for _, s := range powerset(tail) {
h := []int{head}
h = append(h, s...)
p2 = append(p2, h)
}
return append(p1, p2...)
}
func isPractical(n int) bool {
if n == 1 {
return true
}
divs := rcu.ProperDivisors(n)
subsets := powerset(divs)
found := make([]bool, n)
count := 0
for _, subset := range subsets {
sum := rcu.SumInts(subset)
if sum > 0 && sum < n && !found[sum] {
found[sum] = true
count++
if count == n-1 {
return true
}
}
}
return false
}
func main() {
fmt.Println("In the range 1..333, there are:")
var practical []int
for i := 1; i <= 333; i++ {
if isPractical(i) {
practical = append(practical, i)
}
}
fmt.Println(" ", len(practical), "practical numbers")
fmt.Println(" The first ten are", practical[0:10])
fmt.Println(" The final ten are", practical[len(practical)-10:])
fmt.Println("\n666 is practical:", isPractical(666))
}
| import java.util.*;
public class PracticalNumbers {
public static void main(String[] args) {
final int from = 1;
final int to = 333;
List<Integer> practical = new ArrayList<>();
for (int i = from; i <= to; ++i) {
if (isPractical(i))
practical.add(i);
}
System.out.printf("Found %d practical numbers between %d and %d:\n%s\n",
practical.size(), from, to, shorten(practical, 10));
printPractical(666);
printPractical(6666);
printPractical(66666);
printPractical(672);
printPractical(720);
printPractical(222222);
}
private static void printPractical(int n) {
if (isPractical(n))
System.out.printf("%d is a practical number.\n", n);
else
System.out.printf("%d is not a practical number.\n", n);
}
private static boolean isPractical(int n) {
int[] divisors = properDivisors(n);
for (int i = 1; i < n; ++i) {
if (!sumOfAnySubset(i, divisors, divisors.length))
return false;
}
return true;
}
private static boolean sumOfAnySubset(int n, int[] f, int len) {
if (len == 0)
return false;
int total = 0;
for (int i = 0; i < len; ++i) {
if (n == f[i])
return true;
total += f[i];
}
if (n == total)
return true;
if (n > total)
return false;
--len;
int d = n - f[len];
return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);
}
private static int[] properDivisors(int n) {
List<Integer> divisors = new ArrayList<>();
divisors.add(1);
for (int i = 2;; ++i) {
int i2 = i * i;
if (i2 > n)
break;
if (n % i == 0) {
divisors.add(i);
if (i2 != n)
divisors.add(n / i);
}
}
int[] result = new int[divisors.size()];
for (int i = 0; i < result.length; ++i)
result[i] = divisors.get(i);
Arrays.sort(result);
return result;
}
private static String shorten(List<Integer> list, int n) {
StringBuilder str = new StringBuilder();
int len = list.size(), i = 0;
if (n > 0 && len > 0)
str.append(list.get(i++));
for (; i < n && i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
if (len > i + n) {
if (n > 0)
str.append(", ...");
i = len - n;
}
for (; i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
return str.toString();
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
| import java.util.*;
public class ErdosPrimes {
public static void main(String[] args) {
boolean[] sieve = primeSieve(1000000);
int maxPrint = 2500;
int maxCount = 7875;
System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint);
for (int count = 0, prime = 1; count < maxCount; ++prime) {
if (erdos(sieve, prime)) {
++count;
if (prime < maxPrint) {
System.out.printf("%6d", prime);
if (count % 10 == 0)
System.out.println();
}
if (count == maxCount)
System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime);
}
}
}
private static boolean erdos(boolean[] sieve, int p) {
if (!sieve[p])
return false;
for (int k = 1, f = 1; f < p; ++k, f *= k) {
if (sieve[p - f])
return false;
}
return true;
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3; ; p += 2) {
int q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
int inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
| import java.util.*;
public class ErdosPrimes {
public static void main(String[] args) {
boolean[] sieve = primeSieve(1000000);
int maxPrint = 2500;
int maxCount = 7875;
System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint);
for (int count = 0, prime = 1; count < maxCount; ++prime) {
if (erdos(sieve, prime)) {
++count;
if (prime < maxPrint) {
System.out.printf("%6d", prime);
if (count % 10 == 0)
System.out.println();
}
if (count == maxCount)
System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime);
}
}
}
private static boolean erdos(boolean[] sieve, int p) {
if (!sieve[p])
return false;
for (int k = 1, f = 1; f < p; ++k, f *= k) {
if (sieve[p - f])
return false;
}
return true;
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3; ; p += 2) {
int q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
int inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
| import java.util.*;
public class ErdosPrimes {
public static void main(String[] args) {
boolean[] sieve = primeSieve(1000000);
int maxPrint = 2500;
int maxCount = 7875;
System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint);
for (int count = 0, prime = 1; count < maxCount; ++prime) {
if (erdos(sieve, prime)) {
++count;
if (prime < maxPrint) {
System.out.printf("%6d", prime);
if (count % 10 == 0)
System.out.println();
}
if (count == maxCount)
System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime);
}
}
}
private static boolean erdos(boolean[] sieve, int p) {
if (!sieve[p])
return false;
for (int k = 1, f = 1; f < p; ++k, f *= k) {
if (sieve[p - f])
return false;
}
return true;
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3; ; p += 2) {
int q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
int inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
| import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
| import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
| import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
| package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four)));
System.out.println("4+3=" + toInt(plus(four).apply(three)));
System.out.println("3*4=" + toInt(mult(three).apply(four)));
System.out.println("4*3=" + toInt(mult(four).apply(three)));
System.out.println("3^4=" + toInt(pow(four).apply(three)));
System.out.println("4^3=" + toInt(pow(three).apply(four)));
System.out.println(" 8=" + toInt(toChurchNum(8)));
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
| package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four)));
System.out.println("4+3=" + toInt(plus(four).apply(three)));
System.out.println("3*4=" + toInt(mult(three).apply(four)));
System.out.println("4*3=" + toInt(mult(four).apply(three)));
System.out.println("3^4=" + toInt(pow(four).apply(three)));
System.out.println("4^3=" + toInt(pow(three).apply(four)));
System.out.println(" 8=" + toInt(toChurchNum(8)));
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
| import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
| import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
| import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import (
"fmt"
"strings"
)
type BitSet []bool
func (bs BitSet) and(other BitSet) {
for i := range bs {
if bs[i] && other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func (bs BitSet) or(other BitSet) {
for i := range bs {
if bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
| import java.util.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.toList;
public class NonogramSolver {
static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"};
static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE "
+ "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"};
static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH "
+ "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF "
+ "AAAAD BDG CEF CBDB BBB FC"};
static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q "
+ "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ "
+ "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"};
public static void main(String[] args) {
for (String[] puzzleData : new String[][]{p1, p2, p3, p4})
newPuzzle(puzzleData);
}
static void newPuzzle(String[] data) {
String[] rowData = data[0].split("\\s");
String[] colData = data[1].split("\\s");
List<List<BitSet>> cols, rows;
rows = getCandidates(rowData, colData.length);
cols = getCandidates(colData, rowData.length);
int numChanged;
do {
numChanged = reduceMutual(cols, rows);
if (numChanged == -1) {
System.out.println("No solution");
return;
}
} while (numChanged > 0);
for (List<BitSet> row : rows) {
for (int i = 0; i < cols.size(); i++)
System.out.print(row.get(0).get(i) ? "# " : ". ");
System.out.println();
}
System.out.println();
}
static List<List<BitSet>> getCandidates(String[] data, int len) {
List<List<BitSet>> result = new ArrayList<>();
for (String s : data) {
List<BitSet> lst = new LinkedList<>();
int sumChars = s.chars().map(c -> c - 'A' + 1).sum();
List<String> prep = stream(s.split(""))
.map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList());
for (String r : genSequence(prep, len - sumChars + 1)) {
char[] bits = r.substring(1).toCharArray();
BitSet bitset = new BitSet(bits.length);
for (int i = 0; i < bits.length; i++)
bitset.set(i, bits[i] == '1');
lst.add(bitset);
}
result.add(lst);
}
return result;
}
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {
int countRemoved1 = reduce(cols, rows);
if (countRemoved1 == -1)
return -1;
int countRemoved2 = reduce(rows, cols);
if (countRemoved2 == -1)
return -1;
return countRemoved1 + countRemoved2;
}
static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {
int countRemoved = 0;
for (int i = 0; i < a.size(); i++) {
BitSet commonOn = new BitSet();
commonOn.set(0, b.size());
BitSet commonOff = new BitSet();
for (BitSet candidate : a.get(i)) {
commonOn.and(candidate);
commonOff.or(candidate);
}
for (int j = 0; j < b.size(); j++) {
final int fi = i, fj = j;
if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))
|| (!commonOff.get(fj) && cnd.get(fi))))
countRemoved++;
if (b.get(j).isEmpty())
return -1;
}
}
return countRemoved;
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"strings"
)
type BitSet []bool
func (bs BitSet) and(other BitSet) {
for i := range bs {
if bs[i] && other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func (bs BitSet) or(other BitSet) {
for i := range bs {
if bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
| import java.util.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.toList;
public class NonogramSolver {
static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"};
static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE "
+ "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"};
static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH "
+ "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF "
+ "AAAAD BDG CEF CBDB BBB FC"};
static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q "
+ "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ "
+ "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"};
public static void main(String[] args) {
for (String[] puzzleData : new String[][]{p1, p2, p3, p4})
newPuzzle(puzzleData);
}
static void newPuzzle(String[] data) {
String[] rowData = data[0].split("\\s");
String[] colData = data[1].split("\\s");
List<List<BitSet>> cols, rows;
rows = getCandidates(rowData, colData.length);
cols = getCandidates(colData, rowData.length);
int numChanged;
do {
numChanged = reduceMutual(cols, rows);
if (numChanged == -1) {
System.out.println("No solution");
return;
}
} while (numChanged > 0);
for (List<BitSet> row : rows) {
for (int i = 0; i < cols.size(); i++)
System.out.print(row.get(0).get(i) ? "# " : ". ");
System.out.println();
}
System.out.println();
}
static List<List<BitSet>> getCandidates(String[] data, int len) {
List<List<BitSet>> result = new ArrayList<>();
for (String s : data) {
List<BitSet> lst = new LinkedList<>();
int sumChars = s.chars().map(c -> c - 'A' + 1).sum();
List<String> prep = stream(s.split(""))
.map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList());
for (String r : genSequence(prep, len - sumChars + 1)) {
char[] bits = r.substring(1).toCharArray();
BitSet bitset = new BitSet(bits.length);
for (int i = 0; i < bits.length; i++)
bitset.set(i, bits[i] == '1');
lst.add(bitset);
}
result.add(lst);
}
return result;
}
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {
int countRemoved1 = reduce(cols, rows);
if (countRemoved1 == -1)
return -1;
int countRemoved2 = reduce(rows, cols);
if (countRemoved2 == -1)
return -1;
return countRemoved1 + countRemoved2;
}
static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {
int countRemoved = 0;
for (int i = 0; i < a.size(); i++) {
BitSet commonOn = new BitSet();
commonOn.set(0, b.size());
BitSet commonOff = new BitSet();
for (BitSet candidate : a.get(i)) {
commonOn.and(candidate);
commonOff.or(candidate);
}
for (int j = 0; j < b.size(); j++) {
final int fi = i, fj = j;
if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))
|| (!commonOff.get(fj) && cnd.get(fi))))
countRemoved++;
if (b.get(j).isEmpty())
return -1;
}
}
return countRemoved;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"regexp"
"strings"
"time"
)
var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}
const (
nRows = 10
nCols = nRows
gridSize = nRows * nCols
minWords = 25
)
var (
re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows))
re2 = regexp.MustCompile("[^A-Z]")
)
type grid struct {
numAttempts int
cells [nRows][nCols]byte
solutions []string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(strings.TrimSpace(scanner.Text()))
if re1.MatchString(word) {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func createWordSearch(words []string) *grid {
var gr *grid
outer:
for i := 1; i < 100; i++ {
gr = new(grid)
messageLen := gr.placeMessage("Rosetta Code")
target := gridSize - messageLen
cellsFilled := 0
rand.Shuffle(len(words), func(i, j int) {
words[i], words[j] = words[j], words[i]
})
for _, word := range words {
cellsFilled += gr.tryPlaceWord(word)
if cellsFilled == target {
if len(gr.solutions) >= minWords {
gr.numAttempts = i
break outer
} else {
break
}
}
}
}
return gr
}
func (gr *grid) placeMessage(msg string) int {
msg = strings.ToUpper(msg)
msg = re2.ReplaceAllLiteralString(msg, "")
messageLen := len(msg)
if messageLen > 0 && messageLen < gridSize {
gapSize := gridSize / messageLen
for i := 0; i < messageLen; i++ {
pos := i*gapSize + rand.Intn(gapSize)
gr.cells[pos/nCols][pos%nCols] = msg[i]
}
return messageLen
}
return 0
}
func (gr *grid) tryPlaceWord(word string) int {
randDir := rand.Intn(len(dirs))
randPos := rand.Intn(gridSize)
for dir := 0; dir < len(dirs); dir++ {
dir = (dir + randDir) % len(dirs)
for pos := 0; pos < gridSize; pos++ {
pos = (pos + randPos) % gridSize
lettersPlaced := gr.tryLocation(word, dir, pos)
if lettersPlaced > 0 {
return lettersPlaced
}
}
}
return 0
}
func (gr *grid) tryLocation(word string, dir, pos int) int {
r := pos / nCols
c := pos % nCols
le := len(word)
if (dirs[dir][0] == 1 && (le+c) > nCols) ||
(dirs[dir][0] == -1 && (le-1) > c) ||
(dirs[dir][1] == 1 && (le+r) > nRows) ||
(dirs[dir][1] == -1 && (le-1) > r) {
return 0
}
overlaps := 0
rr := r
cc := c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {
return 0
}
cc += dirs[dir][0]
rr += dirs[dir][1]
}
rr = r
cc = c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] == word[i] {
overlaps++
} else {
gr.cells[rr][cc] = word[i]
}
if i < le-1 {
cc += dirs[dir][0]
rr += dirs[dir][1]
}
}
lettersPlaced := le - overlaps
if lettersPlaced > 0 {
sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)
gr.solutions = append(gr.solutions, sol)
}
return lettersPlaced
}
func printResult(gr *grid) {
if gr.numAttempts == 0 {
fmt.Println("No grid to display")
return
}
size := len(gr.solutions)
fmt.Println("Attempts:", gr.numAttempts)
fmt.Println("Number of words:", size)
fmt.Println("\n 0 1 2 3 4 5 6 7 8 9")
for r := 0; r < nRows; r++ {
fmt.Printf("\n%d ", r)
for c := 0; c < nCols; c++ {
fmt.Printf(" %c ", gr.cells[r][c])
}
}
fmt.Println("\n")
for i := 0; i < size-1; i += 2 {
fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1])
}
if size%2 == 1 {
fmt.Println(gr.solutions[size-1])
}
}
func main() {
rand.Seed(time.Now().UnixNano())
unixDictPath := "/usr/share/dict/words"
printResult(createWordSearch(readWords(unixDictPath)))
}
| import java.io.*;
import static java.lang.String.format;
import java.util.*;
public class WordSearch {
static class Grid {
int numAttempts;
char[][] cells = new char[nRows][nCols];
List<String> solutions = new ArrayList<>();
}
final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
final static int nRows = 10;
final static int nCols = 10;
final static int gridSize = nRows * nCols;
final static int minWords = 25;
final static Random rand = new Random();
public static void main(String[] args) {
printResult(createWordSearch(readWords("unixdict.txt")));
}
static List<String> readWords(String filename) {
int maxLen = Math.max(nRows, nCols);
List<String> words = new ArrayList<>();
try (Scanner sc = new Scanner(new FileReader(filename))) {
while (sc.hasNext()) {
String s = sc.next().trim().toLowerCase();
if (s.matches("^[a-z]{3," + maxLen + "}$"))
words.add(s);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
return words;
}
static Grid createWordSearch(List<String> words) {
Grid grid = null;
int numAttempts = 0;
outer:
while (++numAttempts < 100) {
Collections.shuffle(words);
grid = new Grid();
int messageLen = placeMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled = 0;
for (String word : words) {
cellsFilled += tryPlaceWord(grid, word);
if (cellsFilled == target) {
if (grid.solutions.size() >= minWords) {
grid.numAttempts = numAttempts;
break outer;
} else break;
}
}
}
return grid;
}
static int placeMessage(Grid grid, String msg) {
msg = msg.toUpperCase().replaceAll("[^A-Z]", "");
int messageLen = msg.length();
if (messageLen > 0 && messageLen < gridSize) {
int gapSize = gridSize / messageLen;
for (int i = 0; i < messageLen; i++) {
int pos = i * gapSize + rand.nextInt(gapSize);
grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);
}
return messageLen;
}
return 0;
}
static int tryPlaceWord(Grid grid, String word) {
int randDir = rand.nextInt(dirs.length);
int randPos = rand.nextInt(gridSize);
for (int dir = 0; dir < dirs.length; dir++) {
dir = (dir + randDir) % dirs.length;
for (int pos = 0; pos < gridSize; pos++) {
pos = (pos + randPos) % gridSize;
int lettersPlaced = tryLocation(grid, word, dir, pos);
if (lettersPlaced > 0)
return lettersPlaced;
}
}
return 0;
}
static int tryLocation(Grid grid, String word, int dir, int pos) {
int r = pos / nCols;
int c = pos % nCols;
int len = word.length();
if ((dirs[dir][0] == 1 && (len + c) > nCols)
|| (dirs[dir][0] == -1 && (len - 1) > c)
|| (dirs[dir][1] == 1 && (len + r) > nRows)
|| (dirs[dir][1] == -1 && (len - 1) > r))
return 0;
int rr, cc, i, overlaps = 0;
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))
return 0;
cc += dirs[dir][0];
rr += dirs[dir][1];
}
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] == word.charAt(i))
overlaps++;
else
grid.cells[rr][cc] = word.charAt(i);
if (i < len - 1) {
cc += dirs[dir][0];
rr += dirs[dir][1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0) {
grid.solutions.add(format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr));
}
return lettersPlaced;
}
static void printResult(Grid grid) {
if (grid == null || grid.numAttempts == 0) {
System.out.println("No grid to display");
return;
}
int size = grid.solutions.size();
System.out.println("Attempts: " + grid.numAttempts);
System.out.println("Number of words: " + size);
System.out.println("\n 0 1 2 3 4 5 6 7 8 9");
for (int r = 0; r < nRows; r++) {
System.out.printf("%n%d ", r);
for (int c = 0; c < nCols; c++)
System.out.printf(" %c ", grid.cells[r][c]);
}
System.out.println("\n");
for (int i = 0; i < size - 1; i += 2) {
System.out.printf("%s %s%n", grid.solutions.get(i),
grid.solutions.get(i + 1));
}
if (size % 2 == 1)
System.out.println(grid.solutions.get(size - 1));
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
| module BreakOO
{
class Exposed
{
public String pub = "public";
protected String pro = "protected";
private String pri = "private";
@Override
String toString()
{
return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
}
}
void run()
{
@Inject Console console;
Exposed expo = new Exposed();
console.print($"before: {expo}");
expo.pub = $"this was {expo.pub}";
assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
expoPro.pro = $"this was {expoPro.pro}";
assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
expoPri.pri = $"this was {expoPri.pri}";
assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
expoStr.pub = $"{expoStr.pub}!!!";
expoStr.pro = $"{expoStr.pro}!!!";
expoStr.pri = $"{expoStr.pri}!!!";
console.print($"after: {expo}");
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
| module BreakOO
{
class Exposed
{
public String pub = "public";
protected String pro = "protected";
private String pri = "private";
@Override
String toString()
{
return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
}
}
void run()
{
@Inject Console console;
Exposed expo = new Exposed();
console.print($"before: {expo}");
expo.pub = $"this was {expo.pub}";
assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
expoPro.pro = $"this was {expoPro.pro}";
assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
expoPri.pri = $"this was {expoPri.pri}";
assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
expoStr.pub = $"{expoStr.pub}!!!";
expoStr.pro = $"{expoStr.pro}!!!";
expoStr.pri = $"{expoStr.pri}!!!";
console.print($"after: {expo}");
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"encoding/gob"
"fmt"
"os"
)
type printable interface {
print()
}
func main() {
animals := []printable{
&Animal{Alive: true},
&Cat{},
&Lab{
Dog: Dog{Animal: Animal{Alive: true}},
Color: "yellow",
},
&Collie{Dog: Dog{
Animal: Animal{Alive: true},
ObedienceTrained: true,
}},
}
fmt.Println("created:")
for _, a := range animals {
a.print()
}
f, err := os.Create("objects.dat")
if err != nil {
fmt.Println(err)
return
}
for _, a := range animals {
gob.Register(a)
}
err = gob.NewEncoder(f).Encode(animals)
if err != nil {
fmt.Println(err)
return
}
f.Close()
f, err = os.Open("objects.dat")
if err != nil {
fmt.Println(err)
return
}
var clones []printable
gob.NewDecoder(f).Decode(&clones)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("\nloaded from objects.dat:")
for _, c := range clones {
c.print()
}
}
type Animal struct {
Alive bool
}
func (a *Animal) print() {
if a.Alive {
fmt.Println(" live animal, unspecified type")
} else {
fmt.Println(" dead animal, unspecified type")
}
}
type Dog struct {
Animal
ObedienceTrained bool
}
func (d *Dog) print() {
switch {
case !d.Alive:
fmt.Println(" dead dog")
case d.ObedienceTrained:
fmt.Println(" trained dog")
default:
fmt.Println(" dog, not trained")
}
}
type Cat struct {
Animal
LitterBoxTrained bool
}
func (c *Cat) print() {
switch {
case !c.Alive:
fmt.Println(" dead cat")
case c.LitterBoxTrained:
fmt.Println(" litter box trained cat")
default:
fmt.Println(" cat, not litter box trained")
}
}
type Lab struct {
Dog
Color string
}
func (l *Lab) print() {
var r string
if l.Color == "" {
r = "lab, color unspecified"
} else {
r = l.Color + " lab"
}
switch {
case !l.Alive:
fmt.Println(" dead", r)
case l.ObedienceTrained:
fmt.Println(" trained", r)
default:
fmt.Printf(" %s, not trained\n", r)
}
}
type Collie struct {
Dog
CatchesFrisbee bool
}
func (c *Collie) print() {
switch {
case !c.Alive:
fmt.Println(" dead collie")
case c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" trained collie, catches frisbee")
case c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" trained collie, but doesn't catch frisbee")
case !c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" collie, not trained, but catches frisbee")
case !c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" collie, not trained, doesn't catch frisbee")
}
}
| import java.io.*;
class Entity implements Serializable {
static final long serialVersionUID = 3504465751164822571L;
String name = "Entity";
public String toString() { return name; }
}
class Person extends Entity implements Serializable {
static final long serialVersionUID = -9170445713373959735L;
Person() { name = "Cletus"; }
}
public class SerializationTest {
public static void main(String[] args) {
Person instance1 = new Person();
System.out.println(instance1);
Entity instance2 = new Entity();
System.out.println(instance2);
try {
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("objects.dat"));
out.writeObject(instance1);
out.writeObject(instance2);
out.close();
System.out.println("Serialized...");
} catch (IOException e) {
System.err.println("Something screwed up while serializing");
e.printStackTrace();
System.exit(1);
}
try {
ObjectInput in = new ObjectInputStream(new FileInputStream("objects.dat"));
Object readObject1 = in.readObject();
Object readObject2 = in.readObject();
in.close();
System.out.println("Deserialized...");
System.out.println(readObject1);
System.out.println(readObject2);
} catch (IOException e) {
System.err.println("Something screwed up while deserializing");
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
System.err.println("Unknown class for deserialized object");
e.printStackTrace();
System.exit(1);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
private static class Node {
int length;
Map<Character, Integer> edges = new HashMap<>();
int suffix;
public Node(int length) {
this.length = length;
}
public Node(int length, Map<Character, Integer> edges, int suffix) {
this.length = length;
this.edges = edges != null ? edges : new HashMap<>();
this.suffix = suffix;
}
}
private static final int EVEN_ROOT = 0;
private static final int ODD_ROOT = 1;
private static List<Node> eertree(String s) {
List<Node> tree = new ArrayList<>();
tree.add(new Node(0, null, ODD_ROOT));
tree.add(new Node(-1, null, ODD_ROOT));
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
for (n = suffix; ; n = tree.get(n).suffix) {
k = tree.get(n).length;
int b = i - k - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
if (tree.get(n).edges.containsKey(c)) {
suffix = tree.get(n).edges.get(c);
continue;
}
suffix = tree.size();
tree.add(new Node(k + 2));
tree.get(n).edges.put(c, suffix);
if (tree.get(suffix).length == 1) {
tree.get(suffix).suffix = 0;
continue;
}
while (true) {
n = tree.get(n).suffix;
int b = i - tree.get(n).length - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
tree.get(suffix).suffix = tree.get(n).edges.get(c);
}
return tree;
}
private static List<String> subPalindromes(List<Node> tree) {
List<String> s = new ArrayList<>();
subPalindromes_children(0, "", tree, s);
for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
String ct = String.valueOf(cm.getKey());
s.add(ct);
subPalindromes_children(cm.getValue(), ct, tree, s);
}
return s;
}
private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
Character c = cm.getKey();
Integer m = cm.getValue();
String pl = c + p + c;
s.add(pl);
subPalindromes_children(m, pl, tree, s);
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
private static class Node {
int length;
Map<Character, Integer> edges = new HashMap<>();
int suffix;
public Node(int length) {
this.length = length;
}
public Node(int length, Map<Character, Integer> edges, int suffix) {
this.length = length;
this.edges = edges != null ? edges : new HashMap<>();
this.suffix = suffix;
}
}
private static final int EVEN_ROOT = 0;
private static final int ODD_ROOT = 1;
private static List<Node> eertree(String s) {
List<Node> tree = new ArrayList<>();
tree.add(new Node(0, null, ODD_ROOT));
tree.add(new Node(-1, null, ODD_ROOT));
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
for (n = suffix; ; n = tree.get(n).suffix) {
k = tree.get(n).length;
int b = i - k - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
if (tree.get(n).edges.containsKey(c)) {
suffix = tree.get(n).edges.get(c);
continue;
}
suffix = tree.size();
tree.add(new Node(k + 2));
tree.get(n).edges.put(c, suffix);
if (tree.get(suffix).length == 1) {
tree.get(suffix).suffix = 0;
continue;
}
while (true) {
n = tree.get(n).suffix;
int b = i - tree.get(n).length - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
tree.get(suffix).suffix = tree.get(n).edges.get(c);
}
return tree;
}
private static List<String> subPalindromes(List<Node> tree) {
List<String> s = new ArrayList<>();
subPalindromes_children(0, "", tree, s);
for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
String ct = String.valueOf(cm.getKey());
s.add(ct);
subPalindromes_children(cm.getValue(), ct, tree, s);
}
return s;
}
private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
Character c = cm.getKey();
Integer m = cm.getValue();
String pl = c + p + c;
s.add(pl);
subPalindromes_children(m, pl, tree, s);
}
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"time"
)
func main() {
centuries := []string{"20th", "21st", "22nd"}
starts := []int{1900, 2000, 2100}
for i := 0; i < len(centuries); i++ {
var longYears []int
fmt.Printf("\nLong years in the %s century:\n", centuries[i])
for j := starts[i]; j < starts[i] + 100; j++ {
t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
if _, week := t.ISOWeek(); week == 53 {
longYears = append(longYears, j)
}
}
fmt.Println(longYears)
}
}
| import java.time.LocalDate;
import java.time.temporal.WeekFields;
public class LongYear {
public static void main(String[] args) {
System.out.printf("Long years this century:%n");
for (int year = 2000 ; year < 2100 ; year++ ) {
if ( longYear(year) ) {
System.out.print(year + " ");
}
}
}
private static boolean longYear(int year) {
return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "fmt"
func getDivisors(n int) []int {
divs := []int{1, n}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs = append(divs, j)
}
}
}
return divs
}
func sum(divs []int) int {
sum := 0
for _, div := range divs {
sum += div
}
return sum
}
func isPartSum(divs []int, sum int) bool {
if sum == 0 {
return true
}
le := len(divs)
if le == 0 {
return false
}
last := divs[le-1]
divs = divs[0 : le-1]
if last > sum {
return isPartSum(divs, sum)
}
return isPartSum(divs, sum) || isPartSum(divs, sum-last)
}
func isZumkeller(n int) bool {
divs := getDivisors(n)
sum := sum(divs)
if sum%2 == 1 {
return false
}
if n%2 == 1 {
abundance := sum - 2*n
return abundance > 0 && abundance%2 == 0
}
return isPartSum(divs, sum/2)
}
func main() {
fmt.Println("The first 220 Zumkeller numbers are:")
for i, count := 2, 0; count < 220; i++ {
if isZumkeller(i) {
fmt.Printf("%3d ", i)
count++
if count%20 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers are:")
for i, count := 3, 0; count < 40; i += 2 {
if isZumkeller(i) {
fmt.Printf("%5d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
for i, count := 3, 0; count < 40; i += 2 {
if (i % 10 != 5) && isZumkeller(i) {
fmt.Printf("%7d ", i)
count++
if count%8 == 0 {
fmt.Println()
}
}
}
fmt.Println()
}
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ZumkellerNumbers {
public static void main(String[] args) {
int n = 1;
System.out.printf("First 220 Zumkeller numbers:%n");
for ( int count = 1 ; count <= 220 ; n += 1 ) {
if ( isZumkeller(n) ) {
System.out.printf("%3d ", n);
if ( count % 20 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( isZumkeller(n) ) {
System.out.printf("%6d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( n % 5 != 0 && isZumkeller(n) ) {
System.out.printf("%8d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
}
private static boolean isZumkeller(int n) {
if ( n % 18 == 6 || n % 18 == 12 ) {
return true;
}
List<Integer> divisors = getDivisors(n);
int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();
if ( divisorSum % 2 == 1 ) {
return false;
}
int abundance = divisorSum - 2 * n;
if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {
return true;
}
Collections.sort(divisors);
int j = divisors.size() - 1;
int sum = divisorSum/2;
if ( divisors.get(j) > sum ) {
return false;
}
return canPartition(j, divisors, sum, new int[2]);
}
private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {
if ( j < 0 ) {
return true;
}
for ( int i = 0 ; i < 2 ; i++ ) {
if ( buckets[i] + divisors.get(j) <= sum ) {
buckets[i] += divisors.get(j);
if ( canPartition(j-1, divisors, sum, buckets) ) {
return true;
}
buckets[i] -= divisors.get(j);
}
if( buckets[i] == 0 ) {
break;
}
}
return false;
}
private static final List<Integer> getDivisors(int number) {
List<Integer> divisors = new ArrayList<Integer>();
long sqrt = (long) Math.sqrt(number);
for ( int i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
int div = number / i;
if ( div != i ) {
divisors.add(div);
}
}
}
return divisors;
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
| import java.util.*;
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.put("price", 15.25);
update.put("color", "red");
update.put("year", 1974);
Map<String, Object> result = new HashMap<>(base);
result.putAll(update);
System.out.println(result);
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
| import java.util.*;
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.put("price", 15.25);
update.put("color", "red");
update.put("year", 1974);
Map<String, Object> result = new HashMap<>(base);
result.putAll(update);
System.out.println(result);
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
| import java.util.*;
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.put("price", 15.25);
update.put("color", "red");
update.put("year", 1974);
Map<String, Object> result = new HashMap<>(base);
result.putAll(update);
System.out.println(result);
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
| import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
public class MetallicRatios {
private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};
public static void main(String[] args) {
int elements = 15;
for ( int b = 0 ; b < 10 ; b++ ) {
System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b);
System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements));
int decimalPlaces = 32;
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
System.out.printf("%n");
}
int b = 1;
int decimalPlaces = 256;
System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b);
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
}
private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {
BigDecimal x0Bi = BigDecimal.valueOf(x0);
BigDecimal x1Bi = BigDecimal.valueOf(x1);
BigDecimal bBi = BigDecimal.valueOf(b);
MathContext mc = new MathContext(digits);
BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);
int iterations = 0;
while ( true ) {
iterations++;
BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);
BigDecimal fractionCurrent = x.divide(x1Bi, mc);
if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {
break;
}
x0Bi = x1Bi;
x1Bi = x;
fractionPrior = fractionCurrent;
}
return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};
}
private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {
List<BigInteger> list = new ArrayList<>();
BigInteger x0Bi = BigInteger.valueOf(x0);
BigInteger x1Bi = BigInteger.valueOf(x1);
BigInteger bBi = BigInteger.valueOf(b);
if ( n > 0 ) {
list.add(x0Bi);
}
if ( n > 1 ) {
list.add(x1Bi);
}
while ( n > 2 ) {
BigInteger x = bBi.multiply(x1Bi).add(x0Bi);
list.add(x);
n--;
x0Bi = x1Bi;
x1Bi = x;
}
return list;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
| import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
public class MetallicRatios {
private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};
public static void main(String[] args) {
int elements = 15;
for ( int b = 0 ; b < 10 ; b++ ) {
System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b);
System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements));
int decimalPlaces = 32;
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
System.out.printf("%n");
}
int b = 1;
int decimalPlaces = 256;
System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b);
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
}
private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {
BigDecimal x0Bi = BigDecimal.valueOf(x0);
BigDecimal x1Bi = BigDecimal.valueOf(x1);
BigDecimal bBi = BigDecimal.valueOf(b);
MathContext mc = new MathContext(digits);
BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);
int iterations = 0;
while ( true ) {
iterations++;
BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);
BigDecimal fractionCurrent = x.divide(x1Bi, mc);
if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {
break;
}
x0Bi = x1Bi;
x1Bi = x;
fractionPrior = fractionCurrent;
}
return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};
}
private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {
List<BigInteger> list = new ArrayList<>();
BigInteger x0Bi = BigInteger.valueOf(x0);
BigInteger x1Bi = BigInteger.valueOf(x1);
BigInteger bBi = BigInteger.valueOf(b);
if ( n > 0 ) {
list.add(x0Bi);
}
if ( n > 1 ) {
list.add(x1Bi);
}
while ( n > 2 ) {
BigInteger x = bBi.multiply(x1Bi).add(x0Bi);
list.add(x);
n--;
x0Bi = x1Bi;
x1Bi = x;
}
return list;
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"math/rand"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
)
func main() {
log.SetFlags(0)
log.SetPrefix("markov: ")
input := flag.String("in", "alice_oz.txt", "input file")
n := flag.Int("n", 2, "number of words to use as prefix")
runs := flag.Int("runs", 1, "number of runs to generate")
wordsPerRun := flag.Int("words", 300, "number of words per run")
startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix")
stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)")
flag.Parse()
rand.Seed(time.Now().UnixNano())
m, err := NewMarkovFromFile(*input, *n)
if err != nil {
log.Fatal(err)
}
for i := 0; i < *runs; i++ {
err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}
}
type Markov struct {
n int
capitalized int
suffix map[string][]string
}
func NewMarkovFromFile(filename string, n int) (*Markov, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return NewMarkov(f, n)
}
func NewMarkov(r io.Reader, n int) (*Markov, error) {
m := &Markov{
n: n,
suffix: make(map[string][]string),
}
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
window := make([]string, 0, n)
for sc.Scan() {
word := sc.Text()
if len(window) > 0 {
prefix := strings.Join(window, " ")
m.suffix[prefix] = append(m.suffix[prefix], word)
if isCapitalized(prefix) {
m.capitalized++
}
}
window = appendMax(n, window, word)
}
if err := sc.Err(); err != nil {
return nil, err
}
return m, nil
}
func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {
bw := bufio.NewWriter(w)
var i int
if startCapital {
i = rand.Intn(m.capitalized)
} else {
i = rand.Intn(len(m.suffix))
}
var prefix string
for prefix = range m.suffix {
if startCapital && !isCapitalized(prefix) {
continue
}
if i == 0 {
break
}
i--
}
bw.WriteString(prefix)
prefixWords := strings.Fields(prefix)
n -= len(prefixWords)
for {
suffixChoices := m.suffix[prefix]
if len(suffixChoices) == 0 {
break
}
i = rand.Intn(len(suffixChoices))
suffix := suffixChoices[i]
bw.WriteByte(' ')
if _, err := bw.WriteString(suffix); err != nil {
break
}
n--
if n < 0 && (!stopSentence || isSentenceEnd(suffix)) {
break
}
prefixWords = appendMax(m.n, prefixWords, suffix)
prefix = strings.Join(prefixWords, " ")
}
return bw.Flush()
}
func isCapitalized(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return unicode.IsUpper(r)
}
func isSentenceEnd(s string) bool {
r, _ := utf8.DecodeLastRuneInString(s)
return r == '.' || r == '?' || r == '!'
}
func appendMax(max int, slice []string, value string) []string {
if len(slice)+1 > max {
n := copy(slice, slice[1:])
slice = slice[:n]
}
return append(slice, value)
}
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
public class MarkovChain {
private static Random r = new Random();
private static String markov(String filePath, int keySize, int outputSize) throws IOException {
if (keySize < 1) throw new IllegalArgumentException("Key size can't be less than 1");
Path path = Paths.get(filePath);
byte[] bytes = Files.readAllBytes(path);
String[] words = new String(bytes).trim().split(" ");
if (outputSize < keySize || outputSize >= words.length) {
throw new IllegalArgumentException("Output size is out of range");
}
Map<String, List<String>> dict = new HashMap<>();
for (int i = 0; i < (words.length - keySize); ++i) {
StringBuilder key = new StringBuilder(words[i]);
for (int j = i + 1; j < i + keySize; ++j) {
key.append(' ').append(words[j]);
}
String value = (i + keySize < words.length) ? words[i + keySize] : "";
if (!dict.containsKey(key.toString())) {
ArrayList<String> list = new ArrayList<>();
list.add(value);
dict.put(key.toString(), list);
} else {
dict.get(key.toString()).add(value);
}
}
int n = 0;
int rn = r.nextInt(dict.size());
String prefix = (String) dict.keySet().toArray()[rn];
List<String> output = new ArrayList<>(Arrays.asList(prefix.split(" ")));
while (true) {
List<String> suffix = dict.get(prefix);
if (suffix.size() == 1) {
if (Objects.equals(suffix.get(0), "")) return output.stream().reduce("", (a, b) -> a + " " + b);
output.add(suffix.get(0));
} else {
rn = r.nextInt(suffix.size());
output.add(suffix.get(rn));
}
if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce("", (a, b) -> a + " " + b);
n++;
prefix = output.stream().skip(n).limit(keySize).reduce("", (a, b) -> a + " " + b).trim();
}
}
public static void main(String[] args) throws IOException {
System.out.println(markov("alice_oz.txt", 3, 200));
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"container/heap"
"fmt"
)
type PriorityQueue struct {
items []Vertex
m map[Vertex]int
pr map[Vertex]int
}
func (pq *PriorityQueue) Len() int { return len(pq.items) }
func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }
func (pq *PriorityQueue) Swap(i, j int) {
pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
pq.m[pq.items[i]] = i
pq.m[pq.items[j]] = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(pq.items)
item := x.(Vertex)
pq.m[item] = n
pq.items = append(pq.items, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := pq.items
n := len(old)
item := old[n-1]
pq.m[item] = -1
pq.items = old[0 : n-1]
return item
}
func (pq *PriorityQueue) update(item Vertex, priority int) {
pq.pr[item] = priority
heap.Fix(pq, pq.m[item])
}
func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {
heap.Push(pq, item)
pq.update(item, priority)
}
const (
Infinity = int(^uint(0) >> 1)
Uninitialized = -1
)
func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {
vs := g.Vertices()
dist = make(map[Vertex]int, len(vs))
prev = make(map[Vertex]Vertex, len(vs))
sid := source
dist[sid] = 0
q := &PriorityQueue{
items: make([]Vertex, 0, len(vs)),
m: make(map[Vertex]int, len(vs)),
pr: make(map[Vertex]int, len(vs)),
}
for _, v := range vs {
if v != sid {
dist[v] = Infinity
}
prev[v] = Uninitialized
q.addWithPriority(v, dist[v])
}
for len(q.items) != 0 {
u := heap.Pop(q).(Vertex)
for _, v := range g.Neighbors(u) {
alt := dist[u] + g.Weight(u, v)
if alt < dist[v] {
dist[v] = alt
prev[v] = u
q.update(v, alt)
}
}
}
return dist, prev
}
type Graph interface {
Vertices() []Vertex
Neighbors(v Vertex) []Vertex
Weight(u, v Vertex) int
}
type Vertex int
type sg struct {
ids map[string]Vertex
names map[Vertex]string
edges map[Vertex]map[Vertex]int
}
func newsg(ids map[string]Vertex) sg {
g := sg{ids: ids}
g.names = make(map[Vertex]string, len(ids))
for k, v := range ids {
g.names[v] = k
}
g.edges = make(map[Vertex]map[Vertex]int)
return g
}
func (g sg) edge(u, v string, w int) {
if _, ok := g.edges[g.ids[u]]; !ok {
g.edges[g.ids[u]] = make(map[Vertex]int)
}
g.edges[g.ids[u]][g.ids[v]] = w
}
func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {
s = g.names[v]
for prev[v] >= 0 {
v = prev[v]
s = g.names[v] + s
}
return s
}
func (g sg) Vertices() []Vertex {
vs := make([]Vertex, 0, len(g.ids))
for _, v := range g.ids {
vs = append(vs, v)
}
return vs
}
func (g sg) Neighbors(u Vertex) []Vertex {
vs := make([]Vertex, 0, len(g.edges[u]))
for v := range g.edges[u] {
vs = append(vs, v)
}
return vs
}
func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }
func main() {
g := newsg(map[string]Vertex{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
})
g.edge("a", "b", 7)
g.edge("a", "c", 9)
g.edge("a", "f", 14)
g.edge("b", "c", 10)
g.edge("b", "d", 15)
g.edge("c", "d", 11)
g.edge("c", "f", 2)
g.edge("d", "e", 6)
g.edge("e", "f", 9)
dist, prev := Dijkstra(g, g.ids["a"])
fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev))
fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev))
}
| import java.io.*;
import java.util.*;
public class Dijkstra {
private static final Graph.Edge[] GRAPH = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
new Graph.Edge("c", "d", 11),
new Graph.Edge("c", "f", 2),
new Graph.Edge("d", "e", 6),
new Graph.Edge("e", "f", 9),
};
private static final String START = "a";
private static final String END = "e";
public static void main(String[] args) {
Graph g = new Graph(GRAPH);
g.dijkstra(START);
g.printPath(END);
}
}
class Graph {
private final Map<String, Vertex> graph;
public static class Edge {
public final String v1, v2;
public final int dist;
public Edge(String v1, String v2, int dist) {
this.v1 = v1;
this.v2 = v2;
this.dist = dist;
}
}
public static class Vertex implements Comparable<Vertex>{
public final String name;
public int dist = Integer.MAX_VALUE;
public Vertex previous = null;
public final Map<Vertex, Integer> neighbours = new HashMap<>();
public Vertex(String name)
{
this.name = name;
}
private void printPath()
{
if (this == this.previous)
{
System.out.printf("%s", this.name);
}
else if (this.previous == null)
{
System.out.printf("%s(unreached)", this.name);
}
else
{
this.previous.printPath();
System.out.printf(" -> %s(%d)", this.name, this.dist);
}
}
public int compareTo(Vertex other)
{
if (dist == other.dist)
return name.compareTo(other.name);
return Integer.compare(dist, other.dist);
}
@Override public String toString()
{
return "(" + name + ", " + dist + ")";
}
}
public Graph(Edge[] edges) {
graph = new HashMap<>(edges.length);
for (Edge e : edges) {
if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
}
for (Edge e : edges) {
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
}
}
public void dijkstra(String startName) {
if (!graph.containsKey(startName)) {
System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
return;
}
final Vertex source = graph.get(startName);
NavigableSet<Vertex> q = new TreeSet<>();
for (Vertex v : graph.values()) {
v.previous = v == source ? source : null;
v.dist = v == source ? 0 : Integer.MAX_VALUE;
q.add(v);
}
dijkstra(q);
}
private void dijkstra(final NavigableSet<Vertex> q) {
Vertex u, v;
while (!q.isEmpty()) {
u = q.pollFirst();
if (u.dist == Integer.MAX_VALUE) break;
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
v = a.getKey();
final int alternateDist = u.dist + a.getValue();
if (alternateDist < v.dist) {
q.remove(v);
v.dist = alternateDist;
v.previous = u;
q.add(v);
}
}
}
}
public void printPath(String endName) {
if (!graph.containsKey(endName)) {
System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
return;
}
graph.get(endName).printPath();
System.out.println();
}
public void printAllPaths() {
for (Vertex v : graph.values()) {
v.printPath();
System.out.println();
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"math/rand"
"time"
)
type vector []float64
func e(n uint) vector {
if n > 4 {
panic("n must be less than 5")
}
result := make(vector, 32)
result[1<<n] = 1.0
return result
}
func cdot(a, b vector) vector {
return mul(vector{0.5}, add(mul(a, b), mul(b, a)))
}
func neg(x vector) vector {
return mul(vector{-1}, x)
}
func bitCount(i int) int {
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
i = (i + (i >> 4)) & 0x0F0F0F0F
i = i + (i >> 8)
i = i + (i >> 16)
return i & 0x0000003F
}
func reorderingSign(i, j int) float64 {
i >>= 1
sum := 0
for i != 0 {
sum += bitCount(i & j)
i >>= 1
}
cond := (sum & 1) == 0
if cond {
return 1.0
}
return -1.0
}
func add(a, b vector) vector {
result := make(vector, 32)
copy(result, a)
for i, _ := range b {
result[i] += b[i]
}
return result
}
func mul(a, b vector) vector {
result := make(vector, 32)
for i, _ := range a {
if a[i] != 0 {
for j, _ := range b {
if b[j] != 0 {
s := reorderingSign(i, j) * a[i] * b[j]
k := i ^ j
result[k] += s
}
}
}
}
return result
}
func randomVector() vector {
result := make(vector, 32)
for i := uint(0); i < 5; i++ {
result = add(result, mul(vector{rand.Float64()}, e(i)))
}
return result
}
func randomMultiVector() vector {
result := make(vector, 32)
for i := 0; i < 32; i++ {
result[i] = rand.Float64()
}
return result
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 5; i++ {
for j := uint(0); j < 5; j++ {
if i < j {
if cdot(e(i), e(j))[0] != 0 {
fmt.Println("Unexpected non-null scalar product.")
return
}
} else if i == j {
if cdot(e(i), e(j))[0] == 0 {
fmt.Println("Unexpected null scalar product.")
}
}
}
}
a := randomMultiVector()
b := randomMultiVector()
c := randomMultiVector()
x := randomVector()
fmt.Println(mul(mul(a, b), c))
fmt.Println(mul(a, mul(b, c)))
fmt.Println(mul(a, add(b, c)))
fmt.Println(add(mul(a, b), mul(a, c)))
fmt.Println(mul(add(a, b), c))
fmt.Println(add(mul(a, c), mul(b, c)))
fmt.Println(mul(x, x))
}
| import java.util.Arrays;
import java.util.Random;
public class GeometricAlgebra {
private static int bitCount(int i) {
i -= ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i + (i >> 4)) & 0x0F0F0F0F;
i += (i >> 8);
i += (i >> 16);
return i & 0x0000003F;
}
private static double reorderingSign(int i, int j) {
int k = i >> 1;
int sum = 0;
while (k != 0) {
sum += bitCount(k & j);
k = k >> 1;
}
return ((sum & 1) == 0) ? 1.0 : -1.0;
}
static class Vector {
private double[] dims;
public Vector(double[] dims) {
this.dims = dims;
}
public Vector dot(Vector rhs) {
return times(rhs).plus(rhs.times(this)).times(0.5);
}
public Vector unaryMinus() {
return times(-1.0);
}
public Vector plus(Vector rhs) {
double[] result = Arrays.copyOf(dims, 32);
for (int i = 0; i < rhs.dims.length; ++i) {
result[i] += rhs.get(i);
}
return new Vector(result);
}
public Vector times(Vector rhs) {
double[] result = new double[32];
for (int i = 0; i < dims.length; ++i) {
if (dims[i] != 0.0) {
for (int j = 0; j < rhs.dims.length; ++j) {
if (rhs.get(j) != 0.0) {
double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];
int k = i ^ j;
result[k] += s;
}
}
}
}
return new Vector(result);
}
public Vector times(double scale) {
double[] result = dims.clone();
for (int i = 0; i < 5; ++i) {
dims[i] *= scale;
}
return new Vector(result);
}
double get(int index) {
return dims[index];
}
void set(int index, double value) {
dims[index] = value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for (double value : dims) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(value);
}
return sb.append(")").toString();
}
}
private static Vector e(int n) {
if (n > 4) {
throw new IllegalArgumentException("n must be less than 5");
}
Vector result = new Vector(new double[32]);
result.set(1 << n, 1.0);
return result;
}
private static final Random rand = new Random();
private static Vector randomVector() {
Vector result = new Vector(new double[32]);
for (int i = 0; i < 5; ++i) {
Vector temp = new Vector(new double[]{rand.nextDouble()});
result = result.plus(temp.times(e(i)));
}
return result;
}
private static Vector randomMultiVector() {
Vector result = new Vector(new double[32]);
for (int i = 0; i < 32; ++i) {
result.set(i, rand.nextDouble());
}
return result;
}
public static void main(String[] args) {
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (i < j) {
if (e(i).dot(e(j)).get(0) != 0.0) {
System.out.println("Unexpected non-null scalar product.");
return;
}
}
}
}
Vector a = randomMultiVector();
Vector b = randomMultiVector();
Vector c = randomMultiVector();
Vector x = randomVector();
System.out.println(a.times(b).times(c));
System.out.println(a.times(b.times(c)));
System.out.println();
System.out.println(a.times(b.plus(c)));
System.out.println(a.times(b).plus(a.times(c)));
System.out.println();
System.out.println(a.plus(b).times(c));
System.out.println(a.times(c).plus(b.times(c)));
System.out.println();
System.out.println(x.times(x));
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
| import java.util.ArrayList;
import java.util.List;
public class SuffixTreeProblem {
private static class Node {
String sub = "";
List<Integer> ch = new ArrayList<>();
}
private static class SuffixTree {
private List<Node> nodes = new ArrayList<>();
public SuffixTree(String str) {
nodes.add(new Node());
for (int i = 0; i < str.length(); ++i) {
addSuffix(str.substring(i));
}
}
private void addSuffix(String suf) {
int n = 0;
int i = 0;
while (i < suf.length()) {
char b = suf.charAt(i);
List<Integer> children = nodes.get(n).ch;
int x2 = 0;
int n2;
while (true) {
if (x2 == children.size()) {
n2 = nodes.size();
Node temp = new Node();
temp.sub = suf.substring(i);
nodes.add(temp);
children.add(n2);
return;
}
n2 = children.get(x2);
if (nodes.get(n2).sub.charAt(0) == b) break;
x2++;
}
String sub2 = nodes.get(n2).sub;
int j = 0;
while (j < sub2.length()) {
if (suf.charAt(i + j) != sub2.charAt(j)) {
int n3 = n2;
n2 = nodes.size();
Node temp = new Node();
temp.sub = sub2.substring(0, j);
temp.ch.add(n3);
nodes.add(temp);
nodes.get(n3).sub = sub2.substring(j);
nodes.get(n).ch.set(x2, n2);
break;
}
j++;
}
i += j;
n = n2;
}
}
public void visualize() {
if (nodes.isEmpty()) {
System.out.println("<empty>");
return;
}
visualize_f(0, "");
}
private void visualize_f(int n, String pre) {
List<Integer> children = nodes.get(n).ch;
if (children.isEmpty()) {
System.out.println("- " + nodes.get(n).sub);
return;
}
System.out.println("┐ " + nodes.get(n).sub);
for (int i = 0; i < children.size() - 1; i++) {
Integer c = children.get(i);
System.out.print(pre + "├─");
visualize_f(c, pre + "│ ");
}
System.out.print(pre + "└─");
visualize_f(children.get(children.size() - 1), pre + " ");
}
}
public static void main(String[] args) {
new SuffixTree("banana$").visualize();
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
| import java.util.ArrayList;
import java.util.List;
public class SuffixTreeProblem {
private static class Node {
String sub = "";
List<Integer> ch = new ArrayList<>();
}
private static class SuffixTree {
private List<Node> nodes = new ArrayList<>();
public SuffixTree(String str) {
nodes.add(new Node());
for (int i = 0; i < str.length(); ++i) {
addSuffix(str.substring(i));
}
}
private void addSuffix(String suf) {
int n = 0;
int i = 0;
while (i < suf.length()) {
char b = suf.charAt(i);
List<Integer> children = nodes.get(n).ch;
int x2 = 0;
int n2;
while (true) {
if (x2 == children.size()) {
n2 = nodes.size();
Node temp = new Node();
temp.sub = suf.substring(i);
nodes.add(temp);
children.add(n2);
return;
}
n2 = children.get(x2);
if (nodes.get(n2).sub.charAt(0) == b) break;
x2++;
}
String sub2 = nodes.get(n2).sub;
int j = 0;
while (j < sub2.length()) {
if (suf.charAt(i + j) != sub2.charAt(j)) {
int n3 = n2;
n2 = nodes.size();
Node temp = new Node();
temp.sub = sub2.substring(0, j);
temp.ch.add(n3);
nodes.add(temp);
nodes.get(n3).sub = sub2.substring(j);
nodes.get(n).ch.set(x2, n2);
break;
}
j++;
}
i += j;
n = n2;
}
}
public void visualize() {
if (nodes.isEmpty()) {
System.out.println("<empty>");
return;
}
visualize_f(0, "");
}
private void visualize_f(int n, String pre) {
List<Integer> children = nodes.get(n).ch;
if (children.isEmpty()) {
System.out.println("- " + nodes.get(n).sub);
return;
}
System.out.println("┐ " + nodes.get(n).sub);
for (int i = 0; i < children.size() - 1; i++) {
Integer c = children.get(i);
System.out.print(pre + "├─");
visualize_f(c, pre + "│ ");
}
System.out.print(pre + "└─");
visualize_f(children.get(children.size() - 1), pre + " ");
}
}
public static void main(String[] args) {
new SuffixTree("banana$").visualize();
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}
| Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);
for (Map.Entry<String, Integer> e : map.entrySet()) {
String key = e.getKey();
Integer value = e.getValue();
System.out.println("key = " + key + ", value = " + value);
}
for (String key : map.keySet()) {
System.out.println("key = " + key);
}
for (Integer value : map.values()) {
System.out.println("value = " + value);
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import "fmt"
type TinyInt int
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1 % t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
}
| class BoundedIntOutOfBoundsException extends Exception
{
public BoundedIntOutOfBoundsException(int v, int l, int u) {
super("value " + v + " is out of bounds [" + l + "," + u + "]");
}
}
class BoundedInt {
private int value;
private int lower;
private int upper;
public BoundedInt(int l, int u) {
lower = Math.min(l, u);
upper = Math.max(l, u);
}
private boolean checkBounds(int v) {
return (v >= this.lower) && (v <= this.upper);
}
public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
assign(i.value());
}
public void assign(int v) throws BoundedIntOutOfBoundsException {
if ( checkBounds(v) ) {
this.value = v;
} else {
throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);
}
}
public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {
return add(i.value());
}
public int add(int i) throws BoundedIntOutOfBoundsException {
if ( checkBounds(this.value + i) ) {
this.value += i;
} else {
throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);
}
return this.value;
}
public int value() {
return this.value;
}
}
public class Bounded {
public static void main(String[] args) throws BoundedIntOutOfBoundsException {
BoundedInt a = new BoundedInt(1, 10);
BoundedInt b = new BoundedInt(1, 10);
a.assign(6);
try {
b.assign(12);
} catch (Exception e) {
System.out.println(e.getMessage());
}
b.assign(9);
try {
a.add(b.value());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import "fmt"
type TinyInt int
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1 % t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
}
| class BoundedIntOutOfBoundsException extends Exception
{
public BoundedIntOutOfBoundsException(int v, int l, int u) {
super("value " + v + " is out of bounds [" + l + "," + u + "]");
}
}
class BoundedInt {
private int value;
private int lower;
private int upper;
public BoundedInt(int l, int u) {
lower = Math.min(l, u);
upper = Math.max(l, u);
}
private boolean checkBounds(int v) {
return (v >= this.lower) && (v <= this.upper);
}
public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
assign(i.value());
}
public void assign(int v) throws BoundedIntOutOfBoundsException {
if ( checkBounds(v) ) {
this.value = v;
} else {
throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);
}
}
public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {
return add(i.value());
}
public int add(int i) throws BoundedIntOutOfBoundsException {
if ( checkBounds(this.value + i) ) {
this.value += i;
} else {
throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);
}
return this.value;
}
public int value() {
return this.value;
}
}
public class Bounded {
public static void main(String[] args) throws BoundedIntOutOfBoundsException {
BoundedInt a = new BoundedInt(1, 10);
BoundedInt b = new BoundedInt(1, 10);
a.assign(6);
try {
b.assign(12);
} catch (Exception e) {
System.out.println(e.getMessage());
}
b.assign(9);
try {
a.add(b.value());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package avl
type Key interface {
Less(Key) bool
Eq(Key) bool
}
type Node struct {
Data Key
Balance int
Link [2]*Node
}
func opp(dir int) int {
return 1 - dir
}
func single(root *Node, dir int) *Node {
save := root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func double(root *Node, dir int) *Node {
save := root.Link[opp(dir)].Link[dir]
root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]
save.Link[opp(dir)] = root.Link[opp(dir)]
root.Link[opp(dir)] = save
save = root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func adjustBalance(root *Node, dir, bal int) {
n := root.Link[dir]
nn := n.Link[opp(dir)]
switch nn.Balance {
case 0:
root.Balance = 0
n.Balance = 0
case bal:
root.Balance = -bal
n.Balance = 0
default:
root.Balance = 0
n.Balance = bal
}
nn.Balance = 0
}
func insertBalance(root *Node, dir int) *Node {
n := root.Link[dir]
bal := 2*dir - 1
if n.Balance == bal {
root.Balance = 0
n.Balance = 0
return single(root, opp(dir))
}
adjustBalance(root, dir, bal)
return double(root, opp(dir))
}
func insertR(root *Node, data Key) (*Node, bool) {
if root == nil {
return &Node{Data: data}, false
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = insertR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 2*dir - 1
switch root.Balance {
case 0:
return root, true
case 1, -1:
return root, false
}
return insertBalance(root, dir), true
}
func Insert(tree **Node, data Key) {
*tree, _ = insertR(*tree, data)
}
func removeBalance(root *Node, dir int) (*Node, bool) {
n := root.Link[opp(dir)]
bal := 2*dir - 1
switch n.Balance {
case -bal:
root.Balance = 0
n.Balance = 0
return single(root, dir), false
case bal:
adjustBalance(root, opp(dir), -bal)
return double(root, dir), false
}
root.Balance = -bal
n.Balance = bal
return single(root, dir), true
}
func removeR(root *Node, data Key) (*Node, bool) {
if root == nil {
return nil, false
}
if root.Data.Eq(data) {
switch {
case root.Link[0] == nil:
return root.Link[1], false
case root.Link[1] == nil:
return root.Link[0], false
}
heir := root.Link[0]
for heir.Link[1] != nil {
heir = heir.Link[1]
}
root.Data = heir.Data
data = heir.Data
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = removeR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 1 - 2*dir
switch root.Balance {
case 1, -1:
return root, true
case 0:
return root, false
}
return removeBalance(root, dir)
}
func Remove(tree **Node, data Key) {
*tree, _ = removeR(*tree, data)
}
| public class AVLtree {
private Node root;
private static class Node {
private int key;
private int balance;
private int height;
private Node left;
private Node right;
private Node parent;
Node(int key, Node parent) {
this.key = key;
this.parent = parent;
}
}
public boolean insert(int key) {
if (root == null) {
root = new Node(key, null);
return true;
}
Node n = root;
while (true) {
if (n.key == key)
return false;
Node parent = n;
boolean goLeft = n.key > key;
n = goLeft ? n.left : n.right;
if (n == null) {
if (goLeft) {
parent.left = new Node(key, parent);
} else {
parent.right = new Node(key, parent);
}
rebalance(parent);
break;
}
}
return true;
}
private void delete(Node node) {
if (node.left == null && node.right == null) {
if (node.parent == null) {
root = null;
} else {
Node parent = node.parent;
if (parent.left == node) {
parent.left = null;
} else {
parent.right = null;
}
rebalance(parent);
}
return;
}
if (node.left != null) {
Node child = node.left;
while (child.right != null) child = child.right;
node.key = child.key;
delete(child);
} else {
Node child = node.right;
while (child.left != null) child = child.left;
node.key = child.key;
delete(child);
}
}
public void delete(int delKey) {
if (root == null)
return;
Node child = root;
while (child != null) {
Node node = child;
child = delKey >= node.key ? node.right : node.left;
if (delKey == node.key) {
delete(node);
return;
}
}
}
private void rebalance(Node n) {
setBalance(n);
if (n.balance == -2) {
if (height(n.left.left) >= height(n.left.right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
} else if (n.balance == 2) {
if (height(n.right.right) >= height(n.right.left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n.parent != null) {
rebalance(n.parent);
} else {
root = n;
}
}
private Node rotateLeft(Node a) {
Node b = a.right;
b.parent = a.parent;
a.right = b.left;
if (a.right != null)
a.right.parent = a;
b.left = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateRight(Node a) {
Node b = a.left;
b.parent = a.parent;
a.left = b.right;
if (a.left != null)
a.left.parent = a;
b.right = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateLeftThenRight(Node n) {
n.left = rotateLeft(n.left);
return rotateRight(n);
}
private Node rotateRightThenLeft(Node n) {
n.right = rotateRight(n.right);
return rotateLeft(n);
}
private int height(Node n) {
if (n == null)
return -1;
return n.height;
}
private void setBalance(Node... nodes) {
for (Node n : nodes) {
reheight(n);
n.balance = height(n.right) - height(n.left);
}
}
public void printBalance() {
printBalance(root);
}
private void printBalance(Node n) {
if (n != null) {
printBalance(n.left);
System.out.printf("%s ", n.balance);
printBalance(n.right);
}
}
private void reheight(Node node) {
if (node != null) {
node.height = 1 + Math.max(height(node.left), height(node.right));
}
}
public static void main(String[] args) {
AVLtree tree = new AVLtree();
System.out.println("Inserting values 1 to 10");
for (int i = 1; i < 10; i++)
tree.insert(i);
System.out.print("Printing balance: ");
tree.printBalance();
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package avl
type Key interface {
Less(Key) bool
Eq(Key) bool
}
type Node struct {
Data Key
Balance int
Link [2]*Node
}
func opp(dir int) int {
return 1 - dir
}
func single(root *Node, dir int) *Node {
save := root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func double(root *Node, dir int) *Node {
save := root.Link[opp(dir)].Link[dir]
root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]
save.Link[opp(dir)] = root.Link[opp(dir)]
root.Link[opp(dir)] = save
save = root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func adjustBalance(root *Node, dir, bal int) {
n := root.Link[dir]
nn := n.Link[opp(dir)]
switch nn.Balance {
case 0:
root.Balance = 0
n.Balance = 0
case bal:
root.Balance = -bal
n.Balance = 0
default:
root.Balance = 0
n.Balance = bal
}
nn.Balance = 0
}
func insertBalance(root *Node, dir int) *Node {
n := root.Link[dir]
bal := 2*dir - 1
if n.Balance == bal {
root.Balance = 0
n.Balance = 0
return single(root, opp(dir))
}
adjustBalance(root, dir, bal)
return double(root, opp(dir))
}
func insertR(root *Node, data Key) (*Node, bool) {
if root == nil {
return &Node{Data: data}, false
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = insertR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 2*dir - 1
switch root.Balance {
case 0:
return root, true
case 1, -1:
return root, false
}
return insertBalance(root, dir), true
}
func Insert(tree **Node, data Key) {
*tree, _ = insertR(*tree, data)
}
func removeBalance(root *Node, dir int) (*Node, bool) {
n := root.Link[opp(dir)]
bal := 2*dir - 1
switch n.Balance {
case -bal:
root.Balance = 0
n.Balance = 0
return single(root, dir), false
case bal:
adjustBalance(root, opp(dir), -bal)
return double(root, dir), false
}
root.Balance = -bal
n.Balance = bal
return single(root, dir), true
}
func removeR(root *Node, data Key) (*Node, bool) {
if root == nil {
return nil, false
}
if root.Data.Eq(data) {
switch {
case root.Link[0] == nil:
return root.Link[1], false
case root.Link[1] == nil:
return root.Link[0], false
}
heir := root.Link[0]
for heir.Link[1] != nil {
heir = heir.Link[1]
}
root.Data = heir.Data
data = heir.Data
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = removeR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 1 - 2*dir
switch root.Balance {
case 1, -1:
return root, true
case 0:
return root, false
}
return removeBalance(root, dir)
}
func Remove(tree **Node, data Key) {
*tree, _ = removeR(*tree, data)
}
| public class AVLtree {
private Node root;
private static class Node {
private int key;
private int balance;
private int height;
private Node left;
private Node right;
private Node parent;
Node(int key, Node parent) {
this.key = key;
this.parent = parent;
}
}
public boolean insert(int key) {
if (root == null) {
root = new Node(key, null);
return true;
}
Node n = root;
while (true) {
if (n.key == key)
return false;
Node parent = n;
boolean goLeft = n.key > key;
n = goLeft ? n.left : n.right;
if (n == null) {
if (goLeft) {
parent.left = new Node(key, parent);
} else {
parent.right = new Node(key, parent);
}
rebalance(parent);
break;
}
}
return true;
}
private void delete(Node node) {
if (node.left == null && node.right == null) {
if (node.parent == null) {
root = null;
} else {
Node parent = node.parent;
if (parent.left == node) {
parent.left = null;
} else {
parent.right = null;
}
rebalance(parent);
}
return;
}
if (node.left != null) {
Node child = node.left;
while (child.right != null) child = child.right;
node.key = child.key;
delete(child);
} else {
Node child = node.right;
while (child.left != null) child = child.left;
node.key = child.key;
delete(child);
}
}
public void delete(int delKey) {
if (root == null)
return;
Node child = root;
while (child != null) {
Node node = child;
child = delKey >= node.key ? node.right : node.left;
if (delKey == node.key) {
delete(node);
return;
}
}
}
private void rebalance(Node n) {
setBalance(n);
if (n.balance == -2) {
if (height(n.left.left) >= height(n.left.right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
} else if (n.balance == 2) {
if (height(n.right.right) >= height(n.right.left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n.parent != null) {
rebalance(n.parent);
} else {
root = n;
}
}
private Node rotateLeft(Node a) {
Node b = a.right;
b.parent = a.parent;
a.right = b.left;
if (a.right != null)
a.right.parent = a;
b.left = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateRight(Node a) {
Node b = a.left;
b.parent = a.parent;
a.left = b.right;
if (a.left != null)
a.left.parent = a;
b.right = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateLeftThenRight(Node n) {
n.left = rotateLeft(n.left);
return rotateRight(n);
}
private Node rotateRightThenLeft(Node n) {
n.right = rotateRight(n.right);
return rotateLeft(n);
}
private int height(Node n) {
if (n == null)
return -1;
return n.height;
}
private void setBalance(Node... nodes) {
for (Node n : nodes) {
reheight(n);
n.balance = height(n.right) - height(n.left);
}
}
public void printBalance() {
printBalance(root);
}
private void printBalance(Node n) {
if (n != null) {
printBalance(n.left);
System.out.printf("%s ", n.balance);
printBalance(n.right);
}
}
private void reheight(Node node) {
if (node != null) {
node.height = 1 + Math.max(height(node.left), height(node.right));
}
}
public static void main(String[] args) {
AVLtree tree = new AVLtree();
System.out.println("Inserting values 1 to 10");
for (int i = 1; i < 10; i++)
tree.insert(i);
System.out.print("Printing balance: ");
tree.printBalance();
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"github.com/fogleman/gg"
"math"
)
type tiletype int
const (
kite tiletype = iota
dart
)
type tile struct {
tt tiletype
x, y float64
angle, size float64
}
var gr = (1 + math.Sqrt(5)) / 2
const theta = math.Pi / 5
func setupPrototiles(w, h int) []tile {
var proto []tile
for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {
ww := float64(w / 2)
hh := float64(h / 2)
proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})
}
return proto
}
func distinctTiles(tls []tile) []tile {
tileset := make(map[tile]bool)
for _, tl := range tls {
tileset[tl] = true
}
distinct := make([]tile, len(tileset))
for tl, _ := range tileset {
distinct = append(distinct, tl)
}
return distinct
}
func deflateTiles(tls []tile, gen int) []tile {
if gen <= 0 {
return tls
}
var next []tile
for _, tl := range tls {
x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr
var nx, ny float64
if tl.tt == dart {
next = append(next, tile{kite, x, y, a + 5*theta, size})
for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {
nx = x + math.Cos(a-4*theta*sign)*gr*tl.size
ny = y - math.Sin(a-4*theta*sign)*gr*tl.size
next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})
}
} else {
for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {
next = append(next, tile{dart, x, y, a - 4*theta*sign, size})
nx = x + math.Cos(a-theta*sign)*gr*tl.size
ny = y - math.Sin(a-theta*sign)*gr*tl.size
next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})
}
}
}
tls = distinctTiles(next)
return deflateTiles(tls, gen-1)
}
func drawTiles(dc *gg.Context, tls []tile) {
dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}
for _, tl := range tls {
angle := tl.angle - theta
dc.MoveTo(tl.x, tl.y)
ord := tl.tt
for i := 0; i < 3; i++ {
x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)
y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)
dc.LineTo(x, y)
angle += theta
}
dc.ClosePath()
if ord == kite {
dc.SetHexColor("FFA500")
} else {
dc.SetHexColor("FFFF00")
}
dc.FillPreserve()
dc.SetHexColor("A9A9A9")
dc.SetLineWidth(1)
dc.Stroke()
}
}
func main() {
w, h := 700, 450
dc := gg.NewContext(w, h)
dc.SetRGB(1, 1, 1)
dc.Clear()
tiles := deflateTiles(setupPrototiles(w, h), 5)
drawTiles(dc, tiles)
dc.SavePNG("penrose_tiling.png")
}
| import java.awt.*;
import java.util.List;
import java.awt.geom.Path2D;
import java.util.*;
import javax.swing.*;
import static java.lang.Math.*;
import static java.util.stream.Collectors.toList;
public class PenroseTiling extends JPanel {
class Tile {
double x, y, angle, size;
Type type;
Tile(Type t, double x, double y, double a, double s) {
type = t;
this.x = x;
this.y = y;
angle = a;
size = s;
}
@Override
public boolean equals(Object o) {
if (o instanceof Tile) {
Tile t = (Tile) o;
return type == t.type && x == t.x && y == t.y && angle == t.angle;
}
return false;
}
}
enum Type {
Kite, Dart
}
static final double G = (1 + sqrt(5)) / 2;
static final double T = toRadians(36);
List<Tile> tiles = new ArrayList<>();
public PenroseTiling() {
int w = 700, h = 450;
setPreferredSize(new Dimension(w, h));
setBackground(Color.white);
tiles = deflateTiles(setupPrototiles(w, h), 5);
}
List<Tile> setupPrototiles(int w, int h) {
List<Tile> proto = new ArrayList<>();
for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)
proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));
return proto;
}
List<Tile> deflateTiles(List<Tile> tls, int generation) {
if (generation <= 0)
return tls;
List<Tile> next = new ArrayList<>();
for (Tile tile : tls) {
double x = tile.x, y = tile.y, a = tile.angle, nx, ny;
double size = tile.size / G;
if (tile.type == Type.Dart) {
next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));
for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {
nx = x + cos(a - 4 * T * sign) * G * tile.size;
ny = y - sin(a - 4 * T * sign) * G * tile.size;
next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));
}
} else {
for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {
next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));
nx = x + cos(a - T * sign) * G * tile.size;
ny = y - sin(a - T * sign) * G * tile.size;
next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));
}
}
}
tls = next.stream().distinct().collect(toList());
return deflateTiles(tls, generation - 1);
}
void drawTiles(Graphics2D g) {
double[][] dist = {{G, G, G}, {-G, -1, -G}};
for (Tile tile : tiles) {
double angle = tile.angle - T;
Path2D path = new Path2D.Double();
path.moveTo(tile.x, tile.y);
int ord = tile.type.ordinal();
for (int i = 0; i < 3; i++) {
double x = tile.x + dist[ord][i] * tile.size * cos(angle);
double y = tile.y - dist[ord][i] * tile.size * sin(angle);
path.lineTo(x, y);
angle += T;
}
path.closePath();
g.setColor(ord == 0 ? Color.orange : Color.yellow);
g.fill(path);
g.setColor(Color.darkGray);
g.draw(path);
}
}
@Override
public void paintComponent(Graphics og) {
super.paintComponent(og);
Graphics2D g = (Graphics2D) og;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawTiles(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Penrose Tiling");
f.setResizable(false);
f.add(new PenroseTiling(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
const limit = 1000000
limit2 := int(math.Cbrt(limit))
primes := rcu.Primes(limit / 6)
pc := len(primes)
var sphenic []int
fmt.Println("Sphenic numbers less than 1,000:")
for i := 0; i < pc-2; i++ {
if primes[i] > limit2 {
break
}
for j := i + 1; j < pc-1; j++ {
prod := primes[i] * primes[j]
if prod+primes[j+1] >= limit {
break
}
for k := j + 1; k < pc; k++ {
res := prod * primes[k]
if res >= limit {
break
}
sphenic = append(sphenic, res)
}
}
}
sort.Ints(sphenic)
ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })
rcu.PrintTable(sphenic[:ix], 15, 3, false)
fmt.Println("\nSphenic triplets less than 10,000:")
var triplets [][3]int
for i := 0; i < len(sphenic)-2; i++ {
s := sphenic[i]
if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {
triplets = append(triplets, [3]int{s, s + 1, s + 2})
}
}
ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })
for i := 0; i < ix; i++ {
fmt.Printf("%4d ", triplets[i])
if (i+1)%3 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThere are %s sphenic numbers less than 1,000,000.\n", rcu.Commatize(len(sphenic)))
fmt.Printf("There are %s sphenic triplets less than 1,000,000.\n", rcu.Commatize(len(triplets)))
s := sphenic[199999]
pf := rcu.PrimeFactors(s)
fmt.Printf("The 200,000th sphenic number is %s (%d*%d*%d).\n", rcu.Commatize(s), pf[0], pf[1], pf[2])
fmt.Printf("The 5,000th sphenic triplet is %v.\n.", triplets[4999])
}
| import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class SphenicNumbers {
public static void main(String[] args) {
final int limit = 1000000;
final int imax = limit / 6;
boolean[] sieve = primeSieve(imax + 1);
boolean[] sphenic = new boolean[limit + 1];
for (int i = 0; i <= imax; ++i) {
if (!sieve[i])
continue;
int jmax = Math.min(imax, limit / (i * i));
if (jmax <= i)
break;
for (int j = i + 1; j <= jmax; ++j) {
if (!sieve[j])
continue;
int p = i * j;
int kmax = Math.min(imax, limit / p);
if (kmax <= j)
break;
for (int k = j + 1; k <= kmax; ++k) {
if (!sieve[k])
continue;
assert(p * k <= limit);
sphenic[p * k] = true;
}
}
}
System.out.println("Sphenic numbers < 1000:");
for (int i = 0, n = 0; i < 1000; ++i) {
if (!sphenic[i])
continue;
++n;
System.out.printf("%3d%c", i, n % 15 == 0 ? '\n' : ' ');
}
System.out.println("\nSphenic triplets < 10,000:");
for (int i = 0, n = 0; i < 10000; ++i) {
if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {
++n;
System.out.printf("(%d, %d, %d)%c",
i - 2, i - 1, i, n % 3 == 0 ? '\n' : ' ');
}
}
int count = 0, triplets = 0, s200000 = 0, t5000 = 0;
for (int i = 0; i < limit; ++i) {
if (!sphenic[i])
continue;
++count;
if (count == 200000)
s200000 = i;
if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {
++triplets;
if (triplets == 5000)
t5000 = i;
}
}
System.out.printf("\nNumber of sphenic numbers < 1,000,000: %d\n", count);
System.out.printf("Number of sphenic triplets < 1,000,000: %d\n", triplets);
List<Integer> factors = primeFactors(s200000);
assert(factors.size() == 3);
System.out.printf("The 200,000th sphenic number: %d = %d * %d * %d\n",
s200000, factors.get(0), factors.get(1),
factors.get(2));
System.out.printf("The 5,000th sphenic triplet: (%d, %d, %d)\n",
t5000 - 2, t5000 - 1, t5000);
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
private static List<Integer> primeFactors(int n) {
List<Integer> factors = new ArrayList<>();
if (n > 1 && (n & 1) == 0) {
factors.add(2);
while ((n & 1) == 0)
n >>= 1;
}
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
factors.add(p);
while (n % p == 0)
n /= p;
}
}
if (n > 1)
factors.add(n);
return factors;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"crypto/md5"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"time"
)
type fileData struct {
filePath string
info os.FileInfo
}
type hash [16]byte
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func checksum(filePath string) hash {
bytes, err := ioutil.ReadFile(filePath)
check(err)
return hash(md5.Sum(bytes))
}
func findDuplicates(dirPath string, minSize int64) [][2]fileData {
var dups [][2]fileData
m := make(map[hash]fileData)
werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && info.Size() >= minSize {
h := checksum(path)
fd, ok := m[h]
fd2 := fileData{path, info}
if !ok {
m[h] = fd2
} else {
dups = append(dups, [2]fileData{fd, fd2})
}
}
return nil
})
check(werr)
return dups
}
func main() {
dups := findDuplicates(".", 1)
fmt.Println("The following pairs of files have the same size and the same hash:\n")
fmt.Println("File name Size Date last modified")
fmt.Println("==========================================================")
sort.Slice(dups, func(i, j int) bool {
return dups[i][0].info.Size() > dups[j][0].info.Size()
})
for _, dup := range dups {
for i := 0; i < 2; i++ {
d := dup[i]
fmt.Printf("%-20s %8d %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))
}
fmt.Println()
}
}
| import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.security.*;
import java.util.*;
public class DuplicateFiles {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Directory name and minimum file size are required.");
System.exit(1);
}
try {
findDuplicateFiles(args[0], Long.parseLong(args[1]));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void findDuplicateFiles(String directory, long minimumSize)
throws IOException, NoSuchAlgorithmException {
System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes.");
Path path = FileSystems.getDefault().getPath(directory);
FileVisitor visitor = new FileVisitor(path, minimumSize);
Files.walkFileTree(path, visitor);
System.out.println("The following sets of files have the same size and checksum:");
for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {
Map<Object, List<String>> map = e.getValue();
if (!containsDuplicates(map))
continue;
List<List<String>> fileSets = new ArrayList<>(map.values());
for (List<String> files : fileSets)
Collections.sort(files);
Collections.sort(fileSets, new StringListComparator());
FileKey key = e.getKey();
System.out.println();
System.out.println("Size: " + key.size_ + " bytes");
for (List<String> files : fileSets) {
for (int i = 0, n = files.size(); i < n; ++i) {
if (i > 0)
System.out.print(" = ");
System.out.print(files.get(i));
}
System.out.println();
}
}
}
private static class StringListComparator implements Comparator<List<String>> {
public int compare(List<String> a, List<String> b) {
int len1 = a.size(), len2 = b.size();
for (int i = 0; i < len1 && i < len2; ++i) {
int c = a.get(i).compareTo(b.get(i));
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
private static boolean containsDuplicates(Map<Object, List<String>> map) {
if (map.size() > 1)
return true;
for (List<String> files : map.values()) {
if (files.size() > 1)
return true;
}
return false;
}
private static class FileVisitor extends SimpleFileVisitor<Path> {
private MessageDigest digest_;
private Path directory_;
private long minimumSize_;
private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();
private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {
directory_ = directory;
minimumSize_ = minimumSize;
digest_ = MessageDigest.getInstance("MD5");
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (attrs.size() >= minimumSize_) {
FileKey key = new FileKey(file, attrs, getMD5Sum(file));
Map<Object, List<String>> map = fileMap_.get(key);
if (map == null)
fileMap_.put(key, map = new HashMap<>());
List<String> files = map.get(attrs.fileKey());
if (files == null)
map.put(attrs.fileKey(), files = new ArrayList<>());
Path relative = directory_.relativize(file);
files.add(relative.toString());
}
return FileVisitResult.CONTINUE;
}
private byte[] getMD5Sum(Path file) throws IOException {
digest_.reset();
try (InputStream in = new FileInputStream(file.toString())) {
byte[] buffer = new byte[8192];
int bytes;
while ((bytes = in.read(buffer)) != -1) {
digest_.update(buffer, 0, bytes);
}
}
return digest_.digest();
}
}
private static class FileKey implements Comparable<FileKey> {
private byte[] hash_;
private long size_;
private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {
size_ = attrs.size();
hash_ = hash;
}
public int compareTo(FileKey other) {
int c = Long.compare(other.size_, size_);
if (c == 0)
c = hashCompare(hash_, other.hash_);
return c;
}
}
private static int hashCompare(byte[] a, byte[] b) {
int len1 = a.length, len2 = b.length;
for (int i = 0; i < len1 && i < len2; ++i) {
int c = Byte.compare(a[i], b[i]);
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
| import java.util.*;
public class HolyKnightsTour {
final static String[] board = {
" xxx ",
" x xx ",
" xxxxxxx",
"xxx x x",
"x x xxx",
"1xxxxxx ",
" xx x ",
" xxx "};
private final static int base = 12;
private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},
{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};
private static int[][] grid;
private static int total = 2;
public static void main(String[] args) {
int row = 0, col = 0;
grid = new int[base][base];
for (int r = 0; r < base; r++) {
Arrays.fill(grid[r], -1);
for (int c = 2; c < base - 2; c++) {
if (r >= 2 && r < base - 2) {
if (board[r - 2].charAt(c - 2) == 'x') {
grid[r][c] = 0;
total++;
}
if (board[r - 2].charAt(c - 2) == '1') {
row = r;
col = c;
}
}
}
}
grid[row][col] = 1;
if (solve(row, col, 2))
printResult();
}
private static boolean solve(int r, int c, int count) {
if (count == total)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != total)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
private static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
private static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
private static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
| import java.util.*;
public class HolyKnightsTour {
final static String[] board = {
" xxx ",
" x xx ",
" xxxxxxx",
"xxx x x",
"x x xxx",
"1xxxxxx ",
" xx x ",
" xxx "};
private final static int base = 12;
private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},
{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};
private static int[][] grid;
private static int total = 2;
public static void main(String[] args) {
int row = 0, col = 0;
grid = new int[base][base];
for (int r = 0; r < base; r++) {
Arrays.fill(grid[r], -1);
for (int c = 2; c < base - 2; c++) {
if (r >= 2 && r < base - 2) {
if (board[r - 2].charAt(c - 2) == 'x') {
grid[r][c] = 0;
total++;
}
if (board[r - 2].charAt(c - 2) == '1') {
row = r;
col = c;
}
}
}
}
grid[row][col] = 1;
if (solve(row, col, 2))
printResult();
}
private static boolean solve(int r, int c, int count) {
if (count == total)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != total)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
private static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
private static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
private static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"sort"
"strings"
)
type indexSort struct {
val sort.Interface
ind []int
}
func (s indexSort) Len() int { return len(s.ind) }
func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }
func (s indexSort) Swap(i, j int) {
s.val.Swap(s.ind[i], s.ind[j])
s.ind[i], s.ind[j] = s.ind[j], s.ind[i]
}
func disjointSliceSort(m, n []string) []string {
s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}
used := make(map[int]bool)
for _, nw := range n {
for i, mw := range m {
if used[i] || mw != nw {
continue
}
used[i] = true
s.ind = append(s.ind, i)
break
}
}
sort.Sort(s)
return s.val.(sort.StringSlice)
}
func disjointStringSort(m, n string) string {
return strings.Join(
disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ")
}
func main() {
for _, data := range []struct{ m, n string }{
{"the cat sat on the mat", "mat cat"},
{"the cat sat on the mat", "cat mat"},
{"A B C A B C A B C", "C A C A"},
{"A B C A B D A B E", "E A D A"},
{"A B", "B"},
{"A B", "B A"},
{"A B B A", "B A"},
} {
mp := disjointStringSort(data.m, data.n)
fmt.Printf("%s → %s » %s\n", data.m, data.n, mp)
}
}
| import java.util.Arrays;
import java.util.BitSet;
import org.apache.commons.lang3.ArrayUtils;
public class OrderDisjointItems {
public static void main(String[] args) {
final String[][] MNs = {{"the cat sat on the mat", "mat cat"},
{"the cat sat on the mat", "cat mat"},
{"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"},
{"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}};
for (String[] a : MNs) {
String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" "));
System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r));
}
}
static String[] orderDisjointItems(String[] m, String[] n) {
for (String e : n) {
int idx = ArrayUtils.indexOf(m, e);
if (idx != -1)
m[idx] = null;
}
for (int i = 0, j = 0; i < m.length; i++) {
if (m[i] == null)
m[i] = n[j++];
}
return m;
}
static String[] orderDisjointItems2(String[] m, String[] n) {
BitSet bitSet = new BitSet(m.length);
for (String e : n) {
int idx = -1;
do {
idx = ArrayUtils.indexOf(m, e, idx + 1);
} while (idx != -1 && bitSet.get(idx));
if (idx != -1)
bitSet.set(idx);
}
for (int i = 0, j = 0; i < m.length; i++) {
if (bitSet.get(i))
m[i] = n[j++];
}
return m;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | var m = ` leading spaces
and blank lines`
| package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | var m = ` leading spaces
and blank lines`
| package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.