WeixiangYan/CodeTransOcean huggingface dataset:
Task: Metronome




Go: 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 ")
		}
	}
}


Java: 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();
	}
}
Task: Rep-string




Go: 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)
        }
    }
}


Java: 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";
    }
}
Task: Terminal control_Preserve screen




Go: 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")
}


Java: 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");
    }
}
Task: Literals_String




Go: ch := 'z'
ch = 122          
ch = '\x7a'       
ch = '\u007a'     
ch = '\U0000007a' 
ch = '\172'       


Java:   char a = 'a';  
  String b = "abc";  
  char doubleQuote = '"';  
  char singleQuote = '\'';  
  String singleQuotes = "''";  
  String doubleQuotes = "\"\"";
Task: Changeable words




Go: 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)
            }
        }
    }
}


Java: 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;
    }
}
Task: Next special primes




Go: package main

import "fmt"

func sieve(limit int) []bool {
    limit++
    
    c := make([]bool, limit) 
    c[0] = true
    c[1] = true
    
    p := 3 
    for {
        p2 := p * p
        if p2 >= limit {
            break
        }
        for i := p2; i < limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    return c
}

func main() {
    c := sieve(1049)
    fmt.Println("Special primes under 1,050:")
    fmt.Println("Prime1 Prime2 Gap")
    lastSpecial := 3
    lastGap := 1
    fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
    for i := 5; i < 1050; i += 2 {
        if !c[i] && (i-lastSpecial) > lastGap {
            lastGap = i - lastSpecial
            fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
            lastSpecial = i
        }
    }
}


Java: 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;
            }
        }
    }
}
Task: GUI_Maximum window dimensions




Go: package main

import (
    "fmt"
    "github.com/go-vgo/robotgo"
)

func main() {
    w, h := robotgo.GetScreenSize()
    fmt.Printf("Screen size: %d x %d\n", w, h)
    fpid, err := robotgo.FindIds("firefox")
    if err == nil && len(fpid) > 0 {
        pid := fpid[0]
        robotgo.ActivePID(pid)
        robotgo.MaxWindow(pid)
        _, _, w, h = robotgo.GetBounds(pid)
        fmt.Printf("Max usable : %d x %d\n", w, h)
    }
}


Java: import java.awt.*;
import javax.swing.JFrame;

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    Test() {
        Toolkit toolkit = Toolkit.getDefaultToolkit();

        Dimension screenSize = toolkit.getScreenSize();
        System.out.println("Physical screen size: " + screenSize);

        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());
        System.out.println("Insets: " + insets);

        screenSize.width -= (insets.left + insets.right);
        screenSize.height -= (insets.top + insets.bottom);
        System.out.println("Max available: " + screenSize);
    }
}
Task: Getting the number of decimals




Go: package main

import (
    "fmt"
    "log"
    "math"
    "strings"
)

var error = "Argument must be a numeric literal or a decimal numeric string."

func getNumDecimals(n interface{}) int {
    switch v := n.(type) {
    case int:
        return 0
    case float64:
        if v == math.Trunc(v) {
            return 0
        }
        s := fmt.Sprintf("%g", v)
        return len(strings.Split(s, ".")[1])
    case string:
        if v == "" {
            log.Fatal(error)
        }
        if v[0] == '+' || v[0] == '-' {
            v = v[1:]
        }
        for _, c := range v {
            if strings.IndexRune("0123456789.", c) == -1 {
                log.Fatal(error)
            }
        }
        s := strings.Split(v, ".")
        ls := len(s)
        if ls == 1 {
            return 0
        } else if ls == 2 {
            return len(s[1])
        } else {
            log.Fatal("Too many decimal points")
        }
    default:
        log.Fatal(error)
    }
    return 0
}

func main() {
    var a = []interface{}{12, 12.345, 12.345555555555, "12.3450", "12.34555555555555555555", 12.345e53}
    for _, n := range a {
        d := getNumDecimals(n)
        switch v := n.(type) {
        case string:
            fmt.Printf("%q has %d decimals\n", v, d)
        case float32, float64:
            fmt.Printf("%g has %d decimals\n", v, d)
        default:
            fmt.Printf("%d has %d decimals\n", v, d)
        }
    }
}


Java: public static int findNumOfDec(double x){
    String str = String.valueOf(x);
    if(str.endsWith(".0")) return 0;
    else return (str.substring(str.indexOf('.')).length() - 1);
}
Task: Enumerations




Go: const (
	apple = iota
	banana
	cherry
)


Java: enum Fruits{
   APPLE, BANANA, CHERRY
}
Task: Pentagram




Go: package main

import (
    "github.com/fogleman/gg"
    "math"
)

func Pentagram(x, y, r float64) []gg.Point {
    points := make([]gg.Point, 5)
    for i := 0; i < 5; i++ {
        fi := float64(i)
        angle := 2*math.Pi*fi/5 - math.Pi/2
        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
    }
    return points
}

