Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the programming language of this snippet from Java to Go without modifying what it does. | 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();
}
}
}
}
| 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)
}
|
Change the following Java code into Go without altering its purpose. | 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);
}
}
| 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)
}
|
Port the following code from Java to Go with equivalent syntax and logic. | 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);
}
}
| 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)
}
|
Keep all operations the same but rewrite the snippet in Go. | 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);
}
}
| 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)
}
|
Keep all operations the same but rewrite the snippet in Go. | 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);
}
}
}
}
}
| 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) }
}
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | 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();
}
});
}
}
| 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() {
}
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | 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();
}
});
}
}
| 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() {
}
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | 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;
}
| 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)
}
}
}
|
Produce a language-to-language conversion: from Java to Go, same semantics. | 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();
}
}
| 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
}
}
|
Generate a Go translation of this Java snippet without changing its computational steps. | 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);
}
}
}
| 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()
}
}
|
Generate an equivalent Go version of this Java code. | 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);
}
}
}
| 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()
}
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | 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);
}
}
| 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:],
)
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | 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();
}
}
}
| 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)
}
}
|
Transform the following Java implementation into Go, maintaining the same output and logic. | 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();
}
}
}
| 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)
}
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | 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;
}
}
}
| 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)
}
}
}
}
|
Produce a functionally identical Go code for the snippet given in Java. | 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);
}
}
| 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))
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | 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);
}
}
| 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))
}
|
Write the same code in Go as shown below in Java. | 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);
}
}
| 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))
}
|
Write the same code in Go as shown below in Java. | 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);
}
| 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)
}
}
|
Produce a language-to-language conversion: from Java to Go, same semantics. | 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();
}
}
}
| 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!")
}
|
Convert this Java block to Go, preserving its control flow and logic. | 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();
}
}
}
| 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!")
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | 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();
}
}
}
| 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!")
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | 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.");
}
}
}
| 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}))
}
|
Write the same code in Go as shown below in Java. | 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());
}
}
}
| 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)))
}
}
|
Please provide an equivalent version of this Java code in Go. | 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());
}
}
}
| 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)))
}
}
|
Preserve the algorithm and functionality while converting the code from Java to Go. | 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"));
}
}
| 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"))
}
|
Change the following Java code into Go without altering its purpose. | 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;
}
}
| 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
}
|
Change the following Java code into Go without altering its purpose. | 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;
}
}
| 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)
}
}
|
Keep all operations the same but rewrite the snippet in Go. | 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;
}
}
| 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)
}
}
|
Keep all operations the same but rewrite the snippet in Go. | 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();
}
}
| 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
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | 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;
}
}
| 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()
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? |
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)));
}
}
| 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
}
|
Produce a functionally identical Go code for the snippet given in Java. | 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);
}
}
| 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
}
|
Convert this Java block to Go, preserving its control flow and logic. | 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);
}
}
| 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
}
}
}
}
}
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | 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));
}
}
| 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)
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | 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();
}
}
}
| 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()
}
}
|
Port the provided Java code into Go while preserving the original functionality. | 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();
}
}
| 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())
}
|
Translate this program into Go but keep the logic exactly as in Java. | 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);
}
}
| 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)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | 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));
}
}
|
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
}
|
Convert this Java block to Go, preserving its control flow and logic. | 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;
}
}
| 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
}
}
}
|
Rewrite the snippet below in Go so it works the same as the original Java code. | 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;
}
}
| 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()
}
}
|
Preserve the algorithm and functionality while converting the code from Java to Go. | 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;
}
}
| 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()
}
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | 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();
}
}
| 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()
}
|
Convert this Java block to Go, preserving its control flow and logic. | 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);
});
}
}
| 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
}
|
Convert this Java snippet to Go and keep its semantics consistent. | 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();
}
}
| 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
}
}
}
|
Write the same code in Go as shown below in Java. | 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]);
}
}
}
| 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])
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | 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;
}
}
}
}
}
}
| 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))
}
|
Write the same algorithm in Go as shown in this Java implementation. | 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;
}
}
}
}
}
}
| 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))
}
|
Produce a functionally identical Go code for the snippet given in Java. | 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;
}
}
}
}
}
}
| 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))
}
|
Write the same code in Go as shown below in Java. | 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));
}
}
| 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)
}
}
|
Generate a Go translation of this Java snippet without changing its computational steps. | import processing.sound.*;
SinOsc sine;
size(500,500);
sine = new SinOsc(this);
sine.freq(500);
sine.play();
delay(5000);
| 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)
}
}
|
Convert this Java block to Go, preserving its control flow and logic. | public class Class1 extends Class2
{
}
|
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | public class Class1 extends Class2
{
}
|
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
Generate a Go translation of this Java snippet without changing its computational steps. | 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");
}
}
| 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
}
|
Convert this Java block to Go, preserving its control flow and logic. | 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);
}
}
| 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())
}
|
Generate an equivalent Go version of this Java code. | public static void main(String[] args){
System.out.println(soundex("Soundex"));
System.out.println(soundex("Example"));
System.out.println(soundex("Sownteks"));
System.out.println(soundex("Ekzampul"));
}
private static String getCode(char c){
switch(c){
case 'B': case 'F': case 'P': case 'V':
return "1";
case 'C': case 'G': case 'J': case 'K':
case 'Q': case 'S': case 'X': case 'Z':
return "2";
case 'D': case 'T':
return "3";
case 'L':
return "4";
case 'M': case 'N':
return "5";
case 'R':
return "6";
default:
return "";
}
}
public static String soundex(String s){
String code, previous, soundex;
code = s.toUpperCase().charAt(0) + "";
previous = getCode(s.toUpperCase().charAt(0));
for(int i = 1;i < s.length();i++){
String current = getCode(s.toUpperCase().charAt(i));
if(current.length() > 0 && !current.equals(previous)){
code = code + current;
}
previous = current;
}
soundex = (code + "0000").substring(0, 4);
return soundex;
}
| package main
import (
"errors"
"fmt"
"unicode"
)
var code = []byte("01230127022455012623017202")
func soundex(s string) (string, error) {
var sx [4]byte
var sxi int
var cx, lastCode byte
for i, c := range s {
switch {
case !unicode.IsLetter(c):
if c < ' ' || c == 127 {
return "", errors.New("ASCII control characters disallowed")
}
if i == 0 {
return "", errors.New("initial character must be a letter")
}
lastCode = '0'
continue
case c >= 'A' && c <= 'Z':
cx = byte(c - 'A')
case c >= 'a' && c <= 'z':
cx = byte(c - 'a')
default:
return "", errors.New("non-ASCII letters unsupported")
}
if i == 0 {
sx[0] = cx + 'A'
sxi = 1
continue
}
switch x := code[cx]; x {
case '7', lastCode:
case '0':
lastCode = '0'
default:
sx[sxi] = x
if sxi == 3 {
return string(sx[:]), nil
}
sxi++
lastCode = x
}
}
if sxi == 0 {
return "", errors.New("no letters present")
}
for ; sxi < 4; sxi++ {
sx[sxi] = '0'
}
return string(sx[:]), nil
}
func main() {
for _, s := range []string{
"Robert",
"Rupert",
"Rubin",
"ashcroft",
"ashcraft",
"moses",
"O'Mally",
"d jay",
"R2-D2",
"12p2",
"naΓ―ve",
"",
"bump\t",
} {
if x, err := soundex(s); err == nil {
fmt.Println("soundex", s, "=", x)
} else {
fmt.Printf("\"%s\" fail. %s\n", s, err)
}
}
}
|
Change the following Java code into Go without altering its purpose. | import java.util.ArrayList;
import java.util.List;
public class ListRootedTrees {
private static final List<Long> TREE_LIST = new ArrayList<>();
private static final List<Integer> OFFSET = new ArrayList<>();
static {
for (int i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.add(1);
} else {
OFFSET.add(0);
}
}
}
private static void append(long t) {
TREE_LIST.add(1 | (t << 1));
}
private static void show(long t, int l) {
while (l-- > 0) {
if (t % 2 == 1) {
System.out.print('(');
} else {
System.out.print(')');
}
t = t >> 1;
}
}
private static void listTrees(int n) {
for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {
show(TREE_LIST.get(i), n * 2);
System.out.println();
}
}
private static void assemble(int n, long t, int sl, int pos, int rem) {
if (rem == 0) {
append(t);
return;
}
var pp = pos;
var ss = sl;
if (sl > rem) {
ss = rem;
pp = OFFSET.get(ss);
} else if (pp >= OFFSET.get(ss + 1)) {
ss--;
if (ss == 0) {
return;
}
pp = OFFSET.get(ss);
}
assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);
assemble(n, t, ss, pp + 1, rem);
}
private static void makeTrees(int n) {
if (OFFSET.get(n + 1) != 0) {
return;
}
if (n > 0) {
makeTrees(n - 1);
}
assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);
OFFSET.set(n + 1, TREE_LIST.size());
}
private static void test(int n) {
if (n < 1 || n > 12) {
throw new IllegalArgumentException("Argument must be between 1 and 12");
}
append(0);
makeTrees(n);
System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n));
listTrees(n);
}
public static void main(String[] args) {
test(5);
}
}
| package main
import (
"fmt"
"log"
"os"
"strconv"
)
type tree uint64
var (
list []tree
offset = [32]uint{1: 1}
)
func add(t tree) {
list = append(list, 1|t<<1)
}
func show(t tree, l uint) {
for ; l > 0; t >>= 1 {
l--
var paren byte
if (t & 1) != 0 {
paren = '('
} else {
paren = ')'
}
fmt.Printf("%c", paren)
}
}
func listTrees(n uint) {
for i := offset[n]; i < offset[n+1]; i++ {
show(list[i], n*2)
fmt.Println()
}
}
func assemble(n uint, t tree, sl, pos, rem uint) {
if rem == 0 {
add(t)
return
}
if sl > rem {
sl = rem
pos = offset[sl]
} else if pos >= offset[sl+1] {
sl--
if sl == 0 {
return
}
pos = offset[sl]
}
assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)
assemble(n, t, sl, pos+1, rem)
}
func mktrees(n uint) {
if offset[n+1] > 0 {
return
}
if n > 0 {
mktrees(n - 1)
}
assemble(n, 0, n-1, offset[n-1], n-1)
offset[n+1] = uint(len(list))
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There must be exactly 1 command line argument")
}
n, err := strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal("Argument is not a valid number")
}
if n <= 0 || n > 19 {
n = 5
}
add(0)
mktrees(uint(n))
fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n])
listTrees(uint(n))
}
|
Keep all operations the same but rewrite the snippet in Go. |
public class Doc{
private String field;
public int method(long num) throws BadException{
}
}
|
package example
var (
X, Y, Z int
)
func XP() {
}
func nonXP() {}
var MEMEME int
|
Please provide an equivalent version of this Java code in Go. | public class Circle
{
public double[] center;
public double radius;
public Circle(double[] center, double radius)
{
this.center = center;
this.radius = radius;
}
public String toString()
{
return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1],
radius);
}
}
public class ApolloniusSolver
{
public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,
int s2, int s3)
{
float x1 = c1.center[0];
float y1 = c1.center[1];
float r1 = c1.radius;
float x2 = c2.center[0];
float y2 = c2.center[1];
float r2 = c2.radius;
float x3 = c3.center[0];
float y3 = c3.center[1];
float r3 = c3.radius;
float v11 = 2*x2 - 2*x1;
float v12 = 2*y2 - 2*y1;
float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;
float v14 = 2*s2*r2 - 2*s1*r1;
float v21 = 2*x3 - 2*x2;
float v22 = 2*y3 - 2*y2;
float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;
float v24 = 2*s3*r3 - 2*s2*r2;
float w12 = v12/v11;
float w13 = v13/v11;
float w14 = v14/v11;
float w22 = v22/v21-w12;
float w23 = v23/v21-w13;
float w24 = v24/v21-w14;
float P = -w23/w22;
float Q = w24/w22;
float M = -w12*P-w13;
float N = w14 - w12*Q;
float a = N*N + Q*Q - 1;
float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;
float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;
float D = b*b-4*a*c;
float rs = (-b-Math.sqrt(D))/(2*a);
float xs = M + N * rs;
float ys = P + Q * rs;
return new Circle(new double[]{xs,ys}, rs);
}
public static void main(final String[] args)
{
Circle c1 = new Circle(new double[]{0,0}, 1);
Circle c2 = new Circle(new double[]{4,0}, 1);
Circle c3 = new Circle(new double[]{2,4}, 2);
System.out.println(solveApollonius(c1,c2,c3,1,1,1));
System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));
}
}
| package main
import (
"fmt"
"math"
)
type circle struct {
x, y, r float64
}
func main() {
c1 := circle{0, 0, 1}
c2 := circle{4, 0, 1}
c3 := circle{2, 4, 2}
fmt.Println(ap(c1, c2, c3, true))
fmt.Println(ap(c1, c2, c3, false))
}
func ap(c1, c2, c3 circle, s bool) circle {
x1sq := c1.x * c1.x
y1sq := c1.y * c1.y
r1sq := c1.r * c1.r
x2sq := c2.x * c2.x
y2sq := c2.y * c2.y
r2sq := c2.r * c2.r
x3sq := c3.x * c3.x
y3sq := c3.y * c3.y
r3sq := c3.r * c3.r
v11 := 2 * (c2.x - c1.x)
v12 := 2 * (c2.y - c1.y)
v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq
v14 := 2 * (c2.r - c1.r)
v21 := 2 * (c3.x - c2.x)
v22 := 2 * (c3.y - c2.y)
v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq
v24 := 2 * (c3.r - c2.r)
if s {
v14 = -v14
v24 = -v24
}
w12 := v12 / v11
w13 := v13 / v11
w14 := v14 / v11
w22 := v22/v21 - w12
w23 := v23/v21 - w13
w24 := v24/v21 - w14
p := -w23 / w22
q := w24 / w22
m := -w12*p - w13
n := w14 - w12*q
a := n*n + q*q - 1
b := m*n - n*c1.x + p*q - q*c1.y
if s {
b -= c1.r
} else {
b += c1.r
}
b *= 2
c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq
d := b*b - 4*a*c
rs := (-b - math.Sqrt(d)) / (2 * a)
return circle{m + n*rs, p + q*rs, rs}
}
|
Rewrite the snippet below in Go so it works the same as the original Java code. | import java.util.List;
public class App {
private static String lcs(List<String> a) {
var le = a.size();
if (le == 0) {
return "";
}
if (le == 1) {
return a.get(0);
}
var le0 = a.get(0).length();
var minLen = le0;
for (int i = 1; i < le; i++) {
if (a.get(i).length() < minLen) {
minLen = a.get(i).length();
}
}
if (minLen == 0) {
return "";
}
var res = "";
var a1 = a.subList(1, a.size());
for (int i = 1; i < minLen; i++) {
var suffix = a.get(0).substring(le0 - i);
for (String e : a1) {
if (!e.endsWith(suffix)) {
return res;
}
}
res = suffix;
}
return "";
}
public static void main(String[] args) {
var tests = List.of(
List.of("baabababc", "baabc", "bbbabc"),
List.of("baabababc", "baabc", "bbbazc"),
List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"),
List.of("longest", "common", "suffix"),
List.of("suffix"),
List.of("")
);
for (List<String> test : tests) {
System.out.printf("%s -> `%s`\n", test, lcs(test));
}
}
}
| package main
import (
"fmt"
"strings"
)
func lcs(a []string) string {
le := len(a)
if le == 0 {
return ""
}
if le == 1 {
return a[0]
}
le0 := len(a[0])
minLen := le0
for i := 1; i < le; i++ {
if len(a[i]) < minLen {
minLen = len(a[i])
}
}
if minLen == 0 {
return ""
}
res := ""
a1 := a[1:]
for i := 1; i <= minLen; i++ {
suffix := a[0][le0-i:]
for _, e := range a1 {
if !strings.HasSuffix(e, suffix) {
return res
}
}
res = suffix
}
return res
}
func main() {
tests := [][]string{
{"baabababc", "baabc", "bbbabc"},
{"baabababc", "baabc", "bbbazc"},
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
{"longest", "common", "suffix"},
{"suffix"},
{""},
}
for _, test := range tests {
fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
}
}
|
Preserve the algorithm and functionality while converting the code from Java to Go. | import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer implements Runnable
{
private int port = 0;
private List<Client> clients = new ArrayList<Client>();
public ChatServer(int port)
{ this.port = port; }
public void run()
{
try
{
ServerSocket ss = new ServerSocket(port);
while (true)
{
Socket s = ss.accept();
new Thread(new Client(s)).start();
}
}
catch (Exception e)
{ e.printStackTrace(); }
}
private synchronized boolean registerClient(Client client)
{
for (Client otherClient : clients)
if (otherClient.clientName.equalsIgnoreCase(client.clientName))
return false;
clients.add(client);
return true;
}
private void deregisterClient(Client client)
{
boolean wasRegistered = false;
synchronized (this)
{ wasRegistered = clients.remove(client); }
if (wasRegistered)
broadcast(client, "--- " + client.clientName + " left ---");
}
private synchronized String getOnlineListCSV()
{
StringBuilder sb = new StringBuilder();
sb.append(clients.size()).append(" user(s) online: ");
for (int i = 0; i < clients.size(); i++)
sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName);
return sb.toString();
}
private void broadcast(Client fromClient, String msg)
{
List<Client> clients = null;
synchronized (this)
{ clients = new ArrayList<Client>(this.clients); }
for (Client client : clients)
{
if (client.equals(fromClient))
continue;
try
{ client.write(msg + "\r\n"); }
catch (Exception e)
{ }
}
}
public class Client implements Runnable
{
private Socket socket = null;
private Writer output = null;
private String clientName = null;
public Client(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
socket.setSendBufferSize(16384);
socket.setTcpNoDelay(true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new OutputStreamWriter(socket.getOutputStream());
write("Please enter your name: ");
String line = null;
while ((line = input.readLine()) != null)
{
if (clientName == null)
{
line = line.trim();
if (line.isEmpty())
{
write("A name is required. Please enter your name: ");
continue;
}
clientName = line;
if (!registerClient(this))
{
clientName = null;
write("Name already registered. Please enter your name: ");
continue;
}
write(getOnlineListCSV() + "\r\n");
broadcast(this, "+++ " + clientName + " arrived +++");
continue;
}
if (line.equalsIgnoreCase("/quit"))
return;
broadcast(this, clientName + "> " + line);
}
}
catch (Exception e)
{ }
finally
{
deregisterClient(this);
output = null;
try
{ socket.close(); }
catch (Exception e)
{ }
socket = null;
}
}
public void write(String msg) throws IOException
{
output.write(msg);
output.flush();
}
public boolean equals(Client client)
{
return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);
}
}
public static void main(String[] args)
{
int port = 4004;
if (args.length > 0)
port = Integer.parseInt(args[0]);
new ChatServer(port).run();
}
}
| package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
}
type Server struct {
add chan *conn
rem chan string
msg chan string
stop chan bool
}
func ListenAndServe(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
rwc, err := ln.Accept()
if err != nil {
close(s.stop)
return err
}
log.Println("New connection from", rwc.RemoteAddr())
go newConn(s, rwc).welcome()
}
}
func (s *Server) handleConns() {
conns := make(map[string]*conn)
var dropConn func(string)
writeAll := func(str string) {
log.Printf("Broadcast: %q", str)
for name, c := range conns {
c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))
_, err := c.Write([]byte(str))
if err != nil {
log.Printf("Error writing to %q: %v", name, err)
c.Close()
delete(conns, name)
defer dropConn(name)
}
}
}
dropConn = func(name string) {
if c, ok := conns[name]; ok {
log.Printf("Closing connection with %q from %v",
name, c.RemoteAddr())
c.Close()
delete(conns, name)
} else {
log.Printf("Dropped connection with %q", name)
}
str := fmt.Sprintf("--- %q disconnected ---\n", name)
writeAll(str)
}
defer func() {
writeAll("Server stopping!\n")
for _, c := range conns {
c.Close()
}
}()
for {
select {
case c := <-s.add:
if _, exists := conns[c.name]; exists {
fmt.Fprintf(c, "Name %q is not available\n", c.name)
go c.welcome()
continue
}
str := fmt.Sprintf("+++ %q connected +++\n", c.name)
writeAll(str)
conns[c.name] = c
go c.readloop()
case str := <-s.msg:
writeAll(str)
case name := <-s.rem:
dropConn(name)
case <-s.stop:
return
}
}
}
type conn struct {
*bufio.Reader
net.Conn
server *Server
name string
}
func newConn(s *Server, rwc net.Conn) *conn {
return &conn{
Reader: bufio.NewReader(rwc),
Conn: rwc,
server: s,
}
}
func (c *conn) welcome() {
var err error
for c.name = ""; c.name == ""; {
fmt.Fprint(c, "Enter your name: ")
c.name, err = c.ReadString('\n')
if err != nil {
log.Printf("Reading name from %v: %v", c.RemoteAddr(), err)
c.Close()
return
}
c.name = strings.TrimSpace(c.name)
}
c.server.add <- c
}
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')
if err != nil {
break
}
c.server.msg <- c.name + "> " + msg
}
c.server.rem <- c.name
}
|
Rewrite the snippet below in Go so it works the same as the original Java code. | import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer implements Runnable
{
private int port = 0;
private List<Client> clients = new ArrayList<Client>();
public ChatServer(int port)
{ this.port = port; }
public void run()
{
try
{
ServerSocket ss = new ServerSocket(port);
while (true)
{
Socket s = ss.accept();
new Thread(new Client(s)).start();
}
}
catch (Exception e)
{ e.printStackTrace(); }
}
private synchronized boolean registerClient(Client client)
{
for (Client otherClient : clients)
if (otherClient.clientName.equalsIgnoreCase(client.clientName))
return false;
clients.add(client);
return true;
}
private void deregisterClient(Client client)
{
boolean wasRegistered = false;
synchronized (this)
{ wasRegistered = clients.remove(client); }
if (wasRegistered)
broadcast(client, "--- " + client.clientName + " left ---");
}
private synchronized String getOnlineListCSV()
{
StringBuilder sb = new StringBuilder();
sb.append(clients.size()).append(" user(s) online: ");
for (int i = 0; i < clients.size(); i++)
sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName);
return sb.toString();
}
private void broadcast(Client fromClient, String msg)
{
List<Client> clients = null;
synchronized (this)
{ clients = new ArrayList<Client>(this.clients); }
for (Client client : clients)
{
if (client.equals(fromClient))
continue;
try
{ client.write(msg + "\r\n"); }
catch (Exception e)
{ }
}
}
public class Client implements Runnable
{
private Socket socket = null;
private Writer output = null;
private String clientName = null;
public Client(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
socket.setSendBufferSize(16384);
socket.setTcpNoDelay(true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new OutputStreamWriter(socket.getOutputStream());
write("Please enter your name: ");
String line = null;
while ((line = input.readLine()) != null)
{
if (clientName == null)
{
line = line.trim();
if (line.isEmpty())
{
write("A name is required. Please enter your name: ");
continue;
}
clientName = line;
if (!registerClient(this))
{
clientName = null;
write("Name already registered. Please enter your name: ");
continue;
}
write(getOnlineListCSV() + "\r\n");
broadcast(this, "+++ " + clientName + " arrived +++");
continue;
}
if (line.equalsIgnoreCase("/quit"))
return;
broadcast(this, clientName + "> " + line);
}
}
catch (Exception e)
{ }
finally
{
deregisterClient(this);
output = null;
try
{ socket.close(); }
catch (Exception e)
{ }
socket = null;
}
}
public void write(String msg) throws IOException
{
output.write(msg);
output.flush();
}
public boolean equals(Client client)
{
return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);
}
}
public static void main(String[] args)
{
int port = 4004;
if (args.length > 0)
port = Integer.parseInt(args[0]);
new ChatServer(port).run();
}
}
| package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
}
type Server struct {
add chan *conn
rem chan string
msg chan string
stop chan bool
}
func ListenAndServe(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
rwc, err := ln.Accept()
if err != nil {
close(s.stop)
return err
}
log.Println("New connection from", rwc.RemoteAddr())
go newConn(s, rwc).welcome()
}
}
func (s *Server) handleConns() {
conns := make(map[string]*conn)
var dropConn func(string)
writeAll := func(str string) {
log.Printf("Broadcast: %q", str)
for name, c := range conns {
c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))
_, err := c.Write([]byte(str))
if err != nil {
log.Printf("Error writing to %q: %v", name, err)
c.Close()
delete(conns, name)
defer dropConn(name)
}
}
}
dropConn = func(name string) {
if c, ok := conns[name]; ok {
log.Printf("Closing connection with %q from %v",
name, c.RemoteAddr())
c.Close()
delete(conns, name)
} else {
log.Printf("Dropped connection with %q", name)
}
str := fmt.Sprintf("--- %q disconnected ---\n", name)
writeAll(str)
}
defer func() {
writeAll("Server stopping!\n")
for _, c := range conns {
c.Close()
}
}()
for {
select {
case c := <-s.add:
if _, exists := conns[c.name]; exists {
fmt.Fprintf(c, "Name %q is not available\n", c.name)
go c.welcome()
continue
}
str := fmt.Sprintf("+++ %q connected +++\n", c.name)
writeAll(str)
conns[c.name] = c
go c.readloop()
case str := <-s.msg:
writeAll(str)
case name := <-s.rem:
dropConn(name)
case <-s.stop:
return
}
}
}
type conn struct {
*bufio.Reader
net.Conn
server *Server
name string
}
func newConn(s *Server, rwc net.Conn) *conn {
return &conn{
Reader: bufio.NewReader(rwc),
Conn: rwc,
server: s,
}
}
func (c *conn) welcome() {
var err error
for c.name = ""; c.name == ""; {
fmt.Fprint(c, "Enter your name: ")
c.name, err = c.ReadString('\n')
if err != nil {
log.Printf("Reading name from %v: %v", c.RemoteAddr(), err)
c.Close()
return
}
c.name = strings.TrimSpace(c.name)
}
c.server.add <- c
}
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')
if err != nil {
break
}
c.server.msg <- c.name + "> " + msg
}
c.server.rem <- c.name
}
|
Change the following Java code into Go without altering its purpose. | import java.util.stream.IntStream;
public class Letters {
public static void main(String[] args) throws Exception {
System.out.print("Upper case: ");
IntStream.rangeClosed(0, 0x10FFFF)
.filter(Character::isUpperCase)
.limit(72)
.forEach(n -> System.out.printf("%c", n));
System.out.println("...");
System.out.print("Lower case: ");
IntStream.rangeClosed(0, 0x10FFFF)
.filter(Character::isLowerCase)
.limit(72)
.forEach(n -> System.out.printf("%c", n));
System.out.println("...");
}
}
| package main
import (
"fmt"
"unicode"
)
const (
lcASCII = "abcdefghijklmnopqrstuvwxyz"
ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func main() {
fmt.Println("ASCII lower case:")
fmt.Println(lcASCII)
for l := 'a'; l <= 'z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nASCII upper case:")
fmt.Println(ucASCII)
for l := 'A'; l <= 'Z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nUnicode version " + unicode.Version)
showRange16("Lower case 16-bit code points:", unicode.Lower.R16)
showRange32("Lower case 32-bit code points:", unicode.Lower.R32)
showRange16("Upper case 16-bit code points:", unicode.Upper.R16)
showRange32("Upper case 32-bit code points:", unicode.Upper.R32)
}
func showRange16(hdr string, rList []unicode.Range16) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
func showRange32(hdr string, rList []unicode.Range32) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
|
Write a version of this Java function in Go with identical behavior. | public static void main(String[] args) {
int[][] matrix = {{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5}};
int sum = 0;
for (int row = 1; row < matrix.length; row++) {
for (int col = 0; col < row; col++) {
sum += matrix[row][col];
}
}
System.out.println(sum);
}
| package main
import (
"fmt"
"log"
)
func main() {
m := [][]int{
{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5},
}
if len(m) != len(m[0]) {
log.Fatal("Matrix must be square.")
}
sum := 0
for i := 1; i < len(m); i++ {
for j := 0; j < i; j++ {
sum = sum + m[i][j]
}
}
fmt.Println("Sum of elements below main diagonal is", sum)
}
|
Generate an equivalent Go version of this Java code. |
import java.util.*;
public class TreeSortTest {
public static void main(String[] args) {
test1();
System.out.println();
test2();
}
private static void test1() {
LinkedList<Integer> list = new LinkedList<>();
Random r = new Random();
for (int i = 0; i < 16; ++i)
list.add(Integer.valueOf(r.nextInt(100)));
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
private static void test2() {
LinkedList<String> list = new LinkedList<>();
String[] strings = { "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"};
for (String str : strings)
list.add(str);
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
}
| package main
import (
"container/list"
"fmt"
)
type BinaryTree struct {
node int
leftSubTree *BinaryTree
rightSubTree *BinaryTree
}
func (bt *BinaryTree) insert(item int) {
if bt.node == 0 {
bt.node = item
bt.leftSubTree = &BinaryTree{}
bt.rightSubTree = &BinaryTree{}
} else if item < bt.node {
bt.leftSubTree.insert(item)
} else {
bt.rightSubTree.insert(item)
}
}
func (bt *BinaryTree) inOrder(ll *list.List) {
if bt.node == 0 {
return
}
bt.leftSubTree.inOrder(ll)
ll.PushBack(bt.node)
bt.rightSubTree.inOrder(ll)
}
func treeSort(ll *list.List) *list.List {
searchTree := &BinaryTree{}
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
searchTree.insert(i)
}
ll2 := list.New()
searchTree.inOrder(ll2)
return ll2
}
func printLinkedList(ll *list.List, f string, sorted bool) {
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
fmt.Printf(f+" ", i)
}
if !sorted {
fmt.Print("-> ")
} else {
fmt.Println()
}
}
func main() {
sl := []int{5, 3, 7, 9, 1}
ll := list.New()
for _, i := range sl {
ll.PushBack(i)
}
printLinkedList(ll, "%d", false)
lls := treeSort(ll)
printLinkedList(lls, "%d", true)
sl2 := []int{'d', 'c', 'e', 'b', 'a'}
ll2 := list.New()
for _, c := range sl2 {
ll2.PushBack(c)
}
printLinkedList(ll2, "%c", false)
lls2 := treeSort(ll2)
printLinkedList(lls2, "%c", true)
}
|
Translate this program into Go but keep the logic exactly as in Java. |
import java.util.*;
public class TreeSortTest {
public static void main(String[] args) {
test1();
System.out.println();
test2();
}
private static void test1() {
LinkedList<Integer> list = new LinkedList<>();
Random r = new Random();
for (int i = 0; i < 16; ++i)
list.add(Integer.valueOf(r.nextInt(100)));
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
private static void test2() {
LinkedList<String> list = new LinkedList<>();
String[] strings = { "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"};
for (String str : strings)
list.add(str);
System.out.println("before sort: " + list);
list.treeSort();
System.out.println(" after sort: " + list);
}
}
| package main
import (
"container/list"
"fmt"
)
type BinaryTree struct {
node int
leftSubTree *BinaryTree
rightSubTree *BinaryTree
}
func (bt *BinaryTree) insert(item int) {
if bt.node == 0 {
bt.node = item
bt.leftSubTree = &BinaryTree{}
bt.rightSubTree = &BinaryTree{}
} else if item < bt.node {
bt.leftSubTree.insert(item)
} else {
bt.rightSubTree.insert(item)
}
}
func (bt *BinaryTree) inOrder(ll *list.List) {
if bt.node == 0 {
return
}
bt.leftSubTree.inOrder(ll)
ll.PushBack(bt.node)
bt.rightSubTree.inOrder(ll)
}
func treeSort(ll *list.List) *list.List {
searchTree := &BinaryTree{}
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
searchTree.insert(i)
}
ll2 := list.New()
searchTree.inOrder(ll2)
return ll2
}
func printLinkedList(ll *list.List, f string, sorted bool) {
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
fmt.Printf(f+" ", i)
}
if !sorted {
fmt.Print("-> ")
} else {
fmt.Println()
}
}
func main() {
sl := []int{5, 3, 7, 9, 1}
ll := list.New()
for _, i := range sl {
ll.PushBack(i)
}
printLinkedList(ll, "%d", false)
lls := treeSort(ll)
printLinkedList(lls, "%d", true)
sl2 := []int{'d', 'c', 'e', 'b', 'a'}
ll2 := list.New()
for _, c := range sl2 {
ll2.PushBack(c)
}
printLinkedList(ll2, "%c", false)
lls2 := treeSort(ll2)
printLinkedList(lls2, "%c", true)
}
|
Ensure the translated Go code behaves exactly like the original Java snippet. | import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
long newSize = Long.parseLong(args[1]);
outChan.truncate(newSize);
outChan.close();
}
}
| import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
long newSize = Long.parseLong(args[1]);
outChan.truncate(newSize);
outChan.close();
}
}
| import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
|
Write the same algorithm in Go as shown in this Java implementation. | import java.util.function.Function;
public class NumericalIntegrationAdaptiveSimpsons {
public static void main(String[] args) {
Function<Double,Double> f = x -> sin(x);
System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);
functionCount = 0;
System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);
}
private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {
double fa = function.apply(a);
double fb = function.apply(b);
Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);
}
private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {
Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);
Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);
double delta = left.s + right.s - whole;
if ( Math.abs(delta) <= 15*error ) {
return left.s + right.s + delta / 15;
}
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +
quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);
}
private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = function.apply(m);
return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));
}
private static class Triple {
double x, fx, s;
private Triple(double m, double fm, double s) {
this.x = m;
this.fx = fm;
this.s = s;
}
}
private static int functionCount = 0;
private static double sin(double x) {
functionCount++;
return Math.sin(x);
}
}
| package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
|
Translate the given Java code snippet into Go without altering its behavior. | import java.util.function.Function;
public class NumericalIntegrationAdaptiveSimpsons {
public static void main(String[] args) {
Function<Double,Double> f = x -> sin(x);
System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);
functionCount = 0;
System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);
}
private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {
double fa = function.apply(a);
double fb = function.apply(b);
Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);
}
private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {
Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);
Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);
double delta = left.s + right.s - whole;
if ( Math.abs(delta) <= 15*error ) {
return left.s + right.s + delta / 15;
}
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +
quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);
}
private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = function.apply(m);
return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));
}
private static class Triple {
double x, fx, s;
private Triple(double m, double fm, double s) {
this.x = m;
this.fx = fm;
this.s = s;
}
}
private static int functionCount = 0;
private static double sin(double x) {
functionCount++;
return Math.sin(x);
}
}
| package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
|
Convert this Java snippet to Go and keep its semantics consistent. | import java.io.*;
import java.util.Scanner;
public class ReadFastaFile {
public static void main(String[] args) throws FileNotFoundException {
boolean first = true;
try (Scanner sc = new Scanner(new File("test.fasta"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.charAt(0) == '>') {
if (first)
first = false;
else
System.out.println();
System.out.printf("%s: ", line.substring(1));
} else {
System.out.print(line);
}
}
}
System.out.println();
}
}
| package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.Open("rc.fasta")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
headerFound := false
for s.Scan() {
line := s.Text()
switch {
case line == "":
continue
case line[0] != '>':
if !headerFound {
fmt.Println("missing header")
return
}
fmt.Print(line)
case headerFound:
fmt.Println()
fallthrough
default:
fmt.Printf("%s: ", line[1:])
headerFound = true
}
}
if headerFound {
fmt.Println()
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
}
|
Port the provided Java code into Go while preserving the original functionality. | public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue;
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
| package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("DecimalΒ :", n)
fmt.Println("Binary Β :", strconv.FormatUint(n, 2))
fmt.Println("TernaryΒ :", strconv.FormatUint(n, 3))
fmt.Println("Time Β :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary areΒ :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
|
Convert this Java snippet to Go and keep its semantics consistent. | public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue;
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
| package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("DecimalΒ :", n)
fmt.Println("Binary Β :", strconv.FormatUint(n, 2))
fmt.Println("TernaryΒ :", strconv.FormatUint(n, 3))
fmt.Println("Time Β :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary areΒ :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WindowExample {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
createAndShow();
}
};
SwingUtilities.invokeLater(runnable);
}
static void createAndShow() {
JFrame frame = new JFrame("Hello World");
frame.setSize(640,480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
| package main
import (
"log"
"github.com/jezek/xgb"
"github.com/jezek/xgb/xproto"
)
func main() {
X, err := xgb.NewConn()
if err != nil {
log.Fatal(err)
}
points := []xproto.Point{
{10, 10},
{10, 20},
{20, 10},
{20, 20}};
polyline := []xproto.Point{
{50, 10},
{ 5, 20},
{25,-20},
{10, 10}};
segments := []xproto.Segment{
{100, 10, 140, 30},
{110, 25, 130, 60}};
rectangles := []xproto.Rectangle{
{ 10, 50, 40, 20},
{ 80, 50, 10, 40}};
arcs := []xproto.Arc{
{10, 100, 60, 40, 0, 90 << 6},
{90, 100, 55, 40, 0, 270 << 6}};
setup := xproto.Setup(X)
screen := setup.DefaultScreen(X)
foreground, _ := xproto.NewGcontextId(X)
mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)
values := []uint32{screen.BlackPixel, 0}
xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)
win, _ := xproto.NewWindowId(X)
winDrawable := xproto.Drawable(win)
mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)
values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}
xproto.CreateWindow(X,
screen.RootDepth,
win,
screen.Root,
0, 0,
150, 150,
10,
xproto.WindowClassInputOutput,
screen.RootVisual,
mask, values)
xproto.MapWindow(X, win)
for {
evt, err := X.WaitForEvent()
switch evt.(type) {
case xproto.ExposeEvent:
xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)
xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)
xproto.PolySegment(X, winDrawable, foreground, segments)
xproto.PolyRectangle(X, winDrawable, foreground, rectangles)
xproto.PolyArc(X, winDrawable, foreground, arcs)
default:
}
if err != nil {
log.Fatal(err)
}
}
return
}
|
Write a version of this Java function in Go with identical behavior. | import java.util.*;
public class FiniteStateMachine {
private enum State {
Ready(true, "Deposit", "Quit"),
Waiting(true, "Select", "Refund"),
Dispensing(true, "Remove"),
Refunding(false, "Refunding"),
Exiting(false, "Quiting");
State(boolean exp, String... in) {
inputs = Arrays.asList(in);
explicit = exp;
}
State nextState(String input, State current) {
if (inputs.contains(input)) {
return map.getOrDefault(input, current);
}
return current;
}
final List<String> inputs;
final static Map<String, State> map = new HashMap<>();
final boolean explicit;
static {
map.put("Deposit", State.Waiting);
map.put("Quit", State.Exiting);
map.put("Select", State.Dispensing);
map.put("Refund", State.Refunding);
map.put("Remove", State.Ready);
map.put("Refunding", State.Ready);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
State state = State.Ready;
while (state != State.Exiting) {
System.out.println(state.inputs);
if (state.explicit){
System.out.print("> ");
state = state.nextState(sc.nextLine().trim(), state);
} else {
state = state.nextState(state.inputs.get(0), state);
}
}
}
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
type state int
const (
ready state = iota
waiting
exit
dispense
refunding
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func fsm() {
fmt.Println("Please enter your option when prompted")
fmt.Println("(any characters after the first will be ignored)")
state := ready
var trans string
scanner := bufio.NewScanner(os.Stdin)
for {
switch state {
case ready:
for {
fmt.Print("\n(D)ispense or (Q)uitΒ : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'd' {
state = waiting
break
} else if option == 'q' {
state = exit
break
}
}
case waiting:
fmt.Println("OK, put your money in the slot")
for {
fmt.Print("(S)elect product or choose a (R)efundΒ : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 's' {
state = dispense
break
} else if option == 'r' {
state = refunding
break
}
}
case dispense:
for {
fmt.Print("(R)emove productΒ : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'r' {
state = ready
break
}
}
case refunding:
fmt.Println("OK, refunding your money")
state = ready
case exit:
fmt.Println("OK, quitting")
return
}
}
}
func main() {
fsm()
}
|
Port the following code from Java to Go with equivalent syntax and logic. |
int counter = 100;
void setup(){
size(1000,1000);
}
void draw(){
for(int i=0;i<20;i++){
fill(counter - 5*i);
rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);
}
counter++;
if(counter > 255)
counter = 100;
delay(100);
}
| package main
import (
"image"
"image/color"
"image/gif"
"log"
"os"
)
var (
black = color.RGBA{0, 0, 0, 255}
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
yellow = color.RGBA{255, 255, 0, 255}
white = color.RGBA{255, 255, 255, 255}
)
var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}
func hline(img *image.Paletted, x1, y, x2 int, ci uint8) {
for ; x1 <= x2; x1++ {
img.SetColorIndex(x1, y, ci)
}
}
func vline(img *image.Paletted, x, y1, y2 int, ci uint8) {
for ; y1 <= y2; y1++ {
img.SetColorIndex(x, y1, ci)
}
}
func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
img.SetColorIndex(x, y, ci)
}
}
}
func drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
hline(img, x1, y1, x2, ci)
hline(img, x1, y2, x2, ci)
vline(img, x1, y1, y2, ci)
vline(img, x2, y1, y2, ci)
}
func main() {
const nframes = 140
const delay = 10
width, height := 500, 500
anim := gif.GIF{LoopCount: nframes}
rect := image.Rect(0, 0, width, height)
for c := uint8(0); c < 7; c++ {
for f := 0; f < 20; f++ {
img := image.NewPaletted(rect, palette)
setBackgroundColor(img, width, height, 7)
for r := 0; r < 20; r++ {
ix := c
if r < f {
ix = (ix + 1) % 7
}
x := width * (r + 1) / 50
y := height * (r + 1) / 50
w := width - x
h := height - y
drawRectangle(img, x, y, w, h, ix)
}
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
}
file, err := os.Create("vibrating.gif")
if err != nil {
log.Fatal(err)
}
defer file.Close()
if err2 := gif.EncodeAll(file, &anim); err != nil {
log.Fatal(err2)
}
}
|
Generate a Go translation of this Java snippet without changing its computational steps. | import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
| package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, Ο2 int
for a = 0; ; a++ {
Ο2 = (a*a + p - n) % p
if ls(Ο2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*Ο2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
|
Port the following code from Java to Go with equivalent syntax and logic. | import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
| package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, Ο2 int
for a = 0; ; a++ {
Ο2 = (a*a + p - n) % p
if ls(Ο2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*Ο2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
|
Convert the following code from Java to Go, ensuring the logic remains intact. | public class PCG32 {
private static final long N = 6364136223846793005L;
private long state = 0x853c49e6748fea9bL;
private long inc = 0xda3e39cb94b95bdbL;
public void seed(long seedState, long seedSequence) {
state = 0;
inc = (seedSequence << 1) | 1;
nextInt();
state = state + seedState;
nextInt();
}
public int nextInt() {
long old = state;
state = old * N + inc;
int shifted = (int) (((old >>> 18) ^ old) >>> 27);
int rot = (int) (old >>> 59);
return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));
}
public double nextFloat() {
var u = Integer.toUnsignedLong(nextInt());
return (double) u / (1L << 32);
}
public static void main(String[] args) {
var r = new PCG32();
r.seed(42, 54);
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
r.seed(987654321, 1);
for (int i = 0; i < 100_000; i++) {
int j = (int) Math.floor(r.nextFloat() * 5.0);
counts[j]++;
}
System.out.println("The counts for 100,000 repetitions are:");
for (int i = 0; i < counts.length; i++) {
System.out.printf(" %dΒ : %d\n", i, counts[i]);
}
}
}
| package main
import (
"fmt"
"math"
)
const CONST = 6364136223846793005
type Pcg32 struct{ state, inc uint64 }
func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }
func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
pcg.state = 0
pcg.inc = (seedSequence << 1) | 1
pcg.nextInt()
pcg.state = pcg.state + seedState
pcg.nextInt()
}
func (pcg *Pcg32) nextInt() uint32 {
old := pcg.state
pcg.state = old*CONST + pcg.inc
pcgshifted := uint32(((old >> 18) ^ old) >> 27)
rot := uint32(old >> 59)
return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}
func (pcg *Pcg32) nextFloat() float64 {
return float64(pcg.nextInt()) / (1 << 32)
}
func main() {
randomGen := Pcg32New()
randomGen.seed(42, 54)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321, 1)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %dΒ : %d\n", i, counts[i])
}
}
|
Can you help me rewrite this code in Go instead of Java, keeping it the same logically? | import java.util.Arrays;
public class Deconvolution1D {
public static int[] deconv(int[] g, int[] f) {
int[] h = new int[g.length - f.length + 1];
for (int n = 0; n < h.length; n++) {
h[n] = g[n];
int lower = Math.max(n - f.length + 1, 0);
for (int i = lower; i < n; i++)
h[n] -= h[i] * f[n - i];
h[n] /= f[0];
}
return h;
}
public static void main(String[] args) {
int[] h = { -8, -9, -3, -1, -6, 7 };
int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };
int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7 };
StringBuilder sb = new StringBuilder();
sb.append("h = " + Arrays.toString(h) + "\n");
sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n");
sb.append("f = " + Arrays.toString(f) + "\n");
sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n");
System.out.println(sb.toString());
}
}
| package main
import "fmt"
func main() {
h := []float64{-8, -9, -3, -1, -6, 7}
f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7}
fmt.Println(h)
fmt.Println(deconv(g, f))
fmt.Println(f)
fmt.Println(deconv(g, h))
}
func deconv(g, f []float64) []float64 {
h := make([]float64, len(g)-len(f)+1)
for n := range h {
h[n] = g[n]
var lower int
if n >= len(f) {
lower = n - len(f) + 1
}
for i := lower; i < n; i++ {
h[n] -= h[i] * f[n-i]
}
h[n] /= f[0]
}
return h
}
|
Maintain the same structure and functionality when rewriting this code in Go. | import static java.util.Arrays.*;
import static java.lang.System.out;
public class NYSIIS {
final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"},
{"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}};
final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"},
{"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}};
final static String Vowels = "AEIOU";
public static void main(String[] args) {
stream(args).parallel().map(n -> transcode(n)).forEach(out::println);
}
static String transcode(String s) {
int len = s.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z')
sb.append((char) (c - 32));
else if (c >= 'A' && c <= 'Z')
sb.append(c);
}
replace(sb, 0, first);
replace(sb, sb.length() - 2, last);
len = sb.length();
sb.append(" ");
for (int i = 1; i < len; i++) {
char prev = sb.charAt(i - 1);
char curr = sb.charAt(i);
char next = sb.charAt(i + 1);
if (curr == 'E' && next == 'V')
sb.replace(i, i + 2, "AF");
else if (isVowel(curr))
sb.setCharAt(i, 'A');
else if (curr == 'Q')
sb.setCharAt(i, 'G');
else if (curr == 'Z')
sb.setCharAt(i, 'S');
else if (curr == 'M')
sb.setCharAt(i, 'N');
else if (curr == 'K' && next == 'N')
sb.setCharAt(i, 'N');
else if (curr == 'K')
sb.setCharAt(i, 'C');
else if (sb.indexOf("SCH", i) == i)
sb.replace(i, i + 3, "SSS");
else if (curr == 'P' && next == 'H')
sb.replace(i, i + 2, "FF");
else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))
sb.setCharAt(i, prev);
else if (curr == 'W' && isVowel(prev))
sb.setCharAt(i, prev);
if (sb.charAt(i) == prev) {
sb.deleteCharAt(i--);
len--;
}
}
sb.setLength(sb.length() - 1);
int lastPos = sb.length() - 1;
if (lastPos > 1) {
if (sb.lastIndexOf("AY") == lastPos - 1)
sb.delete(lastPos - 1, lastPos + 1).append("Y");
else if (sb.charAt(lastPos) == 'S')
sb.setLength(lastPos);
else if (sb.charAt(lastPos) == 'A')
sb.setLength(lastPos);
}
if (sb.length() > 6)
sb.insert(6, '[').append(']');
return String.format("%s -> %s", s, sb);
}
private static void replace(StringBuilder sb, int start, String[][] maps) {
if (start >= 0)
for (String[] map : maps) {
if (sb.indexOf(map[0]) == start) {
sb.replace(start, start + map[0].length(), map[1]);
break;
}
}
}
private static boolean isVowel(char c) {
return Vowels.indexOf(c) != -1;
}
}
| package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16sΒ : %s\n", name, name2)
}
}
|
Port the provided Java code into Go while preserving the original functionality. | import static java.util.Arrays.*;
import static java.lang.System.out;
public class NYSIIS {
final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"},
{"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}};
final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"},
{"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}};
final static String Vowels = "AEIOU";
public static void main(String[] args) {
stream(args).parallel().map(n -> transcode(n)).forEach(out::println);
}
static String transcode(String s) {
int len = s.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z')
sb.append((char) (c - 32));
else if (c >= 'A' && c <= 'Z')
sb.append(c);
}
replace(sb, 0, first);
replace(sb, sb.length() - 2, last);
len = sb.length();
sb.append(" ");
for (int i = 1; i < len; i++) {
char prev = sb.charAt(i - 1);
char curr = sb.charAt(i);
char next = sb.charAt(i + 1);
if (curr == 'E' && next == 'V')
sb.replace(i, i + 2, "AF");
else if (isVowel(curr))
sb.setCharAt(i, 'A');
else if (curr == 'Q')
sb.setCharAt(i, 'G');
else if (curr == 'Z')
sb.setCharAt(i, 'S');
else if (curr == 'M')
sb.setCharAt(i, 'N');
else if (curr == 'K' && next == 'N')
sb.setCharAt(i, 'N');
else if (curr == 'K')
sb.setCharAt(i, 'C');
else if (sb.indexOf("SCH", i) == i)
sb.replace(i, i + 3, "SSS");
else if (curr == 'P' && next == 'H')
sb.replace(i, i + 2, "FF");
else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))
sb.setCharAt(i, prev);
else if (curr == 'W' && isVowel(prev))
sb.setCharAt(i, prev);
if (sb.charAt(i) == prev) {
sb.deleteCharAt(i--);
len--;
}
}
sb.setLength(sb.length() - 1);
int lastPos = sb.length() - 1;
if (lastPos > 1) {
if (sb.lastIndexOf("AY") == lastPos - 1)
sb.delete(lastPos - 1, lastPos + 1).append("Y");
else if (sb.charAt(lastPos) == 'S')
sb.setLength(lastPos);
else if (sb.charAt(lastPos) == 'A')
sb.setLength(lastPos);
}
if (sb.length() > 6)
sb.insert(6, '[').append(']');
return String.format("%s -> %s", s, sb);
}
private static void replace(StringBuilder sb, int start, String[][] maps) {
if (start >= 0)
for (String[] map : maps) {
if (sb.indexOf(map[0]) == start) {
sb.replace(start, start + map[0].length(), map[1]);
break;
}
}
}
private static boolean isVowel(char c) {
return Vowels.indexOf(c) != -1;
}
}
| package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16sΒ : %s\n", name, name2)
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Java version. | import static java.util.Arrays.*;
import static java.lang.System.out;
public class NYSIIS {
final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"},
{"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}};
final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"},
{"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}};
final static String Vowels = "AEIOU";
public static void main(String[] args) {
stream(args).parallel().map(n -> transcode(n)).forEach(out::println);
}
static String transcode(String s) {
int len = s.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z')
sb.append((char) (c - 32));
else if (c >= 'A' && c <= 'Z')
sb.append(c);
}
replace(sb, 0, first);
replace(sb, sb.length() - 2, last);
len = sb.length();
sb.append(" ");
for (int i = 1; i < len; i++) {
char prev = sb.charAt(i - 1);
char curr = sb.charAt(i);
char next = sb.charAt(i + 1);
if (curr == 'E' && next == 'V')
sb.replace(i, i + 2, "AF");
else if (isVowel(curr))
sb.setCharAt(i, 'A');
else if (curr == 'Q')
sb.setCharAt(i, 'G');
else if (curr == 'Z')
sb.setCharAt(i, 'S');
else if (curr == 'M')
sb.setCharAt(i, 'N');
else if (curr == 'K' && next == 'N')
sb.setCharAt(i, 'N');
else if (curr == 'K')
sb.setCharAt(i, 'C');
else if (sb.indexOf("SCH", i) == i)
sb.replace(i, i + 3, "SSS");
else if (curr == 'P' && next == 'H')
sb.replace(i, i + 2, "FF");
else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))
sb.setCharAt(i, prev);
else if (curr == 'W' && isVowel(prev))
sb.setCharAt(i, prev);
if (sb.charAt(i) == prev) {
sb.deleteCharAt(i--);
len--;
}
}
sb.setLength(sb.length() - 1);
int lastPos = sb.length() - 1;
if (lastPos > 1) {
if (sb.lastIndexOf("AY") == lastPos - 1)
sb.delete(lastPos - 1, lastPos + 1).append("Y");
else if (sb.charAt(lastPos) == 'S')
sb.setLength(lastPos);
else if (sb.charAt(lastPos) == 'A')
sb.setLength(lastPos);
}
if (sb.length() > 6)
sb.insert(6, '[').append(']');
return String.format("%s -> %s", s, sb);
}
private static void replace(StringBuilder sb, int start, String[][] maps) {
if (start >= 0)
for (String[] map : maps) {
if (sb.indexOf(map[0]) == start) {
sb.replace(start, start + map[0].length(), map[1]);
break;
}
}
}
private static boolean isVowel(char c) {
return Vowels.indexOf(c) != -1;
}
}
| package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16sΒ : %s\n", name, name2)
}
}
|
Convert the following code from Java to Go, ensuring the logic remains intact. | import java.lang.Math;
public class DisariumNumbers {
public static boolean is_disarium(int num) {
int n = num;
int len = Integer.toString(n).length();
int sum = 0;
int i = 1;
while (n > 0) {
sum += Math.pow(n % 10, len - i + 1);
n /= 10;
i ++;
}
return sum == num;
}
public static void main(String[] args) {
int i = 0;
int count = 0;
while (count <= 18) {
if (is_disarium(i)) {
System.out.printf("%d ", i);
count++;
}
i++;
}
System.out.printf("%s", "\n");
}
}
| package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
|
Write the same algorithm in Go as shown in this Java implementation. | import java.lang.Math;
public class DisariumNumbers {
public static boolean is_disarium(int num) {
int n = num;
int len = Integer.toString(n).length();
int sum = 0;
int i = 1;
while (n > 0) {
sum += Math.pow(n % 10, len - i + 1);
n /= 10;
i ++;
}
return sum == num;
}
public static void main(String[] args) {
int i = 0;
int count = 0;
while (count <= 18) {
if (is_disarium(i)) {
System.out.printf("%d ", i);
count++;
}
i++;
}
System.out.printf("%s", "\n");
}
}
| package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
|
Write the same code in Go as shown below in Java. | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import static java.lang.Math.*;
import java.util.Random;
import javax.swing.*;
public class SierpinskiPentagon extends JPanel {
final double degrees072 = toRadians(72);
final double scaleFactor = 1 / (2 + cos(degrees072) * 2);
final int margin = 20;
int limit = 0;
Random r = new Random();
public SierpinskiPentagon() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
new Timer(3000, (ActionEvent e) -> {
limit++;
if (limit >= 5)
limit = 0;
repaint();
}).start();
}
void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {
double angle = 3 * degrees072;
if (depth == 0) {
Path2D p = new Path2D.Double();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * side;
y = y - sin(angle) * side;
p.lineTo(x, y);
angle += degrees072;
}
g.setColor(RandomHue.next());
g.fill(p);
} else {
side *= scaleFactor;
double distance = side + side * cos(degrees072) * 2;
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * distance;
y = y - sin(angle) * distance;
drawPentagon(g, x, y, side, depth - 1);
angle += degrees072;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
double radius = w / 2 - 2 * margin;
double side = radius * sin(PI / 5) * 2;
drawPentagon(g, w / 2, 3 * margin, side, limit);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Sierpinski Pentagon");
f.setResizable(true);
f.add(new SierpinskiPentagon(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class RandomHue {
final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;
private static double hue = Math.random();
static Color next() {
hue = (hue + goldenRatioConjugate) % 1;
return Color.getHSBColor((float) hue, 1, 1);
}
}
| package main
import (
"github.com/fogleman/gg"
"image/color"
"math"
)
var (
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
)
var (
w, h = 640, 640
dc = gg.NewContext(w, h)
deg72 = gg.Radians(72)
scaleFactor = 1 / (2 + math.Cos(deg72)*2)
palette = [5]color.Color{red, green, blue, magenta, cyan}
colorIndex = 0
)
func drawPentagon(x, y, side float64, depth int) {
angle := 3 * deg72
if depth == 0 {
dc.MoveTo(x, y)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * side
y -= math.Sin(angle) * side
dc.LineTo(x, y)
angle += deg72
}
dc.SetColor(palette[colorIndex])
dc.Fill()
colorIndex = (colorIndex + 1) % 5
} else {
side *= scaleFactor
dist := side * (1 + math.Cos(deg72)*2)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * dist
y -= math.Sin(angle) * dist
drawPentagon(x, y, side, depth-1)
angle += deg72
}
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
order := 5
hw := float64(w / 2)
margin := 20.0
radius := hw - 2*margin
side := radius * math.Sin(math.Pi/5) * 2
drawPentagon(hw, 3*margin, side, order-1)
dc.SavePNG("sierpinski_pentagon.png")
}
|
Change the programming language of this snippet from Java to Go without modifying what it does. | import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImageProcessing {
;
public static void main(String[] args) throws IOException {
BufferedImage img = ImageIO.read(new File("example.png"));
BufferedImage bwimg = toBlackAndWhite(img);
ImageIO.write(bwimg, "png", new File("example-bw.png"));
}
private static int luminance(int rgb) {
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
return (r + b + g) / 3;
}
private static BufferedImage toBlackAndWhite(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int[] histo = computeHistogram(img);
int median = getMedian(width * height, histo);
BufferedImage bwimg = new BufferedImage(width, height, img.getType());
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);
}
}
return bwimg;
}
private static int[] computeHistogram(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int[] histo = new int[256];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
histo[luminance(img.getRGB(x, y))]++;
}
}
return histo;
}
private static int getMedian(int total, int[] histo) {
int median = 0;
int sum = 0;
for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {
sum += histo[i];
median++;
}
return median;
}
}
| package raster
import "math"
func (g *Grmap) Histogram(bins int) []int {
if bins <= 0 {
bins = g.cols
}
h := make([]int, bins)
for _, p := range g.px {
h[int(p)*(bins-1)/math.MaxUint16]++
}
return h
}
func (g *Grmap) Threshold(t uint16) {
for i, p := range g.px {
if p < t {
g.px[i] = 0
} else {
g.px[i] = math.MaxUint16
}
}
}
|
Change the following Java code into Go without altering its purpose. | import java.util.concurrent.Semaphore;
public class VolatileClass{
public Semaphore mutex = new Semaphore(1);
public void needsToBeSynched(){
}
}
| package main
import (
"fmt"
"sync"
"time"
)
var value int
var m sync.Mutex
var wg sync.WaitGroup
func slowInc() {
m.Lock()
v := value
time.Sleep(1e8)
value = v+1
m.Unlock()
wg.Done()
}
func main() {
wg.Add(2)
go slowInc()
go slowInc()
wg.Wait()
fmt.Println(value)
}
|
Write a version of this Java function in Go with identical behavior. | class Metronome{
double bpm;
int measure, counter;
public Metronome(double bpm, int measure){
this.bpm = bpm;
this.measure = measure;
}
public void start(){
while(true){
try {
Thread.sleep((long)(1000*(60.0/bpm)));
}catch(InterruptedException e) {
e.printStackTrace();
}
counter++;
if (counter%measure==0){
System.out.println("TICK");
}else{
System.out.println("TOCK");
}
}
}
}
public class test {
public static void main(String[] args) {
Metronome metronome1 = new Metronome(120,4);
metronome1.start();
}
}
| package main
import (
"fmt"
"time"
)
func main() {
var bpm = 72.0
var bpb = 4
d := time.Duration(float64(time.Minute) / bpm)
fmt.Println("Delay:", d)
t := time.NewTicker(d)
i := 1
for _ = range t.C {
i--
if i == 0 {
i = bpb
fmt.Printf("\nTICK ")
} else {
fmt.Printf("tick ")
}
}
}
|
Preserve the algorithm and functionality while converting the code from Java to Go. | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EKGSequenceConvergence {
public static void main(String[] args) {
System.out.println("Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].");
for ( int i : new int[] {2, 5, 7, 9, 10} ) {
System.out.printf("EKG[%d] = %s%n", i, ekg(i, 10));
}
System.out.println("Calculate and show here at which term EKG[5] and EKG[7] converge.");
List<Integer> ekg5 = ekg(5, 100);
List<Integer> ekg7 = ekg(7, 100);
for ( int i = 1 ; i < ekg5.size() ; i++ ) {
if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {
System.out.printf("EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n", 5, i+1, 7, i+1, ekg5.get(i));
break;
}
}
}
private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {
List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));
Collections.sort(list1);
List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));
Collections.sort(list2);
for ( int i = 0 ; i < n ; i++ ) {
if ( list1.get(i) != list2.get(i) ) {
return false;
}
}
return true;
}
private static List<Integer> ekg(int two, int maxN) {
List<Integer> result = new ArrayList<>();
result.add(1);
result.add(two);
Map<Integer,Integer> seen = new HashMap<>();
seen.put(1, 1);
seen.put(two, 1);
int minUnseen = two == 2 ? 3 : 2;
int prev = two;
for ( int n = 3 ; n <= maxN ; n++ ) {
int test = minUnseen - 1;
while ( true ) {
test++;
if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {
result.add(test);
seen.put(test, n);
prev = test;
if ( minUnseen == test ) {
do {
minUnseen++;
} while ( seen.containsKey(minUnseen) );
}
break;
}
}
}
return result;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
| package main
import (
"fmt"
"sort"
)
func contains(a []int, b int) bool {
for _, j := range a {
if j == b {
return true
}
}
return false
}
func gcd(a, b int) int {
for a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
func areSame(s, t []int) bool {
le := len(s)
if le != len(t) {
return false
}
sort.Ints(s)
sort.Ints(t)
for i := 0; i < le; i++ {
if s[i] != t[i] {
return false
}
}
return true
}
func main() {
const limit = 100
starts := [5]int{2, 5, 7, 9, 10}
var ekg [5][limit]int
for s, start := range starts {
ekg[s][0] = 1
ekg[s][1] = start
for n := 2; n < limit; n++ {
for i := 2; ; i++ {
if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {
ekg[s][n] = i
break
}
}
}
fmt.Printf("EKG(%2d): %v\n", start, ekg[s][:30])
}
for i := 2; i < limit; i++ {
if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {
fmt.Println("\nEKG(5) and EKG(7) converge at term", i+1)
return
}
}
fmt.Println("\nEKG5(5) and EKG(7) do not converge within", limit, "terms")
}
|
Write a version of this Java function in Go with identical behavior. | public class RepString {
static final String[] input = {"1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101", "0100100", "101", "11",
"00", "1", "0100101"};
public static void main(String[] args) {
for (String s : input)
System.out.printf("%sΒ : %s%n", s, repString(s));
}
static String repString(String s) {
int len = s.length();
outer:
for (int part = len / 2; part > 0; part--) {
int tail = len % part;
if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))
continue;
for (int j = 0; j < len / part - 1; j++) {
int a = j * part;
int b = (j + 1) * part;
int c = (j + 2) * part;
if (!s.substring(a, b).equals(s.substring(b, c)))
continue outer;
}
return s.substring(0, part);
}
return "none";
}
}
| package main
import (
"fmt"
"strings"
)
func rep(s string) int {
for x := len(s) / 2; x > 0; x-- {
if strings.HasPrefix(s, s[x:]) {
return x
}
}
return 0
}
const m = `
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1`
func main() {
for _, s := range strings.Fields(m) {
if n := rep(s); n > 0 {
fmt.Printf("%q %d rep-string %q\n", s, n, s[:n])
} else {
fmt.Printf("%q not a rep-string\n", s)
}
}
}
|
Keep all operations the same but rewrite the snippet in Go. | public class PreserveScreen
{
public static void main(String[] args) throws InterruptedException {
System.out.print("\033[?1049h\033[H");
System.out.println("Alternate screen buffer\n");
for (int i = 5; i > 0; i--) {
String s = (i > 1) ? "s" : "";
System.out.printf("\rgoing back in %d second%s...", i, s);
Thread.sleep(1000);
}
System.out.print("\033[?1049l");
}
}
| package main
import (
"fmt"
"time"
)
func main() {
fmt.Print("\033[?1049h\033[H")
fmt.Println("Alternate screen buffer\n")
s := "s"
for i := 5; i > 0; i-- {
if i == 1 {
s = ""
}
fmt.Printf("\rgoing back in %d second%s...", i, s)
time.Sleep(time.Second)
}
fmt.Print("\033[?1049l")
}
|
Translate the given Java code snippet into Go without altering its behavior. | char a = 'a';
String b = "abc";
char doubleQuote = '"';
char singleQuote = '\'';
String singleQuotes = "''";
String doubleQuotes = "\"\"";
| ch := 'z'
ch = 122
ch = '\x7a'
ch = '\u007a'
ch = '\U0000007a'
ch = '\172'
|
Generate an equivalent Go version of this Java code. | import java.io.*;
import java.util.*;
public class ChangeableWords {
public static void main(String[] args) {
try {
final String fileName = "unixdict.txt";
List<String> dictionary = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 11)
dictionary.add(line);
}
}
System.out.printf("Changeable words in %s:\n", fileName);
int n = 1;
for (String word1 : dictionary) {
for (String word2 : dictionary) {
if (word1 != word2 && hammingDistance(word1, word2) == 1)
System.out.printf("%2d:Β %-14s -> %s\n", n++, word1, word2);
}
}
} catch (Exception e) {
e.printStackTtexture();
}
}
private static int hammingDistance(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
if (len1 != len2)
return 0;
int count = 0;
for (int i = 0; i < len1; ++i) {
if (str1.charAt(i) != str2.charAt(i))
++count;
if (count == 2)
break;
}
return count;
}
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func hammingDist(s1, s2 string) int {
r1 := []rune(s1)
r2 := []rune(s2)
if len(r1) != len(r2) {
return 0
}
count := 0
for i := 0; i < len(r1); i++ {
if r1[i] != r2[i] {
count++
if count == 2 {
break
}
}
}
return count
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 11 {
words = append(words, s)
}
}
count := 0
fmt.Println("Changeable words in", wordList, "\b:")
for _, word1 := range words {
for _, word2 := range words {
if word1 != word2 && hammingDist(word1, word2) == 1 {
count++
fmt.Printf("%2d:Β %-14s -> %s\n", count, word1, word2)
}
}
}
}
|
Write a version of this Java function in Go with identical behavior. | import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class WindowController extends JFrame {
public static void main( final String[] args ) {
EventQueue.invokeLater( () -> new WindowController() );
}
private JComboBox<ControlledWindow> list;
private class ControlButton extends JButton {
private ControlButton( final String name ) {
super(
new AbstractAction( name ) {
public void actionPerformed( final ActionEvent e ) {
try {
WindowController.class.getMethod( "do" + name )
.invoke ( WindowController.this );
} catch ( final Exception x ) {
x.printStackTrace();
}
}
}
);
}
}
public WindowController() {
super( "Controller" );
final JPanel main = new JPanel();
final JPanel controls = new JPanel();
setLocationByPlatform( true );
setResizable( false );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLayout( new BorderLayout( 3, 3 ) );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH );
main.add( list = new JComboBox<>() );
add( main, BorderLayout.CENTER );
controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );
controls.add( new ControlButton( "Add" ) );
controls.add( new ControlButton( "Hide" ) );
controls.add( new ControlButton( "Show" ) );
controls.add( new ControlButton( "Close" ) );
controls.add( new ControlButton( "Maximise" ) );
controls.add( new ControlButton( "Minimise" ) );
controls.add( new ControlButton( "Move" ) );
controls.add( new ControlButton( "Resize" ) );
add( controls, BorderLayout.EAST );
pack();
setVisible( true );
}
private static class ControlledWindow extends JFrame {
private int num;
public ControlledWindow( final int num ) {
super( Integer.toString( num ) );
this.num = num;
setLocationByPlatform( true );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
add( new JLabel( "I am window " + num + ". Use the controller to control me." ) );
pack();
setVisible( true );
}
public String toString() {
return "Window " + num;
}
}
public void doAdd() {
list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );
pack();
}
public void doHide() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( false );
}
public void doShow() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( true );
}
public void doClose() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.dispose();
}
public void doMinimise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setState( Frame.ICONIFIED );
}
public void doMaximise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setExtendedState( Frame.MAXIMIZED_BOTH );
}
public void doMove() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int hPos = getInt( "Horizontal position?" );
if ( -1 == hPos ) {
return;
}
final int vPos = getInt( "Vertical position?" );
if ( -1 == vPos ) {
return;
}
window.setLocation ( hPos, vPos );
}
public void doResize() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int width = getInt( "Width?" );
if ( -1 == width ) {
return;
}
final int height = getInt( "Height?" );
if ( -1 == height ) {
return;
}
window.setBounds ( window.getX(), window.getY(), width, height );
}
private JFrame getWindow() {
final JFrame window = ( JFrame ) list.getSelectedItem();
if ( null == window ) {
JOptionPane.showMessageDialog( this, "Add a window first" );
}
return window;
}
private int getInt(final String prompt) {
final String s = JOptionPane.showInputDialog( prompt );
if ( null == s ) {
return -1;
}
try {
return Integer.parseInt( s );
} catch ( final NumberFormatException x ) {
JOptionPane.showMessageDialog( this, "Not a number" );
return -1;
}
}
}
| package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"time"
)
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetResizable(true)
window.SetTitle("Window management")
window.SetBorderWidth(5)
window.Connect("destroy", func() {
gtk.MainQuit()
})
stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)
check(err, "Unable to create stack box:")
bmax, err := gtk.ButtonNewWithLabel("Maximize")
check(err, "Unable to create maximize button:")
bmax.Connect("clicked", func() {
window.Maximize()
})
bunmax, err := gtk.ButtonNewWithLabel("Unmaximize")
check(err, "Unable to create unmaximize button:")
bunmax.Connect("clicked", func() {
window.Unmaximize()
})
bicon, err := gtk.ButtonNewWithLabel("Iconize")
check(err, "Unable to create iconize button:")
bicon.Connect("clicked", func() {
window.Iconify()
})
bdeicon, err := gtk.ButtonNewWithLabel("Deiconize")
check(err, "Unable to create deiconize button:")
bdeicon.Connect("clicked", func() {
window.Deiconify()
})
bhide, err := gtk.ButtonNewWithLabel("Hide")
check(err, "Unable to create hide button:")
bhide.Connect("clicked", func() {
window.Hide()
time.Sleep(10 * time.Second)
window.Show()
})
bshow, err := gtk.ButtonNewWithLabel("Show")
check(err, "Unable to create show button:")
bshow.Connect("clicked", func() {
window.Show()
})
bmove, err := gtk.ButtonNewWithLabel("Move")
check(err, "Unable to create move button:")
isShifted := false
bmove.Connect("clicked", func() {
w, h := window.GetSize()
if isShifted {
window.Move(w-10, h-10)
} else {
window.Move(w+10, h+10)
}
isShifted = !isShifted
})
bquit, err := gtk.ButtonNewWithLabel("Quit")
check(err, "Unable to create quit button:")
bquit.Connect("clicked", func() {
window.Destroy()
})
stackbox.PackStart(bmax, true, true, 0)
stackbox.PackStart(bunmax, true, true, 0)
stackbox.PackStart(bicon, true, true, 0)
stackbox.PackStart(bdeicon, true, true, 0)
stackbox.PackStart(bhide, true, true, 0)
stackbox.PackStart(bshow, true, true, 0)
stackbox.PackStart(bmove, true, true, 0)
stackbox.PackStart(bquit, true, true, 0)
window.Add(stackbox)
window.ShowAll()
gtk.Main()
}
|
Generate an equivalent Go version of this Java code. | class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
|
Preserve the algorithm and functionality while converting the code from Java to Go. | class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
|
Produce a functionally identical Go code for the snippet given in Java. | import java.math.BigInteger;
public class MayanNumerals {
public static void main(String[] args) {
for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {
displayMyan(BigInteger.valueOf(base10));
System.out.printf("%n");
}
}
private static char[] digits = "0123456789ABCDEFGHJK".toCharArray();
private static BigInteger TWENTY = BigInteger.valueOf(20);
private static void displayMyan(BigInteger numBase10) {
System.out.printf("As base 10: %s%n", numBase10);
String numBase20 = "";
while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {
numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;
numBase10 = numBase10.divide(TWENTY);
}
System.out.printf("As base 20: %s%nAs Mayan:%n", numBase20);
displayMyanLine1(numBase20);
displayMyanLine2(numBase20);
displayMyanLine3(numBase20);
displayMyanLine4(numBase20);
displayMyanLine5(numBase20);
displayMyanLine6(numBase20);
}
private static char boxUL = Character.toChars(9556)[0];
private static char boxTeeUp = Character.toChars(9574)[0];
private static char boxUR = Character.toChars(9559)[0];
private static char boxHorz = Character.toChars(9552)[0];
private static char boxVert = Character.toChars(9553)[0];
private static char theta = Character.toChars(952)[0];
private static char boxLL = Character.toChars(9562)[0];
private static char boxLR = Character.toChars(9565)[0];
private static char boxTeeLow = Character.toChars(9577)[0];
private static char bullet = Character.toChars(8729)[0];
private static char dash = Character.toChars(9472)[0];
private static void displayMyanLine1(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxUL);
}
for ( int j = 0 ; j < 4 ; j++ ) {
sb.append(boxHorz);
}
sb.append(i < chars.length-1 ? boxTeeUp : boxUR);
}
System.out.println(sb.toString());
}
private static String getBullet(int count) {
StringBuilder sb = new StringBuilder();
switch ( count ) {
case 1: sb.append(" " + bullet + " "); break;
case 2: sb.append(" " + bullet + bullet + " "); break;
case 3: sb.append("" + bullet + bullet + bullet + " "); break;
case 4: sb.append("" + bullet + bullet + bullet + bullet); break;
default: throw new IllegalArgumentException("Must be 1-4: " + count);
}
return sb.toString();
}
private static void displayMyanLine2(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case 'G': sb.append(getBullet(1)); break;
case 'H': sb.append(getBullet(2)); break;
case 'J': sb.append(getBullet(3)); break;
case 'K': sb.append(getBullet(4)); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static String DASH = getDash();
private static String getDash() {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < 4 ; i++ ) {
sb.append(dash);
}
return sb.toString();
}
private static void displayMyanLine3(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case 'B': sb.append(getBullet(1)); break;
case 'C': sb.append(getBullet(2)); break;
case 'D': sb.append(getBullet(3)); break;
case 'E': sb.append(getBullet(4)); break;
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine4(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case '6': sb.append(getBullet(1)); break;
case '7': sb.append(getBullet(2)); break;
case '8': sb.append(getBullet(3)); break;
case '9': sb.append(getBullet(4)); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine5(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case '0': sb.append(" " + theta + " "); break;
case '1': sb.append(getBullet(1)); break;
case '2': sb.append(getBullet(2)); break;
case '3': sb.append(getBullet(3)); break;
case '4': sb.append(getBullet(4)); break;
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine6(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxLL);
}
for ( int j = 0 ; j < 4 ; j++ ) {
sb.append(boxHorz);
}
sb.append(i < chars.length-1 ? boxTeeLow : boxLR);
}
System.out.println(sb.toString());
}
}
| package main
import (
"fmt"
"strconv"
)
const (
ul = "β"
uc = "β¦"
ur = "β"
ll = "β"
lc = "β©"
lr = "β"
hb = "β"
vb = "β"
)
var mayan = [5]string{
" ",
" β ",
" ββ ",
"βββ ",
"ββββ",
}
const (
m0 = " Ξ "
m5 = "ββββ"
)
func dec2vig(n uint64) []uint64 {
vig := strconv.FormatUint(n, 20)
res := make([]uint64, len(vig))
for i, d := range vig {
res[i], _ = strconv.ParseUint(string(d), 20, 64)
}
return res
}
func vig2quin(n uint64) [4]string {
if n >= 20 {
panic("Cant't convert a number >= 20")
}
res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}
if n == 0 {
res[3] = m0
return res
}
fives := n / 5
rem := n % 5
res[3-fives] = mayan[rem]
for i := 3; i > 3-int(fives); i-- {
res[i] = m5
}
return res
}
func draw(mayans [][4]string) {
lm := len(mayans)
fmt.Print(ul)
for i := 0; i < lm; i++ {
for j := 0; j < 4; j++ {
fmt.Print(hb)
}
if i < lm-1 {
fmt.Print(uc)
} else {
fmt.Println(ur)
}
}
for i := 1; i < 5; i++ {
fmt.Print(vb)
for j := 0; j < lm; j++ {
fmt.Print(mayans[j][i-1])
fmt.Print(vb)
}
fmt.Println()
}
fmt.Print(ll)
for i := 0; i < lm; i++ {
for j := 0; j < 4; j++ {
fmt.Print(hb)
}
if i < lm-1 {
fmt.Print(lc)
} else {
fmt.Println(lr)
}
}
}
func main() {
numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}
for _, n := range numbers {
fmt.Printf("Converting %d to Mayan:\n", n)
vigs := dec2vig(n)
lv := len(vigs)
mayans := make([][4]string, lv)
for i, vig := range vigs {
mayans[i] = vig2quin(vig)
}
draw(mayans)
fmt.Println()
}
}
|
Change the following Java code into Go without altering its purpose. | import java.util.Arrays;
import java.util.stream.IntStream;
public class RamseysTheorem {
static char[][] createMatrix() {
String r = "-" + Integer.toBinaryString(53643);
int len = r.length();
return IntStream.range(0, len)
.mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))
.map(String::toCharArray)
.toArray(char[][]::new);
}
static String ramseyCheck(char[][] mat) {
int len = mat.length;
char[] connectivity = "------".toCharArray();
for (int a = 0; a < len; a++) {
for (int b = 0; b < len; b++) {
if (a == b)
continue;
connectivity[0] = mat[a][b];
for (int c = 0; c < len; c++) {
if (a == c || b == c)
continue;
connectivity[1] = mat[a][c];
connectivity[2] = mat[b][c];
for (int d = 0; d < len; d++) {
if (a == d || b == d || c == d)
continue;
connectivity[3] = mat[a][d];
connectivity[4] = mat[b][d];
connectivity[5] = mat[c][d];
String conn = new String(connectivity);
if (conn.indexOf('0') == -1)
return String.format("Fail, found wholly connected: "
+ "%d %d %d %d", a, b, c, d);
else if (conn.indexOf('1') == -1)
return String.format("Fail, found wholly unconnected: "
+ "%d %d %d %d", a, b, c, d);
}
}
}
}
return "Satisfies Ramsey condition.";
}
public static void main(String[] a) {
char[][] mat = createMatrix();
for (char[] s : mat)
System.out.println(Arrays.toString(s));
System.out.println(ramseyCheck(mat));
}
}
| package main
import "fmt"
var (
a [17][17]int
idx [4]int
)
func findGroup(ctype, min, max, depth int) bool {
if depth == 4 {
cs := ""
if ctype == 0 {
cs = "un"
}
fmt.Printf("Totally %sconnected group:", cs)
for i := 0; i < 4; i++ {
fmt.Printf(" %d", idx[i])
}
fmt.Println()
return true
}
for i := min; i < max; i++ {
n := 0
for ; n < depth; n++ {
if a[idx[n]][i] != ctype {
break
}
}
if n == depth {
idx[n] = i
if findGroup(ctype, 1, max, depth+1) {
return true
}
}
}
return false
}
func main() {
const mark = "01-"
for i := 0; i < 17; i++ {
a[i][i] = 2
}
for k := 1; k <= 8; k <<= 1 {
for i := 0; i < 17; i++ {
j := (i + k) % 17
a[i][j], a[j][i] = 1, 1
}
}
for i := 0; i < 17; i++ {
for j := 0; j < 17; j++ {
fmt.Printf("%c ", mark[a[i][j]])
}
fmt.Println()
}
for i := 0; i < 17; i++ {
idx[0] = i
if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {
fmt.Println("No good.")
return
}
}
fmt.Println("All good.")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.