Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this Go function in Java with identical behavior. | package main
import (
"errors"
"fmt"
"unicode"
)
var code = []byte("01230127022455012623017202")
func soundex(s string) (string, error) {
var sx [4]byte
var sxi int
var cx, lastCode byte
for i, c := range s {
switch {
case !unicode.IsLetter(c):
if c < ' ' || c == 127 {
return "", errors.New("ASCII control characters disallowed")
}
if i == 0 {
return "", errors.New("initial character must be a letter")
}
lastCode = '0'
continue
case c >= 'A' && c <= 'Z':
cx = byte(c - 'A')
case c >= 'a' && c <= 'z':
cx = byte(c - 'a')
default:
return "", errors.New("non-ASCII letters unsupported")
}
if i == 0 {
sx[0] = cx + 'A'
sxi = 1
continue
}
switch x := code[cx]; x {
case '7', lastCode:
case '0':
lastCode = '0'
default:
sx[sxi] = x
if sxi == 3 {
return string(sx[:]), nil
}
sxi++
lastCode = x
}
}
if sxi == 0 {
return "", errors.New("no letters present")
}
for ; sxi < 4; sxi++ {
sx[sxi] = '0'
}
return string(sx[:]), nil
}
func main() {
for _, s := range []string{
"Robert",
"Rupert",
"Rubin",
"ashcroft",
"ashcraft",
"moses",
"O'Mally",
"d jay",
"R2-D2",
"12p2",
"naïve",
"",
"bump\t",
} {
if x, err := soundex(s); err == nil {
fmt.Println("soundex", s, "=", x)
} else {
fmt.Printf("\"%s\" fail. %s\n", s, err)
}
}
}
| public static void main(String[] args){
System.out.println(soundex("Soundex"));
System.out.println(soundex("Example"));
System.out.println(soundex("Sownteks"));
System.out.println(soundex("Ekzampul"));
}
private static String getCode(char c){
switch(c){
case 'B': case 'F': case 'P': case 'V':
return "1";
case 'C': case 'G': case 'J': case 'K':
case 'Q': case 'S': case 'X': case 'Z':
return "2";
case 'D': case 'T':
return "3";
case 'L':
return "4";
case 'M': case 'N':
return "5";
case 'R':
return "6";
default:
return "";
}
}
public static String soundex(String s){
String code, previous, soundex;
code = s.toUpperCase().charAt(0) + "";
previous = getCode(s.toUpperCase().charAt(0));
for(int i = 1;i < s.length();i++){
String current = getCode(s.toUpperCase().charAt(i));
if(current.length() > 0 && !current.equals(previous)){
code = code + current;
}
previous = current;
}
soundex = (code + "0000").substring(0, 4);
return soundex;
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import (
"fmt"
"log"
"os"
"strconv"
)
type tree uint64
var (
list []tree
offset = [32]uint{1: 1}
)
func add(t tree) {
list = append(list, 1|t<<1)
}
func show(t tree, l uint) {
for ; l > 0; t >>= 1 {
l--
var paren byte
if (t & 1) != 0 {
paren = '('
} else {
paren = ')'
}
fmt.Printf("%c", paren)
}
}
func listTrees(n uint) {
for i := offset[n]; i < offset[n+1]; i++ {
show(list[i], n*2)
fmt.Println()
}
}
func assemble(n uint, t tree, sl, pos, rem uint) {
if rem == 0 {
add(t)
return
}
if sl > rem {
sl = rem
pos = offset[sl]
} else if pos >= offset[sl+1] {
sl--
if sl == 0 {
return
}
pos = offset[sl]
}
assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)
assemble(n, t, sl, pos+1, rem)
}
func mktrees(n uint) {
if offset[n+1] > 0 {
return
}
if n > 0 {
mktrees(n - 1)
}
assemble(n, 0, n-1, offset[n-1], n-1)
offset[n+1] = uint(len(list))
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There must be exactly 1 command line argument")
}
n, err := strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal("Argument is not a valid number")
}
if n <= 0 || n > 19 {
n = 5
}
add(0)
mktrees(uint(n))
fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n])
listTrees(uint(n))
}
| import java.util.ArrayList;
import java.util.List;
public class ListRootedTrees {
private static final List<Long> TREE_LIST = new ArrayList<>();
private static final List<Integer> OFFSET = new ArrayList<>();
static {
for (int i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.add(1);
} else {
OFFSET.add(0);
}
}
}
private static void append(long t) {
TREE_LIST.add(1 | (t << 1));
}
private static void show(long t, int l) {
while (l-- > 0) {
if (t % 2 == 1) {
System.out.print('(');
} else {
System.out.print(')');
}
t = t >> 1;
}
}
private static void listTrees(int n) {
for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {
show(TREE_LIST.get(i), n * 2);
System.out.println();
}
}
private static void assemble(int n, long t, int sl, int pos, int rem) {
if (rem == 0) {
append(t);
return;
}
var pp = pos;
var ss = sl;
if (sl > rem) {
ss = rem;
pp = OFFSET.get(ss);
} else if (pp >= OFFSET.get(ss + 1)) {
ss--;
if (ss == 0) {
return;
}
pp = OFFSET.get(ss);
}
assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);
assemble(n, t, ss, pp + 1, rem);
}
private static void makeTrees(int n) {
if (OFFSET.get(n + 1) != 0) {
return;
}
if (n > 0) {
makeTrees(n - 1);
}
assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);
OFFSET.set(n + 1, TREE_LIST.size());
}
private static void test(int n) {
if (n < 1 || n > 12) {
throw new IllegalArgumentException("Argument must be between 1 and 12");
}
append(0);
makeTrees(n);
System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n));
listTrees(n);
}
public static void main(String[] args) {
test(5);
}
}
|
Write a version of this Go function in Java with identical behavior. |
package example
var (
X, Y, Z int
)
func XP() {
}
func nonXP() {}
var MEMEME int
|
public class Doc{
private String field;
public int method(long num) throws BadException{
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"math"
)
type circle struct {
x, y, r float64
}
func main() {
c1 := circle{0, 0, 1}
c2 := circle{4, 0, 1}
c3 := circle{2, 4, 2}
fmt.Println(ap(c1, c2, c3, true))
fmt.Println(ap(c1, c2, c3, false))
}
func ap(c1, c2, c3 circle, s bool) circle {
x1sq := c1.x * c1.x
y1sq := c1.y * c1.y
r1sq := c1.r * c1.r
x2sq := c2.x * c2.x
y2sq := c2.y * c2.y
r2sq := c2.r * c2.r
x3sq := c3.x * c3.x
y3sq := c3.y * c3.y
r3sq := c3.r * c3.r
v11 := 2 * (c2.x - c1.x)
v12 := 2 * (c2.y - c1.y)
v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq
v14 := 2 * (c2.r - c1.r)
v21 := 2 * (c3.x - c2.x)
v22 := 2 * (c3.y - c2.y)
v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq
v24 := 2 * (c3.r - c2.r)
if s {
v14 = -v14
v24 = -v24
}
w12 := v12 / v11
w13 := v13 / v11
w14 := v14 / v11
w22 := v22/v21 - w12
w23 := v23/v21 - w13
w24 := v24/v21 - w14
p := -w23 / w22
q := w24 / w22
m := -w12*p - w13
n := w14 - w12*q
a := n*n + q*q - 1
b := m*n - n*c1.x + p*q - q*c1.y
if s {
b -= c1.r
} else {
b += c1.r
}
b *= 2
c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq
d := b*b - 4*a*c
rs := (-b - math.Sqrt(d)) / (2 * a)
return circle{m + n*rs, p + q*rs, rs}
}
| public class Circle
{
public double[] center;
public double radius;
public Circle(double[] center, double radius)
{
this.center = center;
this.radius = radius;
}
public String toString()
{
return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1],
radius);
}
}
public class ApolloniusSolver
{
public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,
int s2, int s3)
{
float x1 = c1.center[0];
float y1 = c1.center[1];
float r1 = c1.radius;
float x2 = c2.center[0];
float y2 = c2.center[1];
float r2 = c2.radius;
float x3 = c3.center[0];
float y3 = c3.center[1];
float r3 = c3.radius;
float v11 = 2*x2 - 2*x1;
float v12 = 2*y2 - 2*y1;
float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;
float v14 = 2*s2*r2 - 2*s1*r1;
float v21 = 2*x3 - 2*x2;
float v22 = 2*y3 - 2*y2;
float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;
float v24 = 2*s3*r3 - 2*s2*r2;
float w12 = v12/v11;
float w13 = v13/v11;
float w14 = v14/v11;
float w22 = v22/v21-w12;
float w23 = v23/v21-w13;
float w24 = v24/v21-w14;
float P = -w23/w22;
float Q = w24/w22;
float M = -w12*P-w13;
float N = w14 - w12*Q;
float a = N*N + Q*Q - 1;
float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;
float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;
float D = b*b-4*a*c;
float rs = (-b-Math.sqrt(D))/(2*a);
float xs = M + N * rs;
float ys = P + Q * rs;
return new Circle(new double[]{xs,ys}, rs);
}
public static void main(final String[] args)
{
Circle c1 = new Circle(new double[]{0,0}, 1);
Circle c2 = new Circle(new double[]{4,0}, 1);
Circle c3 = new Circle(new double[]{2,4}, 2);
System.out.println(solveApollonius(c1,c2,c3,1,1,1));
System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"strings"
)
func lcs(a []string) string {
le := len(a)
if le == 0 {
return ""
}
if le == 1 {
return a[0]
}
le0 := len(a[0])
minLen := le0
for i := 1; i < le; i++ {
if len(a[i]) < minLen {
minLen = len(a[i])
}
}
if minLen == 0 {
return ""
}
res := ""
a1 := a[1:]
for i := 1; i <= minLen; i++ {
suffix := a[0][le0-i:]
for _, e := range a1 {
if !strings.HasSuffix(e, suffix) {
return res
}
}
res = suffix
}
return res
}
func main() {
tests := [][]string{
{"baabababc", "baabc", "bbbabc"},
{"baabababc", "baabc", "bbbazc"},
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
{"longest", "common", "suffix"},
{"suffix"},
{""},
}
for _, test := range tests {
fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
}
}
| import java.util.List;
public class App {
private static String lcs(List<String> a) {
var le = a.size();
if (le == 0) {
return "";
}
if (le == 1) {
return a.get(0);
}
var le0 = a.get(0).length();
var minLen = le0;
for (int i = 1; i < le; i++) {
if (a.get(i).length() < minLen) {
minLen = a.get(i).length();
}
}
if (minLen == 0) {
return "";
}
var res = "";
var a1 = a.subList(1, a.size());
for (int i = 1; i < minLen; i++) {
var suffix = a.get(0).substring(le0 - i);
for (String e : a1) {
if (!e.endsWith(suffix)) {
return res;
}
}
res = suffix;
}
return "";
}
public static void main(String[] args) {
var tests = List.of(
List.of("baabababc", "baabc", "bbbabc"),
List.of("baabababc", "baabc", "bbbazc"),
List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"),
List.of("longest", "common", "suffix"),
List.of("suffix"),
List.of("")
);
for (List<String> test : tests) {
System.out.printf("%s -> `%s`\n", test, lcs(test));
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
}
type Server struct {
add chan *conn
rem chan string
msg chan string
stop chan bool
}
func ListenAndServe(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
rwc, err := ln.Accept()
if err != nil {
close(s.stop)
return err
}
log.Println("New connection from", rwc.RemoteAddr())
go newConn(s, rwc).welcome()
}
}
func (s *Server) handleConns() {
conns := make(map[string]*conn)
var dropConn func(string)
writeAll := func(str string) {
log.Printf("Broadcast: %q", str)
for name, c := range conns {
c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))
_, err := c.Write([]byte(str))
if err != nil {
log.Printf("Error writing to %q: %v", name, err)
c.Close()
delete(conns, name)
defer dropConn(name)
}
}
}
dropConn = func(name string) {
if c, ok := conns[name]; ok {
log.Printf("Closing connection with %q from %v",
name, c.RemoteAddr())
c.Close()
delete(conns, name)
} else {
log.Printf("Dropped connection with %q", name)
}
str := fmt.Sprintf("--- %q disconnected ---\n", name)
writeAll(str)
}
defer func() {
writeAll("Server stopping!\n")
for _, c := range conns {
c.Close()
}
}()
for {
select {
case c := <-s.add:
if _, exists := conns[c.name]; exists {
fmt.Fprintf(c, "Name %q is not available\n", c.name)
go c.welcome()
continue
}
str := fmt.Sprintf("+++ %q connected +++\n", c.name)
writeAll(str)
conns[c.name] = c
go c.readloop()
case str := <-s.msg:
writeAll(str)
case name := <-s.rem:
dropConn(name)
case <-s.stop:
return
}
}
}
type conn struct {
*bufio.Reader
net.Conn
server *Server
name string
}
func newConn(s *Server, rwc net.Conn) *conn {
return &conn{
Reader: bufio.NewReader(rwc),
Conn: rwc,
server: s,
}
}
func (c *conn) welcome() {
var err error
for c.name = ""; c.name == ""; {
fmt.Fprint(c, "Enter your name: ")
c.name, err = c.ReadString('\n')
if err != nil {
log.Printf("Reading name from %v: %v", c.RemoteAddr(), err)
c.Close()
return
}
c.name = strings.TrimSpace(c.name)
}
c.server.add <- c
}
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')
if err != nil {
break
}
c.server.msg <- c.name + "> " + msg
}
c.server.rem <- c.name
}
| import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer implements Runnable
{
private int port = 0;
private List<Client> clients = new ArrayList<Client>();
public ChatServer(int port)
{ this.port = port; }
public void run()
{
try
{
ServerSocket ss = new ServerSocket(port);
while (true)
{
Socket s = ss.accept();
new Thread(new Client(s)).start();
}
}
catch (Exception e)
{ e.printStackTrace(); }
}
private synchronized boolean registerClient(Client client)
{
for (Client otherClient : clients)
if (otherClient.clientName.equalsIgnoreCase(client.clientName))
return false;
clients.add(client);
return true;
}
private void deregisterClient(Client client)
{
boolean wasRegistered = false;
synchronized (this)
{ wasRegistered = clients.remove(client); }
if (wasRegistered)
broadcast(client, "--- " + client.clientName + " left ---");
}
private synchronized String getOnlineListCSV()
{
StringBuilder sb = new StringBuilder();
sb.append(clients.size()).append(" user(s) online: ");
for (int i = 0; i < clients.size(); i++)
sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName);
return sb.toString();
}
private void broadcast(Client fromClient, String msg)
{
List<Client> clients = null;
synchronized (this)
{ clients = new ArrayList<Client>(this.clients); }
for (Client client : clients)
{
if (client.equals(fromClient))
continue;
try
{ client.write(msg + "\r\n"); }
catch (Exception e)
{ }
}
}
public class Client implements Runnable
{
private Socket socket = null;
private Writer output = null;
private String clientName = null;
public Client(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
socket.setSendBufferSize(16384);
socket.setTcpNoDelay(true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new OutputStreamWriter(socket.getOutputStream());
write("Please enter your name: ");
String line = null;
while ((line = input.readLine()) != null)
{
if (clientName == null)
{
line = line.trim();
if (line.isEmpty())
{
write("A name is required. Please enter your name: ");
continue;
}
clientName = line;
if (!registerClient(this))
{
clientName = null;
write("Name already registered. Please enter your name: ");
continue;
}
write(getOnlineListCSV() + "\r\n");
broadcast(this, "+++ " + clientName + " arrived +++");
continue;
}
if (line.equalsIgnoreCase("/quit"))
return;
broadcast(this, clientName + "> " + line);
}
}
catch (Exception e)
{ }
finally
{
deregisterClient(this);
output = null;
try
{ socket.close(); }
catch (Exception e)
{ }
socket = null;
}
}
public void write(String msg) throws IOException
{
output.write(msg);
output.flush();
}
public boolean equals(Client client)
{
return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);
}
}
public static void main(String[] args)
{
int port = 4004;
if (args.length > 0)
port = Integer.parseInt(args[0]);
new ChatServer(port).run();
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
}
type Server struct {
add chan *conn
rem chan string
msg chan string
stop chan bool
}
func ListenAndServe(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
rwc, err := ln.Accept()
if err != nil {
close(s.stop)
return err
}
log.Println("New connection from", rwc.RemoteAddr())
go newConn(s, rwc).welcome()
}
}
func (s *Server) handleConns() {
conns := make(map[string]*conn)
var dropConn func(string)
writeAll := func(str string) {
log.Printf("Broadcast: %q", str)
for name, c := range conns {
c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))
_, err := c.Write([]byte(str))
if err != nil {
log.Printf("Error writing to %q: %v", name, err)
c.Close()
delete(conns, name)
defer dropConn(name)
}
}
}
dropConn = func(name string) {
if c, ok := conns[name]; ok {
log.Printf("Closing connection with %q from %v",
name, c.RemoteAddr())
c.Close()
delete(conns, name)
} else {
log.Printf("Dropped connection with %q", name)
}
str := fmt.Sprintf("--- %q disconnected ---\n", name)
writeAll(str)
}
defer func() {
writeAll("Server stopping!\n")
for _, c := range conns {
c.Close()
}
}()
for {
select {
case c := <-s.add:
if _, exists := conns[c.name]; exists {
fmt.Fprintf(c, "Name %q is not available\n", c.name)
go c.welcome()
continue
}
str := fmt.Sprintf("+++ %q connected +++\n", c.name)
writeAll(str)
conns[c.name] = c
go c.readloop()
case str := <-s.msg:
writeAll(str)
case name := <-s.rem:
dropConn(name)
case <-s.stop:
return
}
}
}
type conn struct {
*bufio.Reader
net.Conn
server *Server
name string
}
func newConn(s *Server, rwc net.Conn) *conn {
return &conn{
Reader: bufio.NewReader(rwc),
Conn: rwc,
server: s,
}
}
func (c *conn) welcome() {
var err error
for c.name = ""; c.name == ""; {
fmt.Fprint(c, "Enter your name: ")
c.name, err = c.ReadString('\n')
if err != nil {
log.Printf("Reading name from %v: %v", c.RemoteAddr(), err)
c.Close()
return
}
c.name = strings.TrimSpace(c.name)
}
c.server.add <- c
}
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')
if err != nil {
break
}
c.server.msg <- c.name + "> " + msg
}
c.server.rem <- c.name
}
| import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer implements Runnable
{
private int port = 0;
private List<Client> clients = new ArrayList<Client>();
public ChatServer(int port)
{ this.port = port; }
public void run()
{
try
{
ServerSocket ss = new ServerSocket(port);
while (true)
{
Socket s = ss.accept();
new Thread(new Client(s)).start();
}
}
catch (Exception e)
{ e.printStackTrace(); }
}
private synchronized boolean registerClient(Client client)
{
for (Client otherClient : clients)
if (otherClient.clientName.equalsIgnoreCase(client.clientName))
return false;
clients.add(client);
return true;
}
private void deregisterClient(Client client)
{
boolean wasRegistered = false;
synchronized (this)
{ wasRegistered = clients.remove(client); }
if (wasRegistered)
broadcast(client, "--- " + client.clientName + " left ---");
}
private synchronized String getOnlineListCSV()
{
StringBuilder sb = new StringBuilder();
sb.append(clients.size()).append(" user(s) online: ");
for (int i = 0; i < clients.size(); i++)
sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName);
return sb.toString();
}
private void broadcast(Client fromClient, String msg)
{
List<Client> clients = null;
synchronized (this)
{ clients = new ArrayList<Client>(this.clients); }
for (Client client : clients)
{
if (client.equals(fromClient))
continue;
try
{ client.write(msg + "\r\n"); }
catch (Exception e)
{ }
}
}
public class Client implements Runnable
{
private Socket socket = null;
private Writer output = null;
private String clientName = null;
public Client(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
socket.setSendBufferSize(16384);
socket.setTcpNoDelay(true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new OutputStreamWriter(socket.getOutputStream());
write("Please enter your name: ");
String line = null;
while ((line = input.readLine()) != null)
{
if (clientName == null)
{
line = line.trim();
if (line.isEmpty())
{
write("A name is required. Please enter your name: ");
continue;
}
clientName = line;
if (!registerClient(this))
{
clientName = null;
write("Name already registered. Please enter your name: ");
continue;
}
write(getOnlineListCSV() + "\r\n");
broadcast(this, "+++ " + clientName + " arrived +++");
continue;
}
if (line.equalsIgnoreCase("/quit"))
return;
broadcast(this, clientName + "> " + line);
}
}
catch (Exception e)
{ }
finally
{
deregisterClient(this);
output = null;
try
{ socket.close(); }
catch (Exception e)
{ }
socket = null;
}
}
public void write(String msg) throws IOException
{
output.write(msg);
output.flush();
}
public boolean equals(Client client)
{
return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);
}
}
public static void main(String[] args)
{
int port = 4004;
if (args.length > 0)
port = Integer.parseInt(args[0]);
new ChatServer(port).run();
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"unicode"
)
const (
lcASCII = "abcdefghijklmnopqrstuvwxyz"
ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func main() {
fmt.Println("ASCII lower case:")
fmt.Println(lcASCII)
for l := 'a'; l <= 'z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nASCII upper case:")
fmt.Println(ucASCII)
for l := 'A'; l <= 'Z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nUnicode version " + unicode.Version)
showRange16("Lower case 16-bit code points:", unicode.Lower.R16)
showRange32("Lower case 32-bit code points:", unicode.Lower.R32)
showRange16("Upper case 16-bit code points:", unicode.Upper.R16)
showRange32("Upper case 32-bit code points:", unicode.Upper.R32)
}
func showRange16(hdr string, rList []unicode.Range16) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
func showRange32(hdr string, rList []unicode.Range32) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
| import java.util.stream.IntStream;
public class Letters {
public static void main(String[] args) throws Exception {
System.out.print("Upper case: ");
IntStream.rangeClosed(0, 0x10FFFF)
.filter(Character::isUpperCase)
.limit(72)
.forEach(n -> System.out.printf("%c", n));
System.out.println("...");
System.out.print("Lower case: ");
IntStream.rangeClosed(0, 0x10FFFF)
.filter(Character::isLowerCase)
.limit(72)
.forEach(n -> System.out.printf("%c", n));
System.out.println("...");
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"log"
)
func main() {
m := [][]int{
{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5},
}
if len(m) != len(m[0]) {
log.Fatal("Matrix must be square.")
}
sum := 0
for i := 1; i < len(m); i++ {
for j := 0; j < i; j++ {
sum = sum + m[i][j]
}
}
fmt.Println("Sum of elements below main diagonal is", sum)
}
| public static void main(String[] args) {
int[][] matrix = {{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5}};
int sum = 0;
for (int row = 1; row < matrix.length; row++) {
for (int col = 0; col < row; col++) {
sum += matrix[row][col];
}
}
System.out.println(sum);
}
|
Write the same code in Java as shown below in Go. | package main
import (
"container/list"
"fmt"
)
type BinaryTree struct {
node int
leftSubTree *BinaryTree
rightSubTree *BinaryTree
}
func (bt *BinaryTree) insert(item int) {
if bt.node == 0 {
bt.node = item
bt.leftSubTree = &BinaryTree{}
bt.rightSubTree = &BinaryTree{}
} else if item < bt.node {
bt.leftSubTree.insert(item)
} else {
bt.rightSubTree.insert(item)
}
}
func (bt *BinaryTree) inOrder(ll *list.List) {
if bt.node == 0 {
return
}
bt.leftSubTree.inOrder(ll)
ll.PushBack(bt.node)
bt.rightSubTree.inOrder(ll)
}
func treeSort(ll *list.List) *list.List {
searchTree := &BinaryTree{}
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
searchTree.insert(i)
}
ll2 := list.New()
searchTree.inOrder(ll2)
return ll2
}
func printLinkedList(ll *list.List, f string, sorted bool) {
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
fmt.Printf(f+" ", i)
}
if !sorted {
fmt.Print("-> ")
} else {
fmt.Println()
}
}
func main() {
sl := []int{5, 3, 7, 9, 1}
ll := list.New()
for _, i := range sl {
ll.PushBack(i)
}
printLinkedList(ll, "%d", false)
lls := treeSort(ll)
printLinkedList(lls, "%d", true)
sl2 := []int{'d', 'c', 'e', 'b', 'a'}
ll2 := list.New()
for _, c := range sl2 {
ll2.PushBack(c)
}
printLinkedList(ll2, "%c", false)
lls2 := treeSort(ll2)
printLinkedList(lls2, "%c", true)
}
|
import java.util.*;
public class TreeSortTest {
public static void main(String[] args) {
test1();
System.out.println();
test2();
}
private static void test1() {
LinkedList<Integer> list = new LinkedList<>();
Random r = new Random();
for (int i = 0; i < 16; ++i)
list.add(Integer.valueOf(r.nextInt(100)));
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
private static void test2() {
LinkedList<String> list = new LinkedList<>();
String[] strings = { "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"};
for (String str : strings)
list.add(str);
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"container/list"
"fmt"
)
type BinaryTree struct {
node int
leftSubTree *BinaryTree
rightSubTree *BinaryTree
}
func (bt *BinaryTree) insert(item int) {
if bt.node == 0 {
bt.node = item
bt.leftSubTree = &BinaryTree{}
bt.rightSubTree = &BinaryTree{}
} else if item < bt.node {
bt.leftSubTree.insert(item)
} else {
bt.rightSubTree.insert(item)
}
}
func (bt *BinaryTree) inOrder(ll *list.List) {
if bt.node == 0 {
return
}
bt.leftSubTree.inOrder(ll)
ll.PushBack(bt.node)
bt.rightSubTree.inOrder(ll)
}
func treeSort(ll *list.List) *list.List {
searchTree := &BinaryTree{}
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
searchTree.insert(i)
}
ll2 := list.New()
searchTree.inOrder(ll2)
return ll2
}
func printLinkedList(ll *list.List, f string, sorted bool) {
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
fmt.Printf(f+" ", i)
}
if !sorted {
fmt.Print("-> ")
} else {
fmt.Println()
}
}
func main() {
sl := []int{5, 3, 7, 9, 1}
ll := list.New()
for _, i := range sl {
ll.PushBack(i)
}
printLinkedList(ll, "%d", false)
lls := treeSort(ll)
printLinkedList(lls, "%d", true)
sl2 := []int{'d', 'c', 'e', 'b', 'a'}
ll2 := list.New()
for _, c := range sl2 {
ll2.PushBack(c)
}
printLinkedList(ll2, "%c", false)
lls2 := treeSort(ll2)
printLinkedList(lls2, "%c", true)
}
|
import java.util.*;
public class TreeSortTest {
public static void main(String[] args) {
test1();
System.out.println();
test2();
}
private static void test1() {
LinkedList<Integer> list = new LinkedList<>();
Random r = new Random();
for (int i = 0; i < 16; ++i)
list.add(Integer.valueOf(r.nextInt(100)));
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
private static void test2() {
LinkedList<String> list = new LinkedList<>();
String[] strings = { "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"};
for (String str : strings)
list.add(str);
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
| import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
long newSize = Long.parseLong(args[1]);
outChan.truncate(newSize);
outChan.close();
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
| import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
long newSize = Long.parseLong(args[1]);
outChan.truncate(newSize);
outChan.close();
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
| import java.util.function.Function;
public class NumericalIntegrationAdaptiveSimpsons {
public static void main(String[] args) {
Function<Double,Double> f = x -> sin(x);
System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);
functionCount = 0;
System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);
}
private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {
double fa = function.apply(a);
double fb = function.apply(b);
Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);
}
private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {
Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);
Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);
double delta = left.s + right.s - whole;
if ( Math.abs(delta) <= 15*error ) {
return left.s + right.s + delta / 15;
}
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +
quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);
}
private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = function.apply(m);
return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));
}
private static class Triple {
double x, fx, s;
private Triple(double m, double fm, double s) {
this.x = m;
this.fx = fm;
this.s = s;
}
}
private static int functionCount = 0;
private static double sin(double x) {
functionCount++;
return Math.sin(x);
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
| import java.util.function.Function;
public class NumericalIntegrationAdaptiveSimpsons {
public static void main(String[] args) {
Function<Double,Double> f = x -> sin(x);
System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);
functionCount = 0;
System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);
}
private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {
double fa = function.apply(a);
double fb = function.apply(b);
Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);
}
private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {
Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);
Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);
double delta = left.s + right.s - whole;
if ( Math.abs(delta) <= 15*error ) {
return left.s + right.s + delta / 15;
}
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +
quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);
}
private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = function.apply(m);
return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));
}
private static class Triple {
double x, fx, s;
private Triple(double m, double fm, double s) {
this.x = m;
this.fx = fm;
this.s = s;
}
}
private static int functionCount = 0;
private static double sin(double x) {
functionCount++;
return Math.sin(x);
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.Open("rc.fasta")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
headerFound := false
for s.Scan() {
line := s.Text()
switch {
case line == "":
continue
case line[0] != '>':
if !headerFound {
fmt.Println("missing header")
return
}
fmt.Print(line)
case headerFound:
fmt.Println()
fallthrough
default:
fmt.Printf("%s: ", line[1:])
headerFound = true
}
}
if headerFound {
fmt.Println()
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
}
| import java.io.*;
import java.util.Scanner;
public class ReadFastaFile {
public static void main(String[] args) throws FileNotFoundException {
boolean first = true;
try (Scanner sc = new Scanner(new File("test.fasta"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.charAt(0) == '>') {
if (first)
first = false;
else
System.out.println();
System.out.printf("%s: ", line.substring(1));
} else {
System.out.print(line);
}
}
}
System.out.println();
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
| public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue;
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
| public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue;
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"log"
"github.com/jezek/xgb"
"github.com/jezek/xgb/xproto"
)
func main() {
X, err := xgb.NewConn()
if err != nil {
log.Fatal(err)
}
points := []xproto.Point{
{10, 10},
{10, 20},
{20, 10},
{20, 20}};
polyline := []xproto.Point{
{50, 10},
{ 5, 20},
{25,-20},
{10, 10}};
segments := []xproto.Segment{
{100, 10, 140, 30},
{110, 25, 130, 60}};
rectangles := []xproto.Rectangle{
{ 10, 50, 40, 20},
{ 80, 50, 10, 40}};
arcs := []xproto.Arc{
{10, 100, 60, 40, 0, 90 << 6},
{90, 100, 55, 40, 0, 270 << 6}};
setup := xproto.Setup(X)
screen := setup.DefaultScreen(X)
foreground, _ := xproto.NewGcontextId(X)
mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)
values := []uint32{screen.BlackPixel, 0}
xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)
win, _ := xproto.NewWindowId(X)
winDrawable := xproto.Drawable(win)
mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)
values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}
xproto.CreateWindow(X,
screen.RootDepth,
win,
screen.Root,
0, 0,
150, 150,
10,
xproto.WindowClassInputOutput,
screen.RootVisual,
mask, values)
xproto.MapWindow(X, win)
for {
evt, err := X.WaitForEvent()
switch evt.(type) {
case xproto.ExposeEvent:
xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)
xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)
xproto.PolySegment(X, winDrawable, foreground, segments)
xproto.PolyRectangle(X, winDrawable, foreground, rectangles)
xproto.PolyArc(X, winDrawable, foreground, arcs)
default:
}
if err != nil {
log.Fatal(err)
}
}
return
}
| import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WindowExample {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
createAndShow();
}
};
SwingUtilities.invokeLater(runnable);
}
static void createAndShow() {
JFrame frame = new JFrame("Hello World");
frame.setSize(640,480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
type state int
const (
ready state = iota
waiting
exit
dispense
refunding
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func fsm() {
fmt.Println("Please enter your option when prompted")
fmt.Println("(any characters after the first will be ignored)")
state := ready
var trans string
scanner := bufio.NewScanner(os.Stdin)
for {
switch state {
case ready:
for {
fmt.Print("\n(D)ispense or (Q)uit : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'd' {
state = waiting
break
} else if option == 'q' {
state = exit
break
}
}
case waiting:
fmt.Println("OK, put your money in the slot")
for {
fmt.Print("(S)elect product or choose a (R)efund : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 's' {
state = dispense
break
} else if option == 'r' {
state = refunding
break
}
}
case dispense:
for {
fmt.Print("(R)emove product : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'r' {
state = ready
break
}
}
case refunding:
fmt.Println("OK, refunding your money")
state = ready
case exit:
fmt.Println("OK, quitting")
return
}
}
}
func main() {
fsm()
}
| import java.util.*;
public class FiniteStateMachine {
private enum State {
Ready(true, "Deposit", "Quit"),
Waiting(true, "Select", "Refund"),
Dispensing(true, "Remove"),
Refunding(false, "Refunding"),
Exiting(false, "Quiting");
State(boolean exp, String... in) {
inputs = Arrays.asList(in);
explicit = exp;
}
State nextState(String input, State current) {
if (inputs.contains(input)) {
return map.getOrDefault(input, current);
}
return current;
}
final List<String> inputs;
final static Map<String, State> map = new HashMap<>();
final boolean explicit;
static {
map.put("Deposit", State.Waiting);
map.put("Quit", State.Exiting);
map.put("Select", State.Dispensing);
map.put("Refund", State.Refunding);
map.put("Remove", State.Ready);
map.put("Refunding", State.Ready);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
State state = State.Ready;
while (state != State.Exiting) {
System.out.println(state.inputs);
if (state.explicit){
System.out.print("> ");
state = state.nextState(sc.nextLine().trim(), state);
} else {
state = state.nextState(state.inputs.get(0), state);
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"image"
"image/color"
"image/gif"
"log"
"os"
)
var (
black = color.RGBA{0, 0, 0, 255}
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
yellow = color.RGBA{255, 255, 0, 255}
white = color.RGBA{255, 255, 255, 255}
)
var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}
func hline(img *image.Paletted, x1, y, x2 int, ci uint8) {
for ; x1 <= x2; x1++ {
img.SetColorIndex(x1, y, ci)
}
}
func vline(img *image.Paletted, x, y1, y2 int, ci uint8) {
for ; y1 <= y2; y1++ {
img.SetColorIndex(x, y1, ci)
}
}
func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
img.SetColorIndex(x, y, ci)
}
}
}
func drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
hline(img, x1, y1, x2, ci)
hline(img, x1, y2, x2, ci)
vline(img, x1, y1, y2, ci)
vline(img, x2, y1, y2, ci)
}
func main() {
const nframes = 140
const delay = 10
width, height := 500, 500
anim := gif.GIF{LoopCount: nframes}
rect := image.Rect(0, 0, width, height)
for c := uint8(0); c < 7; c++ {
for f := 0; f < 20; f++ {
img := image.NewPaletted(rect, palette)
setBackgroundColor(img, width, height, 7)
for r := 0; r < 20; r++ {
ix := c
if r < f {
ix = (ix + 1) % 7
}
x := width * (r + 1) / 50
y := height * (r + 1) / 50
w := width - x
h := height - y
drawRectangle(img, x, y, w, h, ix)
}
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
}
file, err := os.Create("vibrating.gif")
if err != nil {
log.Fatal(err)
}
defer file.Close()
if err2 := gif.EncodeAll(file, &anim); err != nil {
log.Fatal(err2)
}
}
|
int counter = 100;
void setup(){
size(1000,1000);
}
void draw(){
for(int i=0;i<20;i++){
fill(counter - 5*i);
rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);
}
counter++;
if(counter > 255)
counter = 100;
delay(100);
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
| import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
| import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"math"
)
const CONST = 6364136223846793005
type Pcg32 struct{ state, inc uint64 }
func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }
func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
pcg.state = 0
pcg.inc = (seedSequence << 1) | 1
pcg.nextInt()
pcg.state = pcg.state + seedState
pcg.nextInt()
}
func (pcg *Pcg32) nextInt() uint32 {
old := pcg.state
pcg.state = old*CONST + pcg.inc
pcgshifted := uint32(((old >> 18) ^ old) >> 27)
rot := uint32(old >> 59)
return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}
func (pcg *Pcg32) nextFloat() float64 {
return float64(pcg.nextInt()) / (1 << 32)
}
func main() {
randomGen := Pcg32New()
randomGen.seed(42, 54)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321, 1)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
| public class PCG32 {
private static final long N = 6364136223846793005L;
private long state = 0x853c49e6748fea9bL;
private long inc = 0xda3e39cb94b95bdbL;
public void seed(long seedState, long seedSequence) {
state = 0;
inc = (seedSequence << 1) | 1;
nextInt();
state = state + seedState;
nextInt();
}
public int nextInt() {
long old = state;
state = old * N + inc;
int shifted = (int) (((old >>> 18) ^ old) >>> 27);
int rot = (int) (old >>> 59);
return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));
}
public double nextFloat() {
var u = Integer.toUnsignedLong(nextInt());
return (double) u / (1L << 32);
}
public static void main(String[] args) {
var r = new PCG32();
r.seed(42, 54);
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
r.seed(987654321, 1);
for (int i = 0; i < 100_000; i++) {
int j = (int) Math.floor(r.nextFloat() * 5.0);
counts[j]++;
}
System.out.println("The counts for 100,000 repetitions are:");
for (int i = 0; i < counts.length; i++) {
System.out.printf(" %d : %d\n", i, counts[i]);
}
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import "fmt"
func main() {
h := []float64{-8, -9, -3, -1, -6, 7}
f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7}
fmt.Println(h)
fmt.Println(deconv(g, f))
fmt.Println(f)
fmt.Println(deconv(g, h))
}
func deconv(g, f []float64) []float64 {
h := make([]float64, len(g)-len(f)+1)
for n := range h {
h[n] = g[n]
var lower int
if n >= len(f) {
lower = n - len(f) + 1
}
for i := lower; i < n; i++ {
h[n] -= h[i] * f[n-i]
}
h[n] /= f[0]
}
return h
}
| import java.util.Arrays;
public class Deconvolution1D {
public static int[] deconv(int[] g, int[] f) {
int[] h = new int[g.length - f.length + 1];
for (int n = 0; n < h.length; n++) {
h[n] = g[n];
int lower = Math.max(n - f.length + 1, 0);
for (int i = lower; i < n; i++)
h[n] -= h[i] * f[n - i];
h[n] /= f[0];
}
return h;
}
public static void main(String[] args) {
int[] h = { -8, -9, -3, -1, -6, 7 };
int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };
int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7 };
StringBuilder sb = new StringBuilder();
sb.append("h = " + Arrays.toString(h) + "\n");
sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n");
sb.append("f = " + Arrays.toString(f) + "\n");
sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n");
System.out.println(sb.toString());
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16s : %s\n", name, name2)
}
}
| import static java.util.Arrays.*;
import static java.lang.System.out;
public class NYSIIS {
final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"},
{"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}};
final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"},
{"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}};
final static String Vowels = "AEIOU";
public static void main(String[] args) {
stream(args).parallel().map(n -> transcode(n)).forEach(out::println);
}
static String transcode(String s) {
int len = s.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z')
sb.append((char) (c - 32));
else if (c >= 'A' && c <= 'Z')
sb.append(c);
}
replace(sb, 0, first);
replace(sb, sb.length() - 2, last);
len = sb.length();
sb.append(" ");
for (int i = 1; i < len; i++) {
char prev = sb.charAt(i - 1);
char curr = sb.charAt(i);
char next = sb.charAt(i + 1);
if (curr == 'E' && next == 'V')
sb.replace(i, i + 2, "AF");
else if (isVowel(curr))
sb.setCharAt(i, 'A');
else if (curr == 'Q')
sb.setCharAt(i, 'G');
else if (curr == 'Z')
sb.setCharAt(i, 'S');
else if (curr == 'M')
sb.setCharAt(i, 'N');
else if (curr == 'K' && next == 'N')
sb.setCharAt(i, 'N');
else if (curr == 'K')
sb.setCharAt(i, 'C');
else if (sb.indexOf("SCH", i) == i)
sb.replace(i, i + 3, "SSS");
else if (curr == 'P' && next == 'H')
sb.replace(i, i + 2, "FF");
else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))
sb.setCharAt(i, prev);
else if (curr == 'W' && isVowel(prev))
sb.setCharAt(i, prev);
if (sb.charAt(i) == prev) {
sb.deleteCharAt(i--);
len--;
}
}
sb.setLength(sb.length() - 1);
int lastPos = sb.length() - 1;
if (lastPos > 1) {
if (sb.lastIndexOf("AY") == lastPos - 1)
sb.delete(lastPos - 1, lastPos + 1).append("Y");
else if (sb.charAt(lastPos) == 'S')
sb.setLength(lastPos);
else if (sb.charAt(lastPos) == 'A')
sb.setLength(lastPos);
}
if (sb.length() > 6)
sb.insert(6, '[').append(']');
return String.format("%s -> %s", s, sb);
}
private static void replace(StringBuilder sb, int start, String[][] maps) {
if (start >= 0)
for (String[] map : maps) {
if (sb.indexOf(map[0]) == start) {
sb.replace(start, start + map[0].length(), map[1]);
break;
}
}
}
private static boolean isVowel(char c) {
return Vowels.indexOf(c) != -1;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16s : %s\n", name, name2)
}
}
| import static java.util.Arrays.*;
import static java.lang.System.out;
public class NYSIIS {
final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"},
{"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}};
final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"},
{"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}};
final static String Vowels = "AEIOU";
public static void main(String[] args) {
stream(args).parallel().map(n -> transcode(n)).forEach(out::println);
}
static String transcode(String s) {
int len = s.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z')
sb.append((char) (c - 32));
else if (c >= 'A' && c <= 'Z')
sb.append(c);
}
replace(sb, 0, first);
replace(sb, sb.length() - 2, last);
len = sb.length();
sb.append(" ");
for (int i = 1; i < len; i++) {
char prev = sb.charAt(i - 1);
char curr = sb.charAt(i);
char next = sb.charAt(i + 1);
if (curr == 'E' && next == 'V')
sb.replace(i, i + 2, "AF");
else if (isVowel(curr))
sb.setCharAt(i, 'A');
else if (curr == 'Q')
sb.setCharAt(i, 'G');
else if (curr == 'Z')
sb.setCharAt(i, 'S');
else if (curr == 'M')
sb.setCharAt(i, 'N');
else if (curr == 'K' && next == 'N')
sb.setCharAt(i, 'N');
else if (curr == 'K')
sb.setCharAt(i, 'C');
else if (sb.indexOf("SCH", i) == i)
sb.replace(i, i + 3, "SSS");
else if (curr == 'P' && next == 'H')
sb.replace(i, i + 2, "FF");
else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))
sb.setCharAt(i, prev);
else if (curr == 'W' && isVowel(prev))
sb.setCharAt(i, prev);
if (sb.charAt(i) == prev) {
sb.deleteCharAt(i--);
len--;
}
}
sb.setLength(sb.length() - 1);
int lastPos = sb.length() - 1;
if (lastPos > 1) {
if (sb.lastIndexOf("AY") == lastPos - 1)
sb.delete(lastPos - 1, lastPos + 1).append("Y");
else if (sb.charAt(lastPos) == 'S')
sb.setLength(lastPos);
else if (sb.charAt(lastPos) == 'A')
sb.setLength(lastPos);
}
if (sb.length() > 6)
sb.insert(6, '[').append(']');
return String.format("%s -> %s", s, sb);
}
private static void replace(StringBuilder sb, int start, String[][] maps) {
if (start >= 0)
for (String[] map : maps) {
if (sb.indexOf(map[0]) == start) {
sb.replace(start, start + map[0].length(), map[1]);
break;
}
}
}
private static boolean isVowel(char c) {
return Vowels.indexOf(c) != -1;
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16s : %s\n", name, name2)
}
}
| import static java.util.Arrays.*;
import static java.lang.System.out;
public class NYSIIS {
final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"},
{"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}};
final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"},
{"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}};
final static String Vowels = "AEIOU";
public static void main(String[] args) {
stream(args).parallel().map(n -> transcode(n)).forEach(out::println);
}
static String transcode(String s) {
int len = s.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z')
sb.append((char) (c - 32));
else if (c >= 'A' && c <= 'Z')
sb.append(c);
}
replace(sb, 0, first);
replace(sb, sb.length() - 2, last);
len = sb.length();
sb.append(" ");
for (int i = 1; i < len; i++) {
char prev = sb.charAt(i - 1);
char curr = sb.charAt(i);
char next = sb.charAt(i + 1);
if (curr == 'E' && next == 'V')
sb.replace(i, i + 2, "AF");
else if (isVowel(curr))
sb.setCharAt(i, 'A');
else if (curr == 'Q')
sb.setCharAt(i, 'G');
else if (curr == 'Z')
sb.setCharAt(i, 'S');
else if (curr == 'M')
sb.setCharAt(i, 'N');
else if (curr == 'K' && next == 'N')
sb.setCharAt(i, 'N');
else if (curr == 'K')
sb.setCharAt(i, 'C');
else if (sb.indexOf("SCH", i) == i)
sb.replace(i, i + 3, "SSS");
else if (curr == 'P' && next == 'H')
sb.replace(i, i + 2, "FF");
else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))
sb.setCharAt(i, prev);
else if (curr == 'W' && isVowel(prev))
sb.setCharAt(i, prev);
if (sb.charAt(i) == prev) {
sb.deleteCharAt(i--);
len--;
}
}
sb.setLength(sb.length() - 1);
int lastPos = sb.length() - 1;
if (lastPos > 1) {
if (sb.lastIndexOf("AY") == lastPos - 1)
sb.delete(lastPos - 1, lastPos + 1).append("Y");
else if (sb.charAt(lastPos) == 'S')
sb.setLength(lastPos);
else if (sb.charAt(lastPos) == 'A')
sb.setLength(lastPos);
}
if (sb.length() > 6)
sb.insert(6, '[').append(']');
return String.format("%s -> %s", s, sb);
}
private static void replace(StringBuilder sb, int start, String[][] maps) {
if (start >= 0)
for (String[] map : maps) {
if (sb.indexOf(map[0]) == start) {
sb.replace(start, start + map[0].length(), map[1]);
break;
}
}
}
private static boolean isVowel(char c) {
return Vowels.indexOf(c) != -1;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
| import java.lang.Math;
public class DisariumNumbers {
public static boolean is_disarium(int num) {
int n = num;
int len = Integer.toString(n).length();
int sum = 0;
int i = 1;
while (n > 0) {
sum += Math.pow(n % 10, len - i + 1);
n /= 10;
i ++;
}
return sum == num;
}
public static void main(String[] args) {
int i = 0;
int count = 0;
while (count <= 18) {
if (is_disarium(i)) {
System.out.printf("%d ", i);
count++;
}
i++;
}
System.out.printf("%s", "\n");
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
| import java.lang.Math;
public class DisariumNumbers {
public static boolean is_disarium(int num) {
int n = num;
int len = Integer.toString(n).length();
int sum = 0;
int i = 1;
while (n > 0) {
sum += Math.pow(n % 10, len - i + 1);
n /= 10;
i ++;
}
return sum == num;
}
public static void main(String[] args) {
int i = 0;
int count = 0;
while (count <= 18) {
if (is_disarium(i)) {
System.out.printf("%d ", i);
count++;
}
i++;
}
System.out.printf("%s", "\n");
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"github.com/fogleman/gg"
"image/color"
"math"
)
var (
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
)
var (
w, h = 640, 640
dc = gg.NewContext(w, h)
deg72 = gg.Radians(72)
scaleFactor = 1 / (2 + math.Cos(deg72)*2)
palette = [5]color.Color{red, green, blue, magenta, cyan}
colorIndex = 0
)
func drawPentagon(x, y, side float64, depth int) {
angle := 3 * deg72
if depth == 0 {
dc.MoveTo(x, y)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * side
y -= math.Sin(angle) * side
dc.LineTo(x, y)
angle += deg72
}
dc.SetColor(palette[colorIndex])
dc.Fill()
colorIndex = (colorIndex + 1) % 5
} else {
side *= scaleFactor
dist := side * (1 + math.Cos(deg72)*2)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * dist
y -= math.Sin(angle) * dist
drawPentagon(x, y, side, depth-1)
angle += deg72
}
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
order := 5
hw := float64(w / 2)
margin := 20.0
radius := hw - 2*margin
side := radius * math.Sin(math.Pi/5) * 2
drawPentagon(hw, 3*margin, side, order-1)
dc.SavePNG("sierpinski_pentagon.png")
}
| import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import static java.lang.Math.*;
import java.util.Random;
import javax.swing.*;
public class SierpinskiPentagon extends JPanel {
final double degrees072 = toRadians(72);
final double scaleFactor = 1 / (2 + cos(degrees072) * 2);
final int margin = 20;
int limit = 0;
Random r = new Random();
public SierpinskiPentagon() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
new Timer(3000, (ActionEvent e) -> {
limit++;
if (limit >= 5)
limit = 0;
repaint();
}).start();
}
void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {
double angle = 3 * degrees072;
if (depth == 0) {
Path2D p = new Path2D.Double();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * side;
y = y - sin(angle) * side;
p.lineTo(x, y);
angle += degrees072;
}
g.setColor(RandomHue.next());
g.fill(p);
} else {
side *= scaleFactor;
double distance = side + side * cos(degrees072) * 2;
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * distance;
y = y - sin(angle) * distance;
drawPentagon(g, x, y, side, depth - 1);
angle += degrees072;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
double radius = w / 2 - 2 * margin;
double side = radius * sin(PI / 5) * 2;
drawPentagon(g, w / 2, 3 * margin, side, limit);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Sierpinski Pentagon");
f.setResizable(true);
f.add(new SierpinskiPentagon(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class RandomHue {
final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;
private static double hue = Math.random();
static Color next() {
hue = (hue + goldenRatioConjugate) % 1;
return Color.getHSBColor((float) hue, 1, 1);
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package raster
import "math"
func (g *Grmap) Histogram(bins int) []int {
if bins <= 0 {
bins = g.cols
}
h := make([]int, bins)
for _, p := range g.px {
h[int(p)*(bins-1)/math.MaxUint16]++
}
return h
}
func (g *Grmap) Threshold(t uint16) {
for i, p := range g.px {
if p < t {
g.px[i] = 0
} else {
g.px[i] = math.MaxUint16
}
}
}
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImageProcessing {
;
public static void main(String[] args) throws IOException {
BufferedImage img = ImageIO.read(new File("example.png"));
BufferedImage bwimg = toBlackAndWhite(img);
ImageIO.write(bwimg, "png", new File("example-bw.png"));
}
private static int luminance(int rgb) {
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
return (r + b + g) / 3;
}
private static BufferedImage toBlackAndWhite(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int[] histo = computeHistogram(img);
int median = getMedian(width * height, histo);
BufferedImage bwimg = new BufferedImage(width, height, img.getType());
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);
}
}
return bwimg;
}
private static int[] computeHistogram(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int[] histo = new int[256];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
histo[luminance(img.getRGB(x, y))]++;
}
}
return histo;
}
private static int getMedian(int total, int[] histo) {
int median = 0;
int sum = 0;
for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {
sum += histo[i];
median++;
}
return median;
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"fmt"
"sync"
"time"
)
var value int
var m sync.Mutex
var wg sync.WaitGroup
func slowInc() {
m.Lock()
v := value
time.Sleep(1e8)
value = v+1
m.Unlock()
wg.Done()
}
func main() {
wg.Add(2)
go slowInc()
go slowInc()
wg.Wait()
fmt.Println(value)
}
| import java.util.concurrent.Semaphore;
public class VolatileClass{
public Semaphore mutex = new Semaphore(1);
public void needsToBeSynched(){
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"time"
)
func main() {
var bpm = 72.0
var bpb = 4
d := time.Duration(float64(time.Minute) / bpm)
fmt.Println("Delay:", d)
t := time.NewTicker(d)
i := 1
for _ = range t.C {
i--
if i == 0 {
i = bpb
fmt.Printf("\nTICK ")
} else {
fmt.Printf("tick ")
}
}
}
| class Metronome{
double bpm;
int measure, counter;
public Metronome(double bpm, int measure){
this.bpm = bpm;
this.measure = measure;
}
public void start(){
while(true){
try {
Thread.sleep((long)(1000*(60.0/bpm)));
}catch(InterruptedException e) {
e.printStackTrace();
}
counter++;
if (counter%measure==0){
System.out.println("TICK");
}else{
System.out.println("TOCK");
}
}
}
}
public class test {
public static void main(String[] args) {
Metronome metronome1 = new Metronome(120,4);
metronome1.start();
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"sort"
)
func contains(a []int, b int) bool {
for _, j := range a {
if j == b {
return true
}
}
return false
}
func gcd(a, b int) int {
for a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
func areSame(s, t []int) bool {
le := len(s)
if le != len(t) {
return false
}
sort.Ints(s)
sort.Ints(t)
for i := 0; i < le; i++ {
if s[i] != t[i] {
return false
}
}
return true
}
func main() {
const limit = 100
starts := [5]int{2, 5, 7, 9, 10}
var ekg [5][limit]int
for s, start := range starts {
ekg[s][0] = 1
ekg[s][1] = start
for n := 2; n < limit; n++ {
for i := 2; ; i++ {
if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {
ekg[s][n] = i
break
}
}
}
fmt.Printf("EKG(%2d): %v\n", start, ekg[s][:30])
}
for i := 2; i < limit; i++ {
if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {
fmt.Println("\nEKG(5) and EKG(7) converge at term", i+1)
return
}
}
fmt.Println("\nEKG5(5) and EKG(7) do not converge within", limit, "terms")
}
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EKGSequenceConvergence {
public static void main(String[] args) {
System.out.println("Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].");
for ( int i : new int[] {2, 5, 7, 9, 10} ) {
System.out.printf("EKG[%d] = %s%n", i, ekg(i, 10));
}
System.out.println("Calculate and show here at which term EKG[5] and EKG[7] converge.");
List<Integer> ekg5 = ekg(5, 100);
List<Integer> ekg7 = ekg(7, 100);
for ( int i = 1 ; i < ekg5.size() ; i++ ) {
if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {
System.out.printf("EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n", 5, i+1, 7, i+1, ekg5.get(i));
break;
}
}
}
private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {
List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));
Collections.sort(list1);
List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));
Collections.sort(list2);
for ( int i = 0 ; i < n ; i++ ) {
if ( list1.get(i) != list2.get(i) ) {
return false;
}
}
return true;
}
private static List<Integer> ekg(int two, int maxN) {
List<Integer> result = new ArrayList<>();
result.add(1);
result.add(two);
Map<Integer,Integer> seen = new HashMap<>();
seen.put(1, 1);
seen.put(two, 1);
int minUnseen = two == 2 ? 3 : 2;
int prev = two;
for ( int n = 3 ; n <= maxN ; n++ ) {
int test = minUnseen - 1;
while ( true ) {
test++;
if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {
result.add(test);
seen.put(test, n);
prev = test;
if ( minUnseen == test ) {
do {
minUnseen++;
} while ( seen.containsKey(minUnseen) );
}
break;
}
}
}
return result;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"strings"
)
func rep(s string) int {
for x := len(s) / 2; x > 0; x-- {
if strings.HasPrefix(s, s[x:]) {
return x
}
}
return 0
}
const m = `
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1`
func main() {
for _, s := range strings.Fields(m) {
if n := rep(s); n > 0 {
fmt.Printf("%q %d rep-string %q\n", s, n, s[:n])
} else {
fmt.Printf("%q not a rep-string\n", s)
}
}
}
| public class RepString {
static final String[] input = {"1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101", "0100100", "101", "11",
"00", "1", "0100101"};
public static void main(String[] args) {
for (String s : input)
System.out.printf("%s : %s%n", s, repString(s));
}
static String repString(String s) {
int len = s.length();
outer:
for (int part = len / 2; part > 0; part--) {
int tail = len % part;
if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))
continue;
for (int j = 0; j < len / part - 1; j++) {
int a = j * part;
int b = (j + 1) * part;
int c = (j + 2) * part;
if (!s.substring(a, b).equals(s.substring(b, c)))
continue outer;
}
return s.substring(0, part);
}
return "none";
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"time"
)
func main() {
fmt.Print("\033[?1049h\033[H")
fmt.Println("Alternate screen buffer\n")
s := "s"
for i := 5; i > 0; i-- {
if i == 1 {
s = ""
}
fmt.Printf("\rgoing back in %d second%s...", i, s)
time.Sleep(time.Second)
}
fmt.Print("\033[?1049l")
}
| public class PreserveScreen
{
public static void main(String[] args) throws InterruptedException {
System.out.print("\033[?1049h\033[H");
System.out.println("Alternate screen buffer\n");
for (int i = 5; i > 0; i--) {
String s = (i > 1) ? "s" : "";
System.out.printf("\rgoing back in %d second%s...", i, s);
Thread.sleep(1000);
}
System.out.print("\033[?1049l");
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | ch := 'z'
ch = 122
ch = '\x7a'
ch = '\u007a'
ch = '\U0000007a'
ch = '\172'
| char a = 'a';
String b = "abc";
char doubleQuote = '"';
char singleQuote = '\'';
String singleQuotes = "''";
String doubleQuotes = "\"\"";
|
Generate an equivalent Java version of this Go code. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func hammingDist(s1, s2 string) int {
r1 := []rune(s1)
r2 := []rune(s2)
if len(r1) != len(r2) {
return 0
}
count := 0
for i := 0; i < len(r1); i++ {
if r1[i] != r2[i] {
count++
if count == 2 {
break
}
}
}
return count
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 11 {
words = append(words, s)
}
}
count := 0
fmt.Println("Changeable words in", wordList, "\b:")
for _, word1 := range words {
for _, word2 := range words {
if word1 != word2 && hammingDist(word1, word2) == 1 {
count++
fmt.Printf("%2d: %-14s -> %s\n", count, word1, word2)
}
}
}
}
| import java.io.*;
import java.util.*;
public class ChangeableWords {
public static void main(String[] args) {
try {
final String fileName = "unixdict.txt";
List<String> dictionary = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 11)
dictionary.add(line);
}
}
System.out.printf("Changeable words in %s:\n", fileName);
int n = 1;
for (String word1 : dictionary) {
for (String word2 : dictionary) {
if (word1 != word2 && hammingDistance(word1, word2) == 1)
System.out.printf("%2d: %-14s -> %s\n", n++, word1, word2);
}
}
} catch (Exception e) {
e.printStackTtexture();
}
}
private static int hammingDistance(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
if (len1 != len2)
return 0;
int count = 0;
for (int i = 0; i < len1; ++i) {
if (str1.charAt(i) != str2.charAt(i))
++count;
if (count == 2)
break;
}
return count;
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"time"
)
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetResizable(true)
window.SetTitle("Window management")
window.SetBorderWidth(5)
window.Connect("destroy", func() {
gtk.MainQuit()
})
stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)
check(err, "Unable to create stack box:")
bmax, err := gtk.ButtonNewWithLabel("Maximize")
check(err, "Unable to create maximize button:")
bmax.Connect("clicked", func() {
window.Maximize()
})
bunmax, err := gtk.ButtonNewWithLabel("Unmaximize")
check(err, "Unable to create unmaximize button:")
bunmax.Connect("clicked", func() {
window.Unmaximize()
})
bicon, err := gtk.ButtonNewWithLabel("Iconize")
check(err, "Unable to create iconize button:")
bicon.Connect("clicked", func() {
window.Iconify()
})
bdeicon, err := gtk.ButtonNewWithLabel("Deiconize")
check(err, "Unable to create deiconize button:")
bdeicon.Connect("clicked", func() {
window.Deiconify()
})
bhide, err := gtk.ButtonNewWithLabel("Hide")
check(err, "Unable to create hide button:")
bhide.Connect("clicked", func() {
window.Hide()
time.Sleep(10 * time.Second)
window.Show()
})
bshow, err := gtk.ButtonNewWithLabel("Show")
check(err, "Unable to create show button:")
bshow.Connect("clicked", func() {
window.Show()
})
bmove, err := gtk.ButtonNewWithLabel("Move")
check(err, "Unable to create move button:")
isShifted := false
bmove.Connect("clicked", func() {
w, h := window.GetSize()
if isShifted {
window.Move(w-10, h-10)
} else {
window.Move(w+10, h+10)
}
isShifted = !isShifted
})
bquit, err := gtk.ButtonNewWithLabel("Quit")
check(err, "Unable to create quit button:")
bquit.Connect("clicked", func() {
window.Destroy()
})
stackbox.PackStart(bmax, true, true, 0)
stackbox.PackStart(bunmax, true, true, 0)
stackbox.PackStart(bicon, true, true, 0)
stackbox.PackStart(bdeicon, true, true, 0)
stackbox.PackStart(bhide, true, true, 0)
stackbox.PackStart(bshow, true, true, 0)
stackbox.PackStart(bmove, true, true, 0)
stackbox.PackStart(bquit, true, true, 0)
window.Add(stackbox)
window.ShowAll()
gtk.Main()
}
| import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class WindowController extends JFrame {
public static void main( final String[] args ) {
EventQueue.invokeLater( () -> new WindowController() );
}
private JComboBox<ControlledWindow> list;
private class ControlButton extends JButton {
private ControlButton( final String name ) {
super(
new AbstractAction( name ) {
public void actionPerformed( final ActionEvent e ) {
try {
WindowController.class.getMethod( "do" + name )
.invoke ( WindowController.this );
} catch ( final Exception x ) {
x.printStackTrace();
}
}
}
);
}
}
public WindowController() {
super( "Controller" );
final JPanel main = new JPanel();
final JPanel controls = new JPanel();
setLocationByPlatform( true );
setResizable( false );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLayout( new BorderLayout( 3, 3 ) );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH );
main.add( list = new JComboBox<>() );
add( main, BorderLayout.CENTER );
controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );
controls.add( new ControlButton( "Add" ) );
controls.add( new ControlButton( "Hide" ) );
controls.add( new ControlButton( "Show" ) );
controls.add( new ControlButton( "Close" ) );
controls.add( new ControlButton( "Maximise" ) );
controls.add( new ControlButton( "Minimise" ) );
controls.add( new ControlButton( "Move" ) );
controls.add( new ControlButton( "Resize" ) );
add( controls, BorderLayout.EAST );
pack();
setVisible( true );
}
private static class ControlledWindow extends JFrame {
private int num;
public ControlledWindow( final int num ) {
super( Integer.toString( num ) );
this.num = num;
setLocationByPlatform( true );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
add( new JLabel( "I am window " + num + ". Use the controller to control me." ) );
pack();
setVisible( true );
}
public String toString() {
return "Window " + num;
}
}
public void doAdd() {
list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );
pack();
}
public void doHide() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( false );
}
public void doShow() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( true );
}
public void doClose() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.dispose();
}
public void doMinimise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setState( Frame.ICONIFIED );
}
public void doMaximise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setExtendedState( Frame.MAXIMIZED_BOTH );
}
public void doMove() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int hPos = getInt( "Horizontal position?" );
if ( -1 == hPos ) {
return;
}
final int vPos = getInt( "Vertical position?" );
if ( -1 == vPos ) {
return;
}
window.setLocation ( hPos, vPos );
}
public void doResize() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int width = getInt( "Width?" );
if ( -1 == width ) {
return;
}
final int height = getInt( "Height?" );
if ( -1 == height ) {
return;
}
window.setBounds ( window.getX(), window.getY(), width, height );
}
private JFrame getWindow() {
final JFrame window = ( JFrame ) list.getSelectedItem();
if ( null == window ) {
JOptionPane.showMessageDialog( this, "Add a window first" );
}
return window;
}
private int getInt(final String prompt) {
final String s = JOptionPane.showInputDialog( prompt );
if ( null == s ) {
return -1;
}
try {
return Integer.parseInt( s );
} catch ( final NumberFormatException x ) {
JOptionPane.showMessageDialog( this, "Not a number" );
return -1;
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | 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 main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
| class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | 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 main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
| class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | 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 main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
| class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"strconv"
)
const (
ul = "╔"
uc = "╦"
ur = "╗"
ll = "╚"
lc = "╩"
lr = "╝"
hb = "═"
vb = "║"
)
var mayan = [5]string{
" ",
" ∙ ",
" ∙∙ ",
"∙∙∙ ",
"∙∙∙∙",
}
const (
m0 = " Θ "
m5 = "────"
)
func dec2vig(n uint64) []uint64 {
vig := strconv.FormatUint(n, 20)
res := make([]uint64, len(vig))
for i, d := range vig {
res[i], _ = strconv.ParseUint(string(d), 20, 64)
}
return res
}
func vig2quin(n uint64) [4]string {
if n >= 20 {
panic("Cant't convert a number >= 20")
}
res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}
if n == 0 {
res[3] = m0
return res
}
fives := n / 5
rem := n % 5
res[3-fives] = mayan[rem]
for i := 3; i > 3-int(fives); i-- {
res[i] = m5
}
return res
}
func draw(mayans [][4]string) {
lm := len(mayans)
fmt.Print(ul)
for i := 0; i < lm; i++ {
for j := 0; j < 4; j++ {
fmt.Print(hb)
}
if i < lm-1 {
fmt.Print(uc)
} else {
fmt.Println(ur)
}
}
for i := 1; i < 5; i++ {
fmt.Print(vb)
for j := 0; j < lm; j++ {
fmt.Print(mayans[j][i-1])
fmt.Print(vb)
}
fmt.Println()
}
fmt.Print(ll)
for i := 0; i < lm; i++ {
for j := 0; j < 4; j++ {
fmt.Print(hb)
}
if i < lm-1 {
fmt.Print(lc)
} else {
fmt.Println(lr)
}
}
}
func main() {
numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}
for _, n := range numbers {
fmt.Printf("Converting %d to Mayan:\n", n)
vigs := dec2vig(n)
lv := len(vigs)
mayans := make([][4]string, lv)
for i, vig := range vigs {
mayans[i] = vig2quin(vig)
}
draw(mayans)
fmt.Println()
}
}
| import java.math.BigInteger;
public class MayanNumerals {
public static void main(String[] args) {
for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {
displayMyan(BigInteger.valueOf(base10));
System.out.printf("%n");
}
}
private static char[] digits = "0123456789ABCDEFGHJK".toCharArray();
private static BigInteger TWENTY = BigInteger.valueOf(20);
private static void displayMyan(BigInteger numBase10) {
System.out.printf("As base 10: %s%n", numBase10);
String numBase20 = "";
while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {
numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;
numBase10 = numBase10.divide(TWENTY);
}
System.out.printf("As base 20: %s%nAs Mayan:%n", numBase20);
displayMyanLine1(numBase20);
displayMyanLine2(numBase20);
displayMyanLine3(numBase20);
displayMyanLine4(numBase20);
displayMyanLine5(numBase20);
displayMyanLine6(numBase20);
}
private static char boxUL = Character.toChars(9556)[0];
private static char boxTeeUp = Character.toChars(9574)[0];
private static char boxUR = Character.toChars(9559)[0];
private static char boxHorz = Character.toChars(9552)[0];
private static char boxVert = Character.toChars(9553)[0];
private static char theta = Character.toChars(952)[0];
private static char boxLL = Character.toChars(9562)[0];
private static char boxLR = Character.toChars(9565)[0];
private static char boxTeeLow = Character.toChars(9577)[0];
private static char bullet = Character.toChars(8729)[0];
private static char dash = Character.toChars(9472)[0];
private static void displayMyanLine1(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxUL);
}
for ( int j = 0 ; j < 4 ; j++ ) {
sb.append(boxHorz);
}
sb.append(i < chars.length-1 ? boxTeeUp : boxUR);
}
System.out.println(sb.toString());
}
private static String getBullet(int count) {
StringBuilder sb = new StringBuilder();
switch ( count ) {
case 1: sb.append(" " + bullet + " "); break;
case 2: sb.append(" " + bullet + bullet + " "); break;
case 3: sb.append("" + bullet + bullet + bullet + " "); break;
case 4: sb.append("" + bullet + bullet + bullet + bullet); break;
default: throw new IllegalArgumentException("Must be 1-4: " + count);
}
return sb.toString();
}
private static void displayMyanLine2(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case 'G': sb.append(getBullet(1)); break;
case 'H': sb.append(getBullet(2)); break;
case 'J': sb.append(getBullet(3)); break;
case 'K': sb.append(getBullet(4)); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static String DASH = getDash();
private static String getDash() {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < 4 ; i++ ) {
sb.append(dash);
}
return sb.toString();
}
private static void displayMyanLine3(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case 'B': sb.append(getBullet(1)); break;
case 'C': sb.append(getBullet(2)); break;
case 'D': sb.append(getBullet(3)); break;
case 'E': sb.append(getBullet(4)); break;
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine4(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case '6': sb.append(getBullet(1)); break;
case '7': sb.append(getBullet(2)); break;
case '8': sb.append(getBullet(3)); break;
case '9': sb.append(getBullet(4)); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine5(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case '0': sb.append(" " + theta + " "); break;
case '1': sb.append(getBullet(1)); break;
case '2': sb.append(getBullet(2)); break;
case '3': sb.append(getBullet(3)); break;
case '4': sb.append(getBullet(4)); break;
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine6(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxLL);
}
for ( int j = 0 ; j < 4 ; j++ ) {
sb.append(boxHorz);
}
sb.append(i < chars.length-1 ? boxTeeLow : boxLR);
}
System.out.println(sb.toString());
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import "fmt"
var (
a [17][17]int
idx [4]int
)
func findGroup(ctype, min, max, depth int) bool {
if depth == 4 {
cs := ""
if ctype == 0 {
cs = "un"
}
fmt.Printf("Totally %sconnected group:", cs)
for i := 0; i < 4; i++ {
fmt.Printf(" %d", idx[i])
}
fmt.Println()
return true
}
for i := min; i < max; i++ {
n := 0
for ; n < depth; n++ {
if a[idx[n]][i] != ctype {
break
}
}
if n == depth {
idx[n] = i
if findGroup(ctype, 1, max, depth+1) {
return true
}
}
}
return false
}
func main() {
const mark = "01-"
for i := 0; i < 17; i++ {
a[i][i] = 2
}
for k := 1; k <= 8; k <<= 1 {
for i := 0; i < 17; i++ {
j := (i + k) % 17
a[i][j], a[j][i] = 1, 1
}
}
for i := 0; i < 17; i++ {
for j := 0; j < 17; j++ {
fmt.Printf("%c ", mark[a[i][j]])
}
fmt.Println()
}
for i := 0; i < 17; i++ {
idx[0] = i
if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {
fmt.Println("No good.")
return
}
}
fmt.Println("All good.")
}
| import java.util.Arrays;
import java.util.stream.IntStream;
public class RamseysTheorem {
static char[][] createMatrix() {
String r = "-" + Integer.toBinaryString(53643);
int len = r.length();
return IntStream.range(0, len)
.mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))
.map(String::toCharArray)
.toArray(char[][]::new);
}
static String ramseyCheck(char[][] mat) {
int len = mat.length;
char[] connectivity = "------".toCharArray();
for (int a = 0; a < len; a++) {
for (int b = 0; b < len; b++) {
if (a == b)
continue;
connectivity[0] = mat[a][b];
for (int c = 0; c < len; c++) {
if (a == c || b == c)
continue;
connectivity[1] = mat[a][c];
connectivity[2] = mat[b][c];
for (int d = 0; d < len; d++) {
if (a == d || b == d || c == d)
continue;
connectivity[3] = mat[a][d];
connectivity[4] = mat[b][d];
connectivity[5] = mat[c][d];
String conn = new String(connectivity);
if (conn.indexOf('0') == -1)
return String.format("Fail, found wholly connected: "
+ "%d %d %d %d", a, b, c, d);
else if (conn.indexOf('1') == -1)
return String.format("Fail, found wholly unconnected: "
+ "%d %d %d %d", a, b, c, d);
}
}
}
}
return "Satisfies Ramsey condition.";
}
public static void main(String[] a) {
char[][] mat = createMatrix();
for (char[] s : mat)
System.out.println(Arrays.toString(s));
System.out.println(ramseyCheck(mat));
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
var (
a [17][17]int
idx [4]int
)
func findGroup(ctype, min, max, depth int) bool {
if depth == 4 {
cs := ""
if ctype == 0 {
cs = "un"
}
fmt.Printf("Totally %sconnected group:", cs)
for i := 0; i < 4; i++ {
fmt.Printf(" %d", idx[i])
}
fmt.Println()
return true
}
for i := min; i < max; i++ {
n := 0
for ; n < depth; n++ {
if a[idx[n]][i] != ctype {
break
}
}
if n == depth {
idx[n] = i
if findGroup(ctype, 1, max, depth+1) {
return true
}
}
}
return false
}
func main() {
const mark = "01-"
for i := 0; i < 17; i++ {
a[i][i] = 2
}
for k := 1; k <= 8; k <<= 1 {
for i := 0; i < 17; i++ {
j := (i + k) % 17
a[i][j], a[j][i] = 1, 1
}
}
for i := 0; i < 17; i++ {
for j := 0; j < 17; j++ {
fmt.Printf("%c ", mark[a[i][j]])
}
fmt.Println()
}
for i := 0; i < 17; i++ {
idx[0] = i
if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {
fmt.Println("No good.")
return
}
}
fmt.Println("All good.")
}
| import java.util.Arrays;
import java.util.stream.IntStream;
public class RamseysTheorem {
static char[][] createMatrix() {
String r = "-" + Integer.toBinaryString(53643);
int len = r.length();
return IntStream.range(0, len)
.mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))
.map(String::toCharArray)
.toArray(char[][]::new);
}
static String ramseyCheck(char[][] mat) {
int len = mat.length;
char[] connectivity = "------".toCharArray();
for (int a = 0; a < len; a++) {
for (int b = 0; b < len; b++) {
if (a == b)
continue;
connectivity[0] = mat[a][b];
for (int c = 0; c < len; c++) {
if (a == c || b == c)
continue;
connectivity[1] = mat[a][c];
connectivity[2] = mat[b][c];
for (int d = 0; d < len; d++) {
if (a == d || b == d || c == d)
continue;
connectivity[3] = mat[a][d];
connectivity[4] = mat[b][d];
connectivity[5] = mat[c][d];
String conn = new String(connectivity);
if (conn.indexOf('0') == -1)
return String.format("Fail, found wholly connected: "
+ "%d %d %d %d", a, b, c, d);
else if (conn.indexOf('1') == -1)
return String.format("Fail, found wholly unconnected: "
+ "%d %d %d %d", a, b, c, d);
}
}
}
}
return "Satisfies Ramsey condition.";
}
public static void main(String[] a) {
char[][] mat = createMatrix();
for (char[] s : mat)
System.out.println(Arrays.toString(s));
System.out.println(ramseyCheck(mat));
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"fmt"
"github.com/go-vgo/robotgo"
)
func main() {
w, h := robotgo.GetScreenSize()
fmt.Printf("Screen size: %d x %d\n", w, h)
fpid, err := robotgo.FindIds("firefox")
if err == nil && len(fpid) > 0 {
pid := fpid[0]
robotgo.ActivePID(pid)
robotgo.MaxWindow(pid)
_, _, w, h = robotgo.GetBounds(pid)
fmt.Printf("Max usable : %d x %d\n", w, h)
}
}
| import java.awt.*;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
Test() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
System.out.println("Physical screen size: " + screenSize);
Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());
System.out.println("Insets: " + insets);
screenSize.width -= (insets.left + insets.right);
screenSize.height -= (insets.top + insets.bottom);
System.out.println("Max available: " + screenSize);
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"fmt"
"math"
"strings"
)
func main() {
for _, n := range [...]int64{
0, 4, 6, 11, 13, 75, 100, 337, -164,
math.MaxInt64,
} {
fmt.Println(fourIsMagic(n))
}
}
func fourIsMagic(n int64) string {
s := say(n)
s = strings.ToUpper(s[:1]) + s[1:]
t := s
for n != 4 {
n = int64(len(s))
s = say(n)
t += " is " + s + ", " + s
}
t += " is magic."
return t
}
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
}
| public class FourIsMagic {
public static void main(String[] args) {
for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {
String magic = fourIsMagic(n);
System.out.printf("%d = %s%n", n, toSentence(magic));
}
}
private static final String toSentence(String s) {
return s.substring(0,1).toUpperCase() + s.substring(1) + ".";
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String fourIsMagic(long n) {
if ( n == 4 ) {
return numToString(n) + " is magic";
}
String result = numToString(n);
return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length());
}
private static final String numToString(long n) {
if ( n < 0 ) {
return "negative " + numToString(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : "");
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"log"
"math"
"strings"
)
var error = "Argument must be a numeric literal or a decimal numeric string."
func getNumDecimals(n interface{}) int {
switch v := n.(type) {
case int:
return 0
case float64:
if v == math.Trunc(v) {
return 0
}
s := fmt.Sprintf("%g", v)
return len(strings.Split(s, ".")[1])
case string:
if v == "" {
log.Fatal(error)
}
if v[0] == '+' || v[0] == '-' {
v = v[1:]
}
for _, c := range v {
if strings.IndexRune("0123456789.", c) == -1 {
log.Fatal(error)
}
}
s := strings.Split(v, ".")
ls := len(s)
if ls == 1 {
return 0
} else if ls == 2 {
return len(s[1])
} else {
log.Fatal("Too many decimal points")
}
default:
log.Fatal(error)
}
return 0
}
func main() {
var a = []interface{}{12, 12.345, 12.345555555555, "12.3450", "12.34555555555555555555", 12.345e53}
for _, n := range a {
d := getNumDecimals(n)
switch v := n.(type) {
case string:
fmt.Printf("%q has %d decimals\n", v, d)
case float32, float64:
fmt.Printf("%g has %d decimals\n", v, d)
default:
fmt.Printf("%d has %d decimals\n", v, d)
}
}
}
| public static int findNumOfDec(double x){
String str = String.valueOf(x);
if(str.endsWith(".0")) return 0;
else return (str.substring(str.indexOf('.')).length() - 1);
}
|
Write the same algorithm in Java as shown in this Go implementation. | const (
apple = iota
banana
cherry
)
| enum Fruits{
APPLE, BANANA, CHERRY
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"math/big"
)
const branches = 4
const nMax = 500
var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)
func tree(br, n, l, sum int, cnt *big.Int) {
for b := br + 1; b <= branches; b++ {
sum += n
if sum > nMax {
return
}
if l*2 >= sum && b >= branches {
return
}
if b == br+1 {
c[br].Mul(&rooted[n], cnt)
} else {
tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
c[br].Mul(&c[br], tmp)
c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
}
if l*2 < sum {
unrooted[sum].Add(&unrooted[sum], &c[br])
}
if b < branches {
rooted[sum].Add(&rooted[sum], &c[br])
}
for m := n - 1; m > 0; m-- {
tree(b, m, l, sum, &c[br])
}
}
}
func bicenter(s int) {
if s&1 == 0 {
tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
unrooted[s].Add(&unrooted[s], tmp)
}
}
func main() {
rooted[0].SetInt64(1)
rooted[1].SetInt64(1)
unrooted[0].SetInt64(1)
unrooted[1].SetInt64(1)
for n := 1; n <= nMax; n++ {
tree(0, n, n, 1, big.NewInt(1))
bicenter(n)
fmt.Printf("%d: %d\n", n, &unrooted[n])
}
}
| import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"math/big"
)
const branches = 4
const nMax = 500
var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)
func tree(br, n, l, sum int, cnt *big.Int) {
for b := br + 1; b <= branches; b++ {
sum += n
if sum > nMax {
return
}
if l*2 >= sum && b >= branches {
return
}
if b == br+1 {
c[br].Mul(&rooted[n], cnt)
} else {
tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
c[br].Mul(&c[br], tmp)
c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
}
if l*2 < sum {
unrooted[sum].Add(&unrooted[sum], &c[br])
}
if b < branches {
rooted[sum].Add(&rooted[sum], &c[br])
}
for m := n - 1; m > 0; m-- {
tree(b, m, l, sum, &c[br])
}
}
}
func bicenter(s int) {
if s&1 == 0 {
tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
unrooted[s].Add(&unrooted[s], tmp)
}
}
func main() {
rooted[0].SetInt64(1)
rooted[1].SetInt64(1)
unrooted[0].SetInt64(1)
unrooted[1].SetInt64(1)
for n := 1; n <= nMax; n++ {
tree(0, n, n, 1, big.NewInt(1))
bicenter(n)
fmt.Printf("%d: %d\n", n, &unrooted[n])
}
}
| import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"math/big"
)
const branches = 4
const nMax = 500
var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)
func tree(br, n, l, sum int, cnt *big.Int) {
for b := br + 1; b <= branches; b++ {
sum += n
if sum > nMax {
return
}
if l*2 >= sum && b >= branches {
return
}
if b == br+1 {
c[br].Mul(&rooted[n], cnt)
} else {
tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
c[br].Mul(&c[br], tmp)
c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
}
if l*2 < sum {
unrooted[sum].Add(&unrooted[sum], &c[br])
}
if b < branches {
rooted[sum].Add(&rooted[sum], &c[br])
}
for m := n - 1; m > 0; m-- {
tree(b, m, l, sum, &c[br])
}
}
}
func bicenter(s int) {
if s&1 == 0 {
tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
unrooted[s].Add(&unrooted[s], tmp)
}
}
func main() {
rooted[0].SetInt64(1)
rooted[1].SetInt64(1)
unrooted[0].SetInt64(1)
unrooted[1].SetInt64(1)
for n := 1; n <= nMax; n++ {
tree(0, n, n, 1, big.NewInt(1))
bicenter(n)
fmt.Printf("%d: %d\n", n, &unrooted[n])
}
}
| import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1)
dc.Clear()
for i := 0; i <= 5; i++ {
index := (i * 2) % 5
p := points[index]
dc.LineTo(p.X, p.Y)
}
dc.SetHexColor("#6495ED")
dc.SetFillRule(gg.FillRuleWinding)
dc.FillPreserve()
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(5)
dc.Stroke()
dc.SavePNG("pentagram.png")
}
| import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill(p);
g.setColor(stroke);
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pentagram");
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1)
dc.Clear()
for i := 0; i <= 5; i++ {
index := (i * 2) % 5
p := points[index]
dc.LineTo(p.X, p.Y)
}
dc.SetHexColor("#6495ED")
dc.SetFillRule(gg.FillRuleWinding)
dc.FillPreserve()
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(5)
dc.Stroke()
dc.SavePNG("pentagram.png")
}
| import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill(p);
g.setColor(stroke);
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pentagram");
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func parseIPPort(address string) (net.IP, *uint64, error) {
ip := net.ParseIP(address)
if ip != nil {
return ip, nil, nil
}
host, portStr, err := net.SplitHostPort(address)
if err != nil {
return nil, nil, fmt.Errorf("splithostport failed: %w", err)
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse port: %w", err)
}
ip = net.ParseIP(host)
if ip == nil {
return nil, nil, fmt.Errorf("failed to parse ip address")
}
return ip, &port, nil
}
func ipVersion(ip net.IP) int {
if ip.To4() == nil {
return 6
}
return 4
}
func main() {
testCases := []string{
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:443",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80",
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
writeTSV := func(w io.Writer, args ...interface{}) {
fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...)
fmt.Fprintf(w, "\n")
}
writeTSV(w, "Input", "Address", "Space", "Port")
for _, addr := range testCases {
ip, port, err := parseIPPort(addr)
if err != nil {
panic(err)
}
portStr := "n/a"
if port != nil {
portStr = fmt.Sprint(*port)
}
ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip))
writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)
}
w.Flush()
}
| import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParseIPAddress {
public static void main(String[] args) {
String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"};
System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port");
for ( String ip : tests ) {
try {
String [] parsed = parseIP(ip);
System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]);
}
catch (IllegalArgumentException e) {
System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage());
}
}
}
private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$");
private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$");
private static String ipv6Pattern;
static {
ipv6Pattern = "^\\[{0,1}";
for ( int i = 1 ; i <= 7 ; i ++ ) {
ipv6Pattern += "([0-9a-f]+):";
}
ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$";
}
private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);
private static String[] parseIP(String ip) {
String hex = "";
String port = "";
Matcher ipv4Matcher = IPV4_PAT.matcher(ip);
if ( ipv4Matcher.matches() ) {
for ( int i = 1 ; i <= 4 ; i++ ) {
hex += toHex4(ipv4Matcher.group(i));
}
if ( ipv4Matcher.group(5) != null ) {
port = ipv4Matcher.group(5);
}
return new String[] {hex, port};
}
Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);
if ( ipv6DoubleColonMatcher.matches() ) {
String p1 = ipv6DoubleColonMatcher.group(1);
if ( p1.isEmpty() ) {
p1 = "0";
}
String p2 = ipv6DoubleColonMatcher.group(2);
if ( p2.isEmpty() ) {
p2 = "0";
}
ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;
if ( ipv6DoubleColonMatcher.group(3) != null ) {
ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3);
}
}
Matcher ipv6Matcher = IPV6_PAT.matcher(ip);
if ( ipv6Matcher.matches() ) {
for ( int i = 1 ; i <= 8 ; i++ ) {
hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0");
}
if ( ipv6Matcher.group(9) != null ) {
port = ipv6Matcher.group(9);
}
return new String[] {hex, port};
}
throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip);
}
private static int numCount(String s) {
return s.split(":").length;
}
private static String getZero(int count) {
StringBuilder sb = new StringBuilder();
sb.append(":");
while ( count > 0 ) {
sb.append("0:");
count--;
}
return sb.toString();
}
private static String toHex4(String s) {
int val = Integer.parseInt(s);
if ( val < 0 || val > 255 ) {
throw new IllegalArgumentException("ERROR 101: Invalid value : " + s);
}
return String.format("%2s", Integer.toHexString(val)).replace(" ", "0");
}
private static String toHex6(String s) {
int val = Integer.parseInt(s, 16);
if ( val < 0 || val > 65536 ) {
throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s);
}
return s;
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
type Item struct {
Name string
Value int
Weight, Volume float64
}
type Result struct {
Counts []int
Sum int
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func Knapsack(items []Item, weight, volume float64) (best Result) {
if len(items) == 0 {
return
}
n := len(items) - 1
maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))
for count := 0; count <= maxCount; count++ {
sol := Knapsack(items[:n],
weight-float64(count)*items[n].Weight,
volume-float64(count)*items[n].Volume)
sol.Sum += items[n].Value * count
if sol.Sum > best.Sum {
sol.Counts = append(sol.Counts, count)
best = sol
}
}
return
}
func main() {
items := []Item{
{"Panacea", 3000, 0.3, 0.025},
{"Ichor", 1800, 0.2, 0.015},
{"Gold", 2500, 2.0, 0.002},
}
var sumCount, sumValue int
var sumWeight, sumVolume float64
result := Knapsack(items, 25, 0.25)
for i := range result.Counts {
fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n",
items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),
items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])
sumCount += result.Counts[i]
sumValue += items[i].Value * result.Counts[i]
sumWeight += items[i].Weight * float64(result.Counts[i])
sumVolume += items[i].Volume * float64(result.Counts[i])
}
fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n",
sumCount, sumWeight, sumVolume, sumValue)
}
| package hu.pj.alg;
import hu.pj.obj.Item;
import java.text.*;
public class UnboundedKnapsack {
protected Item [] items = {
new Item("panacea", 3000, 0.3, 0.025),
new Item("ichor" , 1800, 0.2, 0.015),
new Item("gold" , 2500, 2.0, 0.002)
};
protected final int n = items.length;
protected Item sack = new Item("sack" , 0, 25.0, 0.250);
protected Item best = new Item("best" , 0, 0.0, 0.000);
protected int [] maxIt = new int [n];
protected int [] iIt = new int [n];
protected int [] bestAm = new int [n];
public UnboundedKnapsack() {
for (int i = 0; i < n; i++) {
maxIt [i] = Math.min(
(int)(sack.getWeight() / items[i].getWeight()),
(int)(sack.getVolume() / items[i].getVolume())
);
}
calcWithRecursion(0);
NumberFormat nf = NumberFormat.getInstance();
System.out.println("Maximum value achievable is: " + best.getValue());
System.out.print("This is achieved by carrying (one solution): ");
for (int i = 0; i < n; i++) {
System.out.print(bestAm[i] + " " + items[i].getName() + ", ");
}
System.out.println();
System.out.println("The weight to carry is: " + nf.format(best.getWeight()) +
" and the volume used is: " + nf.format(best.getVolume())
);
}
public void calcWithRecursion(int item) {
for (int i = 0; i <= maxIt[item]; i++) {
iIt[item] = i;
if (item < n-1) {
calcWithRecursion(item+1);
} else {
int currVal = 0;
double currWei = 0.0;
double currVol = 0.0;
for (int j = 0; j < n; j++) {
currVal += iIt[j] * items[j].getValue();
currWei += iIt[j] * items[j].getWeight();
currVol += iIt[j] * items[j].getVolume();
}
if (currVal > best.getValue()
&&
currWei <= sack.getWeight()
&&
currVol <= sack.getVolume()
)
{
best.setValue (currVal);
best.setWeight(currWei);
best.setVolume(currVol);
for (int j = 0; j < n; j++) bestAm[j] = iIt[j];
}
}
}
}
public static void main(String[] args) {
new UnboundedKnapsack();
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
func main() {
log.SetFlags(0)
log.SetPrefix("textonyms: ")
wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
t := NewTextonym(phoneMap)
_, err := ReadFromFile(t, *wordlist)
if err != nil {
log.Fatal(err)
}
t.Report(os.Stdout, *wordlist)
}
var phoneMap = map[byte][]rune{
'2': []rune("ABC"),
'3': []rune("DEF"),
'4': []rune("GHI"),
'5': []rune("JKL"),
'6': []rune("MNO"),
'7': []rune("PQRS"),
'8': []rune("TUV"),
'9': []rune("WXYZ"),
}
func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
n, err := r.ReadFrom(f)
if cerr := f.Close(); err == nil && cerr != nil {
err = cerr
}
return n, err
}
type Textonym struct {
numberMap map[string][]string
letterMap map[rune]byte
count int
textonyms int
}
func NewTextonym(dm map[byte][]rune) *Textonym {
lm := make(map[rune]byte, 26)
for d, ll := range dm {
for _, l := range ll {
lm[l] = d
}
}
return &Textonym{letterMap: lm}
}
func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {
t.numberMap = make(map[string][]string)
buf := make([]byte, 0, 32)
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
scan:
for sc.Scan() {
buf = buf[:0]
word := sc.Text()
n += int64(len(word)) + 1
for _, r := range word {
d, ok := t.letterMap[unicode.ToUpper(r)]
if !ok {
continue scan
}
buf = append(buf, d)
}
num := string(buf)
t.numberMap[num] = append(t.numberMap[num], word)
t.count++
if len(t.numberMap[num]) == 2 {
t.textonyms++
}
}
return n, sc.Err()
}
func (t *Textonym) Most() (most int, subset map[string][]string) {
for k, v := range t.numberMap {
switch {
case len(v) > most:
subset = make(map[string][]string)
most = len(v)
fallthrough
case len(v) == most:
subset[k] = v
}
}
return most, subset
}
func (t *Textonym) Report(w io.Writer, name string) {
fmt.Fprintf(w, `
There are %v words in %q which can be represented by the digit key mapping.
They require %v digit combinations to represent them.
%v digit combinations represent Textonyms.
`,
t.count, name, len(t.numberMap), t.textonyms)
n, sub := t.Most()
fmt.Fprintln(w, "\nThe numbers mapping to the most words map to",
n, "words each:")
for k, v := range sub {
fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", "))
}
}
| import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
public class RTextonyms {
private static final Map<Character, Character> mapping;
private int total, elements, textonyms, max_found;
private String filename, mappingResult;
private Vector<String> max_strings;
private Map<String, Vector<String>> values;
static {
mapping = new HashMap<Character, Character>();
mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');
mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');
mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');
mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');
mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');
mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');
mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');
mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');
}
public RTextonyms(String filename) {
this.filename = filename;
this.total = this.elements = this.textonyms = this.max_found = 0;
this.values = new HashMap<String, Vector<String>>();
this.max_strings = new Vector<String>();
return;
}
public void add(String line) {
String mapping = "";
total++;
if (!get_mapping(line)) {
return;
}
mapping = mappingResult;
if (values.get(mapping) == null) {
values.put(mapping, new Vector<String>());
}
int num_strings;
num_strings = values.get(mapping).size();
textonyms += num_strings == 1 ? 1 : 0;
elements++;
if (num_strings > max_found) {
max_strings.clear();
max_strings.add(mapping);
max_found = num_strings;
}
else if (num_strings == max_found) {
max_strings.add(mapping);
}
values.get(mapping).add(line);
return;
}
public void results() {
System.out.printf("Read %,d words from %s%n%n", total, filename);
System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements,
filename);
System.out.printf("They require %,d digit combinations to represent them.%n", values.size());
System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms);
System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1);
for (String key : max_strings) {
System.out.printf("%16s maps to: %s%n", key, values.get(key).toString());
}
System.out.println();
return;
}
public void match(String key) {
Vector<String> match;
match = values.get(key);
if (match == null) {
System.out.printf("Key %s not found%n", key);
}
else {
System.out.printf("Key %s matches: %s%n", key, match.toString());
}
return;
}
private boolean get_mapping(String line) {
mappingResult = line;
StringBuilder mappingBuilder = new StringBuilder();
for (char cc : line.toCharArray()) {
if (Character.isAlphabetic(cc)) {
mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));
}
else if (Character.isDigit(cc)) {
mappingBuilder.append(cc);
}
else {
return false;
}
}
mappingResult = mappingBuilder.toString();
return true;
}
public static void main(String[] args) {
String filename;
if (args.length > 0) {
filename = args[0];
}
else {
filename = "./unixdict.txt";
}
RTextonyms tc;
tc = new RTextonyms(filename);
Path fp = Paths.get(filename);
try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {
while (fs.hasNextLine()) {
tc.add(fs.nextLine());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
List<String> numbers = Arrays.asList(
"001", "228", "27484247", "7244967473642",
"."
);
tc.results();
for (String number : numbers) {
if (number.equals(".")) {
System.out.println();
}
else {
tc.match(number);
}
}
return;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. |
package astar
import "container/heap"
type Node interface {
To() []Arc
Heuristic(from Node) int
}
type Arc struct {
To Node
Cost int
}
type rNode struct {
n Node
from Node
l int
g int
f int
fx int
}
type openHeap []*rNode
func Route(start, end Node) (route []Node, cost int) {
cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}
r := map[Node]*rNode{start: cr}
oh := openHeap{cr}
for len(oh) > 0 {
bestRoute := heap.Pop(&oh).(*rNode)
bestNode := bestRoute.n
if bestNode == end {
cost = bestRoute.g
route = make([]Node, bestRoute.l)
for i := len(route) - 1; i >= 0; i-- {
route[i] = bestRoute.n
bestRoute = r[bestRoute.from]
}
return
}
l := bestRoute.l + 1
for _, to := range bestNode.To() {
g := bestRoute.g + to.Cost
if alt, ok := r[to.To]; !ok {
alt = &rNode{n: to.To, from: bestNode, l: l,
g: g, f: g + end.Heuristic(to.To)}
r[to.To] = alt
heap.Push(&oh, alt)
} else {
if g >= alt.g {
continue
}
alt.from = bestNode
alt.l = l
alt.g = g
alt.f = end.Heuristic(alt.n)
if alt.fx < 0 {
heap.Push(&oh, alt)
} else {
heap.Fix(&oh, alt.fx)
}
}
}
}
return nil, 0
}
func (h openHeap) Len() int { return len(h) }
func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }
func (h openHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].fx = i
h[j].fx = j
}
func (p *openHeap) Push(x interface{}) {
h := *p
fx := len(h)
h = append(h, x.(*rNode))
h[fx].fx = fx
*p = h
}
func (p *openHeap) Pop() interface{} {
h := *p
last := len(h) - 1
*p = h[:last]
h[last].fx = -1
return h[last]
}
| package astar;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
class AStar {
private final List<Node> open;
private final List<Node> closed;
private final List<Node> path;
private final int[][] maze;
private Node now;
private final int xstart;
private final int ystart;
private int xend, yend;
private final boolean diag;
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
AStar(int[][] maze, int xstart, int ystart, boolean diag) {
this.open = new ArrayList<>();
this.closed = new ArrayList<>();
this.path = new ArrayList<>();
this.maze = maze;
this.now = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
this.diag = diag;
}
public List<Node> findPathTo(int xend, int yend) {
this.xend = xend;
this.yend = yend;
this.closed.add(this.now);
addNeigborsToOpenList();
while (this.now.x != this.xend || this.now.y != this.yend) {
if (this.open.isEmpty()) {
return null;
}
this.now = this.open.get(0);
this.open.remove(0);
this.closed.add(this.now);
addNeigborsToOpenList();
}
this.path.add(0, this.now);
while (this.now.x != this.xstart || this.now.y != this.ystart) {
this.now = this.now.parent;
this.path.add(0, this.now);
}
return this.path;
}
public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){
Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();
if(maze[stateNode.getR()][stateNode.getC()] == 2){
if(isNodeILegal(stateNode, stateNode.expandDirection())){
exploreNodes.add(stateNode.expandDirection());
}
}
public void AStarSearch(){
this.start.setCostToGoal(this.start.calculateCost(this.goal));
this.start.setPathCost(0);
this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());
Mazecoord intialNode = this.start;
Mazecoord stateNode = intialNode;
frontier.add(intialNode);
while (true){
if(frontier.isEmpty()){
System.out.println("fail");
System.out.println(explored.size());
System.exit(-1);
}
}
public int calculateCost(Mazecoord goal){
int rState = this.getR();
int rGoal = goal.getR();
int diffR = rState - rGoal;
int diffC = this.getC() - goal.getC();
if(diffR * diffC > 0) {
return Math.abs(diffR) + Math.abs(diffC);
} else {
return Math.max(Math.abs(diffR), Math.abs(diffC));
}
}
public Coord getFather(){
return this.father;
}
public void setFather(Mazecoord node){
this.father = node;
}
public int getAStartCost() {
return AStartCost;
}
public void setAStartCost(int aStartCost) {
AStartCost = aStartCost;
}
public int getCostToGoal() {
return costToGoal;
}
public void setCostToGoal(int costToGoal) {
this.costToGoal = costToGoal;
}
private double distance(int dx, int dy) {
if (this.diag) {
return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend);
} else {
return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend);
}
}
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (!this.diag && x != 0 && y != 0) {
continue;
}
node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));
if ((x != 0 || y != 0)
&& this.now.x + x >= 0 && this.now.x + x < this.maze[0].length
&& this.now.y + y >= 0 && this.now.y + y < this.maze.length
&& this.maze[this.now.y + y][this.now.x + x] != -1
&& !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) {
node.g = node.parent.g + 1.;
node.g += maze[this.now.y + y][this.now.x + x];
this.open.add(node);
}
}
}
Collections.sort(this.open);
}
public static void main(String[] args) {
int[][] maze = {
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
};
AStar as = new AStar(maze, 0, 0, true);
List<Node> path = as.findPathTo(7, 7);
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
maze[n.y][n.x] = -1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : maze) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
case 0:
System.out.print("_");
break;
case -1:
System.out.print("*");
break;
default:
System.out.print("#");
}
}
System.out.println();
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. |
package astar
import "container/heap"
type Node interface {
To() []Arc
Heuristic(from Node) int
}
type Arc struct {
To Node
Cost int
}
type rNode struct {
n Node
from Node
l int
g int
f int
fx int
}
type openHeap []*rNode
func Route(start, end Node) (route []Node, cost int) {
cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}
r := map[Node]*rNode{start: cr}
oh := openHeap{cr}
for len(oh) > 0 {
bestRoute := heap.Pop(&oh).(*rNode)
bestNode := bestRoute.n
if bestNode == end {
cost = bestRoute.g
route = make([]Node, bestRoute.l)
for i := len(route) - 1; i >= 0; i-- {
route[i] = bestRoute.n
bestRoute = r[bestRoute.from]
}
return
}
l := bestRoute.l + 1
for _, to := range bestNode.To() {
g := bestRoute.g + to.Cost
if alt, ok := r[to.To]; !ok {
alt = &rNode{n: to.To, from: bestNode, l: l,
g: g, f: g + end.Heuristic(to.To)}
r[to.To] = alt
heap.Push(&oh, alt)
} else {
if g >= alt.g {
continue
}
alt.from = bestNode
alt.l = l
alt.g = g
alt.f = end.Heuristic(alt.n)
if alt.fx < 0 {
heap.Push(&oh, alt)
} else {
heap.Fix(&oh, alt.fx)
}
}
}
}
return nil, 0
}
func (h openHeap) Len() int { return len(h) }
func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }
func (h openHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].fx = i
h[j].fx = j
}
func (p *openHeap) Push(x interface{}) {
h := *p
fx := len(h)
h = append(h, x.(*rNode))
h[fx].fx = fx
*p = h
}
func (p *openHeap) Pop() interface{} {
h := *p
last := len(h) - 1
*p = h[:last]
h[last].fx = -1
return h[last]
}
| package astar;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
class AStar {
private final List<Node> open;
private final List<Node> closed;
private final List<Node> path;
private final int[][] maze;
private Node now;
private final int xstart;
private final int ystart;
private int xend, yend;
private final boolean diag;
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
AStar(int[][] maze, int xstart, int ystart, boolean diag) {
this.open = new ArrayList<>();
this.closed = new ArrayList<>();
this.path = new ArrayList<>();
this.maze = maze;
this.now = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
this.diag = diag;
}
public List<Node> findPathTo(int xend, int yend) {
this.xend = xend;
this.yend = yend;
this.closed.add(this.now);
addNeigborsToOpenList();
while (this.now.x != this.xend || this.now.y != this.yend) {
if (this.open.isEmpty()) {
return null;
}
this.now = this.open.get(0);
this.open.remove(0);
this.closed.add(this.now);
addNeigborsToOpenList();
}
this.path.add(0, this.now);
while (this.now.x != this.xstart || this.now.y != this.ystart) {
this.now = this.now.parent;
this.path.add(0, this.now);
}
return this.path;
}
public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){
Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();
if(maze[stateNode.getR()][stateNode.getC()] == 2){
if(isNodeILegal(stateNode, stateNode.expandDirection())){
exploreNodes.add(stateNode.expandDirection());
}
}
public void AStarSearch(){
this.start.setCostToGoal(this.start.calculateCost(this.goal));
this.start.setPathCost(0);
this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());
Mazecoord intialNode = this.start;
Mazecoord stateNode = intialNode;
frontier.add(intialNode);
while (true){
if(frontier.isEmpty()){
System.out.println("fail");
System.out.println(explored.size());
System.exit(-1);
}
}
public int calculateCost(Mazecoord goal){
int rState = this.getR();
int rGoal = goal.getR();
int diffR = rState - rGoal;
int diffC = this.getC() - goal.getC();
if(diffR * diffC > 0) {
return Math.abs(diffR) + Math.abs(diffC);
} else {
return Math.max(Math.abs(diffR), Math.abs(diffC));
}
}
public Coord getFather(){
return this.father;
}
public void setFather(Mazecoord node){
this.father = node;
}
public int getAStartCost() {
return AStartCost;
}
public void setAStartCost(int aStartCost) {
AStartCost = aStartCost;
}
public int getCostToGoal() {
return costToGoal;
}
public void setCostToGoal(int costToGoal) {
this.costToGoal = costToGoal;
}
private double distance(int dx, int dy) {
if (this.diag) {
return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend);
} else {
return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend);
}
}
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (!this.diag && x != 0 && y != 0) {
continue;
}
node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));
if ((x != 0 || y != 0)
&& this.now.x + x >= 0 && this.now.x + x < this.maze[0].length
&& this.now.y + y >= 0 && this.now.y + y < this.maze.length
&& this.maze[this.now.y + y][this.now.x + x] != -1
&& !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) {
node.g = node.parent.g + 1.;
node.g += maze[this.now.y + y][this.now.x + x];
this.open.add(node);
}
}
}
Collections.sort(this.open);
}
public static void main(String[] args) {
int[][] maze = {
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
};
AStar as = new AStar(maze, 0, 0, true);
List<Node> path = as.findPathTo(7, 7);
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
maze[n.y][n.x] = -1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : maze) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
case 0:
System.out.print("_");
break;
case -1:
System.out.print("*");
break;
default:
System.out.print("#");
}
}
System.out.println();
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(strings.TrimSpace(scanner.Text()))
if len(word) >= 3 {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func rotate(runes []rune) {
first := runes[0]
copy(runes, runes[1:])
runes[len(runes)-1] = first
}
func main() {
dicts := []string{"mit_10000.txt", "unixdict.txt"}
for _, dict := range dicts {
fmt.Printf("Using %s:\n\n", dict)
words := readWords(dict)
n := len(words)
used := make(map[string]bool)
outer:
for _, word := range words {
runes := []rune(word)
variants := []string{word}
for i := 0; i < len(runes)-1; i++ {
rotate(runes)
word2 := string(runes)
if word == word2 || used[word2] {
continue outer
}
ix := sort.SearchStrings(words, word2)
if ix == n || words[ix] != word2 {
continue outer
}
variants = append(variants, word2)
}
for _, variant := range variants {
used[variant] = true
}
fmt.Println(variants)
}
fmt.Println()
}
}
| import java.io.*;
import java.util.*;
public class Teacup {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java Teacup dictionary");
System.exit(1);
}
try {
findTeacupWords(loadDictionary(args[0]));
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
private static Set<String> loadDictionary(String fileName) throws IOException {
Set<String> words = new TreeSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String word;
while ((word = reader.readLine()) != null)
words.add(word);
return words;
}
}
private static void findTeacupWords(Set<String> words) {
List<String> teacupWords = new ArrayList<>();
Set<String> found = new HashSet<>();
for (String word : words) {
int len = word.length();
if (len < 3 || found.contains(word))
continue;
teacupWords.clear();
teacupWords.add(word);
char[] chars = word.toCharArray();
for (int i = 0; i < len - 1; ++i) {
String rotated = new String(rotate(chars));
if (rotated.equals(word) || !words.contains(rotated))
break;
teacupWords.add(rotated);
}
if (teacupWords.size() == len) {
found.addAll(teacupWords);
System.out.print(word);
for (int i = 1; i < len; ++i)
System.out.print(" " + teacupWords.get(i));
System.out.println();
}
}
}
private static char[] rotate(char[] ch) {
char c = ch[0];
System.arraycopy(ch, 1, ch, 0, ch.length - 1);
ch[ch.length - 1] = c;
return ch;
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import "fmt"
type is func() uint64
func newSum() is {
var ms is
ms = func() uint64 {
ms = newSum()
return ms()
}
var msd, d uint64
return func() uint64 {
if d < 9 {
d++
} else {
d = 0
msd = ms()
}
return msd + d
}
}
func newHarshard() is {
i := uint64(0)
sum := newSum()
return func() uint64 {
for i++; i%sum() != 0; i++ {
}
return i
}
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("Gap Index of gap Starting Niven")
fmt.Println("=== ============= ==============")
h := newHarshard()
pg := uint64(0)
pn := h()
for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {
g := n - pn
if g > pg {
fmt.Printf("%3d %13s %14s\n", g, commatize(i), commatize(pn))
pg = g
}
pn = n
}
}
| public class NivenNumberGaps {
public static void main(String[] args) {
long prevGap = 0;
long prevN = 1;
long index = 0;
System.out.println("Gap Gap Index Starting Niven");
for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {
if ( isNiven(n) ) {
index++;
long curGap = n - prevN;
if ( curGap > prevGap ) {
System.out.printf("%3d %,13d %,15d%n", curGap, index, prevN);
prevGap = curGap;
}
prevN = n;
}
}
}
public static boolean isNiven(long n) {
long sum = 0;
long nSave = n;
while ( n > 0 ) {
sum += n % 10;
n /= 10;
}
return nSave % sum == 0;
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"runtime"
)
type point struct {
x, y float64
}
func add(x, y int) int {
result := x + y
debug("x", x)
debug("y", y)
debug("result", result)
debug("result+1", result+1)
return result
}
func debug(s string, x interface{}) {
_, _, lineNo, _ := runtime.Caller(1)
fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x)
}
func main() {
add(2, 7)
b := true
debug("b", b)
s := "Hello"
debug("s", s)
p := point{2, 3}
debug("p", p)
q := &p
debug("q", q)
}
| import java.util.Objects;
public class PrintDebugStatement {
private static void printDebug(String message) {
Objects.requireNonNull(message);
RuntimeException exception = new RuntimeException();
StackTraceElement[] stackTrace = exception.getStackTrace();
StackTraceElement stackTraceElement = stackTrace[1];
String fileName = stackTraceElement.getFileName();
String className = stackTraceElement.getClassName();
String methodName = stackTraceElement.getMethodName();
int lineNumber = stackTraceElement.getLineNumber();
System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message);
}
private static void blah() {
printDebug("Made It!");
}
public static void main(String[] args) {
printDebug("Hello world.");
blah();
Runnable oops = () -> printDebug("oops");
oops.run();
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"github.com/fogleman/gg"
"math"
)
func superEllipse(dc *gg.Context, n float64, a int) {
hw := float64(dc.Width() / 2)
hh := float64(dc.Height() / 2)
y := make([]float64, a+1)
for x := 0; x <= a; x++ {
aa := math.Pow(float64(a), n)
xx := math.Pow(float64(x), n)
y[x] = math.Pow(aa-xx, 1.0/n)
}
for x := a; x >= 0; x-- {
dc.LineTo(hw+float64(x), hh-y[x])
}
for x := 0; x <= a; x++ {
dc.LineTo(hw+float64(x), hh+y[x])
}
for x := a; x >= 0; x-- {
dc.LineTo(hw-float64(x), hh+y[x])
}
for x := 0; x <= a; x++ {
dc.LineTo(hw-float64(x), hh-y[x])
}
dc.SetRGB(1, 1, 1)
dc.Fill()
}
func main() {
dc := gg.NewContext(500, 500)
dc.SetRGB(0, 0, 0)
dc.Clear()
superEllipse(dc, 2.5, 200)
dc.SavePNG("superellipse.png")
}
| import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Dimension(650, 650));
setBackground(Color.white);
setFont(new Font("Serif", Font.PLAIN, 18));
}
void drawGrid(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0xEEEEEE));
int w = getWidth();
int h = getHeight();
int spacing = 25;
for (int i = 0; i < w / spacing; i++) {
g.drawLine(0, i * spacing, w, i * spacing);
g.drawLine(i * spacing, 0, i * spacing, w);
}
g.drawLine(0, h - 1, w, h - 1);
g.setColor(new Color(0xAAAAAA));
g.drawLine(0, w / 2, w, w / 2);
g.drawLine(w / 2, 0, w / 2, w);
}
void drawLegend(Graphics2D g) {
g.setColor(Color.black);
g.setFont(getFont());
g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45);
g.drawString("a = b = 200", getWidth() - 150, 75);
}
void drawEllipse(Graphics2D g) {
final int a = 200;
double[] points = new double[a + 1];
Path2D p = new Path2D.Double();
p.moveTo(a, 0);
for (int x = a; x >= 0; x--) {
points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp);
p.lineTo(x, -points[x]);
}
for (int x = 0; x <= a; x++)
p.lineTo(x, points[x]);
for (int x = a; x >= 0; x--)
p.lineTo(-x, points[x]);
for (int x = 0; x <= a; x++)
p.lineTo(-x, -points[x]);
g.translate(getWidth() / 2, getHeight() / 2);
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0x25B0C4DE, true));
g.fill(p);
g.setColor(new Color(0xB0C4DE));
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
drawGrid(g);
drawLegend(g);
drawEllipse(g);
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
exp = source.getValue() / 2.0;
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Super Ellipse");
f.setResizable(false);
SuperEllipse panel = new SuperEllipse();
f.add(panel, BorderLayout.CENTER);
JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);
exponent.addChangeListener(panel);
exponent.setMajorTickSpacing(1);
exponent.setPaintLabels(true);
exponent.setBackground(Color.white);
exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
Hashtable<Integer, JLabel> labelTable = new Hashtable<>();
for (int i = 1; i < 10; i++)
labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));
exponent.setLabelTable(labelTable);
f.add(exponent, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"github.com/fogleman/gg"
"math"
)
func superEllipse(dc *gg.Context, n float64, a int) {
hw := float64(dc.Width() / 2)
hh := float64(dc.Height() / 2)
y := make([]float64, a+1)
for x := 0; x <= a; x++ {
aa := math.Pow(float64(a), n)
xx := math.Pow(float64(x), n)
y[x] = math.Pow(aa-xx, 1.0/n)
}
for x := a; x >= 0; x-- {
dc.LineTo(hw+float64(x), hh-y[x])
}
for x := 0; x <= a; x++ {
dc.LineTo(hw+float64(x), hh+y[x])
}
for x := a; x >= 0; x-- {
dc.LineTo(hw-float64(x), hh+y[x])
}
for x := 0; x <= a; x++ {
dc.LineTo(hw-float64(x), hh-y[x])
}
dc.SetRGB(1, 1, 1)
dc.Fill()
}
func main() {
dc := gg.NewContext(500, 500)
dc.SetRGB(0, 0, 0)
dc.Clear()
superEllipse(dc, 2.5, 200)
dc.SavePNG("superellipse.png")
}
| import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Dimension(650, 650));
setBackground(Color.white);
setFont(new Font("Serif", Font.PLAIN, 18));
}
void drawGrid(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0xEEEEEE));
int w = getWidth();
int h = getHeight();
int spacing = 25;
for (int i = 0; i < w / spacing; i++) {
g.drawLine(0, i * spacing, w, i * spacing);
g.drawLine(i * spacing, 0, i * spacing, w);
}
g.drawLine(0, h - 1, w, h - 1);
g.setColor(new Color(0xAAAAAA));
g.drawLine(0, w / 2, w, w / 2);
g.drawLine(w / 2, 0, w / 2, w);
}
void drawLegend(Graphics2D g) {
g.setColor(Color.black);
g.setFont(getFont());
g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45);
g.drawString("a = b = 200", getWidth() - 150, 75);
}
void drawEllipse(Graphics2D g) {
final int a = 200;
double[] points = new double[a + 1];
Path2D p = new Path2D.Double();
p.moveTo(a, 0);
for (int x = a; x >= 0; x--) {
points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp);
p.lineTo(x, -points[x]);
}
for (int x = 0; x <= a; x++)
p.lineTo(x, points[x]);
for (int x = a; x >= 0; x--)
p.lineTo(-x, points[x]);
for (int x = 0; x <= a; x++)
p.lineTo(-x, -points[x]);
g.translate(getWidth() / 2, getHeight() / 2);
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0x25B0C4DE, true));
g.fill(p);
g.setColor(new Color(0xB0C4DE));
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
drawGrid(g);
drawLegend(g);
drawEllipse(g);
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
exp = source.getValue() / 2.0;
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Super Ellipse");
f.setResizable(false);
SuperEllipse panel = new SuperEllipse();
f.add(panel, BorderLayout.CENTER);
JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);
exponent.addChangeListener(panel);
exponent.setMajorTickSpacing(1);
exponent.setPaintLabels(true);
exponent.setBackground(Color.white);
exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
Hashtable<Integer, JLabel> labelTable = new Hashtable<>();
for (int i = 1; i < 10; i++)
labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));
exponent.setLabelTable(labelTable);
f.add(exponent, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"math/rand"
)
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
func ident(n int) []int {
p := make([]int, n)
for i := range p {
p[i] = i
}
return p
}
func MRRank(p []int) (r int) {
p = append([]int{}, p...)
inv := inverse(p)
for i := len(p) - 1; i > 0; i-- {
s := p[i]
p[inv[i]] = s
inv[s] = inv[i]
}
for i := 1; i < len(p); i++ {
r = r*(i+1) + p[i]
}
return
}
func inverse(p []int) []int {
r := make([]int, len(p))
for i, x := range p {
r[x] = i
}
return r
}
func fact(n int) (f int) {
for f = n; n > 2; {
n--
f *= n
}
return
}
func main() {
n := 3
fmt.Println("permutations of", n, "items")
f := fact(n)
for i := 0; i < f; i++ {
p := MRPerm(i, n)
fmt.Println(i, p, MRRank(p))
}
n = 12
fmt.Println("permutations of", n, "items")
f = fact(n)
m := map[int]bool{}
for len(m) < 4 {
r := rand.Intn(f)
if m[r] {
continue
}
m[r] = true
fmt.Println(r, MRPerm(r, n))
}
}
| import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println("n = " + n);
for (int i = 0; i < 5; i++)
{
BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);
rank = rank.mod(factorial);
int[] permutation = getPermutation(n, rank);
System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"math/rand"
)
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
func ident(n int) []int {
p := make([]int, n)
for i := range p {
p[i] = i
}
return p
}
func MRRank(p []int) (r int) {
p = append([]int{}, p...)
inv := inverse(p)
for i := len(p) - 1; i > 0; i-- {
s := p[i]
p[inv[i]] = s
inv[s] = inv[i]
}
for i := 1; i < len(p); i++ {
r = r*(i+1) + p[i]
}
return
}
func inverse(p []int) []int {
r := make([]int, len(p))
for i, x := range p {
r[x] = i
}
return r
}
func fact(n int) (f int) {
for f = n; n > 2; {
n--
f *= n
}
return
}
func main() {
n := 3
fmt.Println("permutations of", n, "items")
f := fact(n)
for i := 0; i < f; i++ {
p := MRPerm(i, n)
fmt.Println(i, p, MRRank(p))
}
n = 12
fmt.Println("permutations of", n, "items")
f = fact(n)
m := map[int]bool{}
for len(m) < 4 {
r := rand.Intn(f)
if m[r] {
continue
}
m[r] = true
fmt.Println(r, MRPerm(r, n))
}
}
| import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println("n = " + n);
for (int i = 0; i < 5; i++)
{
BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);
rank = rank.mod(factorial);
int[] permutation = getPermutation(n, rank);
System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
rf, err := rangeFormat([]int{
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39,
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("range format:", rf)
}
func rangeFormat(a []int) (string, error) {
if len(a) == 0 {
return "", nil
}
var parts []string
for n1 := 0; ; {
n2 := n1 + 1
for n2 < len(a) && a[n2] == a[n2-1]+1 {
n2++
}
s := strconv.Itoa(a[n1])
if n2 == n1+2 {
s += "," + strconv.Itoa(a[n2-1])
} else if n2 > n1+2 {
s += "-" + strconv.Itoa(a[n2-1])
}
parts = append(parts, s)
if n2 == len(a) {
break
}
if a[n2] == a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence repeats value %d", a[n2]))
}
if a[n2] < a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence not ordered: %d < %d", a[n2], a[n2-1]))
}
n1 = n2
}
return strings.Join(parts, ","), nil
}
| public class RangeExtraction {
public static void main(String[] args) {
int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39};
int len = arr.length;
int idx = 0, idx2 = 0;
while (idx < len) {
while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);
if (idx2 - idx > 2) {
System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]);
idx = idx2;
} else {
for (; idx < idx2; idx++)
System.out.printf("%s,", arr[idx]);
}
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import "fmt"
type any = interface{}
func showType(a any) {
switch a.(type) {
case rune:
fmt.Printf("The type of '%c' is %T\n", a, a)
default:
fmt.Printf("The type of '%v' is %T\n", a, a)
}
}
func main() {
values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"}
for _, value := range values {
showType(value)
}
}
| public class TypeDetection {
private static void showType(Object a) {
if (a instanceof Integer) {
System.out.printf("'%s' is an integer\n", a);
} else if (a instanceof Double) {
System.out.printf("'%s' is a double\n", a);
} else if (a instanceof Character) {
System.out.printf("'%s' is a character\n", a);
} else {
System.out.printf("'%s' is some other type\n", a);
}
}
public static void main(String[] args) {
showType(5);
showType(7.5);
showType('d');
showType(true);
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"strconv"
"strings"
)
const t = ` 55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`
func main() {
lines := strings.Split(t, "\n")
f := strings.Fields(lines[len(lines)-1])
d := make([]int, len(f))
var err error
for i, s := range f {
if d[i], err = strconv.Atoi(s); err != nil {
panic(err)
}
}
d1 := d[1:]
var l, r, u int
for row := len(lines) - 2; row >= 0; row-- {
l = d[0]
for i, s := range strings.Fields(lines[row]) {
if u, err = strconv.Atoi(s); err != nil {
panic(err)
}
if r = d1[i]; l > r {
d[i] = u + l
} else {
d[i] = u + r
}
l = r
}
}
fmt.Println(d[0])
}
| import java.nio.file.*;
import static java.util.Arrays.stream;
public class MaxPathSum {
public static void main(String[] args) throws Exception {
int[][] data = Files.lines(Paths.get("triangle.txt"))
.map(s -> stream(s.trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
for (int r = data.length - 1; r > 0; r--)
for (int c = 0; c < data[r].length - 1; c++)
data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);
System.out.println(data[0][0]);
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000`
func main() {
b := wbFromString(in, '1')
b.zhangSuen()
fmt.Println(b)
}
const (
white = 0
black = 1
)
type wbArray [][]byte
func wbFromString(s string, blk byte) wbArray {
lines := strings.Split(s, "\n")[1:]
b := make(wbArray, len(lines))
for i, sl := range lines {
bl := make([]byte, len(sl))
for j := 0; j < len(sl); j++ {
bl[j] = sl[j] & 1
}
b[i] = bl
}
return b
}
var sym = [2]byte{
white: ' ',
black: '#',
}
func (b wbArray) String() string {
b2 := bytes.Join(b, []byte{'\n'})
for i, b1 := range b2 {
if b1 > 1 {
continue
}
b2[i] = sym[b1]
}
return string(b2)
}
var nb = [...][2]int{
2: {-1, 0},
3: {-1, 1},
4: {0, 1},
5: {1, 1},
6: {1, 0},
7: {1, -1},
8: {0, -1},
9: {-1, -1},
}
func (b wbArray) reset(en []int) (rs bool) {
var r, c int
var p [10]byte
readP := func() {
for nx := 1; nx <= 9; nx++ {
n := nb[nx]
p[nx] = b[r+n[0]][c+n[1]]
}
}
shiftRead := func() {
n := nb[3]
p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]
n = nb[4]
p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]
n = nb[5]
p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]
}
countA := func() (ct byte) {
bit := p[9]
for nx := 2; nx <= 9; nx++ {
last := bit
bit = p[nx]
if last == white {
ct += bit
}
}
return ct
}
countB := func() (ct byte) {
for nx := 2; nx <= 9; nx++ {
ct += p[nx]
}
return ct
}
lastRow := len(b) - 1
lastCol := len(b[0]) - 1
mark := make([][]bool, lastRow)
for r = range mark {
mark[r] = make([]bool, lastCol)
}
for r = 1; r < lastRow; r++ {
c = 1
readP()
for {
m := false
if !(p[1] == black) {
goto markDone
}
if b1 := countB(); !(2 <= b1 && b1 <= 6) {
goto markDone
}
if !(countA() == 1) {
goto markDone
}
{
e1, e2 := p[en[1]], p[en[2]]
if !(p[en[0]]&e1&e2 == 0) {
goto markDone
}
if !(e1&e2&p[en[3]] == 0) {
goto markDone
}
}
m = true
rs = true
markDone:
mark[r][c] = m
c++
if c == lastCol {
break
}
shiftRead()
}
}
if rs {
for r = 1; r < lastRow; r++ {
for c = 1; c < lastCol; c++ {
if mark[r][c] {
b[r][c] = white
}
}
}
}
return rs
}
var step1 = []int{2, 4, 6, 8}
var step2 = []int{4, 2, 8, 6}
func (b wbArray) zhangSuen() {
for {
rs1 := b.reset(step1)
rs2 := b.reset(step2)
if !rs1 && !rs2 {
break
}
}
}
| import java.awt.Point;
import java.util.*;
public class ZhangSuen {
final static String[] image = {
" ",
" ################# ############# ",
" ################## ################ ",
" ################### ################## ",
" ######## ####### ################### ",
" ###### ####### ####### ###### ",
" ###### ####### ####### ",
" ################# ####### ",
" ################ ####### ",
" ################# ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ###### ",
" ######## ####### ################### ",
" ######## ####### ###### ################## ###### ",
" ######## ####### ###### ################ ###### ",
" ######## ####### ###### ############# ###### ",
" "};
final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},
{-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};
final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},
{0, 4, 6}}};
static List<Point> toWhite = new ArrayList<>();
static char[][] grid;
public static void main(String[] args) {
grid = new char[image.length][];
for (int r = 0; r < image.length; r++)
grid[r] = image[r].toCharArray();
thinImage();
}
static void thinImage() {
boolean firstStep = false;
boolean hasChanged;
do {
hasChanged = false;
firstStep = !firstStep;
for (int r = 1; r < grid.length - 1; r++) {
for (int c = 1; c < grid[0].length - 1; c++) {
if (grid[r][c] != '#')
continue;
int nn = numNeighbors(r, c);
if (nn < 2 || nn > 6)
continue;
if (numTransitions(r, c) != 1)
continue;
if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))
continue;
toWhite.add(new Point(c, r));
hasChanged = true;
}
}
for (Point p : toWhite)
grid[p.y][p.x] = ' ';
toWhite.clear();
} while (firstStep || hasChanged);
printResult();
}
static int numNeighbors(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')
count++;
return count;
}
static int numTransitions(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {
if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')
count++;
}
return count;
}
static boolean atLeastOneIsWhite(int r, int c, int step) {
int count = 0;
int[][] group = nbrGroups[step];
for (int i = 0; i < 2; i++)
for (int j = 0; j < group[i].length; j++) {
int[] nbr = nbrs[group[i][j]];
if (grid[r + nbr[1]][c + nbr[0]] == ' ') {
count++;
break;
}
}
return count > 1;
}
static void printResult() {
for (char[] row : grid)
System.out.println(row);
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import "fmt"
func main() {
s := []int{1, 2, 2, 3, 4, 4, 5}
for i := 0; i < len(s); i++ {
curr := s[i]
var prev int
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
var prev int
for i := 0; i < len(s); i++ {
curr := s[i]
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
}
| public class VariableDeclarationReset {
public static void main(String[] args) {
int[] s = {1, 2, 2, 3, 4, 4, 5};
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) System.out.println(i);
prev = curr;
}
int gprev = 0;
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) System.out.println(i);
gprev = curr;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"math/big"
)
const (
mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota
mask1, bit1
mask2, bit2
mask3, bit3
mask4, bit4
mask5, bit5
)
func rupb(x uint64) (out int) {
if x == 0 {
return -1
}
if x&^mask5 != 0 {
x >>= bit5
out |= bit5
}
if x&^mask4 != 0 {
x >>= bit4
out |= bit4
}
if x&^mask3 != 0 {
x >>= bit3
out |= bit3
}
if x&^mask2 != 0 {
x >>= bit2
out |= bit2
}
if x&^mask1 != 0 {
x >>= bit1
out |= bit1
}
if x&^mask0 != 0 {
out |= bit0
}
return
}
func rlwb(x uint64) (out int) {
if x == 0 {
return 0
}
if x&mask5 == 0 {
x >>= bit5
out |= bit5
}
if x&mask4 == 0 {
x >>= bit4
out |= bit4
}
if x&mask3 == 0 {
x >>= bit3
out |= bit3
}
if x&mask2 == 0 {
x >>= bit2
out |= bit2
}
if x&mask1 == 0 {
x >>= bit1
out |= bit1
}
if x&mask0 == 0 {
out |= bit0
}
return
}
func rupbBig(x *big.Int) int {
return x.BitLen() - 1
}
func rlwbBig(x *big.Int) int {
if x.BitLen() < 2 {
return 0
}
bit := uint(1)
mask := big.NewInt(1)
var ms []*big.Int
var y, z big.Int
for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {
ms = append(ms, mask)
mask = new(big.Int).Or(mask, &z)
bit <<= 1
}
out := bit
for i := len(ms) - 1; i >= 0; i-- {
bit >>= 1
if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {
out |= bit
}
}
return int(out)
}
func main() {
show()
showBig()
}
func show() {
fmt.Println("uint64:")
fmt.Println("power number rupb rlwb")
const base = 42
n := uint64(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n))
n *= base
}
}
func showBig() {
fmt.Println("\nbig numbers:")
fmt.Println(" power number rupb rlwb")
base := big.NewInt(1302)
n := big.NewInt(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n))
n.Mul(n, base)
}
}
| public class FirstLastBits {
public static int mssb(int x) {
return Integer.highestOneBit(x);
}
public static long mssb(long x) {
return Long.highestOneBit(x);
}
public static int mssb_idx(int x) {
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);
}
public static int mssb_idx(long x) {
return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);
}
public static int mssb_idx(BigInteger x) {
return x.bitLength() - 1;
}
public static int lssb(int x) {
return Integer.lowestOneBit(x);
}
public static long lssb(long x) {
return Long.lowestOneBit(x);
}
public static int lssb_idx(int x) {
return Integer.numberOfTrailingZeros(x);
}
public static int lssb_idx(long x) {
return Long.numberOfTrailingZeros(x);
}
public static int lssb_idx(BigInteger x) {
return x.getLowestSetBit();
}
public static void main(String[] args) {
System.out.println("int:");
int n1 = 1;
for (int i = 0; ; i++, n1 *= 42) {
System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n1, n1,
mssb(n1), mssb_idx(n1),
lssb(n1), lssb_idx(n1));
if (n1 >= Integer.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("long:");
long n2 = 1;
for (int i = 0; ; i++, n2 *= 42) {
System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n",
i, n2, n2,
mssb(n2), mssb_idx(n2),
lssb(n2), lssb_idx(n2));
if (n2 >= Long.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("BigInteger:");
BigInteger n3 = BigInteger.ONE;
BigInteger k = BigInteger.valueOf(1302);
for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {
System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n",
i, n3, n3,
mssb_idx(n3),
lssb_idx(n3));
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"math/big"
)
const (
mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota
mask1, bit1
mask2, bit2
mask3, bit3
mask4, bit4
mask5, bit5
)
func rupb(x uint64) (out int) {
if x == 0 {
return -1
}
if x&^mask5 != 0 {
x >>= bit5
out |= bit5
}
if x&^mask4 != 0 {
x >>= bit4
out |= bit4
}
if x&^mask3 != 0 {
x >>= bit3
out |= bit3
}
if x&^mask2 != 0 {
x >>= bit2
out |= bit2
}
if x&^mask1 != 0 {
x >>= bit1
out |= bit1
}
if x&^mask0 != 0 {
out |= bit0
}
return
}
func rlwb(x uint64) (out int) {
if x == 0 {
return 0
}
if x&mask5 == 0 {
x >>= bit5
out |= bit5
}
if x&mask4 == 0 {
x >>= bit4
out |= bit4
}
if x&mask3 == 0 {
x >>= bit3
out |= bit3
}
if x&mask2 == 0 {
x >>= bit2
out |= bit2
}
if x&mask1 == 0 {
x >>= bit1
out |= bit1
}
if x&mask0 == 0 {
out |= bit0
}
return
}
func rupbBig(x *big.Int) int {
return x.BitLen() - 1
}
func rlwbBig(x *big.Int) int {
if x.BitLen() < 2 {
return 0
}
bit := uint(1)
mask := big.NewInt(1)
var ms []*big.Int
var y, z big.Int
for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {
ms = append(ms, mask)
mask = new(big.Int).Or(mask, &z)
bit <<= 1
}
out := bit
for i := len(ms) - 1; i >= 0; i-- {
bit >>= 1
if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {
out |= bit
}
}
return int(out)
}
func main() {
show()
showBig()
}
func show() {
fmt.Println("uint64:")
fmt.Println("power number rupb rlwb")
const base = 42
n := uint64(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n))
n *= base
}
}
func showBig() {
fmt.Println("\nbig numbers:")
fmt.Println(" power number rupb rlwb")
base := big.NewInt(1302)
n := big.NewInt(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n))
n.Mul(n, base)
}
}
| public class FirstLastBits {
public static int mssb(int x) {
return Integer.highestOneBit(x);
}
public static long mssb(long x) {
return Long.highestOneBit(x);
}
public static int mssb_idx(int x) {
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);
}
public static int mssb_idx(long x) {
return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);
}
public static int mssb_idx(BigInteger x) {
return x.bitLength() - 1;
}
public static int lssb(int x) {
return Integer.lowestOneBit(x);
}
public static long lssb(long x) {
return Long.lowestOneBit(x);
}
public static int lssb_idx(int x) {
return Integer.numberOfTrailingZeros(x);
}
public static int lssb_idx(long x) {
return Long.numberOfTrailingZeros(x);
}
public static int lssb_idx(BigInteger x) {
return x.getLowestSetBit();
}
public static void main(String[] args) {
System.out.println("int:");
int n1 = 1;
for (int i = 0; ; i++, n1 *= 42) {
System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n1, n1,
mssb(n1), mssb_idx(n1),
lssb(n1), lssb_idx(n1));
if (n1 >= Integer.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("long:");
long n2 = 1;
for (int i = 0; ; i++, n2 *= 42) {
System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n",
i, n2, n2,
mssb(n2), mssb_idx(n2),
lssb(n2), lssb_idx(n2));
if (n2 >= Long.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("BigInteger:");
BigInteger n3 = BigInteger.ONE;
BigInteger k = BigInteger.valueOf(1302);
for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {
System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n",
i, n3, n3,
mssb_idx(n3),
lssb_idx(n3));
}
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
func risesEqualsFalls(n int) bool {
if n < 10 {
return true
}
rises := 0
falls := 0
prev := -1
for n > 0 {
d := n % 10
if prev >= 0 {
if d < prev {
rises = rises + 1
} else if d > prev {
falls = falls + 1
}
}
prev = d
n /= 10
}
return rises == falls
}
func main() {
fmt.Println("The first 200 numbers in the sequence are:")
count := 0
n := 1
for {
if risesEqualsFalls(n) {
count++
if count <= 200 {
fmt.Printf("%3d ", n)
if count%20 == 0 {
fmt.Println()
}
}
if count == 1e7 {
fmt.Println("\nThe 10 millionth number in the sequence is ", n)
break
}
}
n++
}
}
| public class EqualRisesFalls {
public static void main(String[] args) {
final int limit1 = 200;
final int limit2 = 10000000;
System.out.printf("The first %d numbers in the sequence are:\n", limit1);
int n = 0;
for (int count = 0; count < limit2; ) {
if (equalRisesAndFalls(++n)) {
++count;
if (count <= limit1)
System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' ');
}
}
System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n);
}
private static boolean equalRisesAndFalls(int n) {
int total = 0;
for (int previousDigit = -1; n > 0; n /= 10) {
int digit = n % 10;
if (previousDigit > digit)
++total;
else if (previousDigit >= 0 && previousDigit < digit)
--total;
previousDigit = digit;
}
return total == 0;
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import (
"github.com/fogleman/gg"
"math"
)
var dc = gg.NewContext(512, 512)
func koch(x1, y1, x2, y2 float64, iter int) {
angle := math.Pi / 3
x3 := (x1*2 + x2) / 3
y3 := (y1*2 + y2) / 3
x4 := (x1 + x2*2) / 3
y4 := (y1 + y2*2) / 3
x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)
y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)
if iter > 0 {
iter--
koch(x1, y1, x3, y3, iter)
koch(x3, y3, x5, y5, iter)
koch(x5, y5, x4, y4, iter)
koch(x4, y4, x2, y2, iter)
} else {
dc.LineTo(x1, y1)
dc.LineTo(x3, y3)
dc.LineTo(x5, y5)
dc.LineTo(x4, y4)
dc.LineTo(x2, y2)
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
koch(100, 100, 400, 400, 4)
dc.SetRGB(0, 0, 1)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("koch.png")
}
| int l = 300;
void setup() {
size(400, 400);
background(0, 0, 255);
stroke(255);
translate(width/2.0, height/2.0);
translate(-l/2.0, l*sqrt(3)/6.0);
for (int i = 1; i <= 3; i++) {
kcurve(0, l);
rotate(radians(120));
translate(-l, 0);
}
}
void kcurve(float x1, float x2) {
float s = (x2-x1)/3;
if (s < 5) {
pushMatrix();
translate(x1, 0);
line(0, 0, s, 0);
line(2*s, 0, 3*s, 0);
translate(s, 0);
rotate(radians(60));
line(0, 0, s, 0);
translate(s, 0);
rotate(radians(-120));
line(0, 0, s, 0);
popMatrix();
return;
}
pushMatrix();
translate(x1, 0);
kcurve(0, s);
kcurve(2*s, 3*s);
translate(s, 0);
rotate(radians(60));
kcurve(0, s);
translate(s, 0);
rotate(radians(-120));
kcurve(0, s);
popMatrix();
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"math/rand"
"time"
)
func main() {
rect := image.Rect(0, 0, 640, 480)
img := image.NewRGBA(rect)
blue := color.RGBA{0, 0, 255, 255}
draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)
yellow := color.RGBA{255, 255, 0, 255}
width := img.Bounds().Dx()
height := img.Bounds().Dy()
rand.Seed(time.Now().UnixNano())
x := rand.Intn(width)
y := rand.Intn(height)
img.Set(x, y, yellow)
cmap := map[color.Color]string{blue: "blue", yellow: "yellow"}
for i := 0; i < width; i++ {
for j := 0; j < height; j++ {
c := img.At(i, j)
if cmap[c] == "yellow" {
fmt.Printf("The color of the pixel at (%d, %d) is yellow\n", i, j)
}
}
}
}
|
size(640,480);
stroke(#ffff00);
ellipse(random(640),random(480),1,1);
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
)
func main() {
rect := image.Rect(0, 0, 320, 240)
img := image.NewRGBA(rect)
green := color.RGBA{0, 255, 0, 255}
draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)
red := color.RGBA{255, 0, 0, 255}
img.Set(100, 100, red)
cmap := map[color.Color]string{green: "green", red: "red"}
c1 := img.At(0, 0)
c2 := img.At(100, 100)
fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.")
fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.")
}
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawAPixel extends JFrame{
public DrawAPixel() {
super("Red Pixel");
setSize(320, 240);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void paint(Graphics g) {
g.setColor(new Color(255, 0, 0));
g.drawRect(100, 100, 1, 1);
}
public static void main(String[] args) {
new DrawAPixel();
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
)
func main() {
rect := image.Rect(0, 0, 320, 240)
img := image.NewRGBA(rect)
green := color.RGBA{0, 255, 0, 255}
draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)
red := color.RGBA{255, 0, 0, 255}
img.Set(100, 100, red)
cmap := map[color.Color]string{green: "green", red: "red"}
c1 := img.At(0, 0)
c2 := img.At(100, 100)
fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.")
fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.")
}
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawAPixel extends JFrame{
public DrawAPixel() {
super("Red Pixel");
setSize(320, 240);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void paint(Graphics g) {
g.setColor(new Color(255, 0, 0));
g.drawRect(100, 100, 1, 1);
}
public static void main(String[] args) {
new DrawAPixel();
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) >= 9 {
words = append(words, s)
}
}
count := 0
var alreadyFound []string
le := len(words)
var sb strings.Builder
for i := 0; i < le-9; i++ {
sb.Reset()
for j := i; j < i+9; j++ {
sb.WriteByte(words[j][j-i])
}
word := sb.String()
ix := sort.SearchStrings(words, word)
if ix < le && word == words[ix] {
ix2 := sort.SearchStrings(alreadyFound, word)
if ix2 == len(alreadyFound) {
count++
fmt.Printf("%2d: %s\n", count, word)
alreadyFound = append(alreadyFound, word)
}
}
}
}
| import java.io.*;
import java.util.*;
public class NeighbourWords {
public static void main(String[] args) {
try {
int minLength = 9;
List<String> words = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() >= minLength)
words.add(line);
}
}
Collections.sort(words);
String previousWord = null;
int count = 0;
for (int i = 0, n = words.size(); i + minLength <= n; ++i) {
StringBuilder sb = new StringBuilder(minLength);
for (int j = 0; j < minLength; ++j)
sb.append(words.get(i + j).charAt(j));
String word = sb.toString();
if (word.equals(previousWord))
continue;
if (Collections.binarySearch(words, word) >= 0)
System.out.printf("%2d. %s\n", ++count, word);
previousWord = word;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {
s0, c0 := fa(a0, b0, 0)
s1, c1 := fa(a1, b1, c0)
s2, c2 := fa(a2, b2, c1)
s3, v = fa(a3, b3, c2)
return
}
func main() {
fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}
| public class GateLogic
{
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
public static OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]),
AND.eval(inputs[0], inputs[1])
};
}
};
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0],
OR.eval(haOutputs1[1], haOutputs2[1])
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1];
faInputs[1] = inputs[i];
faInputs[2] = inputs[numBits + i];
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0];
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1];
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {
s0, c0 := fa(a0, b0, 0)
s1, c1 := fa(a1, b1, c0)
s2, c2 := fa(a2, b2, c1)
s3, v = fa(a3, b3, c2)
return
}
func main() {
fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}
| public class GateLogic
{
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
public static OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]),
AND.eval(inputs[0], inputs[1])
};
}
};
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0],
OR.eval(haOutputs1[1], haOutputs2[1])
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1];
faInputs[1] = inputs[i];
faInputs[2] = inputs[numBits + i];
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0];
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1];
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"log"
)
func magicSquareOdd(n int) ([][]int, error) {
if n < 3 || n%2 == 0 {
return nil, fmt.Errorf("base must be odd and > 2")
}
value := 1
gridSize := n * n
c, r := n/2, 0
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for value <= gridSize {
result[r][c] = value
if r == 0 {
if c == n-1 {
r++
} else {
r = n - 1
c++
}
} else if c == n-1 {
r--
c = 0
} else if result[r-1][c+1] == 0 {
r--
c++
} else {
r++
}
value++
}
return result, nil
}
func magicSquareSinglyEven(n int) ([][]int, error) {
if n < 6 || (n-2)%4 != 0 {
return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2")
}
size := n * n
halfN := n / 2
subSquareSize := size / 4
subSquare, err := magicSquareOdd(halfN)
if err != nil {
return nil, err
}
quadrantFactors := [4]int{0, 2, 3, 1}
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for r := 0; r < n; r++ {
for c := 0; c < n; c++ {
quadrant := r/halfN*2 + c/halfN
result[r][c] = subSquare[r%halfN][c%halfN]
result[r][c] += quadrantFactors[quadrant] * subSquareSize
}
}
nColsLeft := halfN / 2
nColsRight := nColsLeft - 1
for r := 0; r < halfN; r++ {
for c := 0; c < n; c++ {
if c < nColsLeft || c >= n-nColsRight ||
(c == nColsLeft && r == nColsLeft) {
if c == 0 && r == nColsLeft {
continue
}
tmp := result[r][c]
result[r][c] = result[r+halfN][c]
result[r+halfN][c] = tmp
}
}
}
return result, nil
}
func main() {
const n = 6
msse, err := magicSquareSinglyEven(n)
if err != nil {
log.Fatal(err)
}
for _, row := range msse {
for _, x := range row {
fmt.Printf("%2d ", x)
}
fmt.Println()
}
fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2)
}
| public class MagicSquareSinglyEven {
public static void main(String[] args) {
int n = 6;
for (int[] row : magicSquareSinglyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int n) {
if (n < 3 || n % 2 == 0)
throw new IllegalArgumentException("base must be odd and > 2");
int value = 0;
int gridSize = n * n;
int c = n / 2, r = 0;
int[][] result = new int[n][n];
while (++value <= gridSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
static int[][] magicSquareSinglyEven(final int n) {
if (n < 6 || (n - 2) % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4 plus 2");
int size = n * n;
int halfN = n / 2;
int subSquareSize = size / 4;
int[][] subSquare = magicSquareOdd(halfN);
int[] quadrantFactors = {0, 2, 3, 1};
int[][] result = new int[n][n];
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int quadrant = (r / halfN) * 2 + (c / halfN);
result[r][c] = subSquare[r % halfN][c % halfN];
result[r][c] += quadrantFactors[quadrant] * subSquareSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"fmt"
"math/rand"
)
type symbols struct{ k, q, r, b, n rune }
var A = symbols{'K', 'Q', 'R', 'B', 'N'}
var W = symbols{'♔', '♕', '♖', '♗', '♘'}
var B = symbols{'♚', '♛', '♜', '♝', '♞'}
var krn = []string{
"nnrkr", "nrnkr", "nrknr", "nrkrn",
"rnnkr", "rnknr", "rnkrn",
"rknnr", "rknrn",
"rkrnn"}
func (sym symbols) chess960(id int) string {
var pos [8]rune
q, r := id/4, id%4
pos[r*2+1] = sym.b
q, r = q/4, q%4
pos[r*2] = sym.b
q, r = q/6, q%6
for i := 0; ; i++ {
if pos[i] != 0 {
continue
}
if r == 0 {
pos[i] = sym.q
break
}
r--
}
i := 0
for _, f := range krn[q] {
for pos[i] != 0 {
i++
}
switch f {
case 'k':
pos[i] = sym.k
case 'r':
pos[i] = sym.r
case 'n':
pos[i] = sym.n
}
}
return string(pos[:])
}
func main() {
fmt.Println(" ID Start position")
for _, id := range []int{0, 518, 959} {
fmt.Printf("%3d %s\n", id, A.chess960(id))
}
fmt.Println("\nRandom")
for i := 0; i < 5; i++ {
fmt.Println(W.chess960(rand.Intn(960)))
}
}
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Chess960{
private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');
public static List<Character> generateFirstRank(){
do{
Collections.shuffle(pieces);
}while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", "")));
return pieces;
}
private static boolean check(String rank){
if(!rank.matches(".*R.*K.*R.*")) return false;
if(!rank.matches(".*B(..|....|......|)B.*")) return false;
return true;
}
public static void main(String[] args){
for(int i = 0; i < 10; i++){
System.out.println(generateFirstRank());
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen)
var dp int
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
}
| import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
memory[i] = 0;
}
ip = 0;
dp = 0;
}
private void load(String program) {
if (program.length() > MEMORY_SIZE - 2) {
throw new RuntimeException("Not enough memory.");
}
reset();
for (; dp < program.length(); dp++) {
memory[dp] = program.charAt(dp);
}
border = dp;
dp += 1;
}
public void execute(String program) {
load(program);
char instruction = memory[ip];
while (instruction != 0) {
switch (instruction) {
case '>':
dp++;
if (dp == MEMORY_SIZE) {
throw new RuntimeException("Out of memory.");
}
break;
case '<':
dp--;
if (dp == border) {
throw new RuntimeException("Invalid data pointer.");
}
break;
case '+':
memory[dp]++;
break;
case '-':
memory[dp]--;
break;
case '.':
System.out.print(memory[dp]);
break;
case ',':
try {
memory[dp] = (char) System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
case '[':
if (memory[dp] == 0) {
skipLoop();
}
break;
case ']':
if (memory[dp] != 0) {
loop();
}
break;
default:
throw new RuntimeException("Unknown instruction.");
}
instruction = memory[++ip];
}
}
private void skipLoop() {
int loopCount = 0;
while (memory[ip] != 0) {
if (memory[ip] == '[') {
loopCount++;
} else if (memory[ip] == ']') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip++;
}
if (memory[ip] == 0) {
throw new RuntimeException("Unable to find a matching ']'.");
}
}
private void loop() {
int loopCount = 0;
while (ip >= 0) {
if (memory[ip] == ']') {
loopCount++;
} else if (memory[ip] == '[') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip--;
}
if (ip == -1) {
throw new RuntimeException("Unable to find a matching '['.");
}
}
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.");
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen)
var dp int
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
}
| import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
memory[i] = 0;
}
ip = 0;
dp = 0;
}
private void load(String program) {
if (program.length() > MEMORY_SIZE - 2) {
throw new RuntimeException("Not enough memory.");
}
reset();
for (; dp < program.length(); dp++) {
memory[dp] = program.charAt(dp);
}
border = dp;
dp += 1;
}
public void execute(String program) {
load(program);
char instruction = memory[ip];
while (instruction != 0) {
switch (instruction) {
case '>':
dp++;
if (dp == MEMORY_SIZE) {
throw new RuntimeException("Out of memory.");
}
break;
case '<':
dp--;
if (dp == border) {
throw new RuntimeException("Invalid data pointer.");
}
break;
case '+':
memory[dp]++;
break;
case '-':
memory[dp]--;
break;
case '.':
System.out.print(memory[dp]);
break;
case ',':
try {
memory[dp] = (char) System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
case '[':
if (memory[dp] == 0) {
skipLoop();
}
break;
case ']':
if (memory[dp] != 0) {
loop();
}
break;
default:
throw new RuntimeException("Unknown instruction.");
}
instruction = memory[++ip];
}
}
private void skipLoop() {
int loopCount = 0;
while (memory[ip] != 0) {
if (memory[ip] == '[') {
loopCount++;
} else if (memory[ip] == ']') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip++;
}
if (memory[ip] == 0) {
throw new RuntimeException("Unable to find a matching ']'.");
}
}
private void loop() {
int loopCount = 0;
while (ip >= 0) {
if (memory[ip] == ']') {
loopCount++;
} else if (memory[ip] == '[') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip--;
}
if (ip == -1) {
throw new RuntimeException("Unable to find a matching '['.");
}
}
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.");
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. |
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
| public class ScriptedMain {
public static int meaningOfLife() {
return 42;
}
public static void main(String[] args) {
System.out.println("Main: The meaning of life is " + meaningOfLife());
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. |
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
| public class ScriptedMain {
public static int meaningOfLife() {
return 42;
}
public static void main(String[] args) {
System.out.println("Main: The meaning of life is " + meaningOfLife());
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(noise(3.14, 42, 7))
}
func noise(x, y, z float64) float64 {
X := int(math.Floor(x)) & 255
Y := int(math.Floor(y)) & 255
Z := int(math.Floor(z)) & 255
x -= math.Floor(x)
y -= math.Floor(y)
z -= math.Floor(z)
u := fade(x)
v := fade(y)
w := fade(z)
A := p[X] + Y
AA := p[A] + Z
AB := p[A+1] + Z
B := p[X+1] + Y
BA := p[B] + Z
BB := p[B+1] + Z
return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),
grad(p[BA], x-1, y, z)),
lerp(u, grad(p[AB], x, y-1, z),
grad(p[BB], x-1, y-1, z))),
lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),
grad(p[BA+1], x-1, y, z-1)),
lerp(u, grad(p[AB+1], x, y-1, z-1),
grad(p[BB+1], x-1, y-1, z-1))))
}
func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) }
func lerp(t, a, b float64) float64 { return a + t*(b-a) }
func grad(hash int, x, y, z float64) float64 {
switch hash & 15 {
case 0, 12:
return x + y
case 1, 14:
return y - x
case 2:
return x - y
case 3:
return -x - y
case 4:
return x + z
case 5:
return z - x
case 6:
return x - z
case 7:
return -x - z
case 8:
return y + z
case 9, 13:
return z - y
case 10:
return y - z
}
return -y - z
}
var permutation = []int{
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
}
var p = append(permutation, permutation...)
|
public final class ImprovedNoise {
static public double noise(double x, double y, double z) {
int X = (int)Math.floor(x) & 255,
Y = (int)Math.floor(y) & 255,
Z = (int)Math.floor(z) & 255;
x -= Math.floor(x);
y -= Math.floor(y);
z -= Math.floor(z);
double u = fade(x),
v = fade(y),
w = fade(z);
int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,
B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}
static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
static double lerp(double t, double a, double b) { return a + t * (b - a); }
static double grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h<8 ? x : y,
v = h<4 ? y : h==12||h==14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
};
static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"log"
"os"
"sort"
)
func main() {
f, err := os.Open(".")
if err != nil {
log.Fatal(err)
}
files, err := f.Readdirnames(0)
f.Close()
if err != nil {
log.Fatal(err)
}
sort.Strings(files)
for _, n := range files {
fmt.Println(n)
}
}
| package rosetta;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class UnixLS {
public static void main(String[] args) throws IOException {
Files.list(Path.of("")).sorted().forEach(System.out::println);
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"bytes"
"encoding/hex"
"fmt"
"log"
"strings"
)
var testCases = []struct {
rune
string
}{
{'A', "41"},
{'ö', "C3 B6"},
{'Ж', "D0 96"},
{'€', "E2 82 AC"},
{'𝄞', "F0 9D 84 9E"},
}
func main() {
for _, tc := range testCases {
u := fmt.Sprintf("U+%04X", tc.rune)
b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1))
if err != nil {
log.Fatal("bad test data")
}
e := encodeUTF8(tc.rune)
d := decodeUTF8(b)
fmt.Printf("%c %-7s %X\n", d, u, e)
if !bytes.Equal(e, b) {
log.Fatal("encodeUTF8 wrong")
}
if d != tc.rune {
log.Fatal("decodeUTF8 wrong")
}
}
}
const (
b2Lead = 0xC0
b2Mask = 0x1F
b3Lead = 0xE0
b3Mask = 0x0F
b4Lead = 0xF0
b4Mask = 0x07
mbLead = 0x80
mbMask = 0x3F
)
func encodeUTF8(r rune) []byte {
switch i := uint32(r); {
case i <= 1<<7-1:
return []byte{byte(r)}
case i <= 1<<11-1:
return []byte{
b2Lead | byte(r>>6),
mbLead | byte(r)&mbMask}
case i <= 1<<16-1:
return []byte{
b3Lead | byte(r>>12),
mbLead | byte(r>>6)&mbMask,
mbLead | byte(r)&mbMask}
default:
return []byte{
b4Lead | byte(r>>18),
mbLead | byte(r>>12)&mbMask,
mbLead | byte(r>>6)&mbMask,
mbLead | byte(r)&mbMask}
}
}
func decodeUTF8(b []byte) rune {
switch b0 := b[0]; {
case b0 < 0x80:
return rune(b0)
case b0 < 0xE0:
return rune(b0&b2Mask)<<6 |
rune(b[1]&mbMask)
case b0 < 0xF0:
return rune(b0&b3Mask)<<12 |
rune(b[1]&mbMask)<<6 |
rune(b[2]&mbMask)
default:
return rune(b0&b4Mask)<<18 |
rune(b[1]&mbMask)<<12 |
rune(b[2]&mbMask)<<6 |
rune(b[3]&mbMask)
}
}
| import java.nio.charset.StandardCharsets;
import java.util.Formatter;
public class UTF8EncodeDecode {
public static byte[] utf8encode(int codepoint) {
return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
}
public static int utf8decode(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
}
public static void main(String[] args) {
System.out.printf("%-7s %-43s %7s\t%s\t%7s%n",
"Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");
for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {
byte[] encoded = utf8encode(codepoint);
Formatter formatter = new Formatter();
for (byte b : encoded) {
formatter.format("%02X ", b);
}
String encodedHex = formatter.toString();
int decoded = utf8decode(encoded);
System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n",
codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package raster
import "math"
func ipart(x float64) float64 {
return math.Floor(x)
}
func round(x float64) float64 {
return ipart(x + .5)
}
func fpart(x float64) float64 {
return x - ipart(x)
}
func rfpart(x float64) float64 {
return 1 - fpart(x)
}
func (g *Grmap) AaLine(x1, y1, x2, y2 float64) {
dx := x2 - x1
dy := y2 - y1
ax := dx
if ax < 0 {
ax = -ax
}
ay := dy
if ay < 0 {
ay = -ay
}
var plot func(int, int, float64)
if ax < ay {
x1, y1 = y1, x1
x2, y2 = y2, x2
dx, dy = dy, dx
plot = func(x, y int, c float64) {
g.SetPx(y, x, uint16(c*math.MaxUint16))
}
} else {
plot = func(x, y int, c float64) {
g.SetPx(x, y, uint16(c*math.MaxUint16))
}
}
if x2 < x1 {
x1, x2 = x2, x1
y1, y2 = y2, y1
}
gradient := dy / dx
xend := round(x1)
yend := y1 + gradient*(xend-x1)
xgap := rfpart(x1 + .5)
xpxl1 := int(xend)
ypxl1 := int(ipart(yend))
plot(xpxl1, ypxl1, rfpart(yend)*xgap)
plot(xpxl1, ypxl1+1, fpart(yend)*xgap)
intery := yend + gradient
xend = round(x2)
yend = y2 + gradient*(xend-x2)
xgap = fpart(x2 + 0.5)
xpxl2 := int(xend)
ypxl2 := int(ipart(yend))
plot(xpxl2, ypxl2, rfpart(yend)*xgap)
plot(xpxl2, ypxl2+1, fpart(yend)*xgap)
for x := xpxl1 + 1; x <= xpxl2-1; x++ {
plot(x, int(ipart(intery)), rfpart(intery))
plot(x, int(ipart(intery))+1, fpart(intery))
intery = intery + gradient
}
}
| import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class XiaolinWu extends JPanel {
public XiaolinWu() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
}
void plot(Graphics2D g, double x, double y, double c) {
g.setColor(new Color(0f, 0f, 0f, (float)c));
g.fillOval((int) x, (int) y, 2, 2);
}
int ipart(double x) {
return (int) x;
}
double fpart(double x) {
return x - floor(x);
}
double rfpart(double x) {
return 1.0 - fpart(x);
}
void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {
boolean steep = abs(y1 - y0) > abs(x1 - x0);
if (steep)
drawLine(g, y0, x0, y1, x1);
if (x0 > x1)
drawLine(g, x1, y1, x0, y0);
double dx = x1 - x0;
double dy = y1 - y0;
double gradient = dy / dx;
double xend = round(x0);
double yend = y0 + gradient * (xend - x0);
double xgap = rfpart(x0 + 0.5);
double xpxl1 = xend;
double ypxl1 = ipart(yend);
if (steep) {
plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);
plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);
} else {
plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);
plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);
}
double intery = yend + gradient;
xend = round(x1);
yend = y1 + gradient * (xend - x1);
xgap = fpart(x1 + 0.5);
double xpxl2 = xend;
double ypxl2 = ipart(yend);
if (steep) {
plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);
plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);
} else {
plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);
plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);
}
for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {
if (steep) {
plot(g, ipart(intery), x, rfpart(intery));
plot(g, ipart(intery) + 1, x, fpart(intery));
} else {
plot(g, x, ipart(intery), rfpart(intery));
plot(g, x, ipart(intery) + 1, fpart(intery));
}
intery = intery + gradient;
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
drawLine(g, 550, 170, 50, 435);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Xiaolin Wu's line algorithm");
f.setResizable(false);
f.add(new XiaolinWu(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import "C"
import "fmt"
import "unsafe"
func main() {
d := C.XOpenDisplay(nil)
f7, f6 := C.CString("F7"), C.CString("F6")
defer C.free(unsafe.Pointer(f7))
defer C.free(unsafe.Pointer(f6))
if d != nil {
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
C.Mod1Mask,
C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),
C.Mod1Mask,
C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
var event C.XEvent
for {
C.XNextEvent(d, &event)
if C.getXEvent_type(event) == C.KeyPress {
xkeyEvent := C.getXEvent_xkey(event)
s := C.XLookupKeysym(&xkeyEvent, 0)
if s == C.XK_F7 {
fmt.Println("something's happened")
} else if s == C.XK_F6 {
break
}
}
}
C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
} else {
fmt.Println("XOpenDisplay did not succeed")
}
}
| package keybord.macro.demo;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
class KeyboardMacroDemo {
public static void main( String [] args ) {
final JFrame frame = new JFrame();
String directions = "<html><b>Ctrl-S</b> to show frame title<br>"
+"<b>Ctrl-H</b> to hide it</html>";
frame.add( new JLabel(directions));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener( new KeyAdapter(){
public void keyReleased( KeyEvent e ) {
if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){
frame.setTitle("Hello there");
}else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){
frame.setTitle("");
}
}
});
frame.pack();
frame.setVisible(true);
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "fmt"
func mcnugget(limit int) {
sv := make([]bool, limit+1)
for s := 0; s <= limit; s += 6 {
for n := s; n <= limit; n += 9 {
for t := n; t <= limit; t += 20 {
sv[t] = true
}
}
}
for i := limit; i >= 0; i-- {
if !sv[i] {
fmt.Println("Maximum non-McNuggets number is", i)
return
}
}
}
func main() {
mcnugget(100)
}
| public class McNuggets {
public static void main(String... args) {
int[] SIZES = new int[] { 6, 9, 20 };
int MAX_TOTAL = 100;
int numSizes = SIZES.length;
int[] counts = new int[numSizes];
int maxFound = MAX_TOTAL + 1;
boolean[] found = new boolean[maxFound];
int numFound = 0;
int total = 0;
boolean advancedState = false;
do {
if (!found[total]) {
found[total] = true;
numFound++;
}
advancedState = false;
for (int i = 0; i < numSizes; i++) {
int curSize = SIZES[i];
if ((total + curSize) > MAX_TOTAL) {
total -= counts[i] * curSize;
counts[i] = 0;
}
else {
counts[i]++;
total += curSize;
advancedState = true;
break;
}
}
} while ((numFound < maxFound) && advancedState);
if (numFound < maxFound) {
for (int i = MAX_TOTAL; i >= 0; i--) {
if (!found[i]) {
System.out.println("Largest non-McNugget number in the search space is " + i);
break;
}
}
}
else {
System.out.println("All numbers in the search space are McNugget numbers");
}
return;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"log"
"strings"
)
const dimensions int = 8
func setupMagicSquareData(d int) ([][]int, error) {
var output [][]int
if d < 4 || d%4 != 0 {
return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
}
var bits uint = 0x9669
size := d * d
mult := d / 4
for i, r := 0, 0; r < d; r++ {
output = append(output, []int{})
for c := 0; c < d; i, c = i+1, c+1 {
bitPos := c/mult + (r/mult)*4
if (bits & (1 << uint(bitPos))) != 0 {
output[r] = append(output[r], i+1)
} else {
output[r] = append(output[r], size-i)
}
}
}
return output, nil
}
func arrayItoa(input []int) []string {
var output []string
for _, i := range input {
output = append(output, fmt.Sprintf("%4d", i))
}
return output
}
func main() {
data, err := setupMagicSquareData(dimensions)
if err != nil {
log.Fatal(err)
}
magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2
for _, row := range data {
fmt.Println(strings.Join(arrayItoa(row), " "))
}
fmt.Printf("\nMagic Constant: %d\n", magicConstant)
}
| public class MagicSquareDoublyEven {
public static void main(String[] args) {
int n = 8;
for (int[] row : magicSquareDoublyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
static int[][] magicSquareDoublyEven(final int n) {
if (n < 4 || n % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4");
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4;
int[][] result = new int[n][n];
for (int r = 0, i = 0; r < n; r++) {
for (int c = 0; c < n; c++, i++) {
int bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
func main() {
var zero float64
var negZero, posInf, negInf, nan float64
negZero = zero * -1
posInf = 1 / zero
negInf = -1 / zero
nan = zero / zero
fmt.Println(negZero, posInf, negInf, nan)
fmt.Println(math.Float64frombits(1<<63),
math.Inf(1), math.Inf(-1), math.NaN())
fmt.Println()
validateNaN(negInf+posInf, "-Inf + Inf")
validateNaN(0*posInf, "0 * Inf")
validateNaN(posInf/posInf, "Inf / Inf")
validateNaN(math.Mod(posInf, 1), "Inf % 1")
validateNaN(1+nan, "1 + NaN")
validateZero(1/posInf, "1 / Inf")
validateGT(posInf, math.MaxFloat64, "Inf > max value")
validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
validateNE(nan, nan, "NaN != NaN")
validateEQ(negZero, 0, "-0 == 0")
}
func validateNaN(n float64, op string) {
if math.IsNaN(n) {
fmt.Println(op, "-> NaN")
} else {
fmt.Println("!!! Expected NaN from", op, " Found", n)
}
}
func validateZero(n float64, op string) {
if n == 0 {
fmt.Println(op, "-> 0")
} else {
fmt.Println("!!! Expected 0 from", op, " Found", n)
}
}
func validateGT(a, b float64, op string) {
if a > b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
func validateNE(a, b float64, op string) {
if a == b {
fmt.Println("!!! Expected", op, " Found not true.")
} else {
fmt.Println(op)
}
}
func validateEQ(a, b float64, op string) {
if a == b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
| public class Extreme {
public static void main(String[] args) {
double negInf = -1.0 / 0.0;
double inf = 1.0 / 0.0;
double nan = 0.0 / 0.0;
double negZero = -2.0 / inf;
System.out.println("Negative inf: " + negInf);
System.out.println("Positive inf: " + inf);
System.out.println("NaN: " + nan);
System.out.println("Negative 0: " + negZero);
System.out.println("inf + -inf: " + (inf + negInf));
System.out.println("0 * NaN: " + (0 * nan));
System.out.println("NaN == NaN: " + (nan == nan));
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"math"
)
func main() {
var zero float64
var negZero, posInf, negInf, nan float64
negZero = zero * -1
posInf = 1 / zero
negInf = -1 / zero
nan = zero / zero
fmt.Println(negZero, posInf, negInf, nan)
fmt.Println(math.Float64frombits(1<<63),
math.Inf(1), math.Inf(-1), math.NaN())
fmt.Println()
validateNaN(negInf+posInf, "-Inf + Inf")
validateNaN(0*posInf, "0 * Inf")
validateNaN(posInf/posInf, "Inf / Inf")
validateNaN(math.Mod(posInf, 1), "Inf % 1")
validateNaN(1+nan, "1 + NaN")
validateZero(1/posInf, "1 / Inf")
validateGT(posInf, math.MaxFloat64, "Inf > max value")
validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
validateNE(nan, nan, "NaN != NaN")
validateEQ(negZero, 0, "-0 == 0")
}
func validateNaN(n float64, op string) {
if math.IsNaN(n) {
fmt.Println(op, "-> NaN")
} else {
fmt.Println("!!! Expected NaN from", op, " Found", n)
}
}
func validateZero(n float64, op string) {
if n == 0 {
fmt.Println(op, "-> 0")
} else {
fmt.Println("!!! Expected 0 from", op, " Found", n)
}
}
func validateGT(a, b float64, op string) {
if a > b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
func validateNE(a, b float64, op string) {
if a == b {
fmt.Println("!!! Expected", op, " Found not true.")
} else {
fmt.Println(op)
}
}
func validateEQ(a, b float64, op string) {
if a == b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
| public class Extreme {
public static void main(String[] args) {
double negInf = -1.0 / 0.0;
double inf = 1.0 / 0.0;
double nan = 0.0 / 0.0;
double negZero = -2.0 / inf;
System.out.println("Negative inf: " + negInf);
System.out.println("Positive inf: " + inf);
System.out.println("NaN: " + nan);
System.out.println("Negative 0: " + negZero);
System.out.println("inf + -inf: " + (inf + negInf));
System.out.println("0 * NaN: " + (0 * nan));
System.out.println("NaN == NaN: " + (nan == nan));
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"fmt"
"math"
)
func main() {
var zero float64
var negZero, posInf, negInf, nan float64
negZero = zero * -1
posInf = 1 / zero
negInf = -1 / zero
nan = zero / zero
fmt.Println(negZero, posInf, negInf, nan)
fmt.Println(math.Float64frombits(1<<63),
math.Inf(1), math.Inf(-1), math.NaN())
fmt.Println()
validateNaN(negInf+posInf, "-Inf + Inf")
validateNaN(0*posInf, "0 * Inf")
validateNaN(posInf/posInf, "Inf / Inf")
validateNaN(math.Mod(posInf, 1), "Inf % 1")
validateNaN(1+nan, "1 + NaN")
validateZero(1/posInf, "1 / Inf")
validateGT(posInf, math.MaxFloat64, "Inf > max value")
validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
validateNE(nan, nan, "NaN != NaN")
validateEQ(negZero, 0, "-0 == 0")
}
func validateNaN(n float64, op string) {
if math.IsNaN(n) {
fmt.Println(op, "-> NaN")
} else {
fmt.Println("!!! Expected NaN from", op, " Found", n)
}
}
func validateZero(n float64, op string) {
if n == 0 {
fmt.Println(op, "-> 0")
} else {
fmt.Println("!!! Expected 0 from", op, " Found", n)
}
}
func validateGT(a, b float64, op string) {
if a > b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
func validateNE(a, b float64, op string) {
if a == b {
fmt.Println("!!! Expected", op, " Found not true.")
} else {
fmt.Println(op)
}
}
func validateEQ(a, b float64, op string) {
if a == b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
| public class Extreme {
public static void main(String[] args) {
double negInf = -1.0 / 0.0;
double inf = 1.0 / 0.0;
double nan = 0.0 / 0.0;
double negZero = -2.0 / inf;
System.out.println("Negative inf: " + negInf);
System.out.println("Positive inf: " + inf);
System.out.println("NaN: " + nan);
System.out.println("Negative 0: " + negZero);
System.out.println("inf + -inf: " + (inf + negInf));
System.out.println("0 * NaN: " + (0 * nan));
System.out.println("NaN == NaN: " + (nan == nan));
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"math"
)
const CONST = 0x2545F4914F6CDD1D
type XorshiftStar struct{ state uint64 }
func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }
func (xor *XorshiftStar) seed(state uint64) { xor.state = state }
func (xor *XorshiftStar) nextInt() uint32 {
x := xor.state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
xor.state = x
return uint32((x * CONST) >> 32)
}
func (xor *XorshiftStar) nextFloat() float64 {
return float64(xor.nextInt()) / (1 << 32)
}
func main() {
randomGen := XorshiftStarNew(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
| public class XorShiftStar {
private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16);
private long state;
public void seed(long num) {
state = num;
}
public int nextInt() {
long x;
int answer;
x = state;
x = x ^ (x >>> 12);
x = x ^ (x << 25);
x = x ^ (x >>> 27);
state = x;
answer = (int) ((x * MAGIC) >> 32);
return answer;
}
public float nextFloat() {
return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);
}
public static void main(String[] args) {
var rng = new XorShiftStar();
rng.seed(1234567);
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
rng.seed(987654321);
for (int i = 0; i < 100_000; i++) {
int j = (int) Math.floor(rng.nextFloat() * 5.0);
counts[j]++;
}
for (int i = 0; i < counts.length; i++) {
System.out.printf("%d: %d\n", i, counts[i]);
}
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := NewFourIsSeq()
fmt.Print("The lengths of the first 201 words are:")
for i := 1; i <= 201; i++ {
if i%25 == 1 {
fmt.Printf("\n%3d: ", i)
}
_, n := f.WordLen(i)
fmt.Printf(" %2d", n)
}
fmt.Println()
fmt.Println("Length of sentence so far:", f.TotalLength())
for i := 1000; i <= 1e7; i *= 10 {
w, n := f.WordLen(i)
fmt.Printf("Word %8d is %q, with %d letters.", i, w, n)
fmt.Println(" Length of sentence so far:", f.TotalLength())
}
}
type FourIsSeq struct {
i int
words []string
}
func NewFourIsSeq() *FourIsSeq {
return &FourIsSeq{
words: []string{
"Four", "is", "the", "number",
"of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,",
},
}
}
func (f *FourIsSeq) WordLen(w int) (string, int) {
for len(f.words) < w {
f.i++
n := countLetters(f.words[f.i])
ns := say(int64(n))
os := sayOrdinal(int64(f.i+1)) + ","
f.words = append(f.words, strings.Fields(ns)...)
f.words = append(f.words, "in", "the")
f.words = append(f.words, strings.Fields(os)...)
}
word := f.words[w-1]
return word, countLetters(word)
}
func (f FourIsSeq) TotalLength() int {
cnt := 0
for _, w := range f.words {
cnt += len(w) + 1
}
return cnt - 1
}
func countLetters(s string) int {
cnt := 0
for _, r := range s {
if unicode.IsLetter(r) {
cnt++
}
}
return cnt
}
| import java.util.HashMap;
import java.util.Map;
public class FourIsTheNumberOfLetters {
public static void main(String[] args) {
String [] words = neverEndingSentence(201);
System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1);
for ( int i = 0 ; i < words.length ; i++ ) {
System.out.printf("%2d ", numberOfLetters(words[i]));
if ( (i+1) % 25 == 0 ) {
System.out.printf("%n%3d: ", i+2);
}
}
System.out.printf("%nTotal number of characters in the sentence is %d%n", characterCount(words));
for ( int i = 3 ; i <= 7 ; i++ ) {
int index = (int) Math.pow(10, i);
words = neverEndingSentence(index);
String last = words[words.length-1].replace(",", "");
System.out.printf("Number of letters of the %s word is %d. The word is \"%s\". The sentence length is %,d characters.%n", toOrdinal(index), numberOfLetters(last), last, characterCount(words));
}
}
@SuppressWarnings("unused")
private static void displaySentence(String[] words, int lineLength) {
int currentLength = 0;
for ( String word : words ) {
if ( word.length() + currentLength > lineLength ) {
String first = word.substring(0, lineLength-currentLength);
String second = word.substring(lineLength-currentLength);
System.out.println(first);
System.out.print(second);
currentLength = second.length();
}
else {
System.out.print(word);
currentLength += word.length();
}
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
System.out.print(" ");
currentLength++;
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
}
System.out.println();
}
private static int numberOfLetters(String word) {
return word.replace(",","").replace("-","").length();
}
private static long characterCount(String[] words) {
int characterCount = 0;
for ( int i = 0 ; i < words.length ; i++ ) {
characterCount += words[i].length() + 1;
}
characterCount--;
return characterCount;
}
private static String[] startSentence = new String[] {"Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,"};
private static String[] neverEndingSentence(int wordCount) {
String[] words = new String[wordCount];
int index;
for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {
words[index] = startSentence[index];
}
int sentencePosition = 1;
while ( index < wordCount ) {
sentencePosition++;
String word = words[sentencePosition-1];
for ( String wordLoop : numToString(numberOfLetters(word)).split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
words[index] = "in";
index++;
if ( index == wordCount ) {
break;
}
words[index] = "the";
index++;
if ( index == wordCount ) {
break;
}
for ( String wordLoop : (toOrdinal(sentencePosition) + ",").split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
}
return words;
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String numToString(long n) {
return numToStringHelper(n);
}
private static final String numToStringHelper(long n) {
if ( n < 0 ) {
return "negative " + numToStringHelper(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : "");
}
private static Map<String,String> ordinalMap = new HashMap<>();
static {
ordinalMap.put("one", "first");
ordinalMap.put("two", "second");
ordinalMap.put("three", "third");
ordinalMap.put("five", "fifth");
ordinalMap.put("eight", "eighth");
ordinalMap.put("nine", "ninth");
ordinalMap.put("twelve", "twelfth");
}
private static String toOrdinal(long n) {
String spelling = numToString(n);
String[] split = spelling.split(" ");
String last = split[split.length - 1];
String replace = "";
if ( last.contains("-") ) {
String[] lastSplit = last.split("-");
String lastWithDash = lastSplit[1];
String lastReplace = "";
if ( ordinalMap.containsKey(lastWithDash) ) {
lastReplace = ordinalMap.get(lastWithDash);
}
else if ( lastWithDash.endsWith("y") ) {
lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth";
}
else {
lastReplace = lastWithDash + "th";
}
replace = lastSplit[0] + "-" + lastReplace;
}
else {
if ( ordinalMap.containsKey(last) ) {
replace = ordinalMap.get(last);
}
else if ( last.endsWith("y") ) {
replace = last.substring(0, last.length() - 1) + "ieth";
}
else {
replace = last + "th";
}
}
split[split.length - 1] = replace;
return String.join(" ", split);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.