func main() {
    points := Pentagram(320, 320, 250)
    dc := gg.NewContext(640, 640)
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    for i := 0; i <= 5; i++ {
        index := (i * 2) % 5
        p := points[index]
        dc.LineTo(p.X, p.Y)
    }
    dc.SetHexColor("#6495ED") 
    dc.SetFillRule(gg.FillRuleWinding)
    dc.FillPreserve()
    dc.SetRGB(0, 0, 0) 
    dc.SetLineWidth(5)
    dc.Stroke()
    dc.SavePNG("pentagram.png")
}


Java: import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;

public class Pentagram extends JPanel {

    final double degrees144 = Math.toRadians(144);

    public Pentagram() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);
    }

    private void drawPentagram(Graphics2D g, int len, int x, int y,
            Color fill, Color stroke) {
        double angle = 0;

        Path2D p = new Path2D.Float();
        p.moveTo(x, y);

        for (int i = 0; i < 5; i++) {
            int x2 = x + (int) (Math.cos(angle) * len);
            int y2 = y + (int) (Math.sin(-angle) * len);
            p.lineTo(x2, y2);
            x = x2;
            y = y2;
            angle -= degrees144;
        }
        p.closePath();

        g.setColor(fill);
        g.fill(p);

        g.setColor(stroke);
        g.draw(p);
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));

        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Pentagram");
            f.setResizable(false);
            f.add(new Pentagram(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}
Task: Increasing gaps between consecutive Niven numbers




Go: package main

import "fmt"

type is func() uint64

func newSum() is {
    var ms is
    ms = func() uint64 {
        ms = newSum()
        return ms()
    }
    var msd, d uint64
    return func() uint64 {
        if d < 9 {
            d++
        } else {
            d = 0
            msd = ms()
        }
        return msd + d
    }
}

func newHarshard() is {
    i := uint64(0)
    sum := newSum()
    return func() uint64 {
        for i++; i%sum() != 0; i++ {
        }
        return i
    }
}

func commatize(n uint64) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    fmt.Println("Gap    Index of gap   Starting Niven")
    fmt.Println("===   =============   ==============")
    h := newHarshard()
    pg := uint64(0) 
    pn := h()       
    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {
        g := n - pn
        if g > pg {
            fmt.Printf("%3d   %13s   %14s\n", g, commatize(i), commatize(pn))
            pg = g
        }
        pn = n
    }
}


Java: public class NivenNumberGaps {

    
    
    public static void main(String[] args) {
        long prevGap = 0;
        long prevN = 1;
        long index = 0;
        System.out.println("Gap      Gap Index   Starting Niven");
        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {
            if ( isNiven(n) ) {
                index++;
                long curGap = n - prevN;
                if ( curGap > prevGap ) {
                    System.out.printf("%3d  %,13d  %,15d%n", curGap, index, prevN);
                    prevGap = curGap;
                }
                prevN = n;
            }
        }
    }
    
    public static boolean isNiven(long n) {
        long sum = 0;
        long nSave = n;
        while ( n > 0 ) {
            sum += n % 10;
            n /= 10;
        }
        return nSave % sum == 0;
    }

}
Task: Print debugging statement




Go: package main

import (
    "fmt"
    "runtime"
)

type point struct {
    x, y float64
}

func add(x, y int) int {
    result := x + y
    debug("x", x)
    debug("y", y)
    debug("result", result)
    debug("result+1", result+1)
    return result
}

func debug(s string, x interface{}) {
    _, _, lineNo, _ := runtime.Caller(1)
    fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x)
}

func main() {
    add(2, 7)
    b := true
    debug("b", b)
    s := "Hello"
    debug("s", s)
    p := point{2, 3}
    debug("p", p)
    q := &p
    debug("q", q)
}


Java: import java.util.Objects;

public class PrintDebugStatement {
    
    private static void printDebug(String message) {
        Objects.requireNonNull(message);

        RuntimeException exception = new RuntimeException();
        StackTraceElement[] stackTrace = exception.getStackTrace();
        
        
        StackTraceElement stackTraceElement = stackTrace[1];
        String fileName = stackTraceElement.getFileName();
        String className = stackTraceElement.getClassName();
        String methodName = stackTraceElement.getMethodName();
        int lineNumber = stackTraceElement.getLineNumber();

        System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message);
    }

    private static void blah() {
        printDebug("Made It!");
    }

    public static void main(String[] args) {
        printDebug("Hello world.");
        blah();

        Runnable oops = () -> printDebug("oops");
        oops.run();
    }
}
Task: Range extraction




Go: package main

import (
    "errors"
    "fmt"
    "strconv"
    "strings"
)

