Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
| import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
func main() {
s := "immutable"
s[0] = 'a'
}
| final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6;
immutableInt = 6;
|
Change the following Go code into Java without altering its purpose. | package main
import "fmt"
type point struct {
x, y float32
}
var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}
var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}
func main() {
var cp1, cp2, s, e point
inside := func(p point) bool {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
}
intersection := func() (p point) {
dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y
dpx, dpy := s.x-e.x, s.y-e.y
n1 := cp1.x*cp2.y - cp1.y*cp2.x
n2 := s.x*e.y - s.y*e.x
n3 := 1 / (dcx*dpy - dcy*dpx)
p.x = (n1*dpx - n2*dcx) * n3
p.y = (n1*dpy - n2*dcy) * n3
return
}
outputList := subjectPolygon
cp1 = clipPolygon[len(clipPolygon)-1]
for _, cp2 = range clipPolygon {
inputList := outputList
outputList = nil
s = inputList[len(inputList)-1]
for _, e = range inputList {
if inside(e) {
if !inside(s) {
outputList = append(outputList, intersection())
}
outputList = append(outputList, e)
} else if inside(s) {
outputList = append(outputList, intersection())
}
s = e
}
cp1 = cp2
}
fmt.Println(outputList)
}
| import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class SutherlandHodgman extends JFrame {
SutherlandHodgmanPanel panel;
public static void main(String[] args) {
JFrame f = new SutherlandHodgman();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public SutherlandHodgman() {
Container content = getContentPane();
content.setLayout(new BorderLayout());
panel = new SutherlandHodgmanPanel();
content.add(panel, BorderLayout.CENTER);
setTitle("SutherlandHodgman");
pack();
setLocationRelativeTo(null);
}
}
class SutherlandHodgmanPanel extends JPanel {
List<double[]> subject, clipper, result;
public SutherlandHodgmanPanel() {
setPreferredSize(new Dimension(600, 500));
double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};
double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};
subject = new ArrayList<>(Arrays.asList(subjPoints));
result = new ArrayList<>(subject);
clipper = new ArrayList<>(Arrays.asList(clipPoints));
clipPolygon();
}
private void clipPolygon() {
int len = clipper.size();
for (int i = 0; i < len; i++) {
int len2 = result.size();
List<double[]> input = result;
result = new ArrayList<>(len2);
double[] A = clipper.get((i + len - 1) % len);
double[] B = clipper.get(i);
for (int j = 0; j < len2; j++) {
double[] P = input.get((j + len2 - 1) % len2);
double[] Q = input.get(j);
if (isInside(A, B, Q)) {
if (!isInside(A, B, P))
result.add(intersection(A, B, P, Q));
result.add(Q);
} else if (isInside(A, B, P))
result.add(intersection(A, B, P, Q));
}
}
}
private boolean isInside(double[] a, double[] b, double[] c) {
return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);
}
private double[] intersection(double[] a, double[] b, double[] p, double[] q) {
double A1 = b[1] - a[1];
double B1 = a[0] - b[0];
double C1 = A1 * a[0] + B1 * a[1];
double A2 = q[1] - p[1];
double B2 = p[0] - q[0];
double C2 = A2 * p[0] + B2 * p[1];
double det = A1 * B2 - A2 * B1;
double x = (B2 * C1 - B1 * C2) / det;
double y = (A1 * C2 - A2 * C1) / det;
return new double[]{x, y};
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.translate(80, 60);
g2.setStroke(new BasicStroke(3));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPolygon(g2, subject, Color.blue);
drawPolygon(g2, clipper, Color.red);
drawPolygon(g2, result, Color.green);
}
private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {
g2.setColor(color);
int len = points.size();
Line2D line = new Line2D.Double();
for (int i = 0; i < len; i++) {
double[] p1 = points.get(i);
double[] p2 = points.get((i + 1) % len);
line.setLine(p1[0], p1[1], p2[0], p2[1]);
g2.draw(line);
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
| import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
| import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"strconv"
)
var n = 5
func main() {
if n < 1 {
return
}
top, left, bottom, right := 0, 0, n-1, n-1
sz := n * n
a := make([]int, sz)
i := 0
for left < right {
for c := left; c <= right; c++ {
a[top*n+c] = i
i++
}
top++
for r := top; r <= bottom; r++ {
a[r*n+right] = i
i++
}
right--
if top == bottom {
break
}
for c := right; c >= left; c-- {
a[bottom*n+c] = i
i++
}
bottom--
for r := bottom; r >= top; r-- {
a[r*n+left] = i
i++
}
left++
}
a[top*n+left] = i
w := len(strconv.Itoa(n*n - 1))
for i, e := range a {
fmt.Printf("%*d ", w, e)
if i%n == n-1 {
fmt.Println("")
}
}
}
| public class Blah {
public static void main(String[] args) {
print2dArray(getSpiralArray(5));
}
public static int[][] getSpiralArray(int dimension) {
int[][] spiralArray = new int[dimension][dimension];
int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);
int j;
int sideLen = dimension;
int currNum = 0;
for (int i = 0; i < numConcentricSquares; i++) {
for (j = 0; j < sideLen; j++) {
spiralArray[i][i + j] = currNum++;
}
for (j = 1; j < sideLen; j++) {
spiralArray[i + j][dimension - 1 - i] = currNum++;
}
for (j = sideLen - 2; j > -1; j--) {
spiralArray[dimension - 1 - i][i + j] = currNum++;
}
for (j = sideLen - 2; j > 0; j--) {
spiralArray[i + j][i] = currNum++;
}
sideLen -= 2;
}
return spiralArray;
}
public static void print2dArray(int[][] array) {
for (int[] row : array) {
for (int elem : row) {
System.out.printf("%3d", elem);
}
System.out.println();
}
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | type cell string
type spec struct {
less func(cell, cell) bool
column int
reverse bool
}
func newSpec() (s spec) {
return
}
t.sort(newSpec())
s := newSpec
s.reverse = true
t.sort(s)
| module OptionalParameters
{
typedef Type<String >.Orderer as ColumnOrderer;
typedef Type<String[]>.Orderer as RowOrderer;
static String[][] sort(String[][] table,
ColumnOrderer? orderer = Null,
Int column = 0,
Boolean reverse = False,
)
{
orderer ?:= (s1, s2) -> s1 <=> s2;
ColumnOrderer byString = reverse
? ((s1, s2) -> orderer(s1, s2).reversed)
: orderer;
RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);
return table.sorted(byColumn);
}
void run()
{
String[][] table =
[
["c", "x", "i"],
["a", "y", "p"],
["b", "z", "a"],
];
show("original input", table);
show("by default sort on column 0", sort(table));
show("by column 2", sort(table, column=2));
show("by column 2 reversed", sort(table, column=2, reverse=True));
}
void show(String title, String[][] table)
{
@Inject Console console;
console.print($"{title}:");
for (val row : table)
{
console.print($" {row}");
}
console.print();
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.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 java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
static double p = 3;
static BufferedImage I;
static int px[], py[], color[], cells = 100, size = 1000;
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.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 java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
static double p = 3;
static BufferedImage I;
static int px[], py[], color[], cells = 100, size = 1000;
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.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 java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
static double p = 3;
static BufferedImage I;
static int px[], py[], color[], cells = 100, size = 1000;
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import "C"
import (
"fmt"
"unsafe"
)
func main() {
go1 := "hello C"
c1 := C.CString(go1)
go1 = ""
c2 := C.strdup(c1)
C.free(unsafe.Pointer(c1))
go2 := C.GoString(c2)
C.free(unsafe.Pointer(c2))
fmt.Println(go2)
}
| public class JNIDemo
{
static
{ System.loadLibrary("JNIDemo"); }
public static void main(String[] args)
{
System.out.println(callStrdup("Hello World!"));
}
private static native String callStrdup(String s);
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "C"
import (
"fmt"
"unsafe"
)
func main() {
go1 := "hello C"
c1 := C.CString(go1)
go1 = ""
c2 := C.strdup(c1)
C.free(unsafe.Pointer(c1))
go2 := C.GoString(c2)
C.free(unsafe.Pointer(c2))
fmt.Println(go2)
}
| public class JNIDemo
{
static
{ System.loadLibrary("JNIDemo"); }
public static void main(String[] args)
{
System.out.println(callStrdup("Hello World!"));
}
private static native String callStrdup(String s);
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| import java.util.*;
class SOfN<T> {
private static final Random rand = new Random();
private List<T> sample;
private int i = 0;
private int n;
public SOfN(int _n) {
n = _n;
sample = new ArrayList<T>(n);
}
public List<T> process(T item) {
if (++i <= n) {
sample.add(item);
} else if (rand.nextInt(i) < n) {
sample.set(rand.nextInt(n), item);
}
return sample;
}
}
public class AlgorithmS {
public static void main(String[] args) {
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
SOfN<Integer> s_of_n = new SOfN<Integer>(3);
for (int i = 0; i < 9; i++) s_of_n.process(i);
for (int s : s_of_n.process(9)) bin[s]++;
}
System.out.println(Arrays.toString(bin));
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| import java.util.*;
class SOfN<T> {
private static final Random rand = new Random();
private List<T> sample;
private int i = 0;
private int n;
public SOfN(int _n) {
n = _n;
sample = new ArrayList<T>(n);
}
public List<T> process(T item) {
if (++i <= n) {
sample.add(item);
} else if (rand.nextInt(i) < n) {
sample.set(rand.nextInt(n), item);
}
return sample;
}
}
public class AlgorithmS {
public static void main(String[] args) {
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
SOfN<Integer> s_of_n = new SOfN<Integer>(3);
for (int i = 0; i < 9; i++) s_of_n.process(i);
for (int s : s_of_n.process(9)) bin[s]++;
}
System.out.println(Arrays.toString(bin));
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"fmt"
"math/big"
)
func bernoulli(n uint) *big.Rat {
a := make([]big.Rat, n+1)
z := new(big.Rat)
for m := range a {
a[m].SetFrac64(1, int64(m+1))
for j := m; j >= 1; j-- {
d := &a[j-1]
d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))
}
}
if n != 1 {
return &a[0]
}
a[0].Neg(&a[0])
return &a[0]
}
func binomial(n, k int) int64 {
if n <= 0 || k <= 0 || n < k {
return 1
}
var num, den int64 = 1, 1
for i := k + 1; i <= n; i++ {
num *= int64(i)
}
for i := 2; i <= n-k; i++ {
den *= int64(i)
}
return num / den
}
func faulhaberTriangle(p int) []big.Rat {
coeffs := make([]big.Rat, p+1)
q := big.NewRat(1, int64(p)+1)
t := new(big.Rat)
u := new(big.Rat)
sign := -1
for j := range coeffs {
sign *= -1
d := &coeffs[p-j]
t.SetInt64(int64(sign))
u.SetInt64(binomial(p+1, j))
d.Mul(q, t)
d.Mul(d, u)
d.Mul(d, bernoulli(uint(j)))
}
return coeffs
}
func main() {
for i := 0; i < 10; i++ {
coeffs := faulhaberTriangle(i)
for _, coeff := range coeffs {
fmt.Printf("%5s ", coeff.RatString())
}
fmt.Println()
}
fmt.Println()
k := 17
cc := faulhaberTriangle(k)
n := int64(1000)
nn := big.NewRat(n, 1)
np := big.NewRat(1, 1)
sum := new(big.Rat)
tmp := new(big.Rat)
for _, c := range cc {
np.Mul(np, nn)
tmp.Set(np)
tmp.Mul(tmp, &c)
sum.Add(sum, tmp)
}
fmt.Println(sum.RatString())
}
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.stream.LongStream;
public class FaulhabersTriangle {
private static final MathContext MC = new MathContext(256);
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static class Frac implements Comparable<Frac> {
private long num;
private long denom;
public static final Frac ZERO = new Frac(0, 1);
public Frac(long n, long d) {
if (d == 0) throw new IllegalArgumentException("d must not be zero");
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.abs(gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
public Frac plus(Frac rhs) {
return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);
}
public Frac unaryMinus() {
return new Frac(-num, denom);
}
public Frac minus(Frac rhs) {
return this.plus(rhs.unaryMinus());
}
public Frac times(Frac rhs) {
return new Frac(this.num * rhs.num, this.denom * rhs.denom);
}
@Override
public int compareTo(Frac o) {
double diff = toDouble() - o.toDouble();
return Double.compare(diff, 0.0);
}
@Override
public boolean equals(Object obj) {
return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;
}
@Override
public String toString() {
if (denom == 1) {
return Long.toString(num);
}
return String.format("%d/%d", num, denom);
}
public double toDouble() {
return (double) num / denom;
}
public BigDecimal toBigDecimal() {
return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);
}
}
private static Frac bernoulli(int n) {
if (n < 0) throw new IllegalArgumentException("n may not be negative or zero");
Frac[] a = new Frac[n + 1];
Arrays.fill(a, Frac.ZERO);
for (int m = 0; m <= n; ++m) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; --j) {
a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));
}
}
if (n != 1) return a[0];
return a[0].unaryMinus();
}
private static long binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();
if (n == 0 || k == 0) return 1;
long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);
long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);
return num / den;
}
private static Frac[] faulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
Arrays.fill(coeffs, Frac.ZERO);
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; ++j) {
sign *= -1;
coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));
}
return coeffs;
}
public static void main(String[] args) {
for (int i = 0; i <= 9; ++i) {
Frac[] coeffs = faulhaberTriangle(i);
for (Frac coeff : coeffs) {
System.out.printf("%5s ", coeff);
}
System.out.println();
}
System.out.println();
int k = 17;
Frac[] cc = faulhaberTriangle(k);
int n = 1000;
BigDecimal nn = BigDecimal.valueOf(n);
BigDecimal np = BigDecimal.ONE;
BigDecimal sum = BigDecimal.ZERO;
for (Frac c : cc) {
np = np.multiply(nn);
sum = sum.add(np.multiply(c.toBigDecimal()));
}
System.out.println(sum.toBigInteger());
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Write the same code in Java as shown below in Go. | package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{7, 12, 60}
c := append(a, b...)
fmt.Println(c)
i := []interface{}{1, 2, 3}
j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
k := append(i, j...)
fmt.Println(k)
l := [...]int{1, 2, 3}
m := [...]int{7, 12, 60}
var n [len(l) + len(m)]int
copy(n[:], l[:])
copy(n[len(l):], m[:])
fmt.Println(n)
}
| String[] fruits = ["apples", "oranges"];
String[] grains = ["wheat", "corn"];
String[] all = fruits + grains;
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
}
| import java.util.Scanner;
public class GetInput {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = s.nextLine();
System.out.print("Enter an integer: ");
int i = Integer.parseInt(s.next());
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
|
import processing.sound.*;
float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};
SinOsc sine;
size(500,500);
sine = new SinOsc(this);
for(int i=0;i<frequencies.length;i++){
sine.freq(frequencies[i]);
sine.play();
delay(500);
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
|
import processing.sound.*;
float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};
SinOsc sine;
size(500,500);
sine = new SinOsc(this);
for(int i=0;i<frequencies.length;i++){
sine.freq(frequencies[i]);
sine.play();
delay(500);
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import "fmt"
type item struct {
string
w, v int
}
var wants = []item{
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
}
const maxWt = 400
func main() {
items, w, v := m(len(wants)-1, maxWt)
fmt.Println(items)
fmt.Println("weight:", w)
fmt.Println("value:", v)
}
func m(i, w int) ([]string, int, int) {
if i < 0 || w == 0 {
return nil, 0, 0
} else if wants[i].w > w {
return m(i-1, w)
}
i0, w0, v0 := m(i-1, w)
i1, w1, v1 := m(i-1, w-wants[i].w)
v1 += wants[i].v
if v1 > v0 {
return append(i1, wants[i].string), w1 + wants[i].w, v1
}
return i0, w0, v0
}
| package hu.pj.alg.test;
import hu.pj.alg.ZeroOneKnapsack;
import hu.pj.obj.Item;
import java.util.*;
import java.text.*;
public class ZeroOneKnapsackForTourists {
public ZeroOneKnapsackForTourists() {
ZeroOneKnapsack zok = new ZeroOneKnapsack(400);
zok.add("map", 9, 150);
zok.add("compass", 13, 35);
zok.add("water", 153, 200);
zok.add("sandwich", 50, 160);
zok.add("glucose", 15, 60);
zok.add("tin", 68, 45);
zok.add("banana", 27, 60);
zok.add("apple", 39, 40);
zok.add("cheese", 23, 30);
zok.add("beer", 52, 10);
zok.add("suntan cream", 11, 70);
zok.add("camera", 32, 30);
zok.add("t-shirt", 24, 15);
zok.add("trousers", 48, 10);
zok.add("umbrella", 73, 40);
zok.add("waterproof trousers", 42, 70);
zok.add("waterproof overclothes", 43, 75);
zok.add("note-case", 22, 80);
zok.add("sunglasses", 7, 20);
zok.add("towel", 18, 12);
zok.add("socks", 4, 50);
zok.add("book", 30, 10);
List<Item> itemList = zok.calcSolution();
if (zok.isCalculated()) {
NumberFormat nf = NumberFormat.getInstance();
System.out.println(
"Maximal weight = " +
nf.format(zok.getMaxWeight() / 100.0) + " kg"
);
System.out.println(
"Total weight of solution = " +
nf.format(zok.getSolutionWeight() / 100.0) + " kg"
);
System.out.println(
"Total value = " +
zok.getProfit()
);
System.out.println();
System.out.println(
"You can carry the following materials " +
"in the knapsack:"
);
for (Item item : itemList) {
if (item.getInKnapsack() == 1) {
System.out.format(
"%1$-23s %2$-3s %3$-5s %4$-15s \n",
item.getName(),
item.getWeight(), "dag ",
"(value = " + item.getValue() + ")"
);
}
}
} else {
System.out.println(
"The problem is not solved. " +
"Maybe you gave wrong data."
);
}
}
public static void main(String[] args) {
new ZeroOneKnapsackForTourists();
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"sort"
)
func getPrimes(max int) []int {
if max < 2 {
return []int{}
}
lprimes := []int{2}
outer:
for x := 3; x <= max; x += 2 {
for _, p := range lprimes {
if x%p == 0 {
continue outer
}
}
lprimes = append(lprimes, x)
}
return lprimes
}
func main() {
const maxSum = 99
descendants := make([][]int64, maxSum+1)
ancestors := make([][]int, maxSum+1)
for i := 0; i <= maxSum; i++ {
descendants[i] = []int64{}
ancestors[i] = []int{}
}
primes := getPrimes(maxSum)
for _, p := range primes {
descendants[p] = append(descendants[p], int64(p))
for s := 1; s < len(descendants)-p; s++ {
temp := make([]int64, len(descendants[s]))
for i := 0; i < len(descendants[s]); i++ {
temp[i] = int64(p) * descendants[s][i]
}
descendants[s+p] = append(descendants[s+p], temp...)
}
}
for _, p := range append(primes, 4) {
le := len(descendants[p])
if le == 0 {
continue
}
descendants[p][le-1] = 0
descendants[p] = descendants[p][:le-1]
}
total := 0
for s := 1; s <= maxSum; s++ {
x := descendants[s]
sort.Slice(x, func(i, j int) bool {
return x[i] < x[j]
})
total += len(descendants[s])
index := 0
for ; index < len(descendants[s]); index++ {
if descendants[s][index] > int64(maxSum) {
break
}
}
for _, d := range descendants[s][:index] {
ancestors[d] = append(ancestors[s], s)
}
if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {
continue
}
temp := fmt.Sprintf("%v", ancestors[s])
fmt.Printf("%2d: %d Ancestor(s): %-14s", s, len(ancestors[s]), temp)
le := len(descendants[s])
if le <= 10 {
fmt.Printf("%5d Descendant(s): %v\n", le, descendants[s])
} else {
fmt.Printf("%5d Descendant(s): %v\b ...]\n", le, descendants[s][:10])
}
}
fmt.Println("\nTotal descendants", total)
}
| import java.io.*;
import java.util.*;
public class PrimeDescendants {
public static void main(String[] args) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {
printPrimeDesc(writer, 100);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void printPrimeDesc(Writer writer, int limit) throws IOException {
List<Long> primes = findPrimes(limit);
List<Long> ancestor = new ArrayList<>(limit);
List<List<Long>> descendants = new ArrayList<>(limit);
for (int i = 0; i < limit; ++i) {
ancestor.add(Long.valueOf(0));
descendants.add(new ArrayList<Long>());
}
for (Long prime : primes) {
int p = prime.intValue();
descendants.get(p).add(prime);
for (int i = 0; i + p < limit; ++i) {
int s = i + p;
for (Long n : descendants.get(i)) {
Long prod = n * p;
descendants.get(s).add(prod);
if (prod < limit)
ancestor.set(prod.intValue(), Long.valueOf(s));
}
}
}
int totalDescendants = 0;
for (int i = 1; i < limit; ++i) {
List<Long> ancestors = getAncestors(ancestor, i);
writer.write("[" + i + "] Level: " + ancestors.size() + "\n");
writer.write("Ancestors: ");
Collections.sort(ancestors);
print(writer, ancestors);
writer.write("Descendants: ");
List<Long> desc = descendants.get(i);
if (!desc.isEmpty()) {
Collections.sort(desc);
if (desc.get(0) == i)
desc.remove(0);
}
writer.write(desc.size() + "\n");
totalDescendants += desc.size();
if (!desc.isEmpty())
print(writer, desc);
writer.write("\n");
}
writer.write("Total descendants: " + totalDescendants + "\n");
}
private static List<Long> findPrimes(int limit) {
boolean[] isprime = new boolean[limit];
Arrays.fill(isprime, true);
isprime[0] = isprime[1] = false;
for (int p = 2; p * p < limit; ++p) {
if (isprime[p]) {
for (int i = p * p; i < limit; i += p)
isprime[i] = false;
}
}
List<Long> primes = new ArrayList<>();
for (int p = 2; p < limit; ++p) {
if (isprime[p])
primes.add(Long.valueOf(p));
}
return primes;
}
private static List<Long> getAncestors(List<Long> ancestor, int n) {
List<Long> result = new ArrayList<>();
for (Long a = ancestor.get(n); a != 0 && a != n; ) {
n = a.intValue();
a = ancestor.get(n);
result.add(Long.valueOf(n));
}
return result;
}
private static void print(Writer writer, List<Long> list) throws IOException {
if (list.isEmpty()) {
writer.write("none\n");
return;
}
int i = 0;
writer.write(String.valueOf(list.get(i++)));
for (; i != list.size(); ++i)
writer.write(", " + list.get(i));
writer.write("\n");
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
| import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
| import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import "math"
import "fmt"
func cube(x float64) float64 { return math.Pow(x, 3) }
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
funclist := []ffType{math.Sin, math.Cos, cube}
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}
| import java.util.ArrayList;
public class FirstClass{
public interface Function<A,B>{
B apply(A x);
}
public static <A,B,C> Function<A, C> compose(
final Function<B, C> f, final Function<A, B> g) {
return new Function<A, C>() {
@Override public C apply(A x) {
return f.apply(g.apply(x));
}
};
}
public static void main(String[] args){
ArrayList<Function<Double, Double>> functions =
new ArrayList<Function<Double,Double>>();
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.cos(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.tan(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return x * x;
}
});
ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.acos(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.atan(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.sqrt(x);
}
});
System.out.println("Compositions:");
for(int i = 0; i < functions.size(); i++){
System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
}
System.out.println("Hard-coded compositions:");
System.out.println(Math.cos(Math.acos(0.5)));
System.out.println(Math.tan(Math.atan(0.5)));
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"strconv"
)
func listProperDivisors(limit int) {
if limit < 1 {
return
}
width := len(strconv.Itoa(limit))
for i := 1; i <= limit; i++ {
fmt.Printf("%*d -> ", width, i)
if i == 1 {
fmt.Println("(None)")
continue
}
for j := 1; j <= i/2; j++ {
if i%j == 0 {
fmt.Printf(" %d", j)
}
}
fmt.Println()
}
}
func countProperDivisors(n int) int {
if n < 2 {
return 0
}
count := 0
for i := 1; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
fmt.Println()
maxCount := 0
most := []int{1}
for n := 2; n <= 20000; n++ {
count := countProperDivisors(n)
if count == maxCount {
most = append(most, n)
} else if count > maxCount {
maxCount = count
most = most[0:1]
most[0] = n
}
}
fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
fmt.Println("namely", maxCount, "\b\n")
for _, n := range most {
fmt.Println(n)
}
}
| import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Proper{
public static List<Integer> properDivs(int n){
List<Integer> divs = new LinkedList<Integer>();
if(n == 1) return divs;
divs.add(1);
for(int x = 2; x < n; x++){
if(n % x == 0) divs.add(x);
}
Collections.sort(divs);
return divs;
}
public static void main(String[] args){
for(int x = 1; x <= 10; x++){
System.out.println(x + ": " + properDivs(x));
}
int x = 0, count = 0;
for(int n = 1; n <= 20000; n++){
if(properDivs(n).size() > count){
x = n;
count = properDivs(n).size();
}
}
System.out.println(x + ": " + count);
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"encoding/xml"
"fmt"
)
func xRemarks(r CharacterRemarks) (string, error) {
b, err := xml.MarshalIndent(r, "", " ")
return string(b), err
}
type CharacterRemarks struct {
Character []crm
}
type crm struct {
Name string `xml:"name,attr"`
Remark string `xml:",chardata"`
}
func main() {
x, err := xRemarks(CharacterRemarks{[]crm{
{`April`, `Bubbly: I'm > Tam and <= Emily`},
{`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
{`Emily`, `Short & shrift`},
}})
if err != nil {
x = err.Error()
}
fmt.Println(x)
}
| import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XmlCreation {
private static final String[] names = {"April", "Tam O'Shanter", "Emily"};
private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift"};
public static void main(String[] args) {
try {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element root = doc.createElement("CharacterRemarks");
doc.appendChild(root);
for(int i = 0; i < names.length; i++) {
final Element character = doc.createElement("Character");
root.appendChild(character);
character.setAttribute("name", names[i]);
character.appendChild(doc.createTextNode(remarks[i]));
}
final Source source = new DOMSource(doc);
final StringWriter buffer = new StringWriter();
final Result result = new StreamResult(buffer);
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.transform(source, result);
System.out.println(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Plot2d extends JApplet {
double[] xi;
double[] yi;
public Plot2d(double[] x, double[] y) {
this.xi = x;
this.yi = y;
}
public static double max(double[] t) {
double maximum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > maximum) {
maximum = t[i];
}
}
return maximum;
}
public static double min(double[] t) {
double minimum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] < minimum) {
minimum = t[i];
}
}
return minimum;
}
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.black);
int x0 = 70;
int y0 = 10;
int xm = 670;
int ym = 410;
int xspan = xm - x0;
int yspan = ym - y0;
double xmax = max(xi);
double xmin = min(xi);
double ymax = max(yi);
double ymin = min(yi);
g2.draw(new Line2D.Double(x0, ym, xm, ym));
g2.draw(new Line2D.Double(x0, ym, x0, y0));
for (int j = 0; j < 5; j++) {
int interv = 4;
g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);
g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),
ym - j * yspan / interv + y0 - 5);
g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));
g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));
}
for (int i = 0; i < xi.length; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
g2.drawString("o", x0 + f - 3, h + 14);
}
for (int i = 0; i < xi.length - 1; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));
g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));
}
}
public static void main(String args[]) {
JFrame f = new JFrame("ShapesDemo2D");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};
JApplet applet = new Plot2d(r, t);
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(720, 480));
f.show();
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Plot2d extends JApplet {
double[] xi;
double[] yi;
public Plot2d(double[] x, double[] y) {
this.xi = x;
this.yi = y;
}
public static double max(double[] t) {
double maximum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > maximum) {
maximum = t[i];
}
}
return maximum;
}
public static double min(double[] t) {
double minimum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] < minimum) {
minimum = t[i];
}
}
return minimum;
}
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.black);
int x0 = 70;
int y0 = 10;
int xm = 670;
int ym = 410;
int xspan = xm - x0;
int yspan = ym - y0;
double xmax = max(xi);
double xmin = min(xi);
double ymax = max(yi);
double ymin = min(yi);
g2.draw(new Line2D.Double(x0, ym, xm, ym));
g2.draw(new Line2D.Double(x0, ym, x0, y0));
for (int j = 0; j < 5; j++) {
int interv = 4;
g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);
g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),
ym - j * yspan / interv + y0 - 5);
g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));
g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));
}
for (int i = 0; i < xi.length; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
g2.drawString("o", x0 + f - 3, h + 14);
}
for (int i = 0; i < xi.length - 1; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));
g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));
}
}
public static void main(String args[]) {
JFrame f = new JFrame("ShapesDemo2D");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};
JApplet applet = new Plot2d(r, t);
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(720, 480));
f.show();
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
}
| String str = "I am a string";
if (str.matches(".*string")) {
System.out.println("ends with 'string'");
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"sort"
)
func main() {
lower, upper := 0, 100
fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
answer := sort.Search(upper-lower, func (i int) bool {
fmt.Printf("Is your number less than or equal to %d? ", lower+i)
s := ""
fmt.Scanf("%s", &s)
return s != "" && s[0] == 'y'
})
fmt.Printf("Your number is %d.\n", lower+answer)
}
| import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;
public class GuessNumber {
public static final int LOWER = 0, UPPER = 100;
public static void main(String[] args) {
System.out.printf("Instructions:\n" +
"Think of integer number from %d (inclusive) to %d (exclusive) and\n" +
"I will guess it. After each guess, you respond with L, H, or C depending\n" +
"on if my guess was too low, too high, or correct.\n",
LOWER, UPPER);
int result = Collections.binarySearch(new AbstractList<Integer>() {
private final Scanner in = new Scanner(System.in);
public int size() { return UPPER - LOWER; }
public Integer get(int i) {
System.out.printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i);
String s = in.nextLine();
assert s.length() > 0;
switch (Character.toLowerCase(s.charAt(0))) {
case 'l':
return -1;
case 'h':
return 1;
case 'c':
return 0;
}
return -1;
}
}, 0);
if (result < 0)
System.out.println("That is impossible.");
else
System.out.printf("Your number is %d.\n", result);
}
}
|
Write the same code in Java as shown below in Go. | package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}
| import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();
for(int i= 0; i < keys.length; i++){
hash.put(keys[i], vals[i]);
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
x2 := x + distance*math.Sin(direction*math.Pi/180)
y2 := y - distance*math.Cos(direction*math.Pi/180)
g.AaLine(x, y, x2, y2)
if depth > 0 {
ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
}
}
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class FractalTree extends JFrame {
public FractalTree() {
super("Fractal Tree");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {
if (depth == 0) return;
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
g.drawLine(x1, y1, x2, y2);
drawTree(g, x2, y2, angle - 20, depth - 1);
drawTree(g, x2, y2, angle + 20, depth - 1);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
drawTree(g, 400, 500, -90, 9);
}
public static void main(String[] args) {
new FractalTree().setVisible(true);
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "github.com/fogleman/gg"
var palette = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 4
for b := 1; b <= 4; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%8])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(900, 600)
pinstripe(dc)
dc.SavePNG("color_pinstripe.png")
}
| import java.awt.*;
import static java.awt.Color.*;
import javax.swing.*;
public class ColourPinstripeDisplay extends JPanel {
final static Color[] palette = {black, red, green, blue, magenta,cyan,
yellow, white};
final int bands = 4;
public ColourPinstripeDisplay() {
setPreferredSize(new Dimension(900, 600));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = getHeight();
for (int b = 1; b <= bands; b++) {
for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {
g.setColor(palette[colIndex % palette.length]);
g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("ColourPinstripeDisplay");
f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| class Doom {
public static void main(String[] args) {
final Date[] dates = {
new Date(1800,1,6),
new Date(1875,3,29),
new Date(1915,12,7),
new Date(1970,12,23),
new Date(2043,5,14),
new Date(2077,2,12),
new Date(2101,4,2)
};
for (Date d : dates)
System.out.println(
String.format("%s: %s", d.format(), d.weekday()));
}
}
class Date {
private int year, month, day;
private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};
private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};
public static final String[] weekdays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean isLeapYear() {
return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
public String format() {
return String.format("%02d/%02d/%04d", month, day, year);
}
public String weekday() {
final int c = year/100;
final int r = year%100;
final int s = r/12;
final int t = r%12;
final int c_anchor = (5 * (c%4) + 2) % 7;
final int doom = (s + t + t/4 + c_anchor) % 7;
final int anchor =
isLeapYear() ? leapdoom[month-1] : normdoom[month-1];
return weekdays[(doom + day - anchor + 7) % 7];
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| class Doom {
public static void main(String[] args) {
final Date[] dates = {
new Date(1800,1,6),
new Date(1875,3,29),
new Date(1915,12,7),
new Date(1970,12,23),
new Date(2043,5,14),
new Date(2077,2,12),
new Date(2101,4,2)
};
for (Date d : dates)
System.out.println(
String.format("%s: %s", d.format(), d.weekday()));
}
}
class Date {
private int year, month, day;
private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};
private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};
public static final String[] weekdays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean isLeapYear() {
return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
public String format() {
return String.format("%02d/%02d/%04d", month, day, year);
}
public String weekday() {
final int c = year/100;
final int r = year%100;
final int s = r/12;
final int t = r%12;
final int c_anchor = (5 * (c%4) + 2) % 7;
final int doom = (s + t + t/4 + c_anchor) % 7;
final int anchor =
isLeapYear() ? leapdoom[month-1] : normdoom[month-1];
return weekdays[(doom + day - anchor + 7) % 7];
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/rand"
"time"
)
func cocktailShakerSort(a []int) {
var begin = 0
var end = len(a) - 2
for begin <= end {
newBegin := end
newEnd := begin
for i := begin; i <= end; i++ {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newEnd = i
}
}
end = newEnd - 1
for i := end; i >= begin; i-- {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newBegin = i
}
}
begin = newBegin + 1
}
}
func cocktailSort(a []int) {
last := len(a) - 1
for {
swapped := false
for i := 0; i < last; i++ {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
swapped = false
for i := last - 1; i >= 0; i-- {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
}
}
func main() {
a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}
fmt.Println("Original array:", a)
b := make([]int, len(a))
copy(b, a)
cocktailSort(a)
fmt.Println("Cocktail sort :", a)
cocktailShakerSort(b)
fmt.Println("C/Shaker sort :", b)
rand.Seed(time.Now().UnixNano())
fmt.Println("\nRelative speed of the two sorts")
fmt.Println(" N x faster (CSS v CS)")
fmt.Println("----- -------------------")
const runs = 10
for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {
sum := 0.0
for i := 1; i <= runs; i++ {
nums := make([]int, n)
for i := 0; i < n; i++ {
rn := rand.Intn(100000)
if i%2 == 1 {
rn = -rn
}
nums[i] = rn
}
nums2 := make([]int, n)
copy(nums2, nums)
start := time.Now()
cocktailSort(nums)
elapsed := time.Since(start)
start2 := time.Now()
cocktailShakerSort(nums2)
elapsed2 := time.Since(start2)
sum += float64(elapsed) / float64(elapsed2)
}
fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs)
}
}
| import java.util.*;
public class CocktailSort {
public static void main(String[] args) {
Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };
System.out.println("before: " + Arrays.toString(array));
cocktailSort(array);
System.out.println("after: " + Arrays.toString(array));
}
public static void cocktailSort(Object[] array) {
int begin = 0;
int end = array.length;
if (end == 0)
return;
for (--end; begin < end; ) {
int new_begin = end;
int new_end = begin;
for (int i = begin; i < end; ++i) {
Comparable c1 = (Comparable)array[i];
Comparable c2 = (Comparable)array[i + 1];
if (c1.compareTo(c2) > 0) {
swap(array, i, i + 1);
new_end = i;
}
}
end = new_end;
for (int i = end; i > begin; --i) {
Comparable c1 = (Comparable)array[i - 1];
Comparable c2 = (Comparable)array[i];
if (c1.compareTo(c2) > 0) {
swap(array, i, i - 1);
new_begin = i;
}
}
begin = new_begin;
}
}
private static void swap(Object[] array, int i, int j) {
Object tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/math"
"github.com/google/gxui/themes/dark"
omath "math"
"time"
)
const (
ANIMATION_WIDTH int = 480
ANIMATION_HEIGHT int = 320
BALL_RADIUS float32 = 25.0
METER_PER_PIXEL float64 = 1.0 / 20.0
PHI_ZERO float64 = omath.Pi * 0.5
)
var (
l float64 = float64(ANIMATION_HEIGHT) * 0.5
freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))
)
type Pendulum interface {
GetPhi() float64
}
type mathematicalPendulum struct {
start time.Time
}
func (p *mathematicalPendulum) GetPhi() float64 {
if (p.start == time.Time{}) {
p.start = time.Now()
}
t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)
return PHI_ZERO * omath.Cos(t*freq)
}
type numericalPendulum struct {
currentPhi float64
angAcc float64
angVel float64
lastTime time.Time
}
func (p *numericalPendulum) GetPhi() float64 {
dt := 0.0
if (p.lastTime != time.Time{}) {
dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)
}
p.lastTime = time.Now()
p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)
p.angVel += p.angAcc * dt
p.currentPhi += p.angVel * dt
return p.currentPhi
}
func draw(p Pendulum, canvas gxui.Canvas, x, y int) {
attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}
phi := p.GetPhi()
ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}
line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}
canvas.DrawLines(line, gxui.DefaultPen)
m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}
rect := math.Rect{ball.Sub(m), ball.Add(m)}
canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))
}
func appMain(driver gxui.Driver) {
theme := dark.CreateTheme(driver)
window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum")
window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))
image := theme.CreateImage()
ticker := time.NewTicker(time.Millisecond * 15)
pendulum := &mathematicalPendulum{}
pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}
go func() {
for _ = range ticker.C {
canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})
canvas.Clear(gxui.White)
draw(pendulum, canvas, 0, 0)
draw(pendulum2, canvas, 0, ANIMATION_HEIGHT)
canvas.Complete()
driver.Call(func() {
image.SetCanvas(canvas)
})
}
}()
window.AddChild(image)
window.OnClose(ticker.Stop)
window.OnClose(driver.Terminate)
}
func main() {
gl.StartDriver(appMain)
}
| import java.awt.*;
import javax.swing.*;
public class Pendulum extends JPanel implements Runnable {
private double angle = Math.PI / 2;
private int length;
public Pendulum(int length) {
this.length = length;
setDoubleBuffered(true);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
int ballX = anchorX + (int) (Math.sin(angle) * length);
int ballY = anchorY + (int) (Math.cos(angle) * length);
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
}
public void run() {
double angleAccel, angleVelocity = 0, dt = 0.1;
while (true) {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try { Thread.sleep(15); } catch (InterruptedException ex) {}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(2 * length + 50, length / 2 * 3);
}
public static void main(String[] args) {
JFrame f = new JFrame("Pendulum");
Pendulum p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| public class Gray {
public static long grayEncode(long n){
return n ^ (n >>> 1);
}
public static long grayDecode(long n) {
long p = n;
while ((n >>>= 1) != 0)
p ^= n;
return p;
}
public static void main(String[] args){
System.out.println("i\tBinary\tGray\tDecoded");
for(int i = -1; i < 32;i++){
System.out.print(i +"\t");
System.out.print(Integer.toBinaryString(i) + "\t");
System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
System.out.println(grayDecode(grayEncode(i)));
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| public class Gray {
public static long grayEncode(long n){
return n ^ (n >>> 1);
}
public static long grayDecode(long n) {
long p = n;
while ((n >>>= 1) != 0)
p ^= n;
return p;
}
public static void main(String[] args){
System.out.println("i\tBinary\tGray\tDecoded");
for(int i = -1; i < 32;i++){
System.out.print(i +"\t");
System.out.print(Integer.toBinaryString(i) + "\t");
System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
System.out.println(grayDecode(grayEncode(i)));
}
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
gzipFlag := flag.Bool("gzip", false, "use gzip compression")
flag.Parse()
var w io.Writer = os.Stdout
if *outfile != "" {
f, err := os.Create(*outfile)
if err != nil {
log.Fatalf("opening/creating %q: %v", *outfile, err)
}
defer f.Close()
w = f
}
if *gzipFlag {
zw := gzip.NewWriter(w)
defer zw.Close()
w = zw
}
tw := tar.NewWriter(w)
defer tw.Close()
w = tw
tw.WriteHeader(&tar.Header{
Name: *filename,
Mode: 0660,
Size: int64(len(*data)),
ModTime: time.Now(),
Typeflag: tar.TypeReg,
Uname: "guest",
Gname: "guest",
})
_, err := w.Write([]byte(*data))
if err != nil {
log.Fatal("writing data:", err)
}
}
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
public class CreateFile {
public static void main(String[] args) throws IOException {
String os = System.getProperty("os.name");
if (os.contains("Windows")) {
Path path = Paths.get("tape.file");
Files.write(path, Collections.singletonList("Hello World!"));
} else {
Path path = Paths.get("/dev/tape");
Files.write(path, Collections.singletonList("Hello World!"));
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"sort"
"container/heap"
"fmt"
)
type HeapHelper struct {
container sort.Interface
length int
}
func (self HeapHelper) Len() int { return self.length }
func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }
func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }
func (self *HeapHelper) Push(x interface{}) { panic("impossible") }
func (self *HeapHelper) Pop() interface{} {
self.length--
return nil
}
func heapSort(a sort.Interface) {
helper := HeapHelper{ a, a.Len() }
heap.Init(&helper)
for helper.length > 0 {
heap.Pop(&helper)
}
}
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
heapSort(sort.IntSlice(a))
fmt.Println("after: ", a)
}
| public static void heapSort(int[] a){
int count = a.length;
heapify(a, count);
int end = count - 1;
while(end > 0){
int tmp = a[end];
a[end] = a[0];
a[0] = tmp;
siftDown(a, 0, end - 1);
end--;
}
}
public static void heapify(int[] a, int count){
int start = (count - 2) / 2;
while(start >= 0){
siftDown(a, start, count - 1);
start--;
}
}
public static void siftDown(int[] a, int start, int end){
int root = start;
while((root * 2 + 1) <= end){
int child = root * 2 + 1;
if(child + 1 <= end && a[child] < a[child + 1])
child = child + 1;
if(a[root] < a[child]){
int tmp = a[root];
a[root] = a[child];
a[child] = tmp;
root = child;
}else
return;
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Five Rank = 5
Six Rank = 6
Seven Rank = 7
Eight Rank = 8
Nine Rank = 9
Ten Rank = 10
Jack Rank = 11
Queen Rank = 12
King Rank = 13
)
func (r Rank) String() string {
const ranks = "A23456789TJQK"
return ranks[r-1 : r]
}
type Card uint8
func NewCard(r Rank, s Suit) Card {
return Card(13*uint8(s) + uint8(r-1))
}
func (c Card) RankSuit() (Rank, Suit) {
return Rank(c%13 + 1), Suit(c / 13)
}
func (c Card) Rank() Rank {
return Rank(c%13 + 1)
}
func (c Card) Suit() Suit {
return Suit(c / 13)
}
func (c Card) String() string {
return c.Rank().String() + c.Suit().String()
}
type Deck []Card
func NewDeck() Deck {
d := make(Deck, 52)
for i := range d {
d[i] = Card(i)
}
return d
}
func (d Deck) String() string {
s := ""
for i, c := range d {
switch {
case i == 0:
case i%13 == 0:
s += "\n"
default:
s += " "
}
s += c.String()
}
return s
}
func (d Deck) Shuffle() {
for i := range d {
j := rand.Intn(i + 1)
d[i], d[j] = d[j], d[i]
}
}
func (d Deck) Contains(tc Card) bool {
for _, c := range d {
if c == tc {
return true
}
}
return false
}
func (d *Deck) AddDeck(decks ...Deck) {
for _, o := range decks {
*d = append(*d, o...)
}
}
func (d *Deck) AddCard(c Card) {
*d = append(*d, c)
}
func (d *Deck) Draw(n int) Deck {
old := *d
*d = old[n:]
return old[:n:n]
}
func (d *Deck) DrawCard() (Card, bool) {
if len(*d) == 0 {
return 0, false
}
old := *d
*d = old[1:]
return old[0], true
}
func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {
for i := 0; i < cards; i++ {
for j := range hands {
if len(*d) == 0 {
return hands, false
}
hands[j] = append(hands[j], (*d)[0])
*d = (*d)[1:]
}
}
return hands, true
}
| public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace }
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
)
func main() {
var a [5]int
fmt.Println("len(a) =", len(a))
fmt.Println("a =", a)
a[0] = 3
fmt.Println("a =", a)
fmt.Println("a[0] =", a[0])
s := a[:4]
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
s = s[:5]
fmt.Println("s =", s)
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
}
| Int[] literalArray = [1,2,3];
Int[] fixedLengthArray = new Int[10];
Int[] variableArray = new Int[];
assert literalArray.size == 3;
Int n = literalArray[2];
fixedLengthArray[4] = 12345;
fixedLengthArray += 6789;
variableArray += 6789;
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
}
| public static boolean inCarpet(long x, long y) {
while (x!=0 && y!=0) {
if (x % 3 == 1 && y % 3 == 1)
return false;
x /= 3;
y /= 3;
}
return true;
}
public static void carpet(final int n) {
final double power = Math.pow(3,n);
for(long i = 0; i < power; i++) {
for(long j = 0; j < power; j++) {
System.out.print(inCarpet(i, j) ? "*" : " ");
}
System.out.println();
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
rand.Seed(time.Now().UnixNano())
fmt.Println("unsorted:", list)
temp := make([]int, len(list))
copy(temp, list)
for !sort.IntsAreSorted(temp) {
for i, v := range rand.Perm(len(list)) {
temp[i] = list[v]
}
}
fmt.Println("sorted! ", temp)
}
| public class BogoSort
{
public static void main(String[] args)
{
int[] arr={4,5,6,0,7,8,9,1,2,3};
BogoSort now=new BogoSort();
System.out.print("Unsorted: ");
now.display1D(arr);
now.bogo(arr);
System.out.print("Sorted: ");
now.display1D(arr);
}
void bogo(int[] arr)
{
int shuffle=1;
for(;!isSorted(arr);shuffle++)
shuffle(arr);
System.out.println("This took "+shuffle+" shuffles.");
}
void shuffle(int[] arr)
{
int i=arr.length-1;
while(i>0)
swap(arr,i--,(int)(Math.random()*i));
}
void swap(int[] arr,int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
boolean isSorted(int[] arr)
{
for(int i=1;i<arr.length;i++)
if(arr[i]<arr[i-1])
return false;
return true;
}
void display1D(int[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"fmt"
"math"
)
type fdy func(float64, float64) float64
func eulerStep(f fdy, x, y, h float64) float64 {
return y + h*f(x, y)
}
func newCoolingRate(k float64) func(float64) float64 {
return func(deltaTemp float64) float64 {
return -k * deltaTemp
}
}
func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {
return func(time float64) float64 {
return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)
}
}
func newCoolingRateDy(k, ambientTemp float64) fdy {
crf := newCoolingRate(k)
return func(_, objectTemp float64) float64 {
return crf(objectTemp - ambientTemp)
}
}
func main() {
k := .07
tempRoom := 20.
tempObject := 100.
fcr := newCoolingRateDy(k, tempRoom)
analytic := newTempFunc(k, tempRoom, tempObject)
for _, deltaTime := range []float64{2, 5, 10} {
fmt.Printf("Step size = %.1f\n", deltaTime)
fmt.Println(" Time Euler's Analytic")
temp := tempObject
for time := 0.; time <= 100; time += deltaTime {
fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time))
temp = eulerStep(fcr, time, temp, deltaTime)
}
fmt.Println()
}
}
| public class Euler {
private static void euler (Callable f, double y0, int a, int b, int h) {
int t = a;
double y = y0;
while (t < b) {
System.out.println ("" + t + " " + y);
t += h;
y += h * f.compute (t, y);
}
System.out.println ("DONE");
}
public static void main (String[] args) {
Callable cooling = new Cooling ();
int[] steps = {2, 5, 10};
for (int stepSize : steps) {
System.out.println ("Step size: " + stepSize);
euler (cooling, 100.0, 0, 100, stepSize);
}
}
}
interface Callable {
public double compute (int time, double t);
}
class Cooling implements Callable {
public double compute (int time, double t) {
return -0.07 * (t - 20);
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
| public class SeqNonSquares {
public static int nonsqr(int n) {
return n + (int)Math.round(Math.sqrt(n));
}
public static void main(String[] args) {
for (int i = 1; i < 23; i++)
System.out.print(nonsqr(i) + " ");
System.out.println();
for (int i = 1; i < 1000000; i++) {
double j = Math.sqrt(nonsqr(i));
assert j != Math.floor(j);
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
| public static String Substring(String str, int n, int m){
return str.substring(n, n+m);
}
public static String Substring(String str, int n){
return str.substring(n);
}
public static String Substring(String str){
return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, int m){
return str.substring(str.indexOf(c), str.indexOf(c)+m+1);
}
public static String Substring(String str, String sub, int m){
return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"log"
"sort"
)
func main() {
log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4}))
log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))
log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))
log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))
}
func jortSort(a []int) bool {
c := make([]int, len(a))
copy(c, a)
sort.Ints(a)
for k, v := range c {
if v == a[k] {
continue
} else {
return false
}
}
return true
}
| public class JortSort {
public static void main(String[] args) {
System.out.println(jortSort(new int[]{1, 2, 3}));
}
static boolean jortSort(int[] arr) {
return true;
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
}
| import java.util.GregorianCalendar;
import java.text.MessageFormat;
public class Leapyear{
public static void main(String[] argv){
int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
GregorianCalendar cal = new GregorianCalendar();
for(int year : yrs){
System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.",
year, cal.isLeapYear(year), isLeapYear(year)));
}
}
public static boolean isLeapYear(int year){
return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"math/big"
)
func main() {
var n, p int64
fmt.Printf("A sample of permutations from 1 to 12:\n")
for n = 1; n < 13; n++ {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 10 to 60:\n")
for n = 10; n < 61; n += 10 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of permutations from 5 to 15000:\n")
nArr := [...]int64{5, 50, 500, 1000, 5000, 15000}
for _, n = range nArr {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 100 to 1000:\n")
for n = 100; n < 1001; n += 100 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
}
func fact(n *big.Int) *big.Int {
if n.Sign() < 1 {
return big.NewInt(0)
}
r := big.NewInt(1)
i := big.NewInt(2)
for i.Cmp(n) < 1 {
r.Mul(r, i)
i.Add(i, big.NewInt(1))
}
return r
}
func perm(n, k *big.Int) *big.Int {
r := fact(n)
r.Div(r, fact(n.Sub(n, k)))
return r
}
func comb(n, r *big.Int) *big.Int {
if r.Cmp(n) == 1 {
return big.NewInt(0)
}
if r.Cmp(n) == 0 {
return big.NewInt(1)
}
c := fact(n)
den := fact(n.Sub(n, r))
den.Mul(den, fact(r))
c.Div(c, den)
return c
}
| import java.math.BigInteger;
public class CombinationsAndPermutations {
public static void main(String[] args) {
System.out.println(Double.MAX_VALUE);
System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:");
for ( int n = 1 ; n <= 12 ; n++ ) {
int k = n / 2;
System.out.printf("%d P %d = %s%n", n, k, permutation(n, k));
}
System.out.println();
System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:");
for ( int n = 10 ; n <= 60 ; n += 5 ) {
int k = n / 2;
System.out.printf("%d C %d = %s%n", n, k, combination(n, k));
}
System.out.println();
System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:");
System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50));
for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {
int k = n / 2;
System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50));
}
System.out.println();
System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:");
for ( int n = 100 ; n <= 1000 ; n += 100 ) {
int k = n / 2;
System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50));
}
}
private static String display(BigInteger val, int precision) {
String s = val.toString();
precision = Math.min(precision, s.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, 1));
sb.append(".");
sb.append(s.substring(1, precision));
sb.append(" * 10^");
sb.append(s.length()-1);
return sb.toString();
}
public static BigInteger combination(int n, int k) {
if ( n-k < k ) {
k = n-k;
}
BigInteger result = permutation(n, k);
while ( k > 0 ) {
result = result.divide(BigInteger.valueOf(k));
k--;
}
return result;
}
public static BigInteger permutation(int n, int k) {
BigInteger result = BigInteger.ONE;
for ( int i = n ; i >= n-k+1 ; i-- ) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"sort"
"strconv"
)
func lexOrder(n int) []int {
first, last, k := 1, n, n
if n < 1 {
first, last, k = n, 1, 2-n
}
strs := make([]string, k)
for i := first; i <= last; i++ {
strs[i-first] = strconv.Itoa(i)
}
sort.Strings(strs)
ints := make([]int, k)
for i := 0; i < k; i++ {
ints[i], _ = strconv.Atoi(strs[i])
}
return ints
}
func main() {
fmt.Println("In lexicographical order:\n")
for _, n := range []int{0, 5, 13, 21, -22} {
fmt.Printf("%3d: %v\n", n, lexOrder(n))
}
}
| import java.util.List;
import java.util.stream.*;
public class LexicographicalNumbers {
static List<Integer> lexOrder(int n) {
int first = 1, last = n;
if (n < 1) {
first = n;
last = 1;
}
return IntStream.rangeClosed(first, last)
.mapToObj(Integer::toString)
.sorted()
.map(Integer::valueOf)
.collect(Collectors.toList());
}
public static void main(String[] args) {
System.out.println("In lexicographical order:\n");
int[] ints = {0, 5, 13, 21, -22};
for (int n : ints) {
System.out.printf("%3d: %s\n", n, lexOrder(n));
}
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
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
}
| module NumberNames
{
void run()
{
@Inject Console console;
Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,
123456789000, 0x123456789ABCDEF];
for (Int test : tests)
{
console.print($"{test} = {toEnglish(test)}");
}
}
static String[] digits = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"];
static String[] teens = ["ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
static String[] tens = ["zero", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"];
static String[] ten3rd = ["?", "thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"];
static String toEnglish(Int n)
{
StringBuffer buf = new StringBuffer();
if (n < 0)
{
"negative ".appendTo(buf);
n = -n;
}
format3digits(n, buf);
return buf.toString();
}
static void format3digits(Int n, StringBuffer buf, Int nested=0)
{
(Int left, Int right) = n /% 1000;
if (left != 0)
{
format3digits(left, buf, nested+1);
}
if (right != 0 || (left == 0 && nested==0))
{
if (right >= 100)
{
(left, right) = (right /% 100);
digits[left].appendTo(buf);
" hundred ".appendTo(buf);
if (right != 0)
{
format2digits(right, buf);
}
}
else
{
format2digits(right, buf);
}
if (nested > 0)
{
ten3rd[nested].appendTo(buf).add(' ');
}
}
}
static void format2digits(Int n, StringBuffer buf)
{
switch (n)
{
case 0..9:
digits[n].appendTo(buf).add(' ');
break;
case 10..19:
teens[n-10].appendTo(buf).add(' ');
break;
default:
(Int left, Int right) = n /% 10;
tens[left].appendTo(buf);
if (right == 0)
{
buf.add(' ');
}
else
{
buf.add('-');
digits[right].appendTo(buf).add(' ');
}
break;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"os"
"sort"
)
func main() {
if len(os.Args) == 1 {
compareStrings("abcd", "123456789", "abcdef", "1234567")
} else {
strings := os.Args[1:]
compareStrings(strings...)
}
}
func compareStrings(strings ...string) {
sort.SliceStable(strings, func(i, j int) bool {
return len(strings[i]) > len(strings[j])
})
for _, s := range strings {
fmt.Printf("%d: %s\n", len(s), s)
}
}
| package stringlensort;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
public class ReportStringLengths {
public static void main(String[] args) {
String[] list = {"abcd", "123456789", "abcdef", "1234567"};
String[] strings = args.length > 0 ? args : list;
compareAndReportStringsLength(strings);
}
public static void compareAndReportStringsLength(String[] strings) {
compareAndReportStringsLength(strings, System.out);
}
public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
if (strings.length > 0) {
strings = strings.clone();
final String QUOTE = "\"";
Arrays.sort(strings, Comparator.comparing(String::length));
int min = strings[0].length();
int max = strings[strings.length - 1].length();
for (int i = strings.length - 1; i >= 0; i--) {
int length = strings[i].length();
String predicate;
if (length == max) {
predicate = "is the longest string";
} else if (length == min) {
predicate = "is the shortest string";
} else {
predicate = "is neither the longest nor the shortest string";
}
stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
+ " and " + predicate);
}
}
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"os"
"sort"
)
func main() {
if len(os.Args) == 1 {
compareStrings("abcd", "123456789", "abcdef", "1234567")
} else {
strings := os.Args[1:]
compareStrings(strings...)
}
}
func compareStrings(strings ...string) {
sort.SliceStable(strings, func(i, j int) bool {
return len(strings[i]) > len(strings[j])
})
for _, s := range strings {
fmt.Printf("%d: %s\n", len(s), s)
}
}
| package stringlensort;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
public class ReportStringLengths {
public static void main(String[] args) {
String[] list = {"abcd", "123456789", "abcdef", "1234567"};
String[] strings = args.length > 0 ? args : list;
compareAndReportStringsLength(strings);
}
public static void compareAndReportStringsLength(String[] strings) {
compareAndReportStringsLength(strings, System.out);
}
public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
if (strings.length > 0) {
strings = strings.clone();
final String QUOTE = "\"";
Arrays.sort(strings, Comparator.comparing(String::length));
int min = strings[0].length();
int max = strings[strings.length - 1].length();
for (int i = strings.length - 1; i >= 0; i--) {
int length = strings[i].length();
String predicate;
if (length == max) {
predicate = "is the longest string";
} else if (length == min) {
predicate = "is the shortest string";
} else {
predicate = "is neither the longest nor the shortest string";
}
stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
+ " and " + predicate);
}
}
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {
for i := inc; i < len(a); i++ {
j, temp := i, a[i]
for ; j >= inc && a[j-inc] > temp; j -= inc {
a[j] = a[j-inc]
}
a[j] = temp
}
}
fmt.Println("after: ", a)
}
| public static void shell(int[] a) {
int increment = a.length / 2;
while (increment > 0) {
for (int i = increment; i < a.length; i++) {
int j = i;
int temp = a[i];
while (j >= increment && a[j - increment] > temp) {
a[j] = a[j - increment];
j = j - increment;
}
a[j] = temp;
}
if (increment == 2) {
increment = 1;
} else {
increment *= (5.0 / 11);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | type dlNode struct {
int
next, prev *dlNode
}
type dlList struct {
members map[*dlNode]int
head, tail **dlNode
}
| import java.util.LinkedList;
public class DoublyLinkedList {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.addFirst("Add First");
list.addLast("Add Last 1");
list.addLast("Add Last 2");
list.addLast("Add Last 1");
traverseList(list);
list.removeFirstOccurrence("Add Last 1");
traverseList(list);
}
private static void traverseList(LinkedList<String> list) {
System.out.println("Traverse List:");
for ( int i = 0 ; i < list.size() ; i++ ) {
System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
}
System.out.println();
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"io/ioutil"
"sort"
"unicode"
)
const file = "unixdict.txt"
func main() {
bs, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return
}
m := make(map[rune]int)
for _, r := range string(bs) {
m[r]++
}
lfs := make(lfList, 0, len(m))
for l, f := range m {
lfs = append(lfs, &letterFreq{l, f})
}
sort.Sort(lfs)
fmt.Println("file:", file)
fmt.Println("letter frequency")
for _, lf := range lfs {
if unicode.IsGraphic(lf.rune) {
fmt.Printf(" %c %7d\n", lf.rune, lf.freq)
} else {
fmt.Printf("%U %7d\n", lf.rune, lf.freq)
}
}
}
type letterFreq struct {
rune
freq int
}
type lfList []*letterFreq
func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
switch fd := lfs[i].freq - lfs[j].freq; {
case fd < 0:
return false
case fd > 0:
return true
}
return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
lfs[i], lfs[j] = lfs[j], lfs[i]
}
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class LetterFreq {
public static int[] countLetters(String filename) throws IOException{
int[] freqs = new int[26];
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line = in.readLine()) != null){
line = line.toUpperCase();
for(char ch:line.toCharArray()){
if(Character.isLetter(ch)){
freqs[ch - 'A']++;
}
}
}
in.close();
return freqs;
}
public static void main(String[] args) throws IOException{
System.out.println(Arrays.toString(countLetters("filename.txt")));
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}
var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
func main() {
all := make([]int, len(tr)+len(ct))
copy(all, tr)
copy(all[len(tr):], ct)
var sumAll int
for _, r := range all {
sumAll += r
}
sd := func(trc []int) int {
var sumTr int
for _, x := range trc {
sumTr += all[x]
}
return sumTr*len(ct) - (sumAll-sumTr)*len(tr)
}
a := make([]int, len(tr))
for i, _ := range a {
a[i] = i
}
sdObs := sd(a)
var nLe, nGt int
comb(len(all), len(tr), func(c []int) {
if sd(c) > sdObs {
nGt++
} else {
nLe++
}
})
pc := 100 / float64(nLe+nGt)
fmt.Printf("differences <= observed: %f%%\n", float64(nLe)*pc)
fmt.Printf("differences > observed: %f%%\n", float64(nGt)*pc)
}
func comb(n, m int, emit func([]int)) {
s := make([]int, m)
last := m - 1
var rc func(int, int)
rc = func(i, next int) {
for j := next; j < n; j++ {
s[i] = j
if i == last {
emit(s)
} else {
rc(i+1, j+1)
}
}
return
}
rc(0, 0)
}
| public class PermutationTest {
private static final int[] data = new int[]{
85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98
};
private static int pick(int at, int remain, int accu, int treat) {
if (remain == 0) return (accu > treat) ? 1 : 0;
return pick(at - 1, remain - 1, accu + data[at - 1], treat)
+ ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);
}
public static void main(String[] args) {
int treat = 0;
double total = 1.0;
for (int i = 0; i <= 8; ++i) {
treat += data[i];
}
for (int i = 19; i >= 11; --i) {
total *= i;
}
for (int i = 9; i >= 1; --i) {
total /= i;
}
int gt = pick(19, 9, 0, treat);
int le = (int) (total - gt);
System.out.printf("<= : %f%% %d\n", 100.0 * le / total, le);
System.out.printf(" > : %f%% %d\n", 100.0 * gt / total, gt);
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import "fmt"
func möbius(to int) []int {
if to < 1 {
to = 1
}
mobs := make([]int, to+1)
primes := []int{2}
for i := 1; i <= to; i++ {
j := i
cp := 0
spf := false
for _, p := range primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes = append(primes, i)
}
if !spf {
if cp%2 == 0 {
mobs[i] = 1
} else {
mobs[i] = -1
}
}
}
return mobs
}
func main() {
mobs := möbius(199)
fmt.Println("Möbius sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
fmt.Print(" ")
continue
}
if i%20 == 0 {
fmt.Println()
}
fmt.Printf(" % d", mobs[i])
}
}
| public class MöbiusFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the möbius function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", möbiusFunction(n));
if ( (n+1) % 20 == 0 ) {
System.out.printf("%n");
}
}
}
private static int MU_MAX = 1_000_000;
private static int[] MU = null;
private static int möbiusFunction(int n) {
if ( MU != null ) {
return MU[n];
}
MU = new int[MU_MAX+1];
int sqrt = (int) Math.sqrt(MU_MAX);
for ( int i = 0 ; i < MU_MAX ; i++ ) {
MU[i] = 1;
}
for ( int i = 2 ; i <= sqrt ; i++ ) {
if ( MU[i] == 1 ) {
for ( int j = i ; j <= MU_MAX ; j += i ) {
MU[j] *= -i;
}
for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {
MU[j] = 0;
}
}
}
for ( int i = 2 ; i <= MU_MAX ; i++ ) {
if ( MU[i] == i ) {
MU[i] = 1;
}
else if ( MU[i] == -i ) {
MU[i] = -1;
}
else if ( MU[i] < 0 ) {
MU[i] = 1;
}
else if ( MU[i] > 0 ) {
MU[i] = -1;
}
}
return MU[n];
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}
| String s = "12345";
IntLiteral lit1 = new IntLiteral(s);
IntLiteral lit2 = 6789;
++lit1;
++lit2;
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}
| class StripChars {
public static String stripChars(String inString, String toStrip) {
return inString.replaceAll("[" + toStrip + "]", "");
}
public static void main(String[] args) {
String sentence = "She was a soul stripper. She took my heart!";
String chars = "aei";
System.out.println("sentence: " + sentence);
System.out.println("to strip: " + chars);
System.out.println("stripped: " + stripChars(sentence, chars));
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
if len(a) > 1 && !recurse(len(a) - 1) {
panic("sorted permutation not found!")
}
fmt.Println("after: ", a)
}
func recurse(last int) bool {
if last <= 0 {
for i := len(a) - 1; a[i] >= a[i-1]; i-- {
if i == 1 {
return true
}
}
return false
}
for i := 0; i <= last; i++ {
a[i], a[last] = a[last], a[i]
if recurse(last - 1) {
return true
}
a[i], a[last] = a[last], a[i]
}
return false
}
| import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class PermutationSort
{
public static void main(String[] args)
{
int[] a={3,2,1,8,9,4,6};
System.out.println("Unsorted: " + Arrays.toString(a));
a=pSort(a);
System.out.println("Sorted: " + Arrays.toString(a));
}
public static int[] pSort(int[] a)
{
List<int[]> list=new ArrayList<int[]>();
permute(a,a.length,list);
for(int[] x : list)
if(isSorted(x))
return x;
return a;
}
private static void permute(int[] a, int n, List<int[]> list)
{
if (n == 1)
{
int[] b=new int[a.length];
System.arraycopy(a, 0, b, 0, a.length);
list.add(b);
return;
}
for (int i = 0; i < n; i++)
{
swap(a, i, n-1);
permute(a, n-1, list);
swap(a, i, n-1);
}
}
private static boolean isSorted(int[] a)
{
for(int i=1;i<a.length;i++)
if(a[i-1]>a[i])
return false;
return true;
}
private static void swap(int[] arr,int i, int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{},
[]float64{math.Inf(1), math.Inf(1)},
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}
| public static double avg(double... arr) {
double sum = 0.0;
for (double x : arr) {
sum += x;
}
return sum / arr.length;
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
| import java.util.*;
public class Abbreviations {
public static void main(String[] args) {
CommandList commands = new CommandList(commandTable);
String input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
System.out.println(" input: " + input);
System.out.println("output: " + test(commands, input));
}
private static String test(CommandList commands, String input) {
StringBuilder output = new StringBuilder();
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
String word = scanner.next();
if (output.length() > 0)
output.append(' ');
Command cmd = commands.findCommand(word);
if (cmd != null)
output.append(cmd.cmd);
else
output.append("*error*");
}
return output.toString();
}
private static String commandTable =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
private static class Command {
private Command(String cmd, int minLength) {
this.cmd = cmd;
this.minLength = minLength;
}
private boolean match(String str) {
int olen = str.length();
return olen >= minLength && olen <= cmd.length()
&& cmd.regionMatches(true, 0, str, 0, olen);
}
private String cmd;
private int minLength;
}
private static Integer parseInteger(String word) {
try {
return Integer.valueOf(word);
} catch (NumberFormatException ex) {
return null;
}
}
private static class CommandList {
private CommandList(String table) {
Scanner scanner = new Scanner(table);
List<String> words = new ArrayList<>();
while (scanner.hasNext()) {
String word = scanner.next();
words.add(word.toUpperCase());
}
for (int i = 0, n = words.size(); i < n; ++i) {
String word = words.get(i);
int len = word.length();
if (i + 1 < n) {
Integer number = parseInteger(words.get(i + 1));
if (number != null) {
len = number.intValue();
++i;
}
}
commands.add(new Command(word, len));
}
}
private Command findCommand(String word) {
for (Command command : commands) {
if (command.match(word))
return command;
}
return null;
}
private List<Command> commands = new ArrayList<>();
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
| import java.util.*;
public class Abbreviations {
public static void main(String[] args) {
CommandList commands = new CommandList(commandTable);
String input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
System.out.println(" input: " + input);
System.out.println("output: " + test(commands, input));
}
private static String test(CommandList commands, String input) {
StringBuilder output = new StringBuilder();
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
String word = scanner.next();
if (output.length() > 0)
output.append(' ');
Command cmd = commands.findCommand(word);
if (cmd != null)
output.append(cmd.cmd);
else
output.append("*error*");
}
return output.toString();
}
private static String commandTable =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
private static class Command {
private Command(String cmd, int minLength) {
this.cmd = cmd;
this.minLength = minLength;
}
private boolean match(String str) {
int olen = str.length();
return olen >= minLength && olen <= cmd.length()
&& cmd.regionMatches(true, 0, str, 0, olen);
}
private String cmd;
private int minLength;
}
private static Integer parseInteger(String word) {
try {
return Integer.valueOf(word);
} catch (NumberFormatException ex) {
return null;
}
}
private static class CommandList {
private CommandList(String table) {
Scanner scanner = new Scanner(table);
List<String> words = new ArrayList<>();
while (scanner.hasNext()) {
String word = scanner.next();
words.add(word.toUpperCase());
}
for (int i = 0, n = words.size(); i < n; ++i) {
String word = words.get(i);
int len = word.length();
if (i + 1 < n) {
Integer number = parseInteger(words.get(i + 1));
if (number != null) {
len = number.intValue();
++i;
}
}
commands.add(new Command(word, len));
}
}
private Command findCommand(String word) {
for (Command command : commands) {
if (command.match(word))
return command;
}
return null;
}
private List<Command> commands = new ArrayList<>();
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"fmt"
"math"
"strings"
)
func main(){
fmt.Println(H("1223334444"))
}
func H(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
}
| import java.lang.Math;
import java.util.Map;
import java.util.HashMap;
public class REntropy {
@SuppressWarnings("boxing")
public static double getShannonEntropy(String s) {
int n = 0;
Map<Character, Integer> occ = new HashMap<>();
for (int c_ = 0; c_ < s.length(); ++c_) {
char cx = s.charAt(c_);
if (occ.containsKey(cx)) {
occ.put(cx, occ.get(cx) + 1);
} else {
occ.put(cx, 1);
}
++n;
}
double e = 0.0;
for (Map.Entry<Character, Integer> entry : occ.entrySet()) {
char cx = entry.getKey();
double p = (double) entry.getValue() / n;
e += p * log2(p);
}
return -e;
}
private static double log2(double a) {
return Math.log(a) / Math.log(2);
}
public static void main(String[] args) {
String[] sstr = {
"1223334444",
"1223334444555555555",
"122333",
"1227774444",
"aaBBcccDDDD",
"1234567890abcdefghijklmnopqrstuvwxyz",
"Rosetta Code",
};
for (String ss : sstr) {
double entropy = REntropy.getShannonEntropy(ss);
System.out.printf("Shannon entropy of %40s: %.12f%n", "\"" + ss + "\"", entropy);
}
return;
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"errors"
"fmt"
)
func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
for _, r := range s {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, r)
case r == escape:
inEscape = true
case r == sep:
tokens = append(tokens, string(runes))
runes = runes[:0]
}
}
tokens = append(tokens, string(runes))
if inEscape {
err = errors.New("invalid terminal escape")
}
return tokens, err
}
func main() {
const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
const separator = '|'
const escape = '^'
fmt.Printf("Input: %q\n", sample)
tokens, err := TokenizeString(sample, separator, escape)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Printf("Tokens: %q\n", tokens)
}
}
| import java.util.*;
public class TokenizeStringWithEscaping {
public static void main(String[] args) {
String sample = "one^|uno||three^^^^|four^^^|^cuatro|";
char separator = '|';
char escape = '^';
System.out.println(sample);
try {
System.out.println(tokenizeString(sample, separator, escape));
} catch (Exception e) {
System.out.println(e);
}
}
public static List<String> tokenizeString(String s, char sep, char escape)
throws Exception {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean inEscape = false;
for (char c : s.toCharArray()) {
if (inEscape) {
inEscape = false;
} else if (c == escape) {
inEscape = true;
continue;
} else if (c == sep) {
tokens.add(sb.toString());
sb.setLength(0);
continue;
}
sb.append(c);
}
if (inEscape)
throw new Exception("Invalid terminal escape");
tokens.add(sb.toString());
return tokens;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import "fmt"
func main() { fmt.Println("Hello world!") }
| module HelloWorld
{
void run()
{
@Inject Console console;
console.print("Hello World!");
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = 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 printHelper(cat string, le, lim, max int) (int, int, string) {
cle, clim := commatize(le), commatize(lim)
if cat != "unsexy primes" {
cat = "sexy prime " + cat
}
fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle)
last := max
if le < last {
last = le
}
verb := "are"
if last == 1 {
verb = "is"
}
return le, last, verb
}
func main() {
lim := 1000035
sv := sieve(lim - 1)
var pairs [][2]int
var trips [][3]int
var quads [][4]int
var quins [][5]int
var unsexy = []int{2, 3}
for i := 3; i < lim; i += 2 {
if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {
unsexy = append(unsexy, i)
continue
}
if i < lim-6 && !sv[i] && !sv[i+6] {
pair := [2]int{i, i + 6}
pairs = append(pairs, pair)
} else {
continue
}
if i < lim-12 && !sv[i+12] {
trip := [3]int{i, i + 6, i + 12}
trips = append(trips, trip)
} else {
continue
}
if i < lim-18 && !sv[i+18] {
quad := [4]int{i, i + 6, i + 12, i + 18}
quads = append(quads, quad)
} else {
continue
}
if i < lim-24 && !sv[i+24] {
quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}
quins = append(quins, quin)
}
}
le, n, verb := printHelper("pairs", len(pairs), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, pairs[le-n:])
le, n, verb = printHelper("triplets", len(trips), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, trips[le-n:])
le, n, verb = printHelper("quadruplets", len(quads), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quads[le-n:])
le, n, verb = printHelper("quintuplets", len(quins), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quins[le-n:])
le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, unsexy[le-n:])
}
| import java.util.ArrayList;
import java.util.List;
public class SexyPrimes {
public static void main(String[] args) {
sieve();
int pairs = 0;
List<String> pairList = new ArrayList<>();
int triples = 0;
List<String> tripleList = new ArrayList<>();
int quadruplets = 0;
List<String> quadrupletList = new ArrayList<>();
int unsexyCount = 1;
List<String> unsexyList = new ArrayList<>();
for ( int i = 3 ; i < MAX ; i++ ) {
if ( i-6 >= 3 && primes[i-6] && primes[i] ) {
pairs++;
pairList.add((i-6) + " " + i);
if ( pairList.size() > 5 ) {
pairList.remove(0);
}
}
else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {
unsexyCount++;
unsexyList.add("" + i);
if ( unsexyList.size() > 10 ) {
unsexyList.remove(0);
}
}
if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {
triples++;
tripleList.add((i-12) + " " + (i-6) + " " + i);
if ( tripleList.size() > 5 ) {
tripleList.remove(0);
}
}
if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {
quadruplets++;
quadrupletList.add((i-18) + " " + (i-12) + " " + (i-6) + " " + i);
if ( quadrupletList.size() > 5 ) {
quadrupletList.remove(0);
}
}
}
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, pairs);
System.out.printf("The last 5 sexy pairs:%n %s%n%n", pairList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, triples);
System.out.printf("The last 5 sexy triples:%n %s%n%n", tripleList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy quadruplets less than %,d = %,d%n", MAX, quadruplets);
System.out.printf("The last 5 sexy quadruplets:%n %s%n%n", quadrupletList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of unsexy primes less than %,d = %,d%n", MAX, unsexyCount);
System.out.printf("The last 10 unsexy primes:%n %s%n%n", unsexyList.toString().replaceAll(", ", "], ["));
}
private static int MAX = 1_000_035;
private static boolean[] primes = new boolean[MAX];
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import "fmt"
func main() {
a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
fmt.Println(a)
fmt.Println(fd(a, 9))
}
func fd(a []int, ord int) []int {
for i := 0; i < ord; i++ {
for j := 0; j < len(a)-i-1; j++ {
a[j] = a[j+1] - a[j]
}
}
return a[:len(a)-ord]
}
| import java.util.Arrays;
public class FD {
public static void main(String args[]) {
double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
System.out.println(Arrays.toString(dif(a, 1)));
System.out.println(Arrays.toString(dif(a, 2)));
System.out.println(Arrays.toString(dif(a, 9)));
System.out.println(Arrays.toString(dif(a, 10)));
System.out.println(Arrays.toString(dif(a, 11)));
System.out.println(Arrays.toString(dif(a, -1)));
System.out.println(Arrays.toString(dif(a, 0)));
}
public static double[] dif(double[] a, int n) {
if (n < 0)
return null;
for (int i = 0; i < n && a.length > 0; i++) {
double[] b = new double[a.length - 1];
for (int j = 0; j < b.length; j++){
b[j] = a[j+1] - a[j];
}
a = b;
}
return a;
}
}
|
Write a version of this Go function in Java with identical behavior. | func IsPrime(n int) bool {
if n < 0 { n = -n }
switch {
case n == 2:
return true
case n < 2 || n % 2 == 0:
return false
default:
for i = 3; i*i <= n; i += 2 {
if n % i == 0 { return false }
}
}
return true
}
| public static boolean prime(long a){
if(a == 2){
return true;
}else if(a <= 1 || a % 2 == 0){
return false;
}
long max = (long)Math.sqrt(a);
for(long n= 3; n <= max; n+= 2){
if(a % n == 0){ return false; }
}
return true;
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import "fmt"
import "math/big"
func main() {
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
}
| public class Binomial {
private static long binomialInt(int n, int k) {
if (k > n - k)
k = n - k;
long binom = 1;
for (int i = 1; i <= k; i++)
binom = binom * (n + 1 - i) / i;
return binom;
}
private static Object binomialIntReliable(int n, int k) {
if (k > n - k)
k = n - k;
long binom = 1;
for (int i = 1; i <= k; i++) {
try {
binom = Math.multiplyExact(binom, n + 1 - i) / i;
} catch (ArithmeticException e) {
return "overflow";
}
}
return binom;
}
private static double binomialFloat(int n, int k) {
if (k > n - k)
k = n - k;
double binom = 1.0;
for (int i = 1; i <= k; i++)
binom = binom * (n + 1 - i) / i;
return binom;
}
private static BigInteger binomialBigInt(int n, int k) {
if (k > n - k)
k = n - k;
BigInteger binom = BigInteger.ONE;
for (int i = 1; i <= k; i++) {
binom = binom.multiply(BigInteger.valueOf(n + 1 - i));
binom = binom.divide(BigInteger.valueOf(i));
}
return binom;
}
private static void demo(int n, int k) {
List<Object> data = Arrays.asList(
n,
k,
binomialInt(n, k),
binomialIntReliable(n, k),
binomialFloat(n, k),
binomialBigInt(n, k));
System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t")));
}
public static void main(String[] args) {
demo(5, 3);
demo(1000, 300);
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func main() {
var a []interface{}
a = append(a, 3)
a = append(a, "apples", "oranges")
fmt.Println(a)
}
| List arrayList = new ArrayList();
arrayList.add(new Integer(0));
arrayList.add(0);
List<Integer> myarrlist = new ArrayList<Integer>();
int sum;
for(int i = 0; i < 10; i++) {
myarrlist.add(i);
}
|
Change the following Go code into Java without altering its purpose. | start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
}
| LinkedList<Type> list = new LinkedList<Type>();
for(Type i: list){
System.out.println(i);
}
|
Convert this Go block to Java, preserving its control flow and logic. | start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
}
| LinkedList<Type> list = new LinkedList<Type>();
for(Type i: list){
System.out.println(i);
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package raster
import (
"fmt"
"io"
"os"
)
func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
if _, err = fmt.Fprintln(w, "P6"); err != nil {
return
}
for _, c := range b.Comments {
if _, err = fmt.Fprintln(w, c); err != nil {
return
}
}
_, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
if err != nil {
return
}
b3 := make([]byte, 3*len(b.px))
n1 := 0
for _, px := range b.px {
b3[n1] = px.R
b3[n1+1] = px.G
b3[n1+2] = px.B
n1 += 3
}
if _, err = w.Write(b3); err != nil {
return
}
return
}
func (b *Bitmap) WritePpmFile(fn string) (err error) {
var f *os.File
if f, err = os.Create(fn); err != nil {
return
}
if err = b.WritePpmTo(f); err != nil {
return
}
return f.Close()
}
| import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class PPMWriter {
public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {
file.delete();
try (var os = new FileOutputStream(file, true);
var bw = new BufferedOutputStream(os)) {
var header = String.format("P6\n%d %d\n255\n",
bitmap.getWidth(), bitmap.getHeight());
bw.write(header.getBytes(StandardCharsets.US_ASCII));
for (var y = 0; y < bitmap.getHeight(); y++) {
for (var x = 0; x < bitmap.getWidth(); x++) {
var pixel = bitmap.getPixel(x, y);
bw.write(pixel.getRed());
bw.write(pixel.getGreen());
bw.write(pixel.getBlue());
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import "os"
func main() {
os.Remove("input.txt")
os.Remove("/input.txt")
os.Remove("docs")
os.Remove("/docs")
os.RemoveAll("docs")
os.RemoveAll("/docs")
}
| import java.io.File;
public class FileDeleteTest {
public static boolean deleteFile(String filename) {
boolean exists = new File(filename).delete();
return exists;
}
public static void test(String type, String filename) {
System.out.println("The following " + type + " called " + filename +
(deleteFile(filename) ? " was deleted." : " could not be deleted.")
);
}
public static void main(String args[]) {
test("file", "input.txt");
test("file", File.seperator + "input.txt");
test("directory", "docs");
test("directory", File.seperator + "docs" + File.seperator);
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package ddate
import (
"strconv"
"strings"
"time"
)
const (
DefaultFmt = "Pungenday, Discord 5, 3131 YOLD"
OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131
Celebrate Mojoday`
)
const (
protoLongSeason = "Discord"
protoShortSeason = "Dsc"
protoLongDay = "Pungenday"
protoShortDay = "PD"
protoOrdDay = "5"
protoCardDay = "5th"
protoHolyday = "Mojoday"
protoYear = "3131"
)
var (
longDay = []string{"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"}
shortDay = []string{"SM", "BT", "PD", "PP", "SO"}
longSeason = []string{
"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}
shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"}
holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"},
{"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}}
)
type DiscDate struct {
StTibs bool
Dayy int
Year int
}
func New(eris time.Time) DiscDate {
t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),
eris.Second(), eris.Nanosecond(), eris.Location())
bob := int(eris.Sub(t).Hours()) / 24
raw := eris.Year()
hastur := DiscDate{Year: raw + 1166}
if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {
if bob > 59 {
bob--
} else if bob == 59 {
hastur.StTibs = true
return hastur
}
}
hastur.Dayy = bob
return hastur
}
func (dd DiscDate) Format(f string) (r string) {
var st, snarf string
var dateElement bool
f6 := func(proto, wibble string) {
if !dateElement {
snarf = r
dateElement = true
}
if st > "" {
r = ""
} else {
r += wibble
}
f = f[len(proto):]
}
f4 := func(proto, wibble string) {
if dd.StTibs {
st = "St. Tib's Day"
}
f6(proto, wibble)
}
season, day := dd.Dayy/73, dd.Dayy%73
for f > "" {
switch {
case strings.HasPrefix(f, protoLongDay):
f4(protoLongDay, longDay[dd.Dayy%5])
case strings.HasPrefix(f, protoShortDay):
f4(protoShortDay, shortDay[dd.Dayy%5])
case strings.HasPrefix(f, protoCardDay):
funkychickens := "th"
if day/10 != 1 {
switch day % 10 {
case 0:
funkychickens = "st"
case 1:
funkychickens = "nd"
case 2:
funkychickens = "rd"
}
}
f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)
case strings.HasPrefix(f, protoOrdDay):
f4(protoOrdDay, strconv.Itoa(day+1))
case strings.HasPrefix(f, protoLongSeason):
f6(protoLongSeason, longSeason[season])
case strings.HasPrefix(f, protoShortSeason):
f6(protoShortSeason, shortSeason[season])
case strings.HasPrefix(f, protoHolyday):
if day == 4 {
r += holyday[season][0]
} else if day == 49 {
r += holyday[season][1]
}
f = f[len(protoHolyday):]
case strings.HasPrefix(f, protoYear):
r += strconv.Itoa(dd.Year)
f = f[4:]
default:
r += f[:1]
f = f[1:]
}
}
if st > "" {
r = snarf + st + r
}
return
}
| import java.util.Calendar;
import java.util.GregorianCalendar;
public class DiscordianDate {
final static String[] seasons = {"Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"};
final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"};
final static String[] apostle = {"Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"};
final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"};
public static String discordianDate(final GregorianCalendar date) {
int y = date.get(Calendar.YEAR);
int yold = y + 1166;
int dayOfYear = date.get(Calendar.DAY_OF_YEAR);
if (date.isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold;
else if (dayOfYear > 60)
dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
if (seasonDay == 5)
return apostle[dayOfYear / 73] + ", in the YOLD " + yold;
if (seasonDay == 50)
return holiday[dayOfYear / 73] + ", in the YOLD " + yold;
String season = seasons[dayOfYear / 73];
String dayOfWeek = weekday[dayOfYear % 5];
return String.format("%s, day %s of %s in the YOLD %s",
dayOfWeek, seasonDay, season, yold);
}
public static void main(String[] args) {
System.out.println(discordianDate(new GregorianCalendar()));
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176");
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178");
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178");
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178");
test(2010, 0, 5, "Mungday, in the YOLD 3176");
test(2011, 4, 3, "Discoflux, in the YOLD 3177");
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181");
}
private static void test(int y, int m, int d, final String result) {
assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var n int = 3
var moves int = 0
a := make([][]int, n)
for i := range a {
a[i] = make([]int, n)
for j := range a {
a[i][j] = rand.Intn(2)
}
}
b := make([][]int, len(a))
for i := range a {
b[i] = make([]int, len(a[i]))
copy(b[i], a[i])
}
for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {
b = flipCol(b, rand.Intn(n) + 1)
b = flipRow(b, rand.Intn(n) + 1)
}
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
var rc rune
var num int
for {
for{
fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n)
_, err := fmt.Scanf("%c%d", &rc, &num)
if err != nil {
fmt.Println(err)
continue
}
if num < 1 || num > n {
fmt.Println("Wrong command!")
continue
}
break
}
switch rc {
case 'c':
fmt.Printf("Column %v will be flipped\n", num)
flipCol(b, num)
case 'r':
fmt.Printf("Row %v will be flipped\n", num)
flipRow(b, num)
default:
fmt.Println("Wrong command!")
continue
}
moves++
fmt.Println("\nMoves taken: ", moves)
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
if compareSlices(a, b) {
fmt.Printf("Finished. You win with %d moves!\n", moves)
break
}
}
}
func drawBoard (m [][]int) {
fmt.Print(" ")
for i := range m {
fmt.Printf("%d ", i+1)
}
for i := range m {
fmt.Println()
fmt.Printf("%d ", i+1)
for _, val := range m[i] {
fmt.Printf(" %d", val)
}
}
fmt.Print("\n")
}
func flipRow(m [][]int, row int) ([][]int) {
for j := range m {
m[row-1][j] ^= 1
}
return m
}
func flipCol(m [][]int, col int) ([][]int) {
for j := range m {
m[j][col-1] ^= 1
}
return m
}
func compareSlices(m [][]int, n[][]int) bool {
o := true
for i := range m {
for j := range m {
if m[i][j] != n[i][j] { o = false }
}
}
return o
}
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class FlippingBitsGame extends JPanel {
final int maxLevel = 7;
final int minLevel = 3;
private Random rand = new Random();
private int[][] grid, target;
private Rectangle box;
private int n = maxLevel;
private boolean solved = true;
FlippingBitsGame() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
setFont(new Font("SansSerif", Font.PLAIN, 18));
box = new Rectangle(120, 90, 400, 400);
startNewGame();
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (solved) {
startNewGame();
} else {
int x = e.getX();
int y = e.getY();
if (box.contains(x, y))
return;
if (x > box.x && x < box.x + box.width) {
flipCol((x - box.x) / (box.width / n));
} else if (y > box.y && y < box.y + box.height)
flipRow((y - box.y) / (box.height / n));
if (solved(grid, target))
solved = true;
printGrid(solved ? "Solved!" : "The board", grid);
}
repaint();
}
});
}
void startNewGame() {
if (solved) {
n = (n == maxLevel) ? minLevel : n + 1;
grid = new int[n][n];
target = new int[n][n];
do {
shuffle();
for (int i = 0; i < n; i++)
target[i] = Arrays.copyOf(grid[i], n);
shuffle();
} while (solved(grid, target));
solved = false;
printGrid("The target", target);
printGrid("The board", grid);
}
}
void printGrid(String msg, int[][] g) {
System.out.println(msg);
for (int[] row : g)
System.out.println(Arrays.toString(row));
System.out.println();
}
boolean solved(int[][] a, int[][] b) {
for (int i = 0; i < n; i++)
if (!Arrays.equals(a[i], b[i]))
return false;
return true;
}
void shuffle() {
for (int i = 0; i < n * n; i++) {
if (rand.nextBoolean())
flipRow(rand.nextInt(n));
else
flipCol(rand.nextInt(n));
}
}
void flipRow(int r) {
for (int c = 0; c < n; c++) {
grid[r][c] ^= 1;
}
}
void flipCol(int c) {
for (int[] row : grid) {
row[c] ^= 1;
}
}
void drawGrid(Graphics2D g) {
g.setColor(getForeground());
if (solved)
g.drawString("Solved! Click here to play again.", 180, 600);
else
g.drawString("Click next to a row or a column to flip.", 170, 600);
int size = box.width / n;
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) {
g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(getBackground());
g.drawRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Flipping Bits Game");
f.setResizable(false);
f.add(new FlippingBitsGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var n int = 3
var moves int = 0
a := make([][]int, n)
for i := range a {
a[i] = make([]int, n)
for j := range a {
a[i][j] = rand.Intn(2)
}
}
b := make([][]int, len(a))
for i := range a {
b[i] = make([]int, len(a[i]))
copy(b[i], a[i])
}
for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {
b = flipCol(b, rand.Intn(n) + 1)
b = flipRow(b, rand.Intn(n) + 1)
}
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
var rc rune
var num int
for {
for{
fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n)
_, err := fmt.Scanf("%c%d", &rc, &num)
if err != nil {
fmt.Println(err)
continue
}
if num < 1 || num > n {
fmt.Println("Wrong command!")
continue
}
break
}
switch rc {
case 'c':
fmt.Printf("Column %v will be flipped\n", num)
flipCol(b, num)
case 'r':
fmt.Printf("Row %v will be flipped\n", num)
flipRow(b, num)
default:
fmt.Println("Wrong command!")
continue
}
moves++
fmt.Println("\nMoves taken: ", moves)
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
if compareSlices(a, b) {
fmt.Printf("Finished. You win with %d moves!\n", moves)
break
}
}
}
func drawBoard (m [][]int) {
fmt.Print(" ")
for i := range m {
fmt.Printf("%d ", i+1)
}
for i := range m {
fmt.Println()
fmt.Printf("%d ", i+1)
for _, val := range m[i] {
fmt.Printf(" %d", val)
}
}
fmt.Print("\n")
}
func flipRow(m [][]int, row int) ([][]int) {
for j := range m {
m[row-1][j] ^= 1
}
return m
}
func flipCol(m [][]int, col int) ([][]int) {
for j := range m {
m[j][col-1] ^= 1
}
return m
}
func compareSlices(m [][]int, n[][]int) bool {
o := true
for i := range m {
for j := range m {
if m[i][j] != n[i][j] { o = false }
}
}
return o
}
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class FlippingBitsGame extends JPanel {
final int maxLevel = 7;
final int minLevel = 3;
private Random rand = new Random();
private int[][] grid, target;
private Rectangle box;
private int n = maxLevel;
private boolean solved = true;
FlippingBitsGame() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
setFont(new Font("SansSerif", Font.PLAIN, 18));
box = new Rectangle(120, 90, 400, 400);
startNewGame();
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (solved) {
startNewGame();
} else {
int x = e.getX();
int y = e.getY();
if (box.contains(x, y))
return;
if (x > box.x && x < box.x + box.width) {
flipCol((x - box.x) / (box.width / n));
} else if (y > box.y && y < box.y + box.height)
flipRow((y - box.y) / (box.height / n));
if (solved(grid, target))
solved = true;
printGrid(solved ? "Solved!" : "The board", grid);
}
repaint();
}
});
}
void startNewGame() {
if (solved) {
n = (n == maxLevel) ? minLevel : n + 1;
grid = new int[n][n];
target = new int[n][n];
do {
shuffle();
for (int i = 0; i < n; i++)
target[i] = Arrays.copyOf(grid[i], n);
shuffle();
} while (solved(grid, target));
solved = false;
printGrid("The target", target);
printGrid("The board", grid);
}
}
void printGrid(String msg, int[][] g) {
System.out.println(msg);
for (int[] row : g)
System.out.println(Arrays.toString(row));
System.out.println();
}
boolean solved(int[][] a, int[][] b) {
for (int i = 0; i < n; i++)
if (!Arrays.equals(a[i], b[i]))
return false;
return true;
}
void shuffle() {
for (int i = 0; i < n * n; i++) {
if (rand.nextBoolean())
flipRow(rand.nextInt(n));
else
flipCol(rand.nextInt(n));
}
}
void flipRow(int r) {
for (int c = 0; c < n; c++) {
grid[r][c] ^= 1;
}
}
void flipCol(int c) {
for (int[] row : grid) {
row[c] ^= 1;
}
}
void drawGrid(Graphics2D g) {
g.setColor(getForeground());
if (solved)
g.drawString("Solved! Click here to play again.", 180, 600);
else
g.drawString("Click next to a row or a column to flip.", 170, 600);
int size = box.width / n;
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) {
g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(getBackground());
g.drawRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Flipping Bits Game");
f.setResizable(false);
f.add(new FlippingBitsGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.Denom())
f.Sub(h, f.SetInt(&w))
y, _ := f.Float64()
d := fmt.Sprintf("%.3f", y)
fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n",
i, &w, d[1:], d[2] == '0' || d[2] == '9')
}
}
| import java.math.*;
public class Hickerson {
final static String LN2 = "0.693147180559945309417232121458";
public static void main(String[] args) {
for (int n = 1; n <= 17; n++)
System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
}
static boolean almostInteger(int n) {
BigDecimal a = new BigDecimal(LN2);
a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));
long f = n;
while (--n > 1)
f *= n;
BigDecimal b = new BigDecimal(f);
b = b.divide(a, MathContext.DECIMAL128);
BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);
return c.toString().matches("0|9");
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.Denom())
f.Sub(h, f.SetInt(&w))
y, _ := f.Float64()
d := fmt.Sprintf("%.3f", y)
fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n",
i, &w, d[1:], d[2] == '0' || d[2] == '9')
}
}
| import java.math.*;
public class Hickerson {
final static String LN2 = "0.693147180559945309417232121458";
public static void main(String[] args) {
for (int n = 1; n <= 17; n++)
System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
}
static boolean almostInteger(int n) {
BigDecimal a = new BigDecimal(LN2);
a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));
long f = n;
while (--n > 1)
f *= n;
BigDecimal b = new BigDecimal(f);
b = b.divide(a, MathContext.DECIMAL128);
BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);
return c.toString().matches("0|9");
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.Denom())
f.Sub(h, f.SetInt(&w))
y, _ := f.Float64()
d := fmt.Sprintf("%.3f", y)
fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n",
i, &w, d[1:], d[2] == '0' || d[2] == '9')
}
}
| import java.math.*;
public class Hickerson {
final static String LN2 = "0.693147180559945309417232121458";
public static void main(String[] args) {
for (int n = 1; n <= 17; n++)
System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
}
static boolean almostInteger(int n) {
BigDecimal a = new BigDecimal(LN2);
a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));
long f = n;
while (--n > 1)
f *= n;
BigDecimal b = new BigDecimal(f);
b = b.divide(a, MathContext.DECIMAL128);
BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);
return c.toString().matches("0|9");
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"fmt"
"math"
"math/rand"
)
const nmax = 20
func main() {
fmt.Println(" N average analytical (error)")
fmt.Println("=== ========= ============ =========")
for n := 1; n <= nmax; n++ {
a := avg(n)
b := ana(n)
fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n",
n, a, b, math.Abs(a-b)/b*100)
}
}
func avg(n int) float64 {
const tests = 1e4
sum := 0
for t := 0; t < tests; t++ {
var v [nmax]bool
for x := 0; !v[x]; x = rand.Intn(n) {
v[x] = true
sum++
}
}
return float64(sum) / tests
}
func ana(n int) float64 {
nn := float64(n)
term := 1.
sum := 1.
for i := nn - 1; i >= 1; i-- {
term *= i / nn
sum += term
}
return sum
}
| import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"math"
"math/rand"
)
const nmax = 20
func main() {
fmt.Println(" N average analytical (error)")
fmt.Println("=== ========= ============ =========")
for n := 1; n <= nmax; n++ {
a := avg(n)
b := ana(n)
fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n",
n, a, b, math.Abs(a-b)/b*100)
}
}
func avg(n int) float64 {
const tests = 1e4
sum := 0
for t := 0; t < tests; t++ {
var v [nmax]bool
for x := 0; !v[x]; x = rand.Intn(n) {
v[x] = true
sum++
}
}
return float64(sum) / tests
}
func ana(n int) float64 {
nn := float64(n)
term := 1.
sum := 1.
for i := nn - 1; i >= 1; i-- {
term *= i / nn
sum += term
}
return sum
}
| import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import (
"fmt"
)
func main() {
str := "Mary had a %s lamb"
txt := "little"
out := fmt.Sprintf(str, txt)
fmt.Println(out)
}
| String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little);
System.out.println(replaced);
System.out.printf("Mary had a %s lamb.", little);
String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"container/heap"
"sort"
)
type IntPile []int
func (self IntPile) Top() int { return self[len(self)-1] }
func (self *IntPile) Pop() int {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
type IntPilesHeap []IntPile
func (self IntPilesHeap) Len() int { return len(self) }
func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }
func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }
func (self *IntPilesHeap) Pop() interface{} {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
func patience_sort (n []int) {
var piles []IntPile
for _, x := range n {
j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })
if j != len(piles) {
piles[j] = append(piles[j], x)
} else {
piles = append(piles, IntPile{ x })
}
}
hp := IntPilesHeap(piles)
heap.Init(&hp)
for i, _ := range n {
smallPile := heap.Pop(&hp).(IntPile)
n[i] = smallPile.Pop()
if len(smallPile) != 0 {
heap.Push(&hp, smallPile)
}
}
if len(hp) != 0 {
panic("something went wrong")
}
}
func main() {
a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}
patience_sort(a)
fmt.Println(a)
}
| import java.util.*;
public class PatienceSort {
public static <E extends Comparable<? super E>> void sort (E[] n) {
List<Pile<E>> piles = new ArrayList<Pile<E>>();
for (E x : n) {
Pile<E> newPile = new Pile<E>();
newPile.push(x);
int i = Collections.binarySearch(piles, newPile);
if (i < 0) i = ~i;
if (i != piles.size())
piles.get(i).push(x);
else
piles.add(newPile);
}
PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);
for (int c = 0; c < n.length; c++) {
Pile<E> smallPile = heap.poll();
n[c] = smallPile.pop();
if (!smallPile.isEmpty())
heap.offer(smallPile);
}
assert(heap.isEmpty());
}
private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {
public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }
}
public static void main(String[] args) {
Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};
sort(a);
System.out.println(Arrays.toString(a));
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
const bases = "ACGT"
func mutate(dna string, w [3]int) string {
le := len(dna)
p := rand.Intn(le)
r := rand.Intn(300)
bytes := []byte(dna)
switch {
case r < w[0]:
base := bases[rand.Intn(4)]
fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base)
bytes[p] = base
case r < w[0]+w[1]:
fmt.Printf(" Delete @%3d %q\n", p, bytes[p])
copy(bytes[p:], bytes[p+1:])
bytes = bytes[0 : le-1]
default:
base := bases[rand.Intn(4)]
bytes = append(bytes, 0)
copy(bytes[p+1:], bytes[p:])
fmt.Printf(" Insert @%3d %q\n", p, base)
bytes[p] = base
}
return string(bytes)
}
func generate(le int) string {
bytes := make([]byte, le)
for i := 0; i < le; i++ {
bytes[i] = bases[rand.Intn(4)]
}
return string(bytes)
}
func prettyPrint(dna string, rowLen int) {
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += rowLen {
k := i + rowLen
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======\n")
}
func wstring(w [3]int) string {
return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2])
}
func main() {
rand.Seed(time.Now().UnixNano())
dna := generate(250)
prettyPrint(dna, 50)
muts := 10
w := [3]int{100, 100, 100}
fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w))
fmt.Printf("MUTATIONS (%d):\n", muts)
for i := 0; i < muts; i++ {
dna = mutate(dna, w)
}
fmt.Println()
prettyPrint(dna, 50)
}
| import java.util.Arrays;
import java.util.Random;
public class SequenceMutation {
public static void main(String[] args) {
SequenceMutation sm = new SequenceMutation();
sm.setWeight(OP_CHANGE, 3);
String sequence = sm.generateSequence(250);
System.out.println("Initial sequence:");
printSequence(sequence);
int count = 10;
for (int i = 0; i < count; ++i)
sequence = sm.mutateSequence(sequence);
System.out.println("After " + count + " mutations:");
printSequence(sequence);
}
public SequenceMutation() {
totalWeight_ = OP_COUNT;
Arrays.fill(operationWeight_, 1);
}
public String generateSequence(int length) {
char[] ch = new char[length];
for (int i = 0; i < length; ++i)
ch[i] = getRandomBase();
return new String(ch);
}
public void setWeight(int operation, int weight) {
totalWeight_ -= operationWeight_[operation];
operationWeight_[operation] = weight;
totalWeight_ += weight;
}
public String mutateSequence(String sequence) {
char[] ch = sequence.toCharArray();
int pos = random_.nextInt(ch.length);
int operation = getRandomOperation();
if (operation == OP_CHANGE) {
char b = getRandomBase();
System.out.println("Change base at position " + pos + " from "
+ ch[pos] + " to " + b);
ch[pos] = b;
} else if (operation == OP_ERASE) {
System.out.println("Erase base " + ch[pos] + " at position " + pos);
char[] newCh = new char[ch.length - 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);
ch = newCh;
} else if (operation == OP_INSERT) {
char b = getRandomBase();
System.out.println("Insert base " + b + " at position " + pos);
char[] newCh = new char[ch.length + 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);
newCh[pos] = b;
ch = newCh;
}
return new String(ch);
}
public static void printSequence(String sequence) {
int[] count = new int[BASES.length];
for (int i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
System.out.println();
System.out.printf("%3d: ", i);
}
char ch = sequence.charAt(i);
System.out.print(ch);
for (int j = 0; j < BASES.length; ++j) {
if (BASES[j] == ch) {
++count[j];
break;
}
}
}
System.out.println();
System.out.println("Base counts:");
int total = 0;
for (int j = 0; j < BASES.length; ++j) {
total += count[j];
System.out.print(BASES[j] + ": " + count[j] + ", ");
}
System.out.println("Total: " + total);
}
private char getRandomBase() {
return BASES[random_.nextInt(BASES.length)];
}
private int getRandomOperation() {
int n = random_.nextInt(totalWeight_), op = 0;
for (int weight = 0; op < OP_COUNT; ++op) {
weight += operationWeight_[op];
if (n < weight)
break;
}
return op;
}
private final Random random_ = new Random();
private int[] operationWeight_ = new int[OP_COUNT];
private int totalWeight_ = 0;
private static final int OP_CHANGE = 0;
private static final int OP_ERASE = 1;
private static final int OP_INSERT = 2;
private static final int OP_COUNT = 3;
private static final char[] BASES = {'A', 'C', 'G', 'T'};
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
const bases = "ACGT"
func mutate(dna string, w [3]int) string {
le := len(dna)
p := rand.Intn(le)
r := rand.Intn(300)
bytes := []byte(dna)
switch {
case r < w[0]:
base := bases[rand.Intn(4)]
fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base)
bytes[p] = base
case r < w[0]+w[1]:
fmt.Printf(" Delete @%3d %q\n", p, bytes[p])
copy(bytes[p:], bytes[p+1:])
bytes = bytes[0 : le-1]
default:
base := bases[rand.Intn(4)]
bytes = append(bytes, 0)
copy(bytes[p+1:], bytes[p:])
fmt.Printf(" Insert @%3d %q\n", p, base)
bytes[p] = base
}
return string(bytes)
}
func generate(le int) string {
bytes := make([]byte, le)
for i := 0; i < le; i++ {
bytes[i] = bases[rand.Intn(4)]
}
return string(bytes)
}
func prettyPrint(dna string, rowLen int) {
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += rowLen {
k := i + rowLen
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======\n")
}
func wstring(w [3]int) string {
return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2])
}
func main() {
rand.Seed(time.Now().UnixNano())
dna := generate(250)
prettyPrint(dna, 50)
muts := 10
w := [3]int{100, 100, 100}
fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w))
fmt.Printf("MUTATIONS (%d):\n", muts)
for i := 0; i < muts; i++ {
dna = mutate(dna, w)
}
fmt.Println()
prettyPrint(dna, 50)
}
| import java.util.Arrays;
import java.util.Random;
public class SequenceMutation {
public static void main(String[] args) {
SequenceMutation sm = new SequenceMutation();
sm.setWeight(OP_CHANGE, 3);
String sequence = sm.generateSequence(250);
System.out.println("Initial sequence:");
printSequence(sequence);
int count = 10;
for (int i = 0; i < count; ++i)
sequence = sm.mutateSequence(sequence);
System.out.println("After " + count + " mutations:");
printSequence(sequence);
}
public SequenceMutation() {
totalWeight_ = OP_COUNT;
Arrays.fill(operationWeight_, 1);
}
public String generateSequence(int length) {
char[] ch = new char[length];
for (int i = 0; i < length; ++i)
ch[i] = getRandomBase();
return new String(ch);
}
public void setWeight(int operation, int weight) {
totalWeight_ -= operationWeight_[operation];
operationWeight_[operation] = weight;
totalWeight_ += weight;
}
public String mutateSequence(String sequence) {
char[] ch = sequence.toCharArray();
int pos = random_.nextInt(ch.length);
int operation = getRandomOperation();
if (operation == OP_CHANGE) {
char b = getRandomBase();
System.out.println("Change base at position " + pos + " from "
+ ch[pos] + " to " + b);
ch[pos] = b;
} else if (operation == OP_ERASE) {
System.out.println("Erase base " + ch[pos] + " at position " + pos);
char[] newCh = new char[ch.length - 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);
ch = newCh;
} else if (operation == OP_INSERT) {
char b = getRandomBase();
System.out.println("Insert base " + b + " at position " + pos);
char[] newCh = new char[ch.length + 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);
newCh[pos] = b;
ch = newCh;
}
return new String(ch);
}
public static void printSequence(String sequence) {
int[] count = new int[BASES.length];
for (int i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
System.out.println();
System.out.printf("%3d: ", i);
}
char ch = sequence.charAt(i);
System.out.print(ch);
for (int j = 0; j < BASES.length; ++j) {
if (BASES[j] == ch) {
++count[j];
break;
}
}
}
System.out.println();
System.out.println("Base counts:");
int total = 0;
for (int j = 0; j < BASES.length; ++j) {
total += count[j];
System.out.print(BASES[j] + ": " + count[j] + ", ");
}
System.out.println("Total: " + total);
}
private char getRandomBase() {
return BASES[random_.nextInt(BASES.length)];
}
private int getRandomOperation() {
int n = random_.nextInt(totalWeight_), op = 0;
for (int weight = 0; op < OP_COUNT; ++op) {
weight += operationWeight_[op];
if (n < weight)
break;
}
return op;
}
private final Random random_ = new Random();
private int[] operationWeight_ = new int[OP_COUNT];
private int totalWeight_ = 0;
private static final int OP_CHANGE = 0;
private static final int OP_ERASE = 1;
private static final int OP_INSERT = 2;
private static final int OP_COUNT = 3;
private static final char[] BASES = {'A', 'C', 'G', 'T'};
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The first 100 tau numbers are:")
count := 0
i := 1
for count < 100 {
tf := countDivisors(i)
if i%tf == 0 {
fmt.Printf("%4d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
i++
}
}
| public class Tau {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("The first %d tau numbers are:%n", limit);
long count = 0;
for (long n = 1; count < limit; ++n) {
if (n % divisorCount(n) == 0) {
System.out.printf("%6d", n);
++count;
if (count % 10 == 0) {
System.out.println();
}
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
}
| import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j<y){
result[i][j] = a[i+1][j];
}else if(i<x && j>=y){
result[i][j] = a[i][j+1];
}else{
result[i][j] = a[i+1][j+1];
}
}
return result;
}
public static double det(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
int sign = 1;
double sum = 0;
for(int i=0;i<a.length;i++){
sum += sign * a[0][i] * det(minor(a,0,i));
sign *= -1;
}
return sum;
}
}
public static double perm(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
double sum = 0;
for(int i=0;i<a.length;i++){
sum += a[0][i] * perm(minor(a,0,i));
}
return sum;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
double[][] a = new double[size][size];
for(int i=0;i<size;i++) for(int j=0;j<size;j++){
a[i][j] = sc.nextDouble();
}
sc.close();
System.out.println("Determinant: "+det(a));
System.out.println("Permanent: "+perm(a));
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
}
| import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j<y){
result[i][j] = a[i+1][j];
}else if(i<x && j>=y){
result[i][j] = a[i][j+1];
}else{
result[i][j] = a[i+1][j+1];
}
}
return result;
}
public static double det(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
int sign = 1;
double sum = 0;
for(int i=0;i<a.length;i++){
sum += sign * a[0][i] * det(minor(a,0,i));
sign *= -1;
}
return sum;
}
}
public static double perm(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
double sum = 0;
for(int i=0;i<a.length;i++){
sum += a[0][i] * perm(minor(a,0,i));
}
return sum;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
double[][] a = new double[size][size];
for(int i=0;i<size;i++) for(int j=0;j<size;j++){
a[i][j] = sc.nextDouble();
}
sc.close();
System.out.println("Determinant: "+det(a));
System.out.println("Permanent: "+perm(a));
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
}
| import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j<y){
result[i][j] = a[i+1][j];
}else if(i<x && j>=y){
result[i][j] = a[i][j+1];
}else{
result[i][j] = a[i+1][j+1];
}
}
return result;
}
public static double det(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
int sign = 1;
double sum = 0;
for(int i=0;i<a.length;i++){
sum += sign * a[0][i] * det(minor(a,0,i));
sign *= -1;
}
return sum;
}
}
public static double perm(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
double sum = 0;
for(int i=0;i<a.length;i++){
sum += a[0][i] * perm(minor(a,0,i));
}
return sum;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
double[][] a = new double[size][size];
for(int i=0;i<size;i++) for(int j=0;j<size;j++){
a[i][j] = sc.nextDouble();
}
sc.close();
System.out.println("Determinant: "+det(a));
System.out.println("Permanent: "+perm(a));
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/big"
"time"
)
var p []*big.Int
var pd []int
func partDiffDiff(n int) int {
if n&1 == 1 {
return (n + 1) / 2
}
return n + 1
}
func partDiff(n int) int {
if n < 2 {
return 1
}
pd[n] = pd[n-1] + partDiffDiff(n-1)
return pd[n]
}
func partitionsP(n int) {
if n < 2 {
return
}
psum := new(big.Int)
for i := 1; i <= n; i++ {
pdi := partDiff(i)
if pdi > n {
break
}
sign := int64(-1)
if (i-1)%4 < 2 {
sign = 1
}
t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))
psum.Add(psum, t)
}
p[n] = psum
}
func main() {
start := time.Now()
const N = 6666
p = make([]*big.Int, N+1)
pd = make([]int, N+1)
p[0], pd[0] = big.NewInt(1), 1
p[1], pd[1] = big.NewInt(1), 1
for n := 2; n <= N; n++ {
partitionsP(n)
}
fmt.Printf("p[%d)] = %d\n", N, p[N])
fmt.Printf("Took %s\n", time.Since(start))
}
| import java.math.BigInteger;
public class PartitionFunction {
public static void main(String[] args) {
long start = System.currentTimeMillis();
BigInteger result = partitions(6666);
long end = System.currentTimeMillis();
System.out.println("P(6666) = " + result);
System.out.printf("elapsed time: %d milliseconds\n", end - start);
}
private static BigInteger partitions(int n) {
BigInteger[] p = new BigInteger[n + 1];
p[0] = BigInteger.ONE;
for (int i = 1; i <= n; ++i) {
p[i] = BigInteger.ZERO;
for (int k = 1; ; ++k) {
int j = (k * (3 * k - 1))/2;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
j += k;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
}
}
return p[n];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.