Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
stoogesort(a)
fmt.Println("after: ", a)
fmt.Println("nyuk nyuk nyuk")
}
func stoogesort(a []int) {
last := len(a) - 1
if a[last] < a[0] {
a[0], a[last] = a[last], a[0]
}
if last > 1 {
t := len(a) / 3
stoogesort(a[:len(a)-t])
stoogesort(a[t:])
stoogesort(a[:len(a)-t])
}
}
| import java.util.Arrays;
public class Stooge {
public static void main(String[] args) {
int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};
stoogeSort(nums);
System.out.println(Arrays.toString(nums));
}
public static void stoogeSort(int[] L) {
stoogeSort(L, 0, L.length - 1);
}
public static void stoogeSort(int[] L, int i, int j) {
if (L[j] < L[i]) {
int tmp = L[i];
L[i] = L[j];
L[j] = tmp;
}
if (j - i > 1) {
int t = (j - i + 1) / 3;
stoogeSort(L, i, j - t);
stoogeSort(L, i + t, j);
stoogeSort(L, i, j - t);
}
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"math/rand"
"time"
)
const boxW = 41
const boxH = 37
const pinsBaseW = 19
const nMaxBalls = 55
const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1
const (
empty = ' '
ball = 'o'
wall = '|'
corner = '+'
floor = '-'
pin = '.'
)
type Ball struct{ x, y int }
func newBall(x, y int) *Ball {
if box[y][x] != empty {
panic("Tried to create a new ball in a non-empty cell. Program terminated.")
}
b := Ball{x, y}
box[y][x] = ball
return &b
}
func (b *Ball) doStep() {
if b.y <= 0 {
return
}
cell := box[b.y-1][b.x]
switch cell {
case empty:
box[b.y][b.x] = empty
b.y--
box[b.y][b.x] = ball
case pin:
box[b.y][b.x] = empty
b.y--
if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty {
b.x += rand.Intn(2)*2 - 1
box[b.y][b.x] = ball
return
} else if box[b.y][b.x-1] == empty {
b.x++
} else {
b.x--
}
box[b.y][b.x] = ball
default:
}
}
type Cell = byte
var box [boxH][boxW]Cell
func initializeBox() {
box[0][0] = corner
box[0][boxW-1] = corner
for i := 1; i < boxW-1; i++ {
box[0][i] = floor
}
for i := 0; i < boxW; i++ {
box[boxH-1][i] = box[0][i]
}
for r := 1; r < boxH-1; r++ {
box[r][0] = wall
box[r][boxW-1] = wall
}
for i := 1; i < boxH-1; i++ {
for j := 1; j < boxW-1; j++ {
box[i][j] = empty
}
}
for nPins := 1; nPins <= pinsBaseW; nPins++ {
for p := 0; p < nPins; p++ {
box[boxH-2-nPins][centerH+1-nPins+p*2] = pin
}
}
}
func drawBox() {
for r := boxH - 1; r >= 0; r-- {
for c := 0; c < boxW; c++ {
fmt.Printf("%c", box[r][c])
}
fmt.Println()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
initializeBox()
var balls []*Ball
for i := 0; i < nMaxBalls+boxH; i++ {
fmt.Println("\nStep", i, ":")
if i < nMaxBalls {
balls = append(balls, newBall(centerH, boxH-2))
}
drawBox()
for _, b := range balls {
b.doStep()
}
}
}
| import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class GaltonBox {
public static void main( final String[] args ) {
new GaltonBox( 8, 200 ).run();
}
private final int m_pinRows;
private final int m_startRow;
private final Position[] m_balls;
private final Random m_random = new Random();
public GaltonBox( final int pinRows, final int ballCount ) {
m_pinRows = pinRows;
m_startRow = pinRows + 1;
m_balls = new Position[ ballCount ];
for ( int ball = 0; ball < ballCount; ball++ )
m_balls[ ball ] = new Position( m_startRow, 0, 'o' );
}
private static class Position {
int m_row;
int m_col;
char m_char;
Position( final int row, final int col, final char ch ) {
m_row = row;
m_col = col;
m_char = ch;
}
}
public void run() {
for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) {
ballsInPlay = dropBalls();
print();
}
}
private int dropBalls() {
int ballsInPlay = 0;
int ballToStart = -1;
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == m_startRow )
ballToStart = ball;
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( ball == ballToStart ) {
m_balls[ ball ].m_row = m_pinRows;
ballsInPlay++;
}
else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {
m_balls[ ball ].m_row -= 1;
m_balls[ ball ].m_col += m_random.nextInt( 2 );
if ( 0 != m_balls[ ball ].m_row )
ballsInPlay++;
}
return ballsInPlay;
}
private void print() {
for ( int row = m_startRow; row --> 1; ) {
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == row )
printBall( m_balls[ ball ] );
System.out.println();
printPins( row );
}
printCollectors();
System.out.println();
}
private static void printBall( final Position pos ) {
for ( int col = pos.m_row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = 0; col < pos.m_col; col++ )
System.out.print( " " );
System.out.print( pos.m_char );
}
private void printPins( final int row ) {
for ( int col = row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = m_startRow - row; col --> 0; )
System.out.print( ". " );
System.out.println();
}
private void printCollectors() {
final List<List<Position>> collectors = new ArrayList<List<Position>>();
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = new ArrayList<Position>();
collectors.add( collector );
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )
collector.add( m_balls[ ball ] );
}
for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = collectors.get( col );
final int pos = row + collector.size() - rows;
System.out.print( '|' );
if ( pos >= 0 )
System.out.print( collector.get( pos ).m_char );
else
System.out.print( ' ' );
}
System.out.println( '|' );
}
}
private static final int longest( final List<List<Position>> collectors ) {
int result = 0;
for ( final List<Position> collector : collectors )
result = Math.max( collector.size(), result );
return result;
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import "fmt"
func circleSort(a []int, lo, hi, swaps int) int {
if lo == hi {
return swaps
}
high, low := hi, lo
mid := (hi - lo) / 2
for lo < hi {
if a[lo] > a[hi] {
a[lo], a[hi] = a[hi], a[lo]
swaps++
}
lo++
hi--
}
if lo == hi {
if a[lo] > a[hi+1] {
a[lo], a[hi+1] = a[hi+1], a[lo]
swaps++
}
}
swaps = circleSort(a, low, low+mid, swaps)
swaps = circleSort(a, low+mid+1, high, swaps)
return swaps
}
func main() {
aa := [][]int{
{6, 7, 8, 9, 2, 5, 3, 4, 1},
{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},
}
for _, a := range aa {
fmt.Printf("Original: %v\n", a)
for circleSort(a, 0, len(a)-1, 0) != 0 {
}
fmt.Printf("Sorted : %v\n\n", a)
}
}
| import java.util.Arrays;
public class CircleSort {
public static void main(String[] args) {
circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});
}
public static void circleSort(int[] arr) {
if (arr.length > 0)
do {
System.out.println(Arrays.toString(arr));
} while (circleSortR(arr, 0, arr.length - 1, 0) != 0);
}
private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {
if (lo == hi)
return numSwaps;
int high = hi;
int low = lo;
int mid = (hi - lo) / 2;
while (lo < hi) {
if (arr[lo] > arr[hi]) {
swap(arr, lo, hi);
numSwaps++;
}
lo++;
hi--;
}
if (lo == hi && arr[lo] > arr[hi + 1]) {
swap(arr, lo, hi + 1);
numSwaps++;
}
numSwaps = circleSortR(arr, low, low + mid, numSwaps);
numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);
return numSwaps;
}
private static void swap(int[] arr, int idx1, int idx2) {
int tmp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = tmp;
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
type matrix [][]int
func (m1 matrix) kroneckerProduct(m2 matrix) matrix {
m := len(m1)
n := len(m1[0])
p := len(m2)
q := len(m2[0])
rtn := m * p
ctn := n * q
r := make(matrix, rtn)
for i := range r {
r[i] = make([]int, ctn)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
for k := 0; k < p; k++ {
for l := 0; l < q; l++ {
r[p*i+k][q*j+l] = m1[i][j] * m2[k][l]
}
}
}
}
return r
}
func (m matrix) kroneckerPower(n int) matrix {
pow := m
for i := 1; i < n; i++ {
pow = pow.kroneckerProduct(m)
}
return pow
}
func (m matrix) print(text string) {
fmt.Println(text, "fractal :\n")
for i := range m {
for j := range m[0] {
if m[i][j] == 1 {
fmt.Print("*")
} else {
fmt.Print(" ")
}
}
fmt.Println()
}
fmt.Println()
}
func main() {
m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}
m1.kroneckerPower(4).print("Vivsek")
m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}
m2.kroneckerPower(4).print("Sierpinski carpet")
}
| package kronecker;
public class ProductFractals {
public static int[][] product(final int[][] a, final int[][] b) {
final int[][] c = new int[a.length*b.length][];
for (int ix = 0; ix < c.length; ix++) {
final int num_cols = a[0].length*b[0].length;
c[ix] = new int[num_cols];
}
for (int ia = 0; ia < a.length; ia++) {
for (int ja = 0; ja < a[ia].length; ja++) {
for (int ib = 0; ib < b.length; ib++) {
for (int jb = 0; jb < b[ib].length; jb++) {
c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];
}
}
}
}
return c;
}
public static void show_matrix(final int[][] m, final char nz, final char z) {
for (int im = 0; im < m.length; im++) {
for (int jm = 0; jm < m[im].length; jm++) {
System.out.print(m[im][jm] == 0 ? z : nz);
}
System.out.println();
}
}
public static int[][] power(final int[][] m, final int n) {
int[][] m_pow = m;
for (int ix = 1; ix < n; ix++) {
m_pow = product(m, m_pow);
}
return m_pow;
}
private static void test(final int[][] m, final int n) {
System.out.println("Test matrix");
show_matrix(m, '*', ' ');
final int[][] m_pow = power(m, n);
System.out.println("Matrix power " + n);
show_matrix(m_pow, '*', ' ');
}
private static void test1() {
final int[][] m = {{0, 1, 0},
{1, 1, 1},
{0, 1, 0}};
test(m, 4);
}
private static void test2() {
final int[][] m = {{1, 1, 1},
{1, 0, 1},
{1, 1, 1}};
test(m, 4);
}
private static void test3() {
final int[][] m = {{1, 0, 1},
{1, 0, 1},
{0, 1, 0}};
test(m, 4);
}
public static void main(final String[] args) {
test1();
test2();
test3();
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package config
import (
"errors"
"io"
"fmt"
"bytes"
"strings"
"io/ioutil"
)
var (
ENONE = errors.New("Requested value does not exist")
EBADTYPE = errors.New("Requested type and actual type do not match")
EBADVAL = errors.New("Value and type do not match")
)
type varError struct {
err error
n string
t VarType
}
func (err *varError) Error() string {
return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t)
}
type VarType int
const (
Bool VarType = 1 + iota
Array
String
)
func (t VarType) String() string {
switch t {
case Bool:
return "Bool"
case Array:
return "Array"
case String:
return "String"
}
panic("Unknown VarType")
}
type confvar struct {
Type VarType
Val interface{}
}
type Config struct {
m map[string]confvar
}
func Parse(r io.Reader) (c *Config, err error) {
c = new(Config)
c.m = make(map[string]confvar)
buf, err := ioutil.ReadAll(r)
if err != nil {
return
}
lines := bytes.Split(buf, []byte{'\n'})
for _, line := range lines {
line = bytes.TrimSpace(line)
if len(line) == 0 {
continue
}
switch line[0] {
case '#', ';':
continue
}
parts := bytes.SplitN(line, []byte{' '}, 2)
nam := string(bytes.ToLower(parts[0]))
if len(parts) == 1 {
c.m[nam] = confvar{Bool, true}
continue
}
if strings.Contains(string(parts[1]), ",") {
tmpB := bytes.Split(parts[1], []byte{','})
for i := range tmpB {
tmpB[i] = bytes.TrimSpace(tmpB[i])
}
tmpS := make([]string, 0, len(tmpB))
for i := range tmpB {
tmpS = append(tmpS, string(tmpB[i]))
}
c.m[nam] = confvar{Array, tmpS}
continue
}
c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))}
}
return
}
func (c *Config) Bool(name string) (bool, error) {
name = strings.ToLower(name)
if _, ok := c.m[name]; !ok {
return false, nil
}
if c.m[name].Type != Bool {
return false, &varError{EBADTYPE, name, Bool}
}
v, ok := c.m[name].Val.(bool)
if !ok {
return false, &varError{EBADVAL, name, Bool}
}
return v, nil
}
func (c *Config) Array(name string) ([]string, error) {
name = strings.ToLower(name)
if _, ok := c.m[name]; !ok {
return nil, &varError{ENONE, name, Array}
}
if c.m[name].Type != Array {
return nil, &varError{EBADTYPE, name, Array}
}
v, ok := c.m[name].Val.([]string)
if !ok {
return nil, &varError{EBADVAL, name, Array}
}
return v, nil
}
func (c *Config) String(name string) (string, error) {
name = strings.ToLower(name)
if _, ok := c.m[name]; !ok {
return "", &varError{ENONE, name, String}
}
if c.m[name].Type != String {
return "", &varError{EBADTYPE, name, String}
}
v, ok := c.m[name].Val.(string)
if !ok {
return "", &varError{EBADVAL, name, String}
}
return v, nil
}
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConfigReader {
private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" );
private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{
put( "needspeeling", false );
put( "seedsremoved", false );
}};
public static void main( final String[] args ) {
System.out.println( parseFile( args[ 0 ] ) );
}
public static Map<String, Object> parseFile( final String fileName ) {
final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader( fileName ) );
for ( String line; null != ( line = reader.readLine() ); ) {
parseLine( line, result );
}
} catch ( final IOException x ) {
throw new RuntimeException( "Oops: " + x, x );
} finally {
if ( null != reader ) try {
reader.close();
} catch ( final IOException x2 ) {
System.err.println( "Could not close " + fileName + " - " + x2 );
}
}
return result;
}
private static void parseLine( final String line, final Map<String, Object> map ) {
if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) )
return;
final Matcher matcher = LINE_PATTERN.matcher( line );
if ( ! matcher.matches() ) {
System.err.println( "Bad config line: " + line );
return;
}
final String key = matcher.group( 1 ).trim().toLowerCase();
final String value = matcher.group( 2 ).trim();
if ( "".equals( value ) ) {
map.put( key, true );
} else if ( -1 == value.indexOf( ',' ) ) {
map.put( key, value );
} else {
final String[] values = value.split( "," );
for ( int i = 0; i < values.length; i++ ) {
values[ i ] = values[ i ].trim();
}
map.put( key, Arrays.asList( values ) );
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"sort"
"strings"
)
type sortable []string
func (s sortable) Len() int { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
a, b := s[i], s[j]
if len(a) != len(b) {
return len(a) > len(b)
}
return strings.ToLower(a) < strings.ToLower(b)
}
func main() {
var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
fmt.Println(s, "(original)")
sort.Sort(s)
fmt.Println(s, "(sorted)")
}
| import java.util.Comparator;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
Arrays.sort(strings, new Comparator<String>() {
public int compare(String s1, String s2) {
int c = s2.length() - s1.length();
if (c == 0)
c = s1.compareToIgnoreCase(s2);
return c;
}
});
for (String s: strings)
System.out.print(s + " ");
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"strings"
)
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func repunit(n int) *big.Int {
ones := strings.Repeat("1", n)
b, _ := new(big.Int).SetString(ones, 10)
return b
}
var circs = []int{}
func alreadyFound(n int) bool {
for _, i := range circs {
if i == n {
return true
}
}
return false
}
func isCircular(n int) bool {
nn := n
pow := 1
for nn > 0 {
pow *= 10
nn /= 10
}
nn = n
for {
nn *= 10
f := nn / pow
nn += f * (1 - pow)
if alreadyFound(nn) {
return false
}
if nn == n {
break
}
if !isPrime(nn) {
return false
}
}
return true
}
func main() {
fmt.Println("The first 19 circular primes are:")
digits := [4]int{1, 3, 7, 9}
q := []int{1, 2, 3, 5, 7, 9}
fq := []int{1, 2, 3, 5, 7, 9}
count := 0
for {
f := q[0]
fd := fq[0]
if isPrime(f) && isCircular(f) {
circs = append(circs, f)
count++
if count == 19 {
break
}
}
copy(q, q[1:])
q = q[:len(q)-1]
copy(fq, fq[1:])
fq = fq[:len(fq)-1]
if f == 2 || f == 5 {
continue
}
for _, d := range digits {
if d >= fd {
q = append(q, f*10+d)
fq = append(fq, fd)
}
}
}
fmt.Println(circs)
fmt.Println("\nThe next 4 circular primes, in repunit format, are:")
count = 0
var rus []string
for i := 7; count < 4; i++ {
if repunit(i).ProbablyPrime(10) {
count++
rus = append(rus, fmt.Sprintf("R(%d)", i))
}
}
fmt.Println(rus)
fmt.Println("\nThe following repunits are probably circular primes:")
for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} {
fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10))
}
}
| import java.math.BigInteger;
import java.util.Arrays;
public class CircularPrimes {
public static void main(String[] args) {
System.out.println("First 19 circular primes:");
int p = 2;
for (int count = 0; count < 19; ++p) {
if (isCircularPrime(p)) {
if (count > 0)
System.out.print(", ");
System.out.print(p);
++count;
}
}
System.out.println();
System.out.println("Next 4 circular primes:");
int repunit = 1, digits = 1;
for (; repunit < p; ++digits)
repunit = 10 * repunit + 1;
BigInteger bignum = BigInteger.valueOf(repunit);
for (int count = 0; count < 4; ) {
if (bignum.isProbablePrime(15)) {
if (count > 0)
System.out.print(", ");
System.out.printf("R(%d)", digits);
++count;
}
++digits;
bignum = bignum.multiply(BigInteger.TEN);
bignum = bignum.add(BigInteger.ONE);
}
System.out.println();
testRepunit(5003);
testRepunit(9887);
testRepunit(15073);
testRepunit(25031);
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static int cycle(int n) {
int m = n, p = 1;
while (m >= 10) {
p *= 10;
m /= 10;
}
return m + 10 * (n % p);
}
private static boolean isCircularPrime(int p) {
if (!isPrime(p))
return false;
int p2 = cycle(p);
while (p2 != p) {
if (p2 < p || !isPrime(p2))
return false;
p2 = cycle(p2);
}
return true;
}
private static void testRepunit(int digits) {
BigInteger repunit = repunit(digits);
if (repunit.isProbablePrime(15))
System.out.printf("R(%d) is probably prime.\n", digits);
else
System.out.printf("R(%d) is not prime.\n", digits);
}
private static BigInteger repunit(int digits) {
char[] ch = new char[digits];
Arrays.fill(ch, '1');
return new BigInteger(new String(ch));
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"strings"
)
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func repunit(n int) *big.Int {
ones := strings.Repeat("1", n)
b, _ := new(big.Int).SetString(ones, 10)
return b
}
var circs = []int{}
func alreadyFound(n int) bool {
for _, i := range circs {
if i == n {
return true
}
}
return false
}
func isCircular(n int) bool {
nn := n
pow := 1
for nn > 0 {
pow *= 10
nn /= 10
}
nn = n
for {
nn *= 10
f := nn / pow
nn += f * (1 - pow)
if alreadyFound(nn) {
return false
}
if nn == n {
break
}
if !isPrime(nn) {
return false
}
}
return true
}
func main() {
fmt.Println("The first 19 circular primes are:")
digits := [4]int{1, 3, 7, 9}
q := []int{1, 2, 3, 5, 7, 9}
fq := []int{1, 2, 3, 5, 7, 9}
count := 0
for {
f := q[0]
fd := fq[0]
if isPrime(f) && isCircular(f) {
circs = append(circs, f)
count++
if count == 19 {
break
}
}
copy(q, q[1:])
q = q[:len(q)-1]
copy(fq, fq[1:])
fq = fq[:len(fq)-1]
if f == 2 || f == 5 {
continue
}
for _, d := range digits {
if d >= fd {
q = append(q, f*10+d)
fq = append(fq, fd)
}
}
}
fmt.Println(circs)
fmt.Println("\nThe next 4 circular primes, in repunit format, are:")
count = 0
var rus []string
for i := 7; count < 4; i++ {
if repunit(i).ProbablyPrime(10) {
count++
rus = append(rus, fmt.Sprintf("R(%d)", i))
}
}
fmt.Println(rus)
fmt.Println("\nThe following repunits are probably circular primes:")
for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} {
fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10))
}
}
| import java.math.BigInteger;
import java.util.Arrays;
public class CircularPrimes {
public static void main(String[] args) {
System.out.println("First 19 circular primes:");
int p = 2;
for (int count = 0; count < 19; ++p) {
if (isCircularPrime(p)) {
if (count > 0)
System.out.print(", ");
System.out.print(p);
++count;
}
}
System.out.println();
System.out.println("Next 4 circular primes:");
int repunit = 1, digits = 1;
for (; repunit < p; ++digits)
repunit = 10 * repunit + 1;
BigInteger bignum = BigInteger.valueOf(repunit);
for (int count = 0; count < 4; ) {
if (bignum.isProbablePrime(15)) {
if (count > 0)
System.out.print(", ");
System.out.printf("R(%d)", digits);
++count;
}
++digits;
bignum = bignum.multiply(BigInteger.TEN);
bignum = bignum.add(BigInteger.ONE);
}
System.out.println();
testRepunit(5003);
testRepunit(9887);
testRepunit(15073);
testRepunit(25031);
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static int cycle(int n) {
int m = n, p = 1;
while (m >= 10) {
p *= 10;
m /= 10;
}
return m + 10 * (n % p);
}
private static boolean isCircularPrime(int p) {
if (!isPrime(p))
return false;
int p2 = cycle(p);
while (p2 != p) {
if (p2 < p || !isPrime(p2))
return false;
p2 = cycle(p2);
}
return true;
}
private static void testRepunit(int digits) {
BigInteger repunit = repunit(digits);
if (repunit.isProbablePrime(15))
System.out.printf("R(%d) is probably prime.\n", digits);
else
System.out.printf("R(%d) is not prime.\n", digits);
}
private static BigInteger repunit(int digits) {
char[] ch = new char[digits];
Arrays.fill(ch, '1');
return new BigInteger(new String(ch));
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"log"
"time"
"github.com/gdamore/tcell"
)
const (
msg = "Hello World! "
x0, y0 = 8, 3
shiftsPerSecond = 4
clicksToExit = 5
)
func main() {
s, err := tcell.NewScreen()
if err != nil {
log.Fatal(err)
}
if err = s.Init(); err != nil {
log.Fatal(err)
}
s.Clear()
s.EnableMouse()
tick := time.Tick(time.Second / shiftsPerSecond)
click := make(chan bool)
go func() {
for {
em, ok := s.PollEvent().(*tcell.EventMouse)
if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
continue
}
mx, my := em.Position()
if my == y0 && mx >= x0 && mx < x0+len(msg) {
click <- true
}
}
}()
for inc, shift, clicks := 1, 0, 0; ; {
select {
case <-tick:
shift = (shift + inc) % len(msg)
for i, r := range msg {
s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
}
s.Show()
case <-click:
clicks++
if clicks == clicksToExit {
s.Fini()
return
}
inc = len(msg) - inc
}
}
}
| import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Rotate {
private static class State {
private final String text = "Hello World! ";
private int startIndex = 0;
private boolean rotateRight = true;
}
public static void main(String[] args) {
State state = new State();
JLabel label = new JLabel(state.text);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
state.rotateRight = !state.rotateRight;
}
});
TimerTask task = new TimerTask() {
public void run() {
int delta = state.rotateRight ? 1 : -1;
state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();
label.setText(rotate(state.text, state.startIndex));
}
};
Timer timer = new Timer(false);
timer.schedule(task, 0, 500);
JFrame rot = new JFrame();
rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
rot.add(label);
rot.pack();
rot.setLocationRelativeTo(null);
rot.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
timer.cancel();
}
});
rot.setVisible(true);
}
private static String rotate(String text, int startIdx) {
char[] rotated = new char[text.length()];
for (int i = 0; i < text.length(); i++) {
rotated[i] = text.charAt((i + startIdx) % text.length());
}
return String.valueOf(rotated);
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"bytes"
"encoding/binary"
"fmt"
)
type word int32
const wordLen = 4
const highBit = -1 << 31
var data = []word{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
buf := bytes.NewBuffer(nil)
ds := make([][]byte, len(data))
for i, x := range data {
binary.Write(buf, binary.LittleEndian, x^highBit)
b := make([]byte, wordLen)
buf.Read(b)
ds[i] = b
}
bins := make([][][]byte, 256)
for i := 0; i < wordLen; i++ {
for _, b := range ds {
bins[b[i]] = append(bins[b[i]], b)
}
j := 0
for k, bs := range bins {
copy(ds[j:], bs)
j += len(bs)
bins[k] = bs[:0]
}
}
fmt.Println("original:", data)
var w word
for i, b := range ds {
buf.Write(b)
binary.Read(buf, binary.LittleEndian, &w)
data[i] = w^highBit
}
fmt.Println("sorted: ", data)
}
| public static int[] sort(int[] old) {
for (int shift = Integer.SIZE - 1; shift > -1; shift--) {
int[] tmp = new int[old.length];
int j = 0;
for (int i = 0; i < old.length; i++) {
boolean move = old[i] << shift >= 0;
if (shift == 0 ? !move : move) {
tmp[j] = old[i];
j++;
} else {
old[i - j] = old[i];
}
}
for (int i = j; i < tmp.length; i++) {
tmp[i] = old[i - j];
}
old = tmp;
}
return old;
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
selectionSort(a)
fmt.Println("after: ", a)
}
func selectionSort(a []int) {
last := len(a) - 1
for i := 0; i < last; i++ {
aMin := a[i]
iMin := i
for j := i + 1; j < len(a); j++ {
if a[j] < aMin {
aMin = a[j]
iMin = j
}
}
a[i], a[iMin] = aMin, a[i]
}
}
| public static void sort(int[] nums){
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
int smallest = Integer.MAX_VALUE;
int smallestAt = currentPlace+1;
for(int check = currentPlace; check<nums.length;check++){
if(nums[check]<smallest){
smallestAt = check;
smallest = nums[check];
}
}
int temp = nums[currentPlace];
nums[currentPlace] = nums[smallestAt];
nums[smallestAt] = temp;
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"log"
"math/big"
)
func jacobi(a, n uint64) int {
if n%2 == 0 {
log.Fatal("'n' must be a positive odd integer")
}
a %= n
result := 1
for a != 0 {
for a%2 == 0 {
a /= 2
nn := n % 8
if nn == 3 || nn == 5 {
result = -result
}
}
a, n = n, a
if a%4 == 3 && n%4 == 3 {
result = -result
}
a %= n
}
if n == 1 {
return result
}
return 0
}
func main() {
fmt.Println("Using hand-coded version:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
fmt.Printf(" % d", jacobi(a, n))
}
fmt.Println()
}
ba, bn := new(big.Int), new(big.Int)
fmt.Println("\nUsing standard library function:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
ba.SetUint64(a)
bn.SetUint64(n)
fmt.Printf(" % d", big.Jacobi(ba, bn))
}
fmt.Println()
}
}
| public class JacobiSymbol {
public static void main(String[] args) {
int max = 30;
System.out.printf("n\\k ");
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", k);
}
System.out.printf("%n");
for ( int n = 1 ; n <= max ; n += 2 ) {
System.out.printf("%2d ", n);
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", jacobiSymbol(k, n));
}
System.out.printf("%n");
}
}
private static int jacobiSymbol(int k, int n) {
if ( k < 0 || n % 2 == 0 ) {
throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n);
}
k %= n;
int jacobi = 1;
while ( k > 0 ) {
while ( k % 2 == 0 ) {
k /= 2;
int r = n % 8;
if ( r == 3 || r == 5 ) {
jacobi = -jacobi;
}
}
int temp = n;
n = k;
k = temp;
if ( k % 4 == 3 && n % 4 == 3 ) {
jacobi = -jacobi;
}
k %= n;
}
if ( n == 1 ) {
return jacobi;
}
return 0;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"log"
"math/big"
)
func jacobi(a, n uint64) int {
if n%2 == 0 {
log.Fatal("'n' must be a positive odd integer")
}
a %= n
result := 1
for a != 0 {
for a%2 == 0 {
a /= 2
nn := n % 8
if nn == 3 || nn == 5 {
result = -result
}
}
a, n = n, a
if a%4 == 3 && n%4 == 3 {
result = -result
}
a %= n
}
if n == 1 {
return result
}
return 0
}
func main() {
fmt.Println("Using hand-coded version:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
fmt.Printf(" % d", jacobi(a, n))
}
fmt.Println()
}
ba, bn := new(big.Int), new(big.Int)
fmt.Println("\nUsing standard library function:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
ba.SetUint64(a)
bn.SetUint64(n)
fmt.Printf(" % d", big.Jacobi(ba, bn))
}
fmt.Println()
}
}
| public class JacobiSymbol {
public static void main(String[] args) {
int max = 30;
System.out.printf("n\\k ");
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", k);
}
System.out.printf("%n");
for ( int n = 1 ; n <= max ; n += 2 ) {
System.out.printf("%2d ", n);
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", jacobiSymbol(k, n));
}
System.out.printf("%n");
}
}
private static int jacobiSymbol(int k, int n) {
if ( k < 0 || n % 2 == 0 ) {
throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n);
}
k %= n;
int jacobi = 1;
while ( k > 0 ) {
while ( k % 2 == 0 ) {
k /= 2;
int r = n % 8;
if ( r == 3 || r == 5 ) {
jacobi = -jacobi;
}
}
int temp = n;
n = k;
k = temp;
if ( k % 4 == 3 && n % 4 == 3 ) {
jacobi = -jacobi;
}
k %= n;
}
if ( n == 1 ) {
return jacobi;
}
return 0;
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. |
package main
import (
"fmt"
"math"
"math/rand"
"sort"
"time"
)
type point []float64
func (p point) sqd(q point) float64 {
var sum float64
for dim, pCoord := range p {
d := pCoord - q[dim]
sum += d * d
}
return sum
}
type kdNode struct {
domElt point
split int
left, right *kdNode
}
type kdTree struct {
n *kdNode
bounds hyperRect
}
type hyperRect struct {
min, max point
}
func (hr hyperRect) copy() hyperRect {
return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}
}
func newKd(pts []point, bounds hyperRect) kdTree {
var nk2 func([]point, int) *kdNode
nk2 = func(exset []point, split int) *kdNode {
if len(exset) == 0 {
return nil
}
sort.Sort(part{exset, split})
m := len(exset) / 2
d := exset[m]
for m+1 < len(exset) && exset[m+1][split] == d[split] {
m++
}
s2 := split + 1
if s2 == len(d) {
s2 = 0
}
return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}
}
return kdTree{nk2(pts, 0), bounds}
}
type part struct {
pts []point
dPart int
}
func (p part) Len() int { return len(p.pts) }
func (p part) Less(i, j int) bool {
return p.pts[i][p.dPart] < p.pts[j][p.dPart]
}
func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }
func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {
return nn(t.n, p, t.bounds, math.Inf(1))
}
func nn(kd *kdNode, target point, hr hyperRect,
maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {
if kd == nil {
return nil, math.Inf(1), 0
}
nodesVisited++
s := kd.split
pivot := kd.domElt
leftHr := hr.copy()
rightHr := hr.copy()
leftHr.max[s] = pivot[s]
rightHr.min[s] = pivot[s]
targetInLeft := target[s] <= pivot[s]
var nearerKd, furtherKd *kdNode
var nearerHr, furtherHr hyperRect
if targetInLeft {
nearerKd, nearerHr = kd.left, leftHr
furtherKd, furtherHr = kd.right, rightHr
} else {
nearerKd, nearerHr = kd.right, rightHr
furtherKd, furtherHr = kd.left, leftHr
}
var nv int
nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)
nodesVisited += nv
if distSqd < maxDistSqd {
maxDistSqd = distSqd
}
d := pivot[s] - target[s]
d *= d
if d > maxDistSqd {
return
}
if d = pivot.sqd(target); d < distSqd {
nearest = pivot
distSqd = d
maxDistSqd = distSqd
}
tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)
nodesVisited += nv
if tempSqd < distSqd {
nearest = tempNearest
distSqd = tempSqd
}
return
}
func main() {
rand.Seed(time.Now().Unix())
kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},
hyperRect{point{0, 0}, point{10, 10}})
showNearest("WP example data", kd, point{9, 2})
kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})
showNearest("1000 random 3d points", kd, randomPt(3))
}
func randomPt(dim int) point {
p := make(point, dim)
for d := range p {
p[d] = rand.Float64()
}
return p
}
func randomPts(dim, n int) []point {
p := make([]point, n)
for i := range p {
p[i] = randomPt(dim)
}
return p
}
func showNearest(heading string, kd kdTree, p point) {
fmt.Println()
fmt.Println(heading)
fmt.Println("point: ", p)
nn, ssq, nv := kd.nearest(p)
fmt.Println("nearest neighbor:", nn)
fmt.Println("distance: ", math.Sqrt(ssq))
fmt.Println("nodes visited: ", nv)
}
| import java.util.*;
public class KdTree {
private int dimensions_;
private Node root_ = null;
private Node best_ = null;
private double bestDistance_ = 0;
private int visited_ = 0;
public KdTree(int dimensions, List<Node> nodes) {
dimensions_ = dimensions;
root_ = makeTree(nodes, 0, nodes.size(), 0);
}
public Node findNearest(Node target) {
if (root_ == null)
throw new IllegalStateException("Tree is empty!");
best_ = null;
visited_ = 0;
bestDistance_ = 0;
nearest(root_, target, 0);
return best_;
}
public int visited() {
return visited_;
}
public double distance() {
return Math.sqrt(bestDistance_);
}
private void nearest(Node root, Node target, int index) {
if (root == null)
return;
++visited_;
double d = root.distance(target);
if (best_ == null || d < bestDistance_) {
bestDistance_ = d;
best_ = root;
}
if (bestDistance_ == 0)
return;
double dx = root.get(index) - target.get(index);
index = (index + 1) % dimensions_;
nearest(dx > 0 ? root.left_ : root.right_, target, index);
if (dx * dx >= bestDistance_)
return;
nearest(dx > 0 ? root.right_ : root.left_, target, index);
}
private Node makeTree(List<Node> nodes, int begin, int end, int index) {
if (end <= begin)
return null;
int n = begin + (end - begin)/2;
Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));
index = (index + 1) % dimensions_;
node.left_ = makeTree(nodes, begin, n, index);
node.right_ = makeTree(nodes, n + 1, end, index);
return node;
}
private static class NodeComparator implements Comparator<Node> {
private int index_;
private NodeComparator(int index) {
index_ = index;
}
public int compare(Node n1, Node n2) {
return Double.compare(n1.get(index_), n2.get(index_));
}
}
public static class Node {
private double[] coords_;
private Node left_ = null;
private Node right_ = null;
public Node(double[] coords) {
coords_ = coords;
}
public Node(double x, double y) {
this(new double[]{x, y});
}
public Node(double x, double y, double z) {
this(new double[]{x, y, z});
}
double get(int index) {
return coords_[index];
}
double distance(Node node) {
double dist = 0;
for (int i = 0; i < coords_.length; ++i) {
double d = coords_[i] - node.coords_[i];
dist += d * d;
}
return dist;
}
public String toString() {
StringBuilder s = new StringBuilder("(");
for (int i = 0; i < coords_.length; ++i) {
if (i > 0)
s.append(", ");
s.append(coords_[i]);
}
s.append(')');
return s.toString();
}
}
}
|
Translate the given Go code snippet into Java without altering its behavior. |
package main
import (
"fmt"
"math"
"math/rand"
"sort"
"time"
)
type point []float64
func (p point) sqd(q point) float64 {
var sum float64
for dim, pCoord := range p {
d := pCoord - q[dim]
sum += d * d
}
return sum
}
type kdNode struct {
domElt point
split int
left, right *kdNode
}
type kdTree struct {
n *kdNode
bounds hyperRect
}
type hyperRect struct {
min, max point
}
func (hr hyperRect) copy() hyperRect {
return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}
}
func newKd(pts []point, bounds hyperRect) kdTree {
var nk2 func([]point, int) *kdNode
nk2 = func(exset []point, split int) *kdNode {
if len(exset) == 0 {
return nil
}
sort.Sort(part{exset, split})
m := len(exset) / 2
d := exset[m]
for m+1 < len(exset) && exset[m+1][split] == d[split] {
m++
}
s2 := split + 1
if s2 == len(d) {
s2 = 0
}
return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}
}
return kdTree{nk2(pts, 0), bounds}
}
type part struct {
pts []point
dPart int
}
func (p part) Len() int { return len(p.pts) }
func (p part) Less(i, j int) bool {
return p.pts[i][p.dPart] < p.pts[j][p.dPart]
}
func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }
func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {
return nn(t.n, p, t.bounds, math.Inf(1))
}
func nn(kd *kdNode, target point, hr hyperRect,
maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {
if kd == nil {
return nil, math.Inf(1), 0
}
nodesVisited++
s := kd.split
pivot := kd.domElt
leftHr := hr.copy()
rightHr := hr.copy()
leftHr.max[s] = pivot[s]
rightHr.min[s] = pivot[s]
targetInLeft := target[s] <= pivot[s]
var nearerKd, furtherKd *kdNode
var nearerHr, furtherHr hyperRect
if targetInLeft {
nearerKd, nearerHr = kd.left, leftHr
furtherKd, furtherHr = kd.right, rightHr
} else {
nearerKd, nearerHr = kd.right, rightHr
furtherKd, furtherHr = kd.left, leftHr
}
var nv int
nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)
nodesVisited += nv
if distSqd < maxDistSqd {
maxDistSqd = distSqd
}
d := pivot[s] - target[s]
d *= d
if d > maxDistSqd {
return
}
if d = pivot.sqd(target); d < distSqd {
nearest = pivot
distSqd = d
maxDistSqd = distSqd
}
tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)
nodesVisited += nv
if tempSqd < distSqd {
nearest = tempNearest
distSqd = tempSqd
}
return
}
func main() {
rand.Seed(time.Now().Unix())
kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},
hyperRect{point{0, 0}, point{10, 10}})
showNearest("WP example data", kd, point{9, 2})
kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})
showNearest("1000 random 3d points", kd, randomPt(3))
}
func randomPt(dim int) point {
p := make(point, dim)
for d := range p {
p[d] = rand.Float64()
}
return p
}
func randomPts(dim, n int) []point {
p := make([]point, n)
for i := range p {
p[i] = randomPt(dim)
}
return p
}
func showNearest(heading string, kd kdTree, p point) {
fmt.Println()
fmt.Println(heading)
fmt.Println("point: ", p)
nn, ssq, nv := kd.nearest(p)
fmt.Println("nearest neighbor:", nn)
fmt.Println("distance: ", math.Sqrt(ssq))
fmt.Println("nodes visited: ", nv)
}
| import java.util.*;
public class KdTree {
private int dimensions_;
private Node root_ = null;
private Node best_ = null;
private double bestDistance_ = 0;
private int visited_ = 0;
public KdTree(int dimensions, List<Node> nodes) {
dimensions_ = dimensions;
root_ = makeTree(nodes, 0, nodes.size(), 0);
}
public Node findNearest(Node target) {
if (root_ == null)
throw new IllegalStateException("Tree is empty!");
best_ = null;
visited_ = 0;
bestDistance_ = 0;
nearest(root_, target, 0);
return best_;
}
public int visited() {
return visited_;
}
public double distance() {
return Math.sqrt(bestDistance_);
}
private void nearest(Node root, Node target, int index) {
if (root == null)
return;
++visited_;
double d = root.distance(target);
if (best_ == null || d < bestDistance_) {
bestDistance_ = d;
best_ = root;
}
if (bestDistance_ == 0)
return;
double dx = root.get(index) - target.get(index);
index = (index + 1) % dimensions_;
nearest(dx > 0 ? root.left_ : root.right_, target, index);
if (dx * dx >= bestDistance_)
return;
nearest(dx > 0 ? root.right_ : root.left_, target, index);
}
private Node makeTree(List<Node> nodes, int begin, int end, int index) {
if (end <= begin)
return null;
int n = begin + (end - begin)/2;
Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));
index = (index + 1) % dimensions_;
node.left_ = makeTree(nodes, begin, n, index);
node.right_ = makeTree(nodes, n + 1, end, index);
return node;
}
private static class NodeComparator implements Comparator<Node> {
private int index_;
private NodeComparator(int index) {
index_ = index;
}
public int compare(Node n1, Node n2) {
return Double.compare(n1.get(index_), n2.get(index_));
}
}
public static class Node {
private double[] coords_;
private Node left_ = null;
private Node right_ = null;
public Node(double[] coords) {
coords_ = coords;
}
public Node(double x, double y) {
this(new double[]{x, y});
}
public Node(double x, double y, double z) {
this(new double[]{x, y, z});
}
double get(int index) {
return coords_[index];
}
double distance(Node node) {
double dist = 0;
for (int i = 0; i < coords_.length; ++i) {
double d = coords_[i] - node.coords_[i];
dist += d * d;
}
return dist;
}
public String toString() {
StringBuilder s = new StringBuilder("(");
for (int i = 0; i < coords_.length; ++i) {
if (i > 0)
s.append(", ");
s.append(coords_[i]);
}
s.append(')');
return s.toString();
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
}
| public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, IntToInt mapper) {
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
update(numbers, new IntToInt() {
@Override
public int run(int x) {
return x * x;
}
});
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
}
| public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, IntToInt mapper) {
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
update(numbers, new IntToInt() {
@Override
public int run(int x) {
return x * x;
}
});
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"log"
"math/rand"
"sync"
"time"
)
var (
instance string
once sync.Once
)
func claim(color string, w *sync.WaitGroup) {
time.Sleep(time.Duration(rand.Intn(1e8)))
log.Println("trying to claim", color)
once.Do(func() { instance = color })
log.Printf("tried %s. instance: %s", color, instance)
w.Done()
}
func main() {
rand.Seed(time.Now().Unix())
var w sync.WaitGroup
w.Add(2)
go claim("red", &w)
go claim("blue", &w)
w.Wait()
log.Println("after trying both, instance =", instance)
}
| class Singleton
{
private static Singleton myInstance;
public static Singleton getInstance()
{
if (myInstance == null)
{
synchronized(Singleton.class)
{
if (myInstance == null)
{
myInstance = new Singleton();
}
}
}
return myInstance;
}
protected Singleton()
{
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"math"
)
type interval struct {
lower, upper float64
}
func stepAway(x float64) interval {
return interval {
math.Nextafter(x, math.Inf(-1)),
math.Nextafter(x, math.Inf(1))}
}
func safeAdd(a, b float64) interval {
return stepAway(a + b)
}
func main() {
a, b := 1.2, .03
fmt.Println(a, b, safeAdd(a, b))
}
| public class SafeAddition {
private static double stepDown(double d) {
return Math.nextAfter(d, Double.NEGATIVE_INFINITY);
}
private static double stepUp(double d) {
return Math.nextUp(d);
}
private static double[] safeAdd(double a, double b) {
return new double[]{stepDown(a + b), stepUp(a + b)};
}
public static void main(String[] args) {
double a = 1.2;
double b = 0.03;
double[] result = safeAdd(a, b);
System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]);
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package dogs
import "fmt"
var dog = "Salt"
var Dog = "Pepper"
var DOG = "Mustard"
func PackageSees() map[*string]int {
fmt.Println("Package sees:", dog, Dog, DOG)
return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}
}
| String dog = "Benjamin";
String Dog = "Samba";
String DOG = "Bernie";
@Inject Console console;
console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
|
Transform the following Go implementation into Java, maintaining the same output and logic. | for i := 10; i >= 0; i-- {
fmt.Println(i)
}
| for (int i = 10; i >= 0; i--) {
System.out.println(i);
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | import "io/ioutil"
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}
| import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
bw.write("abc");
}
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("*")
}
fmt.Printf("\n")
}
}
| for (Integer i = 0; i < 5; i++) {
String line = '';
for (Integer j = 0; j < i; j++) {
line += '*';
}
System.debug(line);
}
List<String> lines = new List<String> {
'*',
'**',
'***',
'****',
'*****'
};
for (String line : lines) {
System.debug(line);
}
|
Translate this program into Java but keep the logic exactly as in Go. | package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) 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 ord(n uint) string {
var suffix string
if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {
suffix = "th"
} else {
switch n % 10 {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
default:
suffix = "th"
}
}
return fmt.Sprintf("%s%s", commatize(n), suffix)
}
func main() {
const max = 10_000_000
data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},
{1e6, 1e6, 16}, {1e7, 1e7, 18}}
results := make(map[uint][]uint64)
for _, d := range data {
for i := d[0]; i <= d[1]; i++ {
results[i] = make([]uint64, 9)
}
}
var p uint64
outer:
for d := uint64(1); d < 10; d++ {
count := uint(0)
pow := uint64(1)
fl := d * 11
for nd := 3; nd < 20; nd++ {
slim := (d + 1) * pow
for s := d * pow; s < slim; s++ {
e := reverse(s)
mlim := uint64(1)
if nd%2 == 1 {
mlim = 10
}
for m := uint64(0); m < mlim; m++ {
if nd%2 == 0 {
p = s*pow*10 + e
} else {
p = s*pow*100 + m*pow*10 + e
}
if p%fl == 0 {
count++
if _, ok := results[count]; ok {
results[count][d-1] = p
}
if count == max {
continue outer
}
}
}
}
if nd%2 == 1 {
pow *= 10
}
}
}
for _, d := range data {
if d[0] != d[1] {
fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1]))
} else {
fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0]))
}
for i := 1; i <= 9; i++ {
fmt.Printf("%d: ", i)
for j := d[0]; j <= d[1]; j++ {
fmt.Printf("%*d ", d[2], results[j][i-1])
}
fmt.Println()
}
fmt.Println()
}
}
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(15, 100));
System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(10, 1000));
}
private static void displayMap(Map<Integer,List<Long>> map) {
for ( int key = 1 ; key <= 9 ; key++ ) {
System.out.println(key + " : " + map.get(key));
}
}
public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {
Map<Integer,List<Long>> map = new HashMap<>();
Map<Integer,Integer> mapCount = new HashMap<>();
for ( int i = 1 ; i <= 9 ; i++ ) {
map.put(i, new ArrayList<>());
mapCount.put(i, 0);
}
boolean notPopulated = true;
for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {
if ( isGapful(n) ) {
int index = (int) (n % 10);
if ( mapCount.get(index) < firstHowMany ) {
map.get(index).add(n);
mapCount.put(index, mapCount.get(index) + 1);
if ( map.get(index).size() > countReturned ) {
map.get(index).remove(0);
}
}
boolean finished = true;
for ( int i = 1 ; i <= 9 ; i++ ) {
if ( mapCount.get(i) < firstHowMany ) {
finished = false;
break;
}
}
if ( finished ) {
notPopulated = false;
}
}
}
return map;
}
public static boolean isGapful(long n) {
String s = Long.toString(n);
return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0;
}
public static int length(long n) {
int length = 0;
while ( n > 0 ) {
length += 1;
n /= 10;
}
return length;
}
public static long nextPalindrome(long n) {
int length = length(n);
if ( length % 2 == 0 ) {
length /= 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/10));
}
return Long.parseLong(n + reverse(n));
}
length = (length - 1) / 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/100));
}
return Long.parseLong(n + reverse(n/10));
}
private static boolean powerTen(long n) {
while ( n > 9 && n % 10 == 0 ) {
n /= 10;
}
return n == 1;
}
private static String reverse(long n) {
return (new StringBuilder(n + "")).reverse().toString();
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) 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 ord(n uint) string {
var suffix string
if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {
suffix = "th"
} else {
switch n % 10 {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
default:
suffix = "th"
}
}
return fmt.Sprintf("%s%s", commatize(n), suffix)
}
func main() {
const max = 10_000_000
data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},
{1e6, 1e6, 16}, {1e7, 1e7, 18}}
results := make(map[uint][]uint64)
for _, d := range data {
for i := d[0]; i <= d[1]; i++ {
results[i] = make([]uint64, 9)
}
}
var p uint64
outer:
for d := uint64(1); d < 10; d++ {
count := uint(0)
pow := uint64(1)
fl := d * 11
for nd := 3; nd < 20; nd++ {
slim := (d + 1) * pow
for s := d * pow; s < slim; s++ {
e := reverse(s)
mlim := uint64(1)
if nd%2 == 1 {
mlim = 10
}
for m := uint64(0); m < mlim; m++ {
if nd%2 == 0 {
p = s*pow*10 + e
} else {
p = s*pow*100 + m*pow*10 + e
}
if p%fl == 0 {
count++
if _, ok := results[count]; ok {
results[count][d-1] = p
}
if count == max {
continue outer
}
}
}
}
if nd%2 == 1 {
pow *= 10
}
}
}
for _, d := range data {
if d[0] != d[1] {
fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1]))
} else {
fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0]))
}
for i := 1; i <= 9; i++ {
fmt.Printf("%d: ", i)
for j := d[0]; j <= d[1]; j++ {
fmt.Printf("%*d ", d[2], results[j][i-1])
}
fmt.Println()
}
fmt.Println()
}
}
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(15, 100));
System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(10, 1000));
}
private static void displayMap(Map<Integer,List<Long>> map) {
for ( int key = 1 ; key <= 9 ; key++ ) {
System.out.println(key + " : " + map.get(key));
}
}
public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {
Map<Integer,List<Long>> map = new HashMap<>();
Map<Integer,Integer> mapCount = new HashMap<>();
for ( int i = 1 ; i <= 9 ; i++ ) {
map.put(i, new ArrayList<>());
mapCount.put(i, 0);
}
boolean notPopulated = true;
for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {
if ( isGapful(n) ) {
int index = (int) (n % 10);
if ( mapCount.get(index) < firstHowMany ) {
map.get(index).add(n);
mapCount.put(index, mapCount.get(index) + 1);
if ( map.get(index).size() > countReturned ) {
map.get(index).remove(0);
}
}
boolean finished = true;
for ( int i = 1 ; i <= 9 ; i++ ) {
if ( mapCount.get(i) < firstHowMany ) {
finished = false;
break;
}
}
if ( finished ) {
notPopulated = false;
}
}
}
return map;
}
public static boolean isGapful(long n) {
String s = Long.toString(n);
return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0;
}
public static int length(long n) {
int length = 0;
while ( n > 0 ) {
length += 1;
n /= 10;
}
return length;
}
public static long nextPalindrome(long n) {
int length = length(n);
if ( length % 2 == 0 ) {
length /= 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/10));
}
return Long.parseLong(n + reverse(n));
}
length = (length - 1) / 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/100));
}
return Long.parseLong(n + reverse(n/10));
}
private static boolean powerTen(long n) {
while ( n > 9 && n % 10 == 0 ) {
n /= 10;
}
return n == 1;
}
private static String reverse(long n) {
return (new StringBuilder(n + "")).reverse().toString();
}
}
|
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"
"image/png"
"os"
)
func main() {
const order = 8
const width = 1 << order
const margin = 10
bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
for y := 0; y < width; y++ {
for x := 0; x < width; x++ {
if x&y == 0 {
im.SetGray(x, y, gBlack)
}
}
}
f, err := os.Create("sierpinski.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| import javax.swing.*;
import java.awt.*;
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3;
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
func main() {
const order = 8
const width = 1 << order
const margin = 10
bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
for y := 0; y < width; y++ {
for x := 0; x < width; x++ {
if x&y == 0 {
im.SetGray(x, y, gBlack)
}
}
}
f, err := os.Create("sierpinski.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| import javax.swing.*;
import java.awt.*;
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3;
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import "fmt"
const (
m = iota
c
cm
cmc
)
func ncs(s []int) [][]int {
if len(s) < 3 {
return nil
}
return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)
}
var skip = []int{m, cm, cm, cmc}
var incl = []int{c, c, cmc, cmc}
func n2(ss, tail []int, seq int) [][]int {
if len(tail) == 0 {
if seq != cmc {
return nil
}
return [][]int{ss}
}
return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),
n2(append(ss, tail[0]), tail[1:], incl[seq])...)
}
func main() {
ss := ncs([]int{1, 2, 3, 4})
fmt.Println(len(ss), "non-continuous subsequences:")
for _, s := range ss {
fmt.Println(" ", s)
}
}
| public class NonContinuousSubsequences {
public static void main(String args[]) {
seqR("1234", "", 0, 0);
}
private static void seqR(String s, String c, int i, int added) {
if (i == s.length()) {
if (c.trim().length() > added)
System.out.println(c);
} else {
seqR(s, c + s.charAt(i), i + 1, added + 1);
seqR(s, c + ' ', i + 1, added);
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"github.com/fogleman/gg"
"strings"
)
func wordFractal(i int) string {
if i < 2 {
if i == 1 {
return "1"
}
return ""
}
var f1 strings.Builder
f1.WriteString("1")
var f2 strings.Builder
f2.WriteString("0")
for j := i - 2; j >= 1; j-- {
tmp := f2.String()
f2.WriteString(f1.String())
f1.Reset()
f1.WriteString(tmp)
}
return f2.String()
}
func draw(dc *gg.Context, x, y, dx, dy float64, wf string) {
for i, c := range wf {
dc.DrawLine(x, y, x+dx, y+dy)
x += dx
y += dy
if c == '0' {
tx := dx
dx = dy
if i%2 == 0 {
dx = -dy
}
dy = -tx
if i%2 == 0 {
dy = tx
}
}
}
}
func main() {
dc := gg.NewContext(450, 620)
dc.SetRGB(0, 0, 0)
dc.Clear()
wf := wordFractal(23)
draw(dc, 20, 20, 1, 0, wf)
dc.SetRGB(0, 1, 0)
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("fib_wordfractal.png")
}
| import java.awt.*;
import javax.swing.*;
public class FibonacciWordFractal extends JPanel {
String wordFractal;
FibonacciWordFractal(int n) {
setPreferredSize(new Dimension(450, 620));
setBackground(Color.white);
wordFractal = wordFractal(n);
}
public String wordFractal(int n) {
if (n < 2)
return n == 1 ? "1" : "";
StringBuilder f1 = new StringBuilder("1");
StringBuilder f2 = new StringBuilder("0");
for (n = n - 2; n > 0; n--) {
String tmp = f2.toString();
f2.append(f1);
f1.setLength(0);
f1.append(tmp);
}
return f2.toString();
}
void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {
for (int n = 0; n < wordFractal.length(); n++) {
g.drawLine(x, y, x + dx, y + dy);
x += dx;
y += dy;
if (wordFractal.charAt(n) == '0') {
int tx = dx;
dx = (n % 2 == 0) ? -dy : dy;
dy = (n % 2 == 0) ? tx : -tx;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawWordFractal(g, 20, 20, 1, 0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Fibonacci Word Fractal");
f.setResizable(false);
f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := uint64(3)
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
c := sieve(1e10 - 1)
limit := 10
start := 3
twins := 0
for i := 1; i < 11; i++ {
for i := start; i < limit; i += 2 {
if !c[i] && !c[i-2] {
twins++
}
}
fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins))
start = limit + 1
limit *= 10
}
}
| import java.math.BigInteger;
import java.util.Scanner;
public class twinPrimes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Search Size: ");
BigInteger max = input.nextBigInteger();
int counter = 0;
for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
}
}
System.out.println(counter + " twin prime pairs.");
}
public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
return false;
}
}
return true;
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
for i := 0; i < n; i++ {
r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
}
return r
}
| import java.util.Locale;
public class Test {
public static void main(String[] a) {
for (int n = 2; n < 6; n++)
unity(n);
}
public static void unity(int n) {
System.out.printf("%n%d: ", n);
for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {
double real = Math.cos(angle);
if (Math.abs(real) < 1.0E-3)
real = 0.0;
double imag = Math.sin(angle);
if (Math.abs(imag) < 1.0E-3)
imag = 0.0;
System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
}
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
for i := 0; i < n; i++ {
r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
}
return r
}
| import java.util.Locale;
public class Test {
public static void main(String[] a) {
for (int n = 2; n < 6; n++)
unity(n);
}
public static void unity(int n) {
System.out.printf("%n%d: ", n);
for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {
double real = Math.cos(angle);
if (Math.abs(real) < 1.0E-3)
real = 0.0;
double imag = Math.sin(angle);
if (Math.abs(imag) < 1.0E-3)
imag = 0.0;
System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
}
}
}
|
Port the provided Go code into Java while preserving the original functionality. |
package main
import "fmt"
func d(b byte) byte {
if b < '0' || b > '9' {
panic("digit 0-9 expected")
}
return b - '0'
}
func add(x, y string) string {
if len(y) > len(x) {
x, y = y, x
}
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
if i <= len(y) {
c += d(y[len(y)-i])
}
s := d(x[len(x)-i]) + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mulDigit(x string, y byte) string {
if y == '0' {
return "0"
}
y = d(y)
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
s := d(x[len(x)-i])*y + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mul(x, y string) string {
result := mulDigit(x, y[len(y)-1])
for i, zeros := 2, ""; i <= len(y); i++ {
zeros += "0"
result = add(result, mulDigit(x, y[len(y)-i])+zeros)
}
return result
}
const n = "18446744073709551616"
func main() {
fmt.Println(mul(n, n))
}
| public class LongMult {
private static byte[] stringToDigits(String num) {
byte[] result = new byte[num.length()];
for (int i = 0; i < num.length(); i++) {
char c = num.charAt(i);
if (c < '0' || c > '9') {
throw new IllegalArgumentException("Invalid digit " + c
+ " found at position " + i);
}
result[num.length() - 1 - i] = (byte) (c - '0');
}
return result;
}
public static String longMult(String num1, String num2) {
byte[] left = stringToDigits(num1);
byte[] right = stringToDigits(num2);
byte[] result = new byte[left.length + right.length];
for (int rightPos = 0; rightPos < right.length; rightPos++) {
byte rightDigit = right[rightPos];
byte temp = 0;
for (int leftPos = 0; leftPos < left.length; leftPos++) {
temp += result[leftPos + rightPos];
temp += rightDigit * left[leftPos];
result[leftPos + rightPos] = (byte) (temp % 10);
temp /= 10;
}
int destPos = rightPos + left.length;
while (temp != 0) {
temp += result[destPos] & 0xFFFFFFFFL;
result[destPos] = (byte) (temp % 10);
temp /= 10;
destPos++;
}
}
StringBuilder stringResultBuilder = new StringBuilder(result.length);
for (int i = result.length - 1; i >= 0; i--) {
byte digit = result[i];
if (digit != 0 || stringResultBuilder.length() > 0) {
stringResultBuilder.append((char) (digit + '0'));
}
}
return stringResultBuilder.toString();
}
public static void main(String[] args) {
System.out.println(longMult("18446744073709551616",
"18446744073709551616"));
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"math/big"
)
var big1 = new(big.Int).SetUint64(1)
func solvePell(nn uint64) (*big.Int, *big.Int) {
n := new(big.Int).SetUint64(nn)
x := new(big.Int).Set(n)
x.Sqrt(x)
y := new(big.Int).Set(x)
z := new(big.Int).SetUint64(1)
r := new(big.Int).Lsh(x, 1)
e1 := new(big.Int).SetUint64(1)
e2 := new(big.Int)
f1 := new(big.Int)
f2 := new(big.Int).SetUint64(1)
t := new(big.Int)
u := new(big.Int)
a := new(big.Int)
b := new(big.Int)
for {
t.Mul(r, z)
y.Sub(t, y)
t.Mul(y, y)
t.Sub(n, t)
z.Quo(t, z)
t.Add(x, y)
r.Quo(t, z)
u.Set(e1)
e1.Set(e2)
t.Mul(r, e2)
e2.Add(t, u)
u.Set(f1)
f1.Set(f2)
t.Mul(r, f2)
f2.Add(t, u)
t.Mul(x, f2)
a.Add(e2, t)
b.Set(f2)
t.Mul(a, a)
u.Mul(n, b)
u.Mul(u, b)
t.Sub(t, u)
if t.Cmp(big1) == 0 {
return a, b
}
}
}
func main() {
ns := []uint64{61, 109, 181, 277}
for _, n := range ns {
x, y := solvePell(n)
fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y)
}
}
| import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class PellsEquation {
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
for ( int n : new int[] {61, 109, 181, 277, 8941} ) {
BigInteger[] pell = pellsEquation(n);
System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1]));
}
}
private static final BigInteger[] pellsEquation(int n) {
int a0 = (int) Math.sqrt(n);
if ( a0*a0 == n ) {
throw new IllegalArgumentException("ERROR 102: Invalid n = " + n);
}
List<Integer> continuedFrac = continuedFraction(n);
int count = 0;
BigInteger ajm2 = BigInteger.ONE;
BigInteger ajm1 = new BigInteger(a0 + "");
BigInteger bjm2 = BigInteger.ZERO;
BigInteger bjm1 = BigInteger.ONE;
boolean stop = (continuedFrac.size() % 2 == 1);
if ( continuedFrac.size() == 2 ) {
stop = true;
}
while ( true ) {
count++;
BigInteger bn = new BigInteger(continuedFrac.get(count) + "");
BigInteger aj = bn.multiply(ajm1).add(ajm2);
BigInteger bj = bn.multiply(bjm1).add(bjm2);
if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {
return new BigInteger[] {aj, bj};
}
else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {
stop = true;
}
if ( count == continuedFrac.size()-1 ) {
count = 0;
}
ajm2 = ajm1;
ajm1 = aj;
bjm2 = bjm1;
bjm1 = bj;
}
}
private static final List<Integer> continuedFraction(int n) {
List<Integer> answer = new ArrayList<Integer>();
int a0 = (int) Math.sqrt(n);
answer.add(a0);
int a = -a0;
int aStart = a;
int b = 1;
int bStart = b;
while ( true ) {
int[] values = iterateFrac(n, a, b);
answer.add(values[0]);
a = values[1];
b = values[2];
if (a == aStart && b == bStart) break;
}
return answer;
}
private static final int[] iterateFrac(int n, int a, int b) {
int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));
int[] answer = new int[3];
answer[0] = x;
answer[1] = -(b * a + x *(n - a * a)) / b;
answer[2] = (n - a * a) / b;
return answer;
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
pat := make([]byte, 4)
rand.Seed(time.Now().Unix())
r := rand.Perm(9)
for i := range pat {
pat[i] = '1' + byte(r[i])
}
valid := []byte("123456789")
guess:
for in := bufio.NewReader(os.Stdin); ; {
fmt.Print("Guess: ")
guess, err := in.ReadString('\n')
if err != nil {
fmt.Println("\nSo, bye.")
return
}
guess = strings.TrimSpace(guess)
if len(guess) != 4 {
fmt.Println("Please guess a four digit number.")
continue
}
var cows, bulls int
for ig, cg := range guess {
if strings.IndexRune(guess[:ig], cg) >= 0 {
fmt.Printf("Repeated digit: %c\n", cg)
continue guess
}
switch bytes.IndexByte(pat, byte(cg)) {
case -1:
if bytes.IndexByte(valid, byte(cg)) == -1 {
fmt.Printf("Invalid digit: %c\n", cg)
continue guess
}
default:
cows++
case ig:
bulls++
}
}
fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
if bulls == 4 {
fmt.Println("You got it.")
return
}
}
}
| import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class BullsAndCows{
public static void main(String[] args){
Random gen= new Random();
int target;
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
String targetStr = target +"";
boolean guessed = false;
Scanner input = new Scanner(System.in);
int guesses = 0;
do{
int bulls = 0;
int cows = 0;
System.out.print("Guess a 4-digit number with no duplicate digits: ");
int guess;
try{
guess = input.nextInt();
if(hasDupes(guess) || guess < 1000) continue;
}catch(InputMismatchException e){
continue;
}
guesses++;
String guessStr = guess + "";
for(int i= 0;i < 4;i++){
if(guessStr.charAt(i) == targetStr.charAt(i)){
bulls++;
}else if(targetStr.contains(guessStr.charAt(i)+"")){
cows++;
}
}
if(bulls == 4){
guessed = true;
}else{
System.out.println(cows+" Cows and "+bulls+" Bulls.");
}
}while(!guessed);
System.out.println("You won after "+guesses+" guesses!");
}
public static boolean hasDupes(int num){
boolean[] digs = new boolean[10];
while(num > 0){
if(digs[num%10]) return true;
digs[num%10] = true;
num/= 10;
}
return false;
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import "fmt"
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
bubblesort(list)
fmt.Println("sorted! ", list)
}
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
for index := 0; index < itemCount; index++ {
if a[index] > a[index+1] {
a[index], a[index+1] = a[index+1], a[index]
hasChanged = true
}
}
if hasChanged == false {
break
}
}
}
| public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
boolean changed = false;
do {
changed = false;
for (int a = 0; a < comparable.length - 1; a++) {
if (comparable[a].compareTo(comparable[a + 1]) > 0) {
E tmp = comparable[a];
comparable[a] = comparable[a + 1];
comparable[a + 1] = tmp;
changed = true;
}
}
} while (changed);
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
func prodDivisors(n int) int {
prod := 1
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
prod *= i
j := n / i
if j != i {
prod *= j
}
}
i += k
}
return prod
}
func main() {
fmt.Println("The products of positive divisors for the first 50 positive integers are:")
for i := 1; i <= 50; i++ {
fmt.Printf("%9d ", prodDivisors(i))
if i%5 == 0 {
fmt.Println()
}
}
}
| public class ProductOfDivisors {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
private static long divisorProduct(long n) {
return (long) Math.pow(n, divisorCount(n) / 2.0);
}
public static void main(String[] args) {
final long limit = 50;
System.out.printf("Product of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; n++) {
System.out.printf("%11d", divisorProduct(n));
if (n % 5 == 0) {
System.out.println();
}
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
func prodDivisors(n int) int {
prod := 1
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
prod *= i
j := n / i
if j != i {
prod *= j
}
}
i += k
}
return prod
}
func main() {
fmt.Println("The products of positive divisors for the first 50 positive integers are:")
for i := 1; i <= 50; i++ {
fmt.Printf("%9d ", prodDivisors(i))
if i%5 == 0 {
fmt.Println()
}
}
}
| public class ProductOfDivisors {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
private static long divisorProduct(long n) {
return (long) Math.pow(n, divisorCount(n) / 2.0);
}
public static void main(String[] args) {
final long limit = 50;
System.out.printf("Product of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; n++) {
System.out.printf("%11d", divisorProduct(n));
if (n % 5 == 0) {
System.out.println();
}
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
func prodDivisors(n int) int {
prod := 1
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
prod *= i
j := n / i
if j != i {
prod *= j
}
}
i += k
}
return prod
}
func main() {
fmt.Println("The products of positive divisors for the first 50 positive integers are:")
for i := 1; i <= 50; i++ {
fmt.Printf("%9d ", prodDivisors(i))
if i%5 == 0 {
fmt.Println()
}
}
}
| public class ProductOfDivisors {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
private static long divisorProduct(long n) {
return (long) Math.pow(n, divisorCount(n) / 2.0);
}
public static void main(String[] args) {
final long limit = 50;
System.out.printf("Product of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; n++) {
System.out.printf("%11d", divisorProduct(n));
if (n % 5 == 0) {
System.out.println();
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Println(err)
return
}
if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
fmt.Println(err)
}
}
| import java.io.*;
public class FileIODemo {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("ouput.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import "fmt"
func main() {
var a, b int
fmt.Print("enter two integers: ")
fmt.Scanln(&a, &b)
fmt.Printf("%d + %d = %d\n", a, b, a+b)
fmt.Printf("%d - %d = %d\n", a, b, a-b)
fmt.Printf("%d * %d = %d\n", a, b, a*b)
fmt.Printf("%d / %d = %d\n", a, b, a/b)
fmt.Printf("%d %% %d = %d\n", a, b, a%b)
}
| import java.util.Scanner;
public class IntegerArithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;
int difference = a - b;
int product = a * b;
int division = a / b;
int remainder = a % b;
System.out.println("a + b = " + sum);
System.out.println("a - b = " + difference);
System.out.println("a * b = " + product);
System.out.println("quotient of a / b = " + division);
System.out.println("remainder of a / b = " + remainder);
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
}
| import java.util.Arrays;
public class Transpose{
public static void main(String[] args){
double[][] m = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}};
double[][] ans = new double[m[0].length][m.length];
for(int rows = 0; rows < m.length; rows++){
for(int cols = 0; cols < m[0].length; cols++){
ans[cols][rows] = m[rows][cols];
}
}
for(double[] i:ans){
System.out.println(Arrays.toString(i));
}
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
}
| import java.util.Arrays;
public class Transpose{
public static void main(String[] args){
double[][] m = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}};
double[][] ans = new double[m[0].length][m.length];
for(int rows = 0; rows < m.length; rows++){
for(int cols = 0; cols < m[0].length; cols++){
ans[cols][rows] = m[rows][cols];
}
}
for(double[] i:ans){
System.out.println(Arrays.toString(i));
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, true)
}
| module test
{
@Inject Console console;
static Boolean show(String name, Boolean value)
{
console.print($"{name}()={value}");
return value;
}
void run()
{
val a = show("a", _);
val b = show("b", _);
for (Boolean v1 : False..True)
{
for (Boolean v2 : False..True)
{
console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}");
console.print();
console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}");
console.print();
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
| public class RecursionTest {
private static void recurse(int i) {
try {
recurse(i+1);
} catch (StackOverflowError e) {
System.out.print("Recursion depth on this system is " + i + ".");
}
}
public static void main(String[] args) {
recurse(0);
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
| public class RecursionTest {
private static void recurse(int i) {
try {
recurse(i+1);
} catch (StackOverflowError e) {
System.out.print("Recursion depth on this system is " + i + ".");
}
}
public static void main(String[] args) {
recurse(0);
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
| public class RecursionTest {
private static void recurse(int i) {
try {
recurse(i+1);
} catch (StackOverflowError e) {
System.out.print("Recursion depth on this system is " + i + ".");
}
}
public static void main(String[] args) {
recurse(0);
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import "fmt"
func mod(n, m int) int {
return ((n % m) + m) % m
}
func isPrime(n int) bool {
if n < 2 { return false }
if n % 2 == 0 { return n == 2 }
if n % 3 == 0 { return n == 3 }
d := 5
for d * d <= n {
if n % d == 0 { return false }
d += 2
if n % d == 0 { return false }
d += 4
}
return true
}
func carmichael(p1 int) {
for h3 := 2; h3 < p1; h3++ {
for d := 1; d < h3 + p1; d++ {
if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {
p2 := 1 + (p1 - 1) * (h3 + p1) / d
if !isPrime(p2) { continue }
p3 := 1 + p1 * p2 / h3
if !isPrime(p3) { continue }
if p2 * p3 % (p1 - 1) != 1 { continue }
c := p1 * p2 * p3
fmt.Printf("%2d %4d %5d %d\n", p1, p2, p3, c)
}
}
}
}
func main() {
fmt.Println("The following are Carmichael munbers for p1 <= 61:\n")
fmt.Println("p1 p2 p3 product")
fmt.Println("== == == =======")
for p1 := 2; p1 <= 61; p1++ {
if isPrime(p1) { carmichael(p1) }
}
}
| public class Test {
static int mod(int n, int m) {
return ((n % m) + m) % m;
}
static boolean isPrime(int n) {
if (n == 2 || n == 3)
return true;
else if (n < 2 || n % 2 == 0 || n % 3 == 0)
return false;
for (int div = 5, inc = 2; Math.pow(div, 2) <= n;
div += inc, inc = 6 - inc)
if (n % div == 0)
return false;
return true;
}
public static void main(String[] args) {
for (int p = 2; p < 62; p++) {
if (!isPrime(p))
continue;
for (int h3 = 2; h3 < p; h3++) {
int g = h3 + p;
for (int d = 1; d < g; d++) {
if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)
continue;
int q = 1 + (p - 1) * g / d;
if (!isPrime(q))
continue;
int r = 1 + (p * q / h3);
if (!isPrime(r) || (q * r) % (p - 1) != 1)
continue;
System.out.printf("%d x %d x %d%n", p, q, r);
}
}
}
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"code.google.com/p/x-go-binding/ui/x11"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"os"
"time"
)
var randcol = genrandcol()
func genrandcol() <-chan color.Color {
c := make(chan color.Color)
go func() {
for {
select {
case c <- image.Black:
case c <- image.White:
}
}
}()
return c
}
func gennoise(screen draw.Image) {
for y := 0; y < 240; y++ {
for x := 0; x < 320; x++ {
screen.Set(x, y, <-randcol)
}
}
}
func fps() chan<- bool {
up := make(chan bool)
go func() {
var frames int64
var lasttime time.Time
var totaltime time.Duration
for {
<-up
frames++
now := time.Now()
totaltime += now.Sub(lasttime)
if totaltime > time.Second {
fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
frames = 0
totaltime = 0
}
lasttime = now
}
}()
return up
}
func main() {
win, err := x11.NewWindow()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer win.Close()
go func() {
upfps := fps()
screen := win.Screen()
for {
gennoise(screen)
win.FlushImage()
upfps <- true
}
}()
for _ = range win.EventChan() {
}
}
| import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.Arrays;
import java.util.Random;
import javax.swing.*;
public class ImageNoise {
int framecount = 0;
int fps = 0;
BufferedImage image;
Kernel kernel;
ConvolveOp cop;
JFrame frame = new JFrame("Java Image Noise");
JPanel panel = new JPanel() {
private int show_fps = 0;
private MouseAdapter ma = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
show_fps = (show_fps + 1) % 3;
}
};
{addMouseListener(ma);}
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
@Override
@SuppressWarnings("fallthrough")
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
drawNoise();
g.drawImage(image, 0, 0, null);
switch (show_fps) {
case 0:
int xblur = getWidth() - 130, yblur = getHeight() - 32;
BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);
BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
cop.filter(bc, bs);
g.drawImage(bs, xblur, yblur , null);
case 1:
g.setColor(Color.RED);
g.setFont(new Font("Monospaced", Font.BOLD, 20));
g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10);
}
framecount++;
}
};
Timer repainter = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
});
Timer framerateChecker = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fps = framecount;
framecount = 0;
}
});
public ImageNoise() {
float[] vals = new float[121];
Arrays.fill(vals, 1/121f);
kernel = new Kernel(11, 11, vals);
cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
repainter.start();
framerateChecker.start();
}
void drawNoise() {
int w = panel.getWidth(), h = panel.getHeight();
if (null == image || image.getWidth() != w || image.getHeight() != h) {
image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
}
Random rand = new Random();
int[] data = new int[w * h];
for (int x = 0; x < w * h / 32; x++) {
int r = rand.nextInt();
for (int i = 0; i < 32; i++) {
data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;
r >>>= 1;
}
}
image.getRaster().setPixels(0, 0, w, h, data);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ImageNoise i = new ImageNoise();
}
});
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"code.google.com/p/x-go-binding/ui/x11"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"os"
"time"
)
var randcol = genrandcol()
func genrandcol() <-chan color.Color {
c := make(chan color.Color)
go func() {
for {
select {
case c <- image.Black:
case c <- image.White:
}
}
}()
return c
}
func gennoise(screen draw.Image) {
for y := 0; y < 240; y++ {
for x := 0; x < 320; x++ {
screen.Set(x, y, <-randcol)
}
}
}
func fps() chan<- bool {
up := make(chan bool)
go func() {
var frames int64
var lasttime time.Time
var totaltime time.Duration
for {
<-up
frames++
now := time.Now()
totaltime += now.Sub(lasttime)
if totaltime > time.Second {
fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
frames = 0
totaltime = 0
}
lasttime = now
}
}()
return up
}
func main() {
win, err := x11.NewWindow()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer win.Close()
go func() {
upfps := fps()
screen := win.Screen()
for {
gennoise(screen)
win.FlushImage()
upfps <- true
}
}()
for _ = range win.EventChan() {
}
}
| import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.Arrays;
import java.util.Random;
import javax.swing.*;
public class ImageNoise {
int framecount = 0;
int fps = 0;
BufferedImage image;
Kernel kernel;
ConvolveOp cop;
JFrame frame = new JFrame("Java Image Noise");
JPanel panel = new JPanel() {
private int show_fps = 0;
private MouseAdapter ma = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
show_fps = (show_fps + 1) % 3;
}
};
{addMouseListener(ma);}
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
@Override
@SuppressWarnings("fallthrough")
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
drawNoise();
g.drawImage(image, 0, 0, null);
switch (show_fps) {
case 0:
int xblur = getWidth() - 130, yblur = getHeight() - 32;
BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);
BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
cop.filter(bc, bs);
g.drawImage(bs, xblur, yblur , null);
case 1:
g.setColor(Color.RED);
g.setFont(new Font("Monospaced", Font.BOLD, 20));
g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10);
}
framecount++;
}
};
Timer repainter = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
});
Timer framerateChecker = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fps = framecount;
framecount = 0;
}
});
public ImageNoise() {
float[] vals = new float[121];
Arrays.fill(vals, 1/121f);
kernel = new Kernel(11, 11, vals);
cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
repainter.start();
framerateChecker.start();
}
void drawNoise() {
int w = panel.getWidth(), h = panel.getHeight();
if (null == image || image.getWidth() != w || image.getHeight() != h) {
image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
}
Random rand = new Random();
int[] data = new int[w * h];
for (int x = 0; x < w * h / 32; x++) {
int r = rand.nextInt();
for (int i = 0; i < 32; i++) {
data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;
r >>>= 1;
}
}
image.getRaster().setPixels(0, 0, w, h, data);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ImageNoise i = new ImageNoise();
}
});
}
}
|
Generate an equivalent Java version of this Go code. | package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
func isPerfect(n int64) bool {
switch n {
case 6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128:
return true
}
return false
}
func main() {
for n := int64(1); ; n++ {
if isPerfect(n) != computePerfect(n) {
panic("bug")
}
if n%1e3 == 0 {
fmt.Println("tested", n)
}
}
}
| public static boolean perf(int n){
int sum= 0;
for(int i= 1;i < n;i++){
if(n % i == 0){
sum+= i;
}
}
return sum == n;
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, aMax)
for pole, space := 0, all; pole < aMax; pole++ {
abacus[pole] = space[:len(a)]
space = space[len(a):]
}
var wg sync.WaitGroup
wg.Add(len(a))
for row, n := range a {
go func(row, n int) {
for pole := 0; pole < n; pole++ {
abacus[pole][row] = bead
}
wg.Done()
}(row, n)
}
wg.Wait()
wg.Add(aMax)
for _, pole := range abacus {
go func(pole []byte) {
top := 0
for row, space := range pole {
if space == bead {
pole[row] = 0
pole[top] = bead
top++
}
}
wg.Done()
}(pole)
}
wg.Wait()
for row := range a {
x := 0
for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
x++
}
a[len(a)-1-row] = x
}
}
| public class BeadSort
{
public static void main(String[] args)
{
BeadSort now=new BeadSort();
int[] arr=new int[(int)(Math.random()*11)+5];
for(int i=0;i<arr.length;i++)
arr[i]=(int)(Math.random()*10);
System.out.print("Unsorted: ");
now.display1D(arr);
int[] sort=now.beadSort(arr);
System.out.print("Sorted: ");
now.display1D(sort);
}
int[] beadSort(int[] arr)
{
int max=a[0];
for(int i=1;i<arr.length;i++)
if(arr[i]>max)
max=arr[i];
char[][] grid=new char[arr.length][max];
int[] levelcount=new int[max];
for(int i=0;i<max;i++)
{
levelcount[i]=0;
for(int j=0;j<arr.length;j++)
grid[j][i]='_';
}
for(int i=0;i<arr.length;i++)
{
int num=arr[i];
for(int j=0;num>0;j++)
{
grid[levelcount[j]++][j]='*';
num--;
}
}
System.out.println();
display2D(grid);
int[] sorted=new int[arr.length];
for(int i=0;i<arr.length;i++)
{
int putt=0;
for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)
putt++;
sorted[i]=putt;
}
return sorted;
}
void display1D(int[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
void display1D(char[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
void display2D(char[][] arr)
{
for(int i=0;i<arr.length;i++)
display1D(arr[i]);
System.out.println();
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func()
func initDraw() {
draw = map[int]func(){
1: func() { horiz(6, 10, 0) },
2: func() { horiz(6, 10, 4) },
3: func() { diagd(6, 10, 0) },
4: func() { diagu(6, 10, 4) },
5: func() { draw[1](); draw[4]() },
6: func() { verti(0, 4, 10) },
7: func() { draw[1](); draw[6]() },
8: func() { draw[2](); draw[6]() },
9: func() { draw[1](); draw[8]() },
10: func() { horiz(0, 4, 0) },
20: func() { horiz(0, 4, 4) },
30: func() { diagu(0, 4, 4) },
40: func() { diagd(0, 4, 0) },
50: func() { draw[10](); draw[40]() },
60: func() { verti(0, 4, 0) },
70: func() { draw[10](); draw[60]() },
80: func() { draw[20](); draw[60]() },
90: func() { draw[10](); draw[80]() },
100: func() { horiz(6, 10, 14) },
200: func() { horiz(6, 10, 10) },
300: func() { diagu(6, 10, 14) },
400: func() { diagd(6, 10, 10) },
500: func() { draw[100](); draw[400]() },
600: func() { verti(10, 14, 10) },
700: func() { draw[100](); draw[600]() },
800: func() { draw[200](); draw[600]() },
900: func() { draw[100](); draw[800]() },
1000: func() { horiz(0, 4, 14) },
2000: func() { horiz(0, 4, 10) },
3000: func() { diagd(0, 4, 10) },
4000: func() { diagu(0, 4, 14) },
5000: func() { draw[1000](); draw[4000]() },
6000: func() { verti(10, 14, 0) },
7000: func() { draw[1000](); draw[6000]() },
8000: func() { draw[2000](); draw[6000]() },
9000: func() { draw[1000](); draw[8000]() },
}
}
func printNumeral() {
for i := 0; i < 15; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("%s ", n[i][j])
}
fmt.Println()
}
fmt.Println()
}
func main() {
initDraw()
numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}
for _, number := range numbers {
initN()
fmt.Printf("%d:\n", number)
thousands := number / 1000
number %= 1000
hundreds := number / 100
number %= 100
tens := number / 10
ones := number % 10
if thousands > 0 {
draw[thousands*1000]()
}
if hundreds > 0 {
draw[hundreds*100]()
}
if tens > 0 {
draw[tens*10]()
}
if ones > 0 {
draw[ones]()
}
printNumeral()
}
}
| import java.util.Arrays;
import java.util.List;
public class Cistercian {
private static final int SIZE = 15;
private final char[][] canvas = new char[SIZE][SIZE];
public Cistercian(int n) {
initN();
draw(n);
}
public void initN() {
for (var row : canvas) {
Arrays.fill(row, ' ');
row[5] = 'x';
}
}
private void horizontal(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
private void vertical(int r1, int r2, int c) {
for (int r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
private void diagd(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
private void diagu(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
private void draw(int v) {
var thousands = v / 1000;
v %= 1000;
var hundreds = v / 100;
v %= 100;
var tens = v / 10;
var ones = v % 10;
drawPart(1000 * thousands);
drawPart(100 * hundreds);
drawPart(10 * tens);
drawPart(ones);
}
private void drawPart(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawPart(1);
drawPart(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawPart(1);
drawPart(6);
break;
case 8:
drawPart(2);
drawPart(6);
break;
case 9:
drawPart(1);
drawPart(8);
break;
case 10:
horizontal(0, 4, 0);
break;
case 20:
horizontal(0, 4, 4);
break;
case 30:
diagu(0, 4, 4);
break;
case 40:
diagd(0, 4, 0);
break;
case 50:
drawPart(10);
drawPart(40);
break;
case 60:
vertical(0, 4, 0);
break;
case 70:
drawPart(10);
drawPart(60);
break;
case 80:
drawPart(20);
drawPart(60);
break;
case 90:
drawPart(10);
drawPart(80);
break;
case 100:
horizontal(6, 10, 14);
break;
case 200:
horizontal(6, 10, 10);
break;
case 300:
diagu(6, 10, 14);
break;
case 400:
diagd(6, 10, 10);
break;
case 500:
drawPart(100);
drawPart(400);
break;
case 600:
vertical(10, 14, 10);
break;
case 700:
drawPart(100);
drawPart(600);
break;
case 800:
drawPart(200);
drawPart(600);
break;
case 900:
drawPart(100);
drawPart(800);
break;
case 1000:
horizontal(0, 4, 14);
break;
case 2000:
horizontal(0, 4, 10);
break;
case 3000:
diagd(0, 4, 10);
break;
case 4000:
diagu(0, 4, 14);
break;
case 5000:
drawPart(1000);
drawPart(4000);
break;
case 6000:
vertical(10, 14, 0);
break;
case 7000:
drawPart(1000);
drawPart(6000);
break;
case 8000:
drawPart(2000);
drawPart(6000);
break;
case 9000:
drawPart(1000);
drawPart(8000);
break;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (var row : canvas) {
builder.append(row);
builder.append('\n');
}
return builder.toString();
}
public static void main(String[] args) {
for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
System.out.printf("%d:\n", number);
var c = new Cistercian(number);
System.out.println(c);
}
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func()
func initDraw() {
draw = map[int]func(){
1: func() { horiz(6, 10, 0) },
2: func() { horiz(6, 10, 4) },
3: func() { diagd(6, 10, 0) },
4: func() { diagu(6, 10, 4) },
5: func() { draw[1](); draw[4]() },
6: func() { verti(0, 4, 10) },
7: func() { draw[1](); draw[6]() },
8: func() { draw[2](); draw[6]() },
9: func() { draw[1](); draw[8]() },
10: func() { horiz(0, 4, 0) },
20: func() { horiz(0, 4, 4) },
30: func() { diagu(0, 4, 4) },
40: func() { diagd(0, 4, 0) },
50: func() { draw[10](); draw[40]() },
60: func() { verti(0, 4, 0) },
70: func() { draw[10](); draw[60]() },
80: func() { draw[20](); draw[60]() },
90: func() { draw[10](); draw[80]() },
100: func() { horiz(6, 10, 14) },
200: func() { horiz(6, 10, 10) },
300: func() { diagu(6, 10, 14) },
400: func() { diagd(6, 10, 10) },
500: func() { draw[100](); draw[400]() },
600: func() { verti(10, 14, 10) },
700: func() { draw[100](); draw[600]() },
800: func() { draw[200](); draw[600]() },
900: func() { draw[100](); draw[800]() },
1000: func() { horiz(0, 4, 14) },
2000: func() { horiz(0, 4, 10) },
3000: func() { diagd(0, 4, 10) },
4000: func() { diagu(0, 4, 14) },
5000: func() { draw[1000](); draw[4000]() },
6000: func() { verti(10, 14, 0) },
7000: func() { draw[1000](); draw[6000]() },
8000: func() { draw[2000](); draw[6000]() },
9000: func() { draw[1000](); draw[8000]() },
}
}
func printNumeral() {
for i := 0; i < 15; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("%s ", n[i][j])
}
fmt.Println()
}
fmt.Println()
}
func main() {
initDraw()
numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}
for _, number := range numbers {
initN()
fmt.Printf("%d:\n", number)
thousands := number / 1000
number %= 1000
hundreds := number / 100
number %= 100
tens := number / 10
ones := number % 10
if thousands > 0 {
draw[thousands*1000]()
}
if hundreds > 0 {
draw[hundreds*100]()
}
if tens > 0 {
draw[tens*10]()
}
if ones > 0 {
draw[ones]()
}
printNumeral()
}
}
| import java.util.Arrays;
import java.util.List;
public class Cistercian {
private static final int SIZE = 15;
private final char[][] canvas = new char[SIZE][SIZE];
public Cistercian(int n) {
initN();
draw(n);
}
public void initN() {
for (var row : canvas) {
Arrays.fill(row, ' ');
row[5] = 'x';
}
}
private void horizontal(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
private void vertical(int r1, int r2, int c) {
for (int r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
private void diagd(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
private void diagu(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
private void draw(int v) {
var thousands = v / 1000;
v %= 1000;
var hundreds = v / 100;
v %= 100;
var tens = v / 10;
var ones = v % 10;
drawPart(1000 * thousands);
drawPart(100 * hundreds);
drawPart(10 * tens);
drawPart(ones);
}
private void drawPart(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawPart(1);
drawPart(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawPart(1);
drawPart(6);
break;
case 8:
drawPart(2);
drawPart(6);
break;
case 9:
drawPart(1);
drawPart(8);
break;
case 10:
horizontal(0, 4, 0);
break;
case 20:
horizontal(0, 4, 4);
break;
case 30:
diagu(0, 4, 4);
break;
case 40:
diagd(0, 4, 0);
break;
case 50:
drawPart(10);
drawPart(40);
break;
case 60:
vertical(0, 4, 0);
break;
case 70:
drawPart(10);
drawPart(60);
break;
case 80:
drawPart(20);
drawPart(60);
break;
case 90:
drawPart(10);
drawPart(80);
break;
case 100:
horizontal(6, 10, 14);
break;
case 200:
horizontal(6, 10, 10);
break;
case 300:
diagu(6, 10, 14);
break;
case 400:
diagd(6, 10, 10);
break;
case 500:
drawPart(100);
drawPart(400);
break;
case 600:
vertical(10, 14, 10);
break;
case 700:
drawPart(100);
drawPart(600);
break;
case 800:
drawPart(200);
drawPart(600);
break;
case 900:
drawPart(100);
drawPart(800);
break;
case 1000:
horizontal(0, 4, 14);
break;
case 2000:
horizontal(0, 4, 10);
break;
case 3000:
diagd(0, 4, 10);
break;
case 4000:
diagu(0, 4, 14);
break;
case 5000:
drawPart(1000);
drawPart(4000);
break;
case 6000:
vertical(10, 14, 0);
break;
case 7000:
drawPart(1000);
drawPart(6000);
break;
case 8000:
drawPart(2000);
drawPart(6000);
break;
case 9000:
drawPart(1000);
drawPart(8000);
break;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (var row : canvas) {
builder.append(row);
builder.append('\n');
}
return builder.toString();
}
public static void main(String[] args) {
for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
System.out.printf("%d:\n", number);
var c = new Cistercian(number);
System.out.println(c);
}
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
}
| import java.math.BigInteger;
class IntegerPower {
public static void main(String[] args) {
BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());
String str = power.toString();
int len = str.length();
System.out.printf("5**4**3**2 = %s...%s and has %d digits%n",
str.substring(0, 20), str.substring(len - 20), len);
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| using System;
namespace Sphere {
internal class Program {
private const string Shades = ".:!*oe%&#@";
private static readonly double[] Light = {30, 30, -50};
private static void Normalize(double[] v) {
double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len;
v[1] /= len;
v[2] /= len;
}
private static double Dot(double[] x, double[] y) {
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
public static void DrawSphere(double r, double k, double ambient) {
var vec = new double[3];
for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {
double x = i + .5;
for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {
double y = j/2.0 + .5;
if(x*x + y*y <= r*r) {
vec[0] = x;
vec[1] = y;
vec[2] = Math.Sqrt(r*r - x*x - y*y);
Normalize(vec);
double b = Math.Pow(Dot(Light, vec), k) + ambient;
int intensity = (b <= 0)
? Shades.Length - 2
: (int)Math.Max((1 - b)*(Shades.Length - 1), 0);
Console.Write(Shades[intensity]);
}
else
Console.Write(' ');
}
Console.WriteLine();
}
}
private static void Main() {
Normalize(Light);
DrawSphere(6, 4, .1);
DrawSphere(10, 2, .4);
Console.ReadKey();
}
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| using System;
namespace Sphere {
internal class Program {
private const string Shades = ".:!*oe%&#@";
private static readonly double[] Light = {30, 30, -50};
private static void Normalize(double[] v) {
double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len;
v[1] /= len;
v[2] /= len;
}
private static double Dot(double[] x, double[] y) {
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
public static void DrawSphere(double r, double k, double ambient) {
var vec = new double[3];
for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {
double x = i + .5;
for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {
double y = j/2.0 + .5;
if(x*x + y*y <= r*r) {
vec[0] = x;
vec[1] = y;
vec[2] = Math.Sqrt(r*r - x*x - y*y);
Normalize(vec);
double b = Math.Pow(Dot(Light, vec), k) + ambient;
int intensity = (b <= 0)
? Shades.Length - 2
: (int)Math.Max((1 - b)*(Shades.Length - 1), 0);
Console.Write(Shades[intensity]);
}
else
Console.Write(' ');
}
Console.WriteLine();
}
}
private static void Main() {
Normalize(Light);
DrawSphere(6, 4, .1);
DrawSphere(10, 2, .4);
Console.ReadKey();
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
)
var index map[string][]int
var indexed []doc
type doc struct {
file string
title string
}
func main() {
index = make(map[string][]int)
if err := indexDir("docs"); err != nil {
fmt.Println(err)
return
}
ui()
}
func indexDir(dir string) error {
df, err := os.Open(dir)
if err != nil {
return err
}
fis, err := df.Readdir(-1)
if err != nil {
return err
}
if len(fis) == 0 {
return errors.New(fmt.Sprintf("no files in %s", dir))
}
indexed := 0
for _, fi := range fis {
if !fi.IsDir() {
if indexFile(dir + "/" + fi.Name()) {
indexed++
}
}
}
return nil
}
func indexFile(fn string) bool {
f, err := os.Open(fn)
if err != nil {
fmt.Println(err)
return false
}
x := len(indexed)
indexed = append(indexed, doc{fn, fn})
pdoc := &indexed[x]
r := bufio.NewReader(f)
lines := 0
for {
b, isPrefix, err := r.ReadLine()
switch {
case err == io.EOF:
return true
case err != nil:
fmt.Println(err)
return true
case isPrefix:
fmt.Printf("%s: unexpected long line\n", fn)
return true
case lines < 20 && bytes.HasPrefix(b, []byte("Title:")):
pdoc.title = string(b[7:])
}
wordLoop:
for _, bword := range bytes.Fields(b) {
bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@")
if len(bword) > 0 {
word := string(bword)
dl := index[word]
for _, d := range dl {
if d == x {
continue wordLoop
}
}
index[word] = append(dl, x)
}
}
}
return true
}
func ui() {
fmt.Println(len(index), "words indexed in", len(indexed), "files")
fmt.Println("enter single words to search for")
fmt.Println("enter a blank line when done")
var word string
for {
fmt.Print("search word: ")
wc, _ := fmt.Scanln(&word)
if wc == 0 {
return
}
switch dl := index[word]; len(dl) {
case 0:
fmt.Println("no match")
case 1:
fmt.Println("one match:")
fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title)
default:
fmt.Println(len(dl), "matches:")
for _, d := range dl {
fmt.Println(" ", indexed[d].file, indexed[d].title)
}
}
}
}
| package org.rosettacode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class InvertedIndex {
List<String> stopwords = Arrays.asList("a", "able", "about",
"across", "after", "all", "almost", "also", "am", "among", "an",
"and", "any", "are", "as", "at", "be", "because", "been", "but",
"by", "can", "cannot", "could", "dear", "did", "do", "does",
"either", "else", "ever", "every", "for", "from", "get", "got",
"had", "has", "have", "he", "her", "hers", "him", "his", "how",
"however", "i", "if", "in", "into", "is", "it", "its", "just",
"least", "let", "like", "likely", "may", "me", "might", "most",
"must", "my", "neither", "no", "nor", "not", "of", "off", "often",
"on", "only", "or", "other", "our", "own", "rather", "said", "say",
"says", "she", "should", "since", "so", "some", "than", "that",
"the", "their", "them", "then", "there", "these", "they", "this",
"tis", "to", "too", "twas", "us", "wants", "was", "we", "were",
"what", "when", "where", "which", "while", "who", "whom", "why",
"will", "with", "would", "yet", "you", "your");
Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();
List<String> files = new ArrayList<String>();
public void indexFile(File file) throws IOException {
int fileno = files.indexOf(file.getPath());
if (fileno == -1) {
files.add(file.getPath());
fileno = files.size() - 1;
}
int pos = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
for (String _word : line.split("\\W+")) {
String word = _word.toLowerCase();
pos++;
if (stopwords.contains(word))
continue;
List<Tuple> idx = index.get(word);
if (idx == null) {
idx = new LinkedList<Tuple>();
index.put(word, idx);
}
idx.add(new Tuple(fileno, pos));
}
}
System.out.println("indexed " + file.getPath() + " " + pos + " words");
}
public void search(List<String> words) {
for (String _word : words) {
Set<String> answer = new HashSet<String>();
String word = _word.toLowerCase();
List<Tuple> idx = index.get(word);
if (idx != null) {
for (Tuple t : idx) {
answer.add(files.get(t.fileno));
}
}
System.out.print(word);
for (String f : answer) {
System.out.print(" " + f);
}
System.out.println("");
}
}
public static void main(String[] args) {
try {
InvertedIndex idx = new InvertedIndex();
for (int i = 1; i < args.length; i++) {
idx.indexFile(new File(args[i]));
}
idx.search(Arrays.asList(args[0].split(",")));
} catch (Exception e) {
e.printStackTrace();
}
}
private class Tuple {
private int fileno;
private int position;
public Tuple(int fileno, int position) {
this.fileno = fileno;
this.position = position;
}
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
| import java.util.Scanner;
public class LCM{
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);
System.out.print("Enter the value of m:");
int m = aScanner.nextInt();
System.out.print("Enter the value of n:");
int n = aScanner.nextInt();
int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);
if (lcm == 0) {
int mm = m, nn = n;
while (mm != nn) {
while (mm < nn) { mm += m; }
while (nn < mm) { nn += n; }
}
lcm = mm;
}
System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
| import java.util.Scanner;
public class LCM{
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);
System.out.print("Enter the value of m:");
int m = aScanner.nextInt();
System.out.print("Enter the value of n:");
int n = aScanner.nextInt();
int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);
if (lcm == 0) {
int mm = m, nn = n;
while (mm != nn) {
while (mm < nn) { mm += m; }
while (nn < mm) { nn += n; }
}
lcm = mm;
}
System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
| import java.util.Scanner;
public class LCM{
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);
System.out.print("Enter the value of m:");
int m = aScanner.nextInt();
System.out.print("Enter the value of n:");
int n = aScanner.nextInt();
int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);
if (lcm == 0) {
int mm = m, nn = n;
while (mm != nn) {
while (mm < nn) { mm += m; }
while (nn < mm) { nn += n; }
}
lcm = mm;
}
System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
}
}
|
Write the same code in Java as shown below in Go. | package main
import "fmt"
import "math/rand"
import "time"
func main() {
rand.Seed(time.Now().UnixNano())
for {
a := rand.Intn(20)
fmt.Println(a)
if a == 10 {
break
}
b := rand.Intn(20)
fmt.Println(b)
}
}
| import java.util.Random;
Random rand = new Random();
while(true){
int a = rand.nextInt(20);
System.out.println(a);
if(a == 10) break;
int b = rand.nextInt(20);
System.out.println(b);
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
}
| import java.io.FileWriter;
import java.io.IOException;
public class LinePrinter {
public static void main(String[] args) {
try {
FileWriter lp0 = new FileWriter("/dev/lp0");
lp0.write("Hello World!");
lp0.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
}
| import java.io.FileWriter;
import java.io.IOException;
public class LinePrinter {
public static void main(String[] args) {
try {
FileWriter lp0 = new FileWriter("/dev/lp0");
lp0.write("Hello World!");
lp0.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
}
| import java.io.FileWriter;
import java.io.IOException;
public class LinePrinter {
public static void main(String[] args) {
try {
FileWriter lp0 = new FileWriter("/dev/lp0");
lp0.write("Hello World!");
lp0.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import "fmt"
func maxl(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := 0; i < len(hm);i++{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func maxr(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := len(hm) - 1 ; i >= 0;i--{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func min(a,b []int) []int {
res := make([]int,len(a))
for i := 0; i < len(a);i++{
if a[i] >= b[i]{
res[i] = b[i]
}else {
res[i] = a[i]
}
}
return res
}
func diff(hm, min []int) []int {
res := make([]int,len(hm))
for i := 0; i < len(hm);i++{
if min[i] > hm[i]{
res[i] = min[i] - hm[i]
}
}
return res
}
func sum(a []int) int {
res := 0
for i := 0; i < len(a);i++{
res += a[i]
}
return res
}
func waterCollected(hm []int) int {
maxr := maxr(hm)
maxl := maxl(hm)
min := min(maxr,maxl)
diff := diff(hm,min)
sum := sum(diff)
return sum
}
func main() {
fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
fmt.Println(waterCollected([]int{5, 5, 5, 5}))
fmt.Println(waterCollected([]int{5, 6, 7, 8}))
fmt.Println(waterCollected([]int{8, 7, 7, 6}))
fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
| public class WaterBetweenTowers {
public static void main(String[] args) {
int i = 1;
int[][] tba = new int[][]{
new int[]{1, 5, 3, 7, 2},
new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
new int[]{5, 5, 5, 5},
new int[]{5, 6, 7, 8},
new int[]{8, 7, 7, 6},
new int[]{6, 7, 10, 7, 6}
};
for (int[] tea : tba) {
int rht, wu = 0, bof;
do {
for (rht = tea.length - 1; rht >= 0; rht--) {
if (tea[rht] > 0) {
break;
}
}
if (rht < 0) {
break;
}
bof = 0;
for (int col = 0; col <= rht; col++) {
if (tea[col] > 0) {
tea[col]--;
bof += 1;
} else if (bof > 0) {
wu++;
}
}
if (bof < 2) {
break;
}
} while (true);
System.out.printf("Block %d", i++);
if (wu == 0) {
System.out.print(" does not hold any");
} else {
System.out.printf(" holds %d", wu);
}
System.out.println(" water units.");
}
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1)
p := uint64(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
}
}
}
for i := uint64(3); i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
func squareFree(from, to uint64) (results []uint64) {
limit := uint64(math.Sqrt(float64(to)))
primes := sieve(limit)
outer:
for i := from; i <= to; i++ {
for _, p := range primes {
p2 := p * p
if p2 > i {
break
}
if i%p2 == 0 {
continue outer
}
}
results = append(results, i)
}
return
}
const trillion uint64 = 1000000000000
func main() {
fmt.Println("Square-free integers from 1 to 145:")
sf := squareFree(1, 145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%20 == 0 {
fmt.Println()
}
fmt.Printf("%4d", sf[i])
}
fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
sf = squareFree(trillion, trillion+145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%5 == 0 {
fmt.Println()
}
fmt.Printf("%14d", sf[i])
}
fmt.Println("\n\nNumber of square-free integers:\n")
a := [...]uint64{100, 1000, 10000, 100000, 1000000}
for _, n := range a {
fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
}
}
| import java.util.ArrayList;
import java.util.List;
public class SquareFree
{
private static List<Long> sieve(long limit) {
List<Long> primes = new ArrayList<Long>();
primes.add(2L);
boolean[] c = new boolean[(int)limit + 1];
long p = 3;
for (;;) {
long p2 = p * p;
if (p2 > limit) break;
for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;
for (;;) {
p += 2;
if (!c[(int)p]) break;
}
}
for (long i = 3; i <= limit; i += 2) {
if (!c[(int)i]) primes.add(i);
}
return primes;
}
private static List<Long> squareFree(long from, long to) {
long limit = (long)Math.sqrt((double)to);
List<Long> primes = sieve(limit);
List<Long> results = new ArrayList<Long>();
outer: for (long i = from; i <= to; i++) {
for (long p : primes) {
long p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) continue outer;
}
results.add(i);
}
return results;
}
private final static long TRILLION = 1000000000000L;
public static void main(String[] args) {
System.out.println("Square-free integers from 1 to 145:");
List<Long> sf = squareFree(1, 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 20 == 0) {
System.out.println();
}
System.out.printf("%4d", sf.get(i));
}
System.out.print("\n\nSquare-free integers");
System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145);
sf = squareFree(TRILLION, TRILLION + 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 5 == 0) System.out.println();
System.out.printf("%14d", sf.get(i));
}
System.out.println("\n\nNumber of square-free integers:\n");
long[] tos = {100, 1000, 10000, 100000, 1000000};
for (long to : tos) {
System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size());
}
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1)
p := uint64(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
}
}
}
for i := uint64(3); i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
func squareFree(from, to uint64) (results []uint64) {
limit := uint64(math.Sqrt(float64(to)))
primes := sieve(limit)
outer:
for i := from; i <= to; i++ {
for _, p := range primes {
p2 := p * p
if p2 > i {
break
}
if i%p2 == 0 {
continue outer
}
}
results = append(results, i)
}
return
}
const trillion uint64 = 1000000000000
func main() {
fmt.Println("Square-free integers from 1 to 145:")
sf := squareFree(1, 145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%20 == 0 {
fmt.Println()
}
fmt.Printf("%4d", sf[i])
}
fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
sf = squareFree(trillion, trillion+145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%5 == 0 {
fmt.Println()
}
fmt.Printf("%14d", sf[i])
}
fmt.Println("\n\nNumber of square-free integers:\n")
a := [...]uint64{100, 1000, 10000, 100000, 1000000}
for _, n := range a {
fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
}
}
| import java.util.ArrayList;
import java.util.List;
public class SquareFree
{
private static List<Long> sieve(long limit) {
List<Long> primes = new ArrayList<Long>();
primes.add(2L);
boolean[] c = new boolean[(int)limit + 1];
long p = 3;
for (;;) {
long p2 = p * p;
if (p2 > limit) break;
for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;
for (;;) {
p += 2;
if (!c[(int)p]) break;
}
}
for (long i = 3; i <= limit; i += 2) {
if (!c[(int)i]) primes.add(i);
}
return primes;
}
private static List<Long> squareFree(long from, long to) {
long limit = (long)Math.sqrt((double)to);
List<Long> primes = sieve(limit);
List<Long> results = new ArrayList<Long>();
outer: for (long i = from; i <= to; i++) {
for (long p : primes) {
long p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) continue outer;
}
results.add(i);
}
return results;
}
private final static long TRILLION = 1000000000000L;
public static void main(String[] args) {
System.out.println("Square-free integers from 1 to 145:");
List<Long> sf = squareFree(1, 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 20 == 0) {
System.out.println();
}
System.out.printf("%4d", sf.get(i));
}
System.out.print("\n\nSquare-free integers");
System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145);
sf = squareFree(TRILLION, TRILLION + 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 5 == 0) System.out.println();
System.out.printf("%14d", sf.get(i));
}
System.out.println("\n\nNumber of square-free integers:\n");
long[] tos = {100, 1000, 10000, 100000, 1000000};
for (long to : tos) {
System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size());
}
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package main
import "fmt"
func jaro(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_distance = match_distance/2 - 1
str1_matches := make([]bool, len(str1))
str2_matches := make([]bool, len(str2))
matches := 0.
transpositions := 0.
for i := range str1 {
start := i - match_distance
if start < 0 {
start = 0
}
end := i + match_distance + 1
if end > len(str2) {
end = len(str2)
}
for k := start; k < end; k++ {
if str2_matches[k] {
continue
}
if str1[i] != str2[k] {
continue
}
str1_matches[i] = true
str2_matches[k] = true
matches++
break
}
}
if matches == 0 {
return 0
}
k := 0
for i := range str1 {
if !str1_matches[i] {
continue
}
for !str2_matches[k] {
k++
}
if str1[i] != str2[k] {
transpositions++
}
k++
}
transpositions /= 2
return (matches/float64(len(str1)) +
matches/float64(len(str2)) +
(matches-transpositions)/matches) / 3
}
func main() {
fmt.Printf("%f\n", jaro("MARTHA", "MARHTA"))
fmt.Printf("%f\n", jaro("DIXON", "DICKSONX"))
fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"))
}
| public class JaroDistance {
public static double jaro(String s, String t) {
int s_len = s.length();
int t_len = t.length();
if (s_len == 0 && t_len == 0) return 1;
int match_distance = Integer.max(s_len, t_len) / 2 - 1;
boolean[] s_matches = new boolean[s_len];
boolean[] t_matches = new boolean[t_len];
int matches = 0;
int transpositions = 0;
for (int i = 0; i < s_len; i++) {
int start = Integer.max(0, i-match_distance);
int end = Integer.min(i+match_distance+1, t_len);
for (int j = start; j < end; j++) {
if (t_matches[j]) continue;
if (s.charAt(i) != t.charAt(j)) continue;
s_matches[i] = true;
t_matches[j] = true;
matches++;
break;
}
}
if (matches == 0) return 0;
int k = 0;
for (int i = 0; i < s_len; i++) {
if (!s_matches[i]) continue;
while (!t_matches[k]) k++;
if (s.charAt(i) != t.charAt(k)) transpositions++;
k++;
}
return (((double)matches / s_len) +
((double)matches / t_len) +
(((double)matches - transpositions/2.0) / matches)) / 3.0;
}
public static void main(String[] args) {
System.out.println(jaro( "MARTHA", "MARHTA"));
System.out.println(jaro( "DIXON", "DICKSONX"));
System.out.println(jaro("JELLYFISH", "SMELLYFISH"));
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import "fmt"
type pair struct{ x, y int }
func main() {
const max = 1685
var all []pair
for a := 2; a < max; a++ {
for b := a + 1; b < max-a; b++ {
all = append(all, pair{a, b})
}
}
fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
products := countProducts(all)
var sPairs []pair
pairs:
for _, p := range all {
s := p.x + p.y
for a := 2; a < s/2+s&1; a++ {
b := s - a
if products[a*b] == 1 {
continue pairs
}
}
sPairs = append(sPairs, p)
}
fmt.Println("S starts with", len(sPairs), "possible pairs.")
sProducts := countProducts(sPairs)
var pPairs []pair
for _, p := range sPairs {
if sProducts[p.x*p.y] == 1 {
pPairs = append(pPairs, p)
}
}
fmt.Println("P then has", len(pPairs), "possible pairs.")
pSums := countSums(pPairs)
var final []pair
for _, p := range pPairs {
if pSums[p.x+p.y] == 1 {
final = append(final, p)
}
}
switch len(final) {
case 1:
fmt.Println("Answer:", final[0].x, "and", final[0].y)
case 0:
fmt.Println("No possible answer.")
default:
fmt.Println(len(final), "possible answers:", final)
}
}
func countProducts(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x*p.y]++
}
return m
}
func countSums(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x+p.y]++
}
return m
}
func decomposeSum(s int) []pair {
pairs := make([]pair, 0, s/2)
for a := 2; a < s/2+s&1; a++ {
pairs = append(pairs, pair{a, s - a})
}
return pairs
}
| package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
public class SumAndProductPuzzle {
private final long beginning;
private final int maxSum;
private static final int MIN_VALUE = 2;
private List<int[]> firstConditionExcludes = new ArrayList<>();
private List<int[]> secondConditionExcludes = new ArrayList<>();
public static void main(String... args){
if (args.length == 0){
new SumAndProductPuzzle(100).run();
new SumAndProductPuzzle(1684).run();
new SumAndProductPuzzle(1685).run();
} else {
for (String arg : args){
try{
new SumAndProductPuzzle(Integer.valueOf(arg)).run();
} catch (NumberFormatException e){
System.out.println("Please provide only integer arguments. " +
"Provided argument " + arg + " was not an integer. " +
"Alternatively, calling the program with no arguments " +
"will run the puzzle where maximum sum equals 100, 1684, and 1865.");
}
}
}
}
public SumAndProductPuzzle(int maxSum){
this.beginning = System.currentTimeMillis();
this.maxSum = maxSum;
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" started at " + String.valueOf(beginning) + ".");
}
public void run(){
for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){
for (int y = x + 1; y < maxSum - MIN_VALUE; y++){
if (isSumNoGreaterThanMax(x,y) &&
isSKnowsPCannotKnow(x,y) &&
isPKnowsNow(x,y) &&
isSKnowsNow(x,y)
){
System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) +
" in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
}
}
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
public boolean isSumNoGreaterThanMax(int x, int y){
return x + y <= maxSum;
}
public boolean isSKnowsPCannotKnow(int x, int y){
if (firstConditionExcludes.contains(new int[] {x, y})){
return false;
}
for (int[] addends : sumAddends(x, y)){
if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {
firstConditionExcludes.add(new int[] {x, y});
return false;
}
}
return true;
}
public boolean isPKnowsNow(int x, int y){
if (secondConditionExcludes.contains(new int[] {x, y})){
return false;
}
int countSolutions = 0;
for (int[] factors : productFactors(x, y)){
if (isSKnowsPCannotKnow(factors[0], factors[1])){
countSolutions++;
}
}
if (countSolutions == 1){
return true;
} else {
secondConditionExcludes.add(new int[] {x, y});
return false;
}
}
public boolean isSKnowsNow(int x, int y){
int countSolutions = 0;
for (int[] addends : sumAddends(x, y)){
if (isPKnowsNow(addends[0], addends[1])){
countSolutions++;
}
}
return countSolutions == 1;
}
public List<int[]> sumAddends(int x, int y){
List<int[]> list = new ArrayList<>();
int sum = x + y;
for (int addend = MIN_VALUE; addend < sum - addend; addend++){
if (isSumNoGreaterThanMax(addend, sum - addend)){
list.add(new int[]{addend, sum - addend});
}
}
return list;
}
public List<int[]> productFactors(int x, int y){
List<int[]> list = new ArrayList<>();
int product = x * y;
for (int factor = MIN_VALUE; factor < product / factor; factor++){
if (product % factor == 0){
if (isSumNoGreaterThanMax(factor, product / factor)){
list.add(new int[]{factor, product / factor});
}
}
}
return list;
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func fairshare(n, base int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
j := i
sum := 0
for j > 0 {
sum += j % base
j /= base
}
res[i] = sum % base
}
return res
}
func turns(n int, fss []int) string {
m := make(map[int]int)
for _, fs := range fss {
m[fs]++
}
m2 := make(map[int]int)
for _, v := range m {
m2[v]++
}
res := []int{}
sum := 0
for k, v := range m2 {
sum += v
res = append(res, k)
}
if sum != n {
return fmt.Sprintf("only %d have a turn", sum)
}
sort.Ints(res)
res2 := make([]string, len(res))
for i := range res {
res2[i] = strconv.Itoa(res[i])
}
return strings.Join(res2, " or ")
}
func main() {
for _, base := range []int{2, 3, 5, 11} {
fmt.Printf("%2d : %2d\n", base, fairshare(25, base))
}
fmt.Println("\nHow many times does each get a turn in 50000 iterations?")
for _, base := range []int{191, 1377, 49999, 50000, 50001} {
t := turns(base, fairshare(50000, base))
fmt.Printf(" With %d people: %s\n", base, t)
}
}
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FairshareBetweenTwoAndMore {
public static void main(String[] args) {
for ( int base : Arrays.asList(2, 3, 5, 11) ) {
System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base));
}
}
private static List<Integer> thueMorseSequence(int terms, int base) {
List<Integer> sequence = new ArrayList<Integer>();
for ( int i = 0 ; i < terms ; i++ ) {
int sum = 0;
int n = i;
while ( n > 0 ) {
sum += n % base;
n /= base;
}
sequence.add(sum % base);
}
return sequence;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func fairshare(n, base int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
j := i
sum := 0
for j > 0 {
sum += j % base
j /= base
}
res[i] = sum % base
}
return res
}
func turns(n int, fss []int) string {
m := make(map[int]int)
for _, fs := range fss {
m[fs]++
}
m2 := make(map[int]int)
for _, v := range m {
m2[v]++
}
res := []int{}
sum := 0
for k, v := range m2 {
sum += v
res = append(res, k)
}
if sum != n {
return fmt.Sprintf("only %d have a turn", sum)
}
sort.Ints(res)
res2 := make([]string, len(res))
for i := range res {
res2[i] = strconv.Itoa(res[i])
}
return strings.Join(res2, " or ")
}
func main() {
for _, base := range []int{2, 3, 5, 11} {
fmt.Printf("%2d : %2d\n", base, fairshare(25, base))
}
fmt.Println("\nHow many times does each get a turn in 50000 iterations?")
for _, base := range []int{191, 1377, 49999, 50000, 50001} {
t := turns(base, fairshare(50000, base))
fmt.Printf(" With %d people: %s\n", base, t)
}
}
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FairshareBetweenTwoAndMore {
public static void main(String[] args) {
for ( int base : Arrays.asList(2, 3, 5, 11) ) {
System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base));
}
}
private static List<Integer> thueMorseSequence(int terms, int base) {
List<Integer> sequence = new ArrayList<Integer>();
for ( int i = 0 ; i < terms ; i++ ) {
int sum = 0;
int n = i;
while ( n > 0 ) {
sum += n % base;
n /= base;
}
sequence.add(sum % base);
}
return sequence;
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
fmt.Println("postfix:", parseInfix(input))
}
func parseInfix(e string) (rpn string) {
var stack []string
for _, tok := range strings.Fields(e) {
switch tok {
case "(":
stack = append(stack, tok)
case ")":
var op string
for {
op, stack = stack[len(stack)-1], stack[:len(stack)-1]
if op == "(" {
break
}
rpn += " " + op
}
default:
if o1, isOp := opa[tok]; isOp {
for len(stack) > 0 {
op := stack[len(stack)-1]
if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||
o1.prec == o2.prec && o1.rAssoc {
break
}
stack = stack[:len(stack)-1]
rpn += " " + op
}
stack = append(stack, tok)
} else {
if rpn > "" {
rpn += " "
}
rpn += tok
}
}
}
for len(stack) > 0 {
rpn += " " + stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
return
}
| import java.util.Stack;
public class ShuntingYard {
public static void main(String[] args) {
String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
System.out.printf("infix: %s%n", infix);
System.out.printf("postfix: %s%n", infixToPostfix(infix));
}
static String infixToPostfix(String infix) {
final String ops = "-+/*^";
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
for (String token : infix.split("\\s")) {
if (token.isEmpty())
continue;
char c = token.charAt(0);
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 > prec1 || (prec2 == prec1 && c != '^'))
sb.append(ops.charAt(s.pop())).append(' ');
else break;
}
s.push(idx);
}
}
else if (c == '(') {
s.push(-2);
}
else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop())).append(' ');
s.pop();
}
else {
sb.append(token).append(' ');
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop())).append(' ');
return sb.toString();
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "fmt"
var canFollow [][]bool
var arrang []int
var bFirst = true
var pmap = make(map[int]bool)
func init() {
for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {
pmap[i] = true
}
}
func ptrs(res, n, done int) int {
ad := arrang[done-1]
if n-done <= 1 {
if canFollow[ad-1][n-1] {
if bFirst {
for _, e := range arrang {
fmt.Printf("%2d ", e)
}
fmt.Println()
bFirst = false
}
res++
}
} else {
done++
for i := done - 1; i <= n-2; i += 2 {
ai := arrang[i]
if canFollow[ad-1][ai-1] {
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
res = ptrs(res, n, done)
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
}
}
}
return res
}
func primeTriangle(n int) int {
canFollow = make([][]bool, n)
for i := 0; i < n; i++ {
canFollow[i] = make([]bool, n)
for j := 0; j < n; j++ {
_, ok := pmap[i+j+2]
canFollow[i][j] = ok
}
}
bFirst = true
arrang = make([]int, n)
for i := 0; i < n; i++ {
arrang[i] = i + 1
}
return ptrs(0, n, 1)
}
func main() {
counts := make([]int, 19)
for i := 2; i <= 20; i++ {
counts[i-2] = primeTriangle(i)
}
fmt.Println()
for i := 0; i < 19; i++ {
fmt.Printf("%d ", counts[i])
}
fmt.Println()
}
| public class PrimeTriangle {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 2; i <= 20; ++i) {
int[] a = new int[i];
for (int j = 0; j < i; ++j)
a[j] = j + 1;
if (findRow(a, 0, i))
printRow(a);
}
System.out.println();
StringBuilder s = new StringBuilder();
for (int i = 2; i <= 20; ++i) {
int[] a = new int[i];
for (int j = 0; j < i; ++j)
a[j] = j + 1;
if (i > 2)
s.append(" ");
s.append(countRows(a, 0, i));
}
System.out.println(s);
long finish = System.currentTimeMillis();
System.out.printf("\nElapsed time: %d milliseconds\n", finish - start);
}
private static void printRow(int[] a) {
for (int i = 0; i < a.length; ++i) {
if (i != 0)
System.out.print(" ");
System.out.printf("%2d", a[i]);
}
System.out.println();
}
private static boolean findRow(int[] a, int start, int length) {
if (length == 2)
return isPrime(a[start] + a[start + 1]);
for (int i = 1; i + 1 < length; i += 2) {
if (isPrime(a[start] + a[start + i])) {
swap(a, start + i, start + 1);
if (findRow(a, start + 1, length - 1))
return true;
swap(a, start + i, start + 1);
}
}
return false;
}
private static int countRows(int[] a, int start, int length) {
int count = 0;
if (length == 2) {
if (isPrime(a[start] + a[start + 1]))
++count;
} else {
for (int i = 1; i + 1 < length; i += 2) {
if (isPrime(a[start] + a[start + i])) {
swap(a, start + i, start + 1);
count += countRows(a, start + 1, length - 1);
swap(a, start + i, start + 1);
}
}
}
return count;
}
private static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
private static boolean isPrime(int n) {
return ((1L << n) & 0x28208a20a08a28acL) != 0;
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"log"
"math"
)
func main() {
fmt.Print("Enter 11 numbers: ")
var s [11]float64
for i := 0; i < 11; {
if n, _ := fmt.Scan(&s[i]); n > 0 {
i++
}
}
for i, item := range s[:5] {
s[i], s[10-i] = s[10-i], item
}
for _, item := range s {
if result, overflow := f(item); overflow {
log.Printf("f(%g) overflow", item)
} else {
fmt.Printf("f(%g) = %g\n", item, result)
}
}
}
func f(x float64) (float64, bool) {
result := math.Sqrt(math.Abs(x)) + 5*x*x*x
return result, result > 400
}
|
import java.util.*;
import java.io.*;
public class TPKA {
public static void main(String... args) {
double[] input = new double[11];
double userInput = 0.0;
Scanner in = new Scanner(System.in);
for(int i = 0; i < 11; i++) {
System.out.print("Please enter a number: ");
String s = in.nextLine();
try {
userInput = Double.parseDouble(s);
} catch (NumberFormatException e) {
System.out.println("You entered invalid input, exiting");
System.exit(1);
}
input[i] = userInput;
}
for(int j = 10; j >= 0; j--) {
double x = input[j]; double y = f(x);
if( y < 400.0) {
System.out.printf("f( %.2f ) = %.2f\n", x, y);
} else {
System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE");
}
}
}
private static double f(double x) {
return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));
}
}
|
Generate a Java translation of this Go snippet without changing its computational steps. | package m3
import (
"errors"
"strconv"
)
var (
ErrorLT3 = errors.New("N of at least three digits required.")
ErrorEven = errors.New("N with odd number of digits required.")
)
func Digits(i int) (string, error) {
if i < 0 {
i = -i
}
if i < 100 {
return "", ErrorLT3
}
s := strconv.Itoa(i)
if len(s)%2 == 0 {
return "", ErrorEven
}
m := len(s) / 2
return s[m-1 : m+2], nil
}
| public class MiddleThreeDigits {
public static void main(String[] args) {
final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};
final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,
Integer.MAX_VALUE};
for (long n : passing)
System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
for (int n : failing)
System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
}
public static <T> String middleThreeDigits(T n) {
String s = String.valueOf(n);
if (s.charAt(0) == '-')
s = s.substring(1);
int len = s.length();
if (len < 3 || len % 2 == 0)
return "Need odd and >= 3 digits";
int mid = len / 2;
return s.substring(mid - 1, mid + 2);
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math"
"math/big"
)
var bi = new(big.Int)
func isPrime(n int) bool {
bi.SetUint64(uint64(n))
return bi.ProbablyPrime(0)
}
func generateSmallPrimes(n int) []int {
primes := make([]int, n)
primes[0] = 2
for i, count := 3, 1; count < n; i += 2 {
if isPrime(i) {
primes[count] = i
count++
}
}
return primes
}
func countDivisors(n int) int {
count := 1
for n%2 == 0 {
n >>= 1
count++
}
for d := 3; d*d <= n; d += 2 {
q, r := n/d, n%d
if r == 0 {
dc := 0
for r == 0 {
dc += count
n = q
q, r = n/d, n%d
}
count += dc
}
}
if n != 1 {
count *= 2
}
return count
}
func main() {
const max = 33
primes := generateSmallPrimes(max)
z := new(big.Int)
p := new(big.Int)
fmt.Println("The first", max, "terms in the sequence are:")
for i := 1; i <= max; i++ {
if isPrime(i) {
z.SetUint64(uint64(primes[i-1]))
p.SetUint64(uint64(i - 1))
z.Exp(z, p, nil)
fmt.Printf("%2d : %d\n", i, z)
} else {
count := 0
for j := 1; ; j++ {
if i%2 == 1 {
sq := int(math.Sqrt(float64(j)))
if sq*sq != j {
continue
}
}
if countDivisors(j) == i {
count++
if count == i {
fmt.Printf("%2d : %d\n", i, j)
break
}
}
}
}
}
}
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class SequenceNthNumberWithExactlyNDivisors {
public static void main(String[] args) {
int max = 45;
smallPrimes(max);
for ( int n = 1; n <= max ; n++ ) {
System.out.printf("A073916(%d) = %s%n", n, OEISA073916(n));
}
}
private static List<Integer> smallPrimes = new ArrayList<>();
private static void smallPrimes(int numPrimes) {
smallPrimes.add(2);
for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {
if ( isPrime(n) ) {
smallPrimes.add(n);
count++;
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) {
return false;
}
for ( long d = 3 ; d*d <= test ; d += 2 ) {
if ( test % d == 0 ) {
return false;
}
}
return true;
}
private static int getDivisorCount(long n) {
int count = 1;
while ( n % 2 == 0 ) {
n /= 2;
count += 1;
}
for ( long d = 3 ; d*d <= n ; d += 2 ) {
long q = n / d;
long r = n % d;
int dc = 0;
while ( r == 0 ) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if ( n != 1 ) {
count *= 2;
}
return count;
}
private static BigInteger OEISA073916(int n) {
if ( isPrime(n) ) {
return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);
}
int count = 0;
int result = 0;
for ( int i = 1 ; count < n ; i++ ) {
if ( n % 2 == 1 ) {
int sqrt = (int) Math.sqrt(i);
if ( sqrt*sqrt != i ) {
continue;
}
}
if ( getDivisorCount(i) == n ) {
count++;
result = i;
}
}
return BigInteger.valueOf(result);
}
}
|
Generate an equivalent Java version of this Go code. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
seq := make([]int, max)
fmt.Println("The first", max, "terms of the sequence are:")
for i, n := 1, 0; n < max; i++ {
if k := countDivisors(i); k <= max && seq[k-1] == 0 {
seq[k-1] = i
n++
}
}
fmt.Println(seq)
}
| import java.util.Arrays;
public class OEIS_A005179 {
static int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
public static void main(String[] args) {
final int max = 15;
int[] seq = new int[max];
System.out.printf("The first %d terms of the sequence are:\n", max);
for (int i = 1, n = 0; n < max; ++i) {
int k = count_divisors(i);
if (k <= max && seq[k - 1] == 0) {
seq[k- 1] = i;
n++;
}
}
System.out.println(Arrays.toString(seq));
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import "fmt"
func pancake(n int) int {
gap, sum, adj := 2, 2, -1
for sum < n {
adj++
gap = gap*2 - 1
sum += gap
}
return n + adj
}
func main() {
for i := 0; i < 4; i++ {
for j := 1; j < 6; j++ {
n := i*5 + j
fmt.Printf("p(%2d) = %2d ", n, pancake(n))
}
fmt.Println()
}
}
| public class Pancake {
private static int pancake(int n) {
int gap = 2;
int sum = 2;
int adj = -1;
while (sum < n) {
adj++;
gap = 2 * gap - 1;
sum += gap;
}
return n + adj;
}
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 6; j++) {
int n = 5 * i + j;
System.out.printf("p(%2d) = %2d ", n, pancake(n));
}
System.out.println();
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var grid [8][8]byte
func abs(i int) int {
if i >= 0 {
return i
} else {
return -i
}
}
func createFen() string {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
return toFen()
}
func placeKings() {
for {
r1 := rand.Intn(8)
c1 := rand.Intn(8)
r2 := rand.Intn(8)
c2 := rand.Intn(8)
if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {
grid[r1][c1] = 'K'
grid[r2][c2] = 'k'
return
}
}
}
func placePieces(pieces string, isPawn bool) {
numToPlace := rand.Intn(len(pieces))
for n := 0; n < numToPlace; n++ {
var r, c int
for {
r = rand.Intn(8)
c = rand.Intn(8)
if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) {
break
}
}
grid[r][c] = pieces[n]
}
}
func toFen() string {
var fen strings.Builder
countEmpty := 0
for r := 0; r < 8; r++ {
for c := 0; c < 8; c++ {
ch := grid[r][c]
if ch == '\000' {
ch = '.'
}
fmt.Printf("%2c ", ch)
if ch == '.' {
countEmpty++
} else {
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteByte(ch)
}
}
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteString("/")
fmt.Println()
}
fen.WriteString(" w - - 0 1")
return fen.String()
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(createFen())
}
| import static java.lang.Math.abs;
import java.util.Random;
public class Fen {
static Random rand = new Random();
public static void main(String[] args) {
System.out.println(createFen());
}
static String createFen() {
char[][] grid = new char[8][8];
placeKings(grid);
placePieces(grid, "PPPPPPPP", true);
placePieces(grid, "pppppppp", true);
placePieces(grid, "RNBQBNR", false);
placePieces(grid, "rnbqbnr", false);
return toFen(grid);
}
static void placeKings(char[][] grid) {
int r1, c1, r2, c2;
while (true) {
r1 = rand.nextInt(8);
c1 = rand.nextInt(8);
r2 = rand.nextInt(8);
c2 = rand.nextInt(8);
if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)
break;
}
grid[r1][c1] = 'K';
grid[r2][c2] = 'k';
}
static void placePieces(char[][] grid, String pieces, boolean isPawn) {
int numToPlace = rand.nextInt(pieces.length());
for (int n = 0; n < numToPlace; n++) {
int r, c;
do {
r = rand.nextInt(8);
c = rand.nextInt(8);
} while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
grid[r][c] = pieces.charAt(n);
}
}
static String toFen(char[][] grid) {
StringBuilder fen = new StringBuilder();
int countEmpty = 0;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
char ch = grid[r][c];
System.out.printf("%2c ", ch == 0 ? '.' : ch);
if (ch == 0) {
countEmpty++;
} else {
if (countEmpty > 0) {
fen.append(countEmpty);
countEmpty = 0;
}
fen.append(ch);
}
}
if (countEmpty > 0) {
fen.append(countEmpty);
countEmpty = 0;
}
fen.append("/");
System.out.println();
}
return fen.append(" w - - 0 1").toString();
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
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() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
}
| import java.util.ArrayList;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class EstheticNumbers {
interface RecTriConsumer<A, B, C> {
void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);
}
private static boolean isEsthetic(long n, long b) {
if (n == 0) {
return false;
}
var i = n % b;
var n2 = n / b;
while (n2 > 0) {
var j = n2 % b;
if (Math.abs(i - j) != 1) {
return false;
}
n2 /= b;
i = j;
}
return true;
}
private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {
var esths = new ArrayList<Long>();
var dfs = new RecTriConsumer<Long, Long, Long>() {
public void accept(Long n, Long m, Long i) {
accept(this, n, m, i);
}
@Override
public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {
if (n <= i && i <= m) {
esths.add(i);
}
if (i == 0 || i > m) {
return;
}
var d = i % 10;
var i1 = i * 10 + d - 1;
var i2 = i1 + 2;
if (d == 0) {
f.accept(f, n, m, i2);
} else if (d == 9) {
f.accept(f, n, m, i1);
} else {
f.accept(f, n, m, i1);
f.accept(f, n, m, i2);
}
}
};
LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));
var le = esths.size();
System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m);
if (all) {
for (int i = 0; i < esths.size(); i++) {
System.out.printf("%d ", esths.get(i));
if ((i + 1) % perLine == 0) {
System.out.println();
}
}
} else {
for (int i = 0; i < perLine; i++) {
System.out.printf("%d ", esths.get(i));
}
System.out.println();
System.out.println("............");
for (int i = le - perLine; i < le; i++) {
System.out.printf("%d ", esths.get(i));
}
}
System.out.println();
System.out.println();
}
public static void main(String[] args) {
IntStream.rangeClosed(2, 16).forEach(b -> {
System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b);
var n = 1L;
var c = 0L;
while (c < 6 * b) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
System.out.printf("%s ", Long.toString(n, b));
}
}
n++;
}
System.out.println();
});
System.out.println();
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);
listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);
listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);
listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);
}
}
|
Port the provided Go code into Java while preserving the original functionality. |
package main
import "fmt"
const (
maxn = 10
maxl = 50
)
func main() {
for i := 1; i <= maxn; i++ {
fmt.Printf("%d: %d\n", i, steps(i))
}
}
func steps(n int) int {
var a, b [maxl][maxn + 1]int
var x [maxl]int
a[0][0] = 1
var m int
for l := 0; ; {
x[l]++
k := int(x[l])
if k >= n {
if l <= 0 {
break
}
l--
continue
}
if a[l][k] == 0 {
if b[l][k+1] != 0 {
continue
}
} else if a[l][k] != k+1 {
continue
}
a[l+1] = a[l]
for j := 1; j <= k; j++ {
a[l+1][j] = a[l][k-j]
}
b[l+1] = b[l]
a[l+1][0] = k + 1
b[l+1][k+1] = 1
if l > m-1 {
m = l + 1
}
l++
x[l] = 0
}
return m
}
| public class Topswops {
static final int maxBest = 32;
static int[] best;
static private void trySwaps(int[] deck, int f, int d, int n) {
if (d > best[n])
best[n] = d;
for (int i = n - 1; i >= 0; i--) {
if (deck[i] == -1 || deck[i] == i)
break;
if (d + best[i] <= best[n])
return;
}
int[] deck2 = deck.clone();
for (int i = 1; i < n; i++) {
final int k = 1 << i;
if (deck2[i] == -1) {
if ((f & k) != 0)
continue;
} else if (deck2[i] != i)
continue;
deck2[0] = i;
for (int j = i - 1; j >= 0; j--)
deck2[i - j] = deck[j];
trySwaps(deck2, f | k, d + 1, n);
}
}
static int topswops(int n) {
assert(n > 0 && n < maxBest);
best[n] = 0;
int[] deck0 = new int[n + 1];
for (int i = 1; i < n; i++)
deck0[i] = -1;
trySwaps(deck0, 1, 0, n);
return best[n];
}
public static void main(String[] args) {
best = new int[maxBest];
for (int i = 1; i < 11; i++)
System.out.println(i + ": " + topswops(i));
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
units := []string{
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer",
}
convs := []float32{
0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668, 74676,
1, 100, 10000,
}
scanner := bufio.NewScanner(os.Stdin)
for {
for i, u := range units {
fmt.Printf("%2d %s\n", i+1, u)
}
fmt.Println()
var unit int
var err error
for {
fmt.Print("Please choose a unit 1 to 13 : ")
scanner.Scan()
unit, err = strconv.Atoi(scanner.Text())
if err == nil && unit >= 1 && unit <= 13 {
break
}
}
unit--
var value float64
for {
fmt.Print("Now enter a value in that unit : ")
scanner.Scan()
value, err = strconv.ParseFloat(scanner.Text(), 32)
if err == nil && value >= 0 {
break
}
}
fmt.Println("\nThe equivalent in the remaining units is:\n")
for i, u := range units {
if i == unit {
continue
}
fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i])
}
fmt.Println()
yn := ""
for yn != "y" && yn != "n" {
fmt.Print("Do another one y/n : ")
scanner.Scan()
yn = strings.ToLower(scanner.Text())
}
if yn == "n" {
return
}
}
}
| public class OldRussianMeasures {
final static String[] keys = {"tochka", "liniya", "centimeter", "diuym",
"vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer",
"versta", "milia"};
final static double[] values = {0.000254, 0.00254, 0.01,0.0254,
0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,
1066.8, 7467.6};
public static void main(String[] a) {
if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) {
double inputVal = lookup(a[1]);
if (!Double.isNaN(inputVal)) {
double magnitude = Double.parseDouble(a[0]);
double meters = magnitude * inputVal;
System.out.printf("%s %s to: %n%n", a[0], a[1]);
for (String k: keys)
System.out.printf("%10s: %g%n", k, meters / lookup(k));
return;
}
}
System.out.println("Please provide a number and unit");
}
public static double lookup(String key) {
for (int i = 0; i < keys.length; i++)
if (keys[i].equals(key))
return values[i];
return Double.NaN;
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"math/rand"
"time"
)
type rateStateS struct {
lastFlush time.Time
period time.Duration
tickCount int
}
func ticRate(pRate *rateStateS) {
pRate.tickCount++
now := time.Now()
if now.Sub(pRate.lastFlush) >= pRate.period {
tps := 0.
if pRate.tickCount > 0 {
tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()
}
fmt.Println(tps, "tics per second.")
pRate.tickCount = 0
pRate.lastFlush = now
}
}
func somethingWeDo() {
time.Sleep(time.Duration(9e7 + rand.Int63n(2e7)))
}
func main() {
start := time.Now()
rateWatch := rateStateS{
lastFlush: start,
period: 5 * time.Second,
}
latest := start
for latest.Sub(start) < 20*time.Second {
somethingWeDo()
ticRate(&rateWatch)
latest = time.Now()
}
}
| import java.util.function.Consumer;
public class RateCounter {
public static void main(String[] args) {
for (double d : benchmark(10, x -> System.out.print(""), 10))
System.out.println(d);
}
static double[] benchmark(int n, Consumer<Integer> f, int arg) {
double[] timings = new double[n];
for (int i = 0; i < n; i++) {
long time = System.nanoTime();
f.accept(arg);
timings[i] = System.nanoTime() - time;
}
return timings;
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"math/rand"
"time"
)
type rateStateS struct {
lastFlush time.Time
period time.Duration
tickCount int
}
func ticRate(pRate *rateStateS) {
pRate.tickCount++
now := time.Now()
if now.Sub(pRate.lastFlush) >= pRate.period {
tps := 0.
if pRate.tickCount > 0 {
tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()
}
fmt.Println(tps, "tics per second.")
pRate.tickCount = 0
pRate.lastFlush = now
}
}
func somethingWeDo() {
time.Sleep(time.Duration(9e7 + rand.Int63n(2e7)))
}
func main() {
start := time.Now()
rateWatch := rateStateS{
lastFlush: start,
period: 5 * time.Second,
}
latest := start
for latest.Sub(start) < 20*time.Second {
somethingWeDo()
ticRate(&rateWatch)
latest = time.Now()
}
}
| import java.util.function.Consumer;
public class RateCounter {
public static void main(String[] args) {
for (double d : benchmark(10, x -> System.out.print(""), 10))
System.out.println(d);
}
static double[] benchmark(int n, Consumer<Integer> f, int arg) {
double[] timings = new double[n];
for (int i = 0; i < n; i++) {
long time = System.nanoTime();
f.accept(arg);
timings[i] = System.nanoTime() - time;
}
return timings;
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
fmt.Println("The first", max, "terms of the sequence are:")
for i, next := 1, 1; next <= max; i++ {
if next == countDivisors(i) {
fmt.Printf("%d ", i)
next++
}
}
fmt.Println()
}
| public class AntiPrimesPlus {
static int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
public static void main(String[] args) {
final int max = 15;
System.out.printf("The first %d terms of the sequence are:\n", max);
for (int i = 1, next = 1; next <= max; ++i) {
if (next == count_divisors(i)) {
System.out.printf("%d ", i);
next++;
}
}
System.out.println();
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
)
const (
width, height = 800, 600
maxDepth = 11
colFactor = uint8(255 / maxDepth)
fileName = "pythagorasTree.png"
)
func main() {
img := image.NewNRGBA(image.Rect(0, 0, width, height))
bg := image.NewUniform(color.RGBA{255, 255, 255, 255})
draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)
drawSquares(340, 550, 460, 550, img, 0)
imgFile, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer imgFile.Close()
if err := png.Encode(imgFile, img); err != nil {
imgFile.Close()
log.Fatal(err)
}
}
func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {
if depth > maxDepth {
return
}
dx, dy := bx-ax, ay-by
x3, y3 := bx-dy, by-dx
x4, y4 := ax-dy, ay-dx
x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2
col := color.RGBA{0, uint8(depth) * colFactor, 0, 255}
drawLine(ax, ay, bx, by, img, col)
drawLine(bx, by, x3, y3, img, col)
drawLine(x3, y3, x4, y4, img, col)
drawLine(x4, y4, ax, ay, img, col)
drawSquares(x4, y4, x5, y5, img, depth+1)
drawSquares(x5, y5, x3, y3, img, depth+1)
}
func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {
dx := abs(x1 - x0)
dy := abs(y1 - y0)
var sx, sy int = -1, -1
if x0 < x1 {
sx = 1
}
if y0 < y1 {
sy = 1
}
err := dx - dy
for {
img.Set(x0, y0, col)
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 > -dy {
err -= dy
x0 += sx
}
if e2 < dx {
err += dx
y0 += sy
}
}
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
| import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class PythagorasTree extends JPanel {
final int depthLimit = 7;
float hue = 0.15f;
public PythagorasTree() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,
int depth) {
if (depth == depthLimit)
return;
float dx = x2 - x1;
float dy = y1 - y2;
float x3 = x2 - dy;
float y3 = y2 - dx;
float x4 = x1 - dy;
float y4 = y1 - dx;
float x5 = x4 + 0.5F * (dx - dy);
float y5 = y4 - 0.5F * (dx + dy);
Path2D square = new Path2D.Float();
square.moveTo(x1, y1);
square.lineTo(x2, y2);
square.lineTo(x3, y3);
square.lineTo(x4, y4);
square.closePath();
g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));
g.fill(square);
g.setColor(Color.lightGray);
g.draw(square);
Path2D triangle = new Path2D.Float();
triangle.moveTo(x3, y3);
triangle.lineTo(x4, y4);
triangle.lineTo(x5, y5);
triangle.closePath();
g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));
g.fill(triangle);
g.setColor(Color.lightGray);
g.draw(triangle);
drawTree(g, x4, y4, x5, y5, depth + 1);
drawTree(g, x5, y5, x3, y3, depth + 1);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawTree((Graphics2D) g, 275, 500, 375, 500, 0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pythagoras Tree");
f.setResizable(false);
f.add(new PythagorasTree(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader) {
byte_in := func () byte {
bs := make([]byte, 1)
src.Read(bs)
return bs[0]
}
byte_out := func (b byte) { dst.Write([]byte{b}) }
var odd func() byte
odd = func() byte {
s := byte_in()
if unicode.IsPunct(rune(s)) {
return s
}
b := odd()
byte_out(s)
return b
}
for {
for {
b := byte_in()
byte_out(b)
if b == '.' {
return
}
if unicode.IsPunct(rune(b)) {
break
}
}
b := odd()
byte_out(b)
if b == '.' {
return
}
}
}
| public class OddWord {
interface CharHandler {
CharHandler handle(char c) throws Exception;
}
final CharHandler fwd = new CharHandler() {
public CharHandler handle(char c) {
System.out.print(c);
return (Character.isLetter(c) ? fwd : rev);
}
};
class Reverser extends Thread implements CharHandler {
Reverser() {
setDaemon(true);
start();
}
private Character ch;
private char recur() throws Exception {
notify();
while (ch == null) wait();
char c = ch, ret = c;
ch = null;
if (Character.isLetter(c)) {
ret = recur();
System.out.print(c);
}
return ret;
}
public synchronized void run() {
try {
while (true) {
System.out.print(recur());
notify();
}
} catch (Exception e) {}
}
public synchronized CharHandler handle(char c) throws Exception {
while (ch != null) wait();
ch = c;
notify();
while (ch != null) wait();
return (Character.isLetter(c) ? rev : fwd);
}
}
final CharHandler rev = new Reverser();
public void loop() throws Exception {
CharHandler handler = fwd;
int c;
while ((c = System.in.read()) >= 0) {
handler = handler.handle((char) c);
}
}
public static void main(String[] args) throws Exception {
new OddWord().loop();
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"log"
"math"
)
var a1 = []int64{0, 1403580, -810728}
var a2 = []int64{527612, 0, -1370589}
const m1 = int64((1 << 32) - 209)
const m2 = int64((1 << 32) - 22853)
const d = m1 + 1
func mod(x, y int64) int64 {
m := x % y
if m < 0 {
if y < 0 {
return m - y
} else {
return m + y
}
}
return m
}
type MRG32k3a struct{ x1, x2 [3]int64 }
func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }
func (mrg *MRG32k3a) seed(seedState int64) {
if seedState <= 0 || seedState >= d {
log.Fatalf("Argument must be in the range [0, %d].\n", d)
}
mrg.x1 = [3]int64{seedState, 0, 0}
mrg.x2 = [3]int64{seedState, 0, 0}
}
func (mrg *MRG32k3a) nextInt() int64 {
x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)
x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)
mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]}
mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]}
return mod(x1i-x2i, m1) + 1
}
func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }
func main() {
randomGen := MRG32k3aNew()
randomGen.seed(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 App {
private static long mod(long x, long y) {
long m = x % y;
if (m < 0) {
if (y < 0) {
return m - y;
} else {
return m + y;
}
}
return m;
}
public static class RNG {
private final long[] a1 = {0, 1403580, -810728};
private static final long m1 = (1L << 32) - 209;
private long[] x1;
private final long[] a2 = {527612, 0, -1370589};
private static final long m2 = (1L << 32) - 22853;
private long[] x2;
private static final long d = m1 + 1;
public void seed(long state) {
x1 = new long[]{state, 0, 0};
x2 = new long[]{state, 0, 0};
}
public long nextInt() {
long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);
long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);
long z = mod(x1i - x2i, m1);
x1 = new long[]{x1i, x1[0], x1[1]};
x2 = new long[]{x2i, x2[0], x2[1]};
return z + 1;
}
public double nextFloat() {
return 1.0 * nextInt() / d;
}
}
public static void main(String[] args) {
RNG rng = new RNG();
rng.seed(1234567);
System.out.println(rng.nextInt());
System.out.println(rng.nextInt());
System.out.println(rng.nextInt());
System.out.println(rng.nextInt());
System.out.println(rng.nextInt());
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
rng.seed(987654321);
for (int i = 0; i < 100_000; i++) {
int value = (int) Math.floor(rng.nextFloat() * 5.0);
counts[value]++;
}
for (int i = 0; i < counts.length; i++) {
System.out.printf("%d: %d%n", i, counts[i]);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
| public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (isColorful(n))
System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
ColorfulNumbers c = new ColorfulNumbers();
System.out.printf("\n\nLargest colorful number: %,d\n", c.largest);
System.out.printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
System.out.printf("%d %,d\n", d + 1, c.count[d]);
total += c.count[d];
}
System.out.printf("\nTotal: %,d\n", total);
}
private ColorfulNumbers() {
countColorful(0, 0, 0);
}
public static boolean isColorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[] = new int[10];
int digits[] = new int[8];
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[] = new int[36];
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
private void countColorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
countColorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (isColorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
countColorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
| public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (isColorful(n))
System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
ColorfulNumbers c = new ColorfulNumbers();
System.out.printf("\n\nLargest colorful number: %,d\n", c.largest);
System.out.printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
System.out.printf("%d %,d\n", d + 1, c.count[d]);
total += c.count[d];
}
System.out.printf("\nTotal: %,d\n", total);
}
private ColorfulNumbers() {
countColorful(0, 0, 0);
}
public static boolean isColorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[] = new int[10];
int digits[] = new int[8];
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[] = new int[36];
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
private void countColorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
countColorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (isColorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
countColorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
}
|
Generate an equivalent Java version of this Go code. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
| public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (isColorful(n))
System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
ColorfulNumbers c = new ColorfulNumbers();
System.out.printf("\n\nLargest colorful number: %,d\n", c.largest);
System.out.printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
System.out.printf("%d %,d\n", d + 1, c.count[d]);
total += c.count[d];
}
System.out.printf("\nTotal: %,d\n", total);
}
private ColorfulNumbers() {
countColorful(0, 0, 0);
}
public static boolean isColorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[] = new int[10];
int digits[] = new int[8];
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[] = new int[36];
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
private void countColorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
countColorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (isColorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
countColorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"fmt"
"html"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
)
func main() {
ex := `<li><a href="/wiki/(.*?)"`
re := regexp.MustCompile(ex)
page := "http:
resp, _ := http.Get(page)
body, _ := ioutil.ReadAll(resp.Body)
matches := re.FindAllStringSubmatch(string(body), -1)
resp.Body.Close()
tasks := make([]string, len(matches))
for i, match := range matches {
tasks[i] = match[1]
}
const base = "http:
const limit = 3
ex = `(?s)using any language you may know.</div>(.*?)<div id="toc"`
ex2 := `</?[^>]*>`
re = regexp.MustCompile(ex)
re2 := regexp.MustCompile(ex2)
for i, task := range tasks {
page = base + task
resp, _ = http.Get(page)
body, _ = ioutil.ReadAll(resp.Body)
match := re.FindStringSubmatch(string(body))
resp.Body.Close()
text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], ""))
fmt.Println(strings.Replace(task, "_", " ", -1), "\n", text)
if i == limit-1 {
break
}
time.Sleep(5 * time.Second)
}
}
| import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class TasksWithoutExamples {
private static String readPage(HttpClient client, URI uri) throws IOException, InterruptedException {
var request = HttpRequest.newBuilder()
.GET()
.uri(uri)
.timeout(Duration.ofSeconds(5))
.setHeader("accept", "text/html")
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
private static void process(HttpClient client, String base, String task) {
try {
var re = Pattern.compile(".*using any language you may know.</div>(.*?)<div id=\"toc\".*", Pattern.DOTALL + Pattern.MULTILINE);
var re2 = Pattern.compile("</?[^>]*>");
var page = base + task;
String body = readPage(client, new URI(page));
var matcher = re.matcher(body);
if (matcher.matches()) {
var group = matcher.group(1);
var m2 = re2.matcher(group);
var text = m2.replaceAll("");
System.out.println(text);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
var re = Pattern.compile("<li><a href=\"/wiki/(.*?)\"", Pattern.DOTALL + Pattern.MULTILINE);
var client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(5))
.build();
var uri = new URI("http", "rosettacode.org", "/wiki/Category:Programming_Tasks", "");
var body = readPage(client, uri);
var matcher = re.matcher(body);
var tasks = new ArrayList<String>();
while (matcher.find()) {
tasks.add(matcher.group(1));
}
var base = "http:
var limit = 3L;
tasks.stream().limit(limit).forEach(task -> process(client, base, task));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"fmt"
"os/exec"
)
func main() {
synthType := "sine"
duration := "5"
frequency := "440"
cmd := exec.Command("play", "-n", "synth", duration, synthType, frequency)
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
}
| import processing.sound.*;
SinOsc sine;
size(500,500);
sine = new SinOsc(this);
sine.freq(500);
sine.play();
delay(5000);
|
Generate a Java translation of this Go snippet without changing its computational steps. |
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
| public class Class1 extends Class2
{
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. |
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
| public class Class1 extends Class2
{
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"fmt"
"sternbrocot"
)
func main() {
g := sb.Generator()
fmt.Println("First 15:")
for i := 1; i <= 15; i++ {
fmt.Printf("%2d: %d\n", i, g())
}
s := sb.New()
fmt.Println("First 15:", s.FirstN(15))
for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {
fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x))
}
fmt.Println("1-based indexes: gcd")
for n, f := range s.FirstN(1000)[:999] {
g := gcd(f, (*s)[n+1])
fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g)
if g != 1 {
panic("oh no!")
return
}
}
}
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
| import java.math.BigInteger;
import java.util.LinkedList;
public class SternBrocot {
static LinkedList<Integer> sequence = new LinkedList<Integer>(){{
add(1); add(1);
}};
private static void genSeq(int n){
for(int conIdx = 1; sequence.size() < n; conIdx++){
int consider = sequence.get(conIdx);
int pre = sequence.get(conIdx - 1);
sequence.add(consider + pre);
sequence.add(consider);
}
}
public static void main(String[] args){
genSeq(1200);
System.out.println("The first 15 elements are: " + sequence.subList(0, 15));
for(int i = 1; i <= 10; i++){
System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1));
}
System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1));
boolean failure = false;
for(int i = 0; i < 999; i++){
failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);
}
System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"math"
)
type unc struct {
n float64
s float64
}
func newUnc(n, s float64) *unc {
return &unc{n, s * s}
}
func (z *unc) errorTerm() float64 {
return math.Sqrt(z.s)
}
func (z *unc) addC(a *unc, c float64) *unc {
*z = *a
z.n += c
return z
}
func (z *unc) subC(a *unc, c float64) *unc {
*z = *a
z.n -= c
return z
}
func (z *unc) addU(a, b *unc) *unc {
z.n = a.n + b.n
z.s = a.s + b.s
return z
}
func (z *unc) subU(a, b *unc) *unc {
z.n = a.n - b.n
z.s = a.s + b.s
return z
}
func (z *unc) mulC(a *unc, c float64) *unc {
z.n = a.n * c
z.s = a.s * c * c
return z
}
func (z *unc) divC(a *unc, c float64) *unc {
z.n = a.n / c
z.s = a.s / (c * c)
return z
}
func (z *unc) mulU(a, b *unc) *unc {
prod := a.n * b.n
z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
func (z *unc) divU(a, b *unc) *unc {
quot := a.n / b.n
z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
func (z *unc) expC(a *unc, c float64) *unc {
f := math.Pow(a.n, c)
g := f * c / a.n
z.n = f
z.s = a.s * g * g
return z
}
func main() {
x1 := newUnc(100, 1.1)
x2 := newUnc(200, 2.2)
y1 := newUnc(50, 1.2)
y2 := newUnc(100, 2.3)
var d, d2 unc
d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)
fmt.Println("d: ", d.n)
fmt.Println("error:", d.errorTerm())
}
| public class Approx {
private double value;
private double error;
public Approx(){this.value = this.error = 0;}
public Approx(Approx b){
this.value = b.value;
this.error = b.error;
}
public Approx(double value, double error){
this.value = value;
this.error = error;
}
public Approx add(Approx b){
value+= b.value;
error = Math.sqrt(error * error + b.error * b.error);
return this;
}
public Approx add(double b){
value+= b;
return this;
}
public Approx sub(Approx b){
value-= b.value;
error = Math.sqrt(error * error + b.error * b.error);
return this;
}
public Approx sub(double b){
value-= b;
return this;
}
public Approx mult(Approx b){
double oldVal = value;
value*= b.value;
error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
(b.error*b.error) / (b.value*b.value));
return this;
}
public Approx mult(double b){
value*= b;
error = Math.abs(b * error);
return this;
}
public Approx div(Approx b){
double oldVal = value;
value/= b.value;
error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
(b.error*b.error) / (b.value*b.value));
return this;
}
public Approx div(double b){
value/= b;
error = Math.abs(b * error);
return this;
}
public Approx pow(double b){
double oldVal = value;
value = Math.pow(value, b);
error = Math.abs(value * b * (error / oldVal));
return this;
}
@Override
public String toString(){return value+"±"+error;}
public static void main(String[] args){
Approx x1 = new Approx(100, 1.1);
Approx y1 = new Approx(50, 1.2);
Approx x2 = new Approx(200, 2.2);
Approx y2 = new Approx(100, 2.3);
x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);
System.out.println(x1);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.