func main() {
    rf, err := rangeFormat([]int{
        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
        37, 38, 39,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("range format:", rf)
}

func rangeFormat(a []int) (string, error) {
    if len(a) == 0 {
        return "", nil
    }
    var parts []string
    for n1 := 0; ; {
        n2 := n1 + 1
        for n2 < len(a) && a[n2] == a[n2-1]+1 {
            n2++
        }
        s := strconv.Itoa(a[n1])
        if n2 == n1+2 {
            s += "," + strconv.Itoa(a[n2-1])
        } else if n2 > n1+2 {
            s += "-" + strconv.Itoa(a[n2-1])
        }
        parts = append(parts, s)
        if n2 == len(a) {
            break
        }
        if a[n2] == a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence repeats value %d", a[n2]))
        }
        if a[n2] < a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence not ordered: %d < %d", a[n2], a[n2-1]))
        }
        n1 = n2
    }
    return strings.Join(parts, ","), nil
}


Java: public class RangeExtraction {

    public static void main(String[] args) {
        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
            37, 38, 39};

        int len = arr.length;
        int idx = 0, idx2 = 0;
        while (idx < len) {
            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);
            if (idx2 - idx > 2) {
                System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]);
                idx = idx2;
            } else {
                for (; idx < idx2; idx++)
                    System.out.printf("%s,", arr[idx]);
            }
        }
    }
}
Task: Type detection




Go: package main

import "fmt"

type any = interface{}

func showType(a any) {
    switch a.(type) {
    case rune:
        fmt.Printf("The type of '%c' is %T\n", a, a)
    default:
        fmt.Printf("The type of '%v' is %T\n", a, a)
    }
}

func main() {
    values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"}
    for _, value := range values {
        showType(value)
    }
}


Java: public class TypeDetection {
    private static void showType(Object a) {
        if (a instanceof Integer) {
            System.out.printf("'%s' is an integer\n", a);
        } else if (a instanceof Double) {
            System.out.printf("'%s' is a double\n", a);
        } else if (a instanceof Character) {
            System.out.printf("'%s' is a character\n", a);
        } else {
            System.out.printf("'%s' is some other type\n", a);
        }
    }

    public static void main(String[] args) {
        showType(5);
        showType(7.5);
        showType('d');
        showType(true);
    }
}
Task: Maximum triangle path sum




Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)

const t = `               55
                        94 48
                       95 30 96
                     77 71 26 67
                    97 13 76 38 45
                  07 36 79 16 37 68
                 48 07 09 18 70 26 06
               18 72 79 46 59 79 29 90
              20 76 87 11 32 07 07 49 18
            27 83 58 35 71 11 25 57 29 85
           14 64 36 96 27 11 58 56 92 18 55
         02 90 03 60 48 49 41 46 33 36 47 23
        92 50 48 02 36 59 42 79 72 20 82 77 42
      56 78 38 80 39 75 02 71 66 66 01 03 55 72
     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`

func main() {
    lines := strings.Split(t, "\n")
    f := strings.Fields(lines[len(lines)-1])
    d := make([]int, len(f))
    var err error
    for i, s := range f {
        if d[i], err = strconv.Atoi(s); err != nil {
            panic(err)
        }
    }
    d1 := d[1:]
    var l, r, u int
    for row := len(lines) - 2; row >= 0; row-- {
        l = d[0]
        for i, s := range strings.Fields(lines[row]) {
            if u, err = strconv.Atoi(s); err != nil {
                panic(err)
            }
            if r = d1[i]; l > r {
                d[i] = u + l
            } else {
                d[i] = u + r
            }
            l = r
        }
    }
    fmt.Println(d[0])
}


Java: import java.nio.file.*;
import static java.util.Arrays.stream;

public class MaxPathSum {

    public static void main(String[] args) throws Exception {
        int[][] data = Files.lines(Paths.get("triangle.txt"))
                .map(s -> stream(s.trim().split("\\s+"))
                        .mapToInt(Integer::parseInt)
                        .toArray())
                .toArray(int[][]::new);

        for (int r = data.length - 1; r > 0; r--)
            for (int c = 0; c < data[r].length - 1; c++)
                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);

        System.out.println(data[0][0]);
    }
}
Task: Variable declaration reset




Go: package main

import "fmt"

func main() {
    s := []int{1, 2, 2, 3, 4, 4, 5}

    
    
    for i := 0; i < len(s); i++ {
        curr := s[i]
        var prev int
        if i > 0 && curr == prev {
            fmt.Println(i)
        }
        prev = curr
    }

    
    
    var prev int
    for i := 0; i < len(s); i++ {
        curr := s[i]
        if i > 0 && curr == prev {
            fmt.Println(i)
        }
        prev = curr
    }
}


Java: public class VariableDeclarationReset {
    public static void main(String[] args) {
        int[] s = {1, 2, 2, 3, 4, 4, 5};

        
        
        for (int i = 0; i < s.length; ++i) {
            int curr = s[i];
            int prev = 0;

            if (i > 0 && curr == prev) System.out.println(i);
            prev = curr;
        }

        int gprev = 0;

        
        
        for (int i = 0; i < s.length; ++i) {
            int curr = s[i];
            if (i > 0 && curr == gprev) System.out.println(i);
            gprev = curr;
        }
    }
}