WeixiangYan/CodeTransOcean huggingface dataset:
Task: Associative array_Merging




Go: package main

import "fmt"

type assoc map[string]interface{}

func merge(base, update assoc) assoc {
    result := make(assoc)
    for k, v := range base {
        result[k] = v
    }
    for k, v := range update {
        result[k] = v
    }
    return result
}

func main() {
    base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
    update := assoc{"price": 15.25, "color": "red", "year": 1974}
    result := merge(base, update)
    fmt.Println(result)
}


Java: import java.util.*;

class MergeMaps {
    public static void main(String[] args) {
        Map<String, Object> base = new HashMap<>();
        base.put("name", "Rocket Skates");
        base.put("price", 12.75);
        base.put("color", "yellow");
        Map<String, Object> update = new HashMap<>();
        update.put("price", 15.25);
        update.put("color", "red");
        update.put("year", 1974);

        Map<String, Object> result = new HashMap<>(base);
        result.putAll(update);

        System.out.println(result);
    }
}
Task: Associative array_Iteration




Go: myMap := map[string]int {
	   "hello": 13,
	   "world": 31,
	   "!"    : 71 }


for key, value := range myMap {
    fmt.Printf("key = %s, value = %d\n", key, value)
}


for key := range myMap {
    fmt.Printf("key = %s\n", key)
}


for _, value := range myMap {
    fmt.Printf("value = %d\n", value)
}


Java: Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);


for (Map.Entry<String, Integer> e : map.entrySet()) {
    String key = e.getKey();
    Integer value = e.getValue();
    System.out.println("key = " + key + ", value = " + value);
}


for (String key : map.keySet()) {
    System.out.println("key = " + key);
}


for (Integer value : map.values()) {
    System.out.println("value = " + value);
}
Task: Define a primitive data type




Go: package main

import "fmt"

type TinyInt int

func NewTinyInt(i int) TinyInt {
    if i < 1 {
        i = 1
    } else if i > 10 {
        i = 10
    }
    return TinyInt(i)
}

func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) + int(t2))
}

func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) - int(t2))
}

func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) * int(t2))
}

func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) / int(t2))
}

func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) % int(t2))
}

func (t TinyInt) Inc() TinyInt {
    return t.Add(TinyInt(1))
}

func (t TinyInt) Dec() TinyInt {
    return t.Sub(TinyInt(1))
}

func main() {
    t1 := NewTinyInt(6)
    t2 := NewTinyInt(3)
    fmt.Println("t1      =", t1)
    fmt.Println("t2      =", t2)
    fmt.Println("t1 + t2 =", t1.Add(t2))
    fmt.Println("t1 - t2 =", t1.Sub(t2))
    fmt.Println("t1 * t2 =", t1.Mul(t2))
    fmt.Println("t1 / t2 =", t1.Div(t2))
    fmt.Println("t1 % t2 =", t1.Rem(t2))
    fmt.Println("t1 + 1  =", t1.Inc())
    fmt.Println("t1 - 1  =", t1.Dec())
}


Java: class BoundedIntOutOfBoundsException extends Exception
{
  public BoundedIntOutOfBoundsException(int v, int l, int u) {
    super("value " + v + " is out of bounds [" + l + "," + u + "]");
  }
}

class BoundedInt {
  private int value;
  private int lower;
  private int upper;

  public BoundedInt(int l, int u) {
    lower = Math.min(l, u);
    upper = Math.max(l, u);
  }

  private boolean checkBounds(int v) {
    return (v >= this.lower) && (v <= this.upper);
  }

  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
    assign(i.value()); 
  }

  public void assign(int v) throws BoundedIntOutOfBoundsException {
    if ( checkBounds(v) ) {
      this.value = v;
    } else {
      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);
    }
  }

  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {
    return add(i.value());
  }

  public int add(int i) throws BoundedIntOutOfBoundsException {
    if ( checkBounds(this.value + i) ) {
      this.value += i;
    }  else {
      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);
    }
    return this.value;
  }

  public int value() {
    return this.value;
  }
}


public class Bounded {
  public static void main(String[] args) throws BoundedIntOutOfBoundsException {
    BoundedInt a = new BoundedInt(1, 10);
    BoundedInt b = new BoundedInt(1, 10);

    a.assign(6);
    try {
      b.assign(12);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    b.assign(9);
    try {
      a.add(b.value());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}
Task: Order disjoint list items




Go: package main

import (
	"fmt"
	"sort"
	"strings"
)

type indexSort struct {
	val sort.Interface
	ind []int
}

func (s indexSort) Len() int           { return len(s.ind) }
func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }
func (s indexSort) Swap(i, j int) {
	s.val.Swap(s.ind[i], s.ind[j])
	s.ind[i], s.ind[j] = s.ind[j], s.ind[i]
}

func disjointSliceSort(m, n []string) []string {
	s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}
	used := make(map[int]bool)
	for _, nw := range n {
		for i, mw := range m {
			if used[i] || mw != nw {
				continue
			}
			used[i] = true
			s.ind = append(s.ind, i)
			break
		}
	}
	sort.Sort(s)
	return s.val.(sort.StringSlice)
}

func disjointStringSort(m, n string) string {
	return strings.Join(
		disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ")
}

func main() {
	for _, data := range []struct{ m, n string }{
		{"the cat sat on the mat", "mat cat"},
		{"the cat sat on the mat", "cat mat"},
		{"A B C A B C A B C", "C A C A"},
		{"A B C A B D A B E", "E A D A"},
		{"A B", "B"},
		{"A B", "B A"},
		{"A B B A", "B A"},
	} {
		mp := disjointStringSort(data.m, data.n)
		fmt.Printf("%s → %s » %s\n", data.m, data.n, mp)
	}

}


Java: import java.util.Arrays;
import java.util.BitSet;
import org.apache.commons.lang3.ArrayUtils;

public class OrderDisjointItems {

    public static void main(String[] args) {
        final String[][] MNs = {{"the cat sat on the mat", "mat cat"},
        {"the cat sat on the mat", "cat mat"},
        {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"},
        {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}};

        for (String[] a : MNs) {
            String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" "));
            System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r));
        }
    }

    
    static String[] orderDisjointItems(String[] m, String[] n) {
        for (String e : n) {
            int idx = ArrayUtils.indexOf(m, e);
            if (idx != -1)
                m[idx] = null;
        }
        for (int i = 0, j = 0; i < m.length; i++) {
            if (m[i] == null)
                m[i] = n[j++];
        }
        return m;
    }

    
    static String[] orderDisjointItems2(String[] m, String[] n) {
        BitSet bitSet = new BitSet(m.length);
        for (String e : n) {
            int idx = -1;
            do {
                idx = ArrayUtils.indexOf(m, e, idx + 1);
            } while (idx != -1 && bitSet.get(idx));
            if (idx != -1)
                bitSet.set(idx);
        }
        for (int i = 0, j = 0; i < m.length; i++) {
            if (bitSet.get(i))
                m[i] = n[j++];
        }
        return m;
    }
}
Task: Here document




Go: var m = `    leading spaces

and blank lines`


Java: package rosettacode.heredoc;
public class MainApp {
	public static void main(String[] args) {
		String hereDoc = """
				This is a multiline string.
				It includes all of this text,
				but on separate lines in the code.
				 """;
		System.out.println(hereDoc);
	}
}
Task: Hash join




Go: package main

import "fmt"

func main() {
    tableA := []struct {
        value int
        key   string
    }{
        {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
        {28, "Alan"},
    }
    tableB := []struct {
        key   string
        value string
    }{
        {"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
    }
    
    h := map[string][]int{}
    for i, r := range tableA {
        h[r.key] = append(h[r.key], i)
    }
    
    for _, x := range tableB {
        for _, a := range h[x.key] {
            fmt.Println(tableA[a], x)
        }
    }
}


Java: import java.util.*;

public class HashJoin {

    public static void main(String[] args) {
        String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
        {"18", "Popeye"}, {"28", "Alan"}};

        String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
        {"Bob", "foo"}};

        hashJoin(table1, 1, table2, 0).stream()
                .forEach(r -> System.out.println(Arrays.deepToString(r)));
    }

    static List<String[][]> hashJoin(String[][] records1, int idx1,
            String[][] records2, int idx2) {

        List<String[][]> result = new ArrayList<>();
        Map<String, List<String[]>> map = new HashMap<>();

        for (String[] record : records1) {
            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
            v.add(record);
            map.put(record[idx1], v);
        }

        for (String[] record : records2) {
            List<String[]> lst = map.get(record[idx2]);
            if (lst != null) {
                lst.stream().forEach(r -> {
                    result.add(new String[][]{r, record});
                });
            }
        }

        return result;
    }
}
Task: Polynomial synthetic division




Go: package main

import (
    "fmt"
    "math/big"
)

func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
    out := make([]*big.Rat, len(dividend))
    for i, c := range dividend {
        out[i] = new(big.Rat).Set(c)
    }
    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
        out[i].Quo(out[i], divisor[0])
        if coef := out[i]; coef.Sign() != 0 {
            var a big.Rat
            for j := 1; j < len(divisor); j++ {
                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
            }
        }
    }
    separator := len(out) - (len(divisor) - 1)
    return out[:separator], out[separator:]
}

func main() {
    N := []*big.Rat{
        big.NewRat(1, 1),
        big.NewRat(-12, 1),
        big.NewRat(0, 1),
        big.NewRat(-42, 1)}
    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
    Q, R := div(N, D)
    fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}


Java: import java.util.Arrays;

public class Test {

    public static void main(String[] args) {
        int[] N = {1, -12, 0, -42};
        int[] D = {1, -3};

        System.out.printf("%s / %s = %s",
                Arrays.toString(N),
                Arrays.toString(D),
                Arrays.deepToString(extendedSyntheticDivision(N, D)));
    }

    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
        int[] out = dividend.clone();
        int normalizer = divisor[0];

        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
            out[i] /= normalizer;

            int coef = out[i];
            if (coef != 0) {
                for (int j = 1; j < divisor.length; j++)
                    out[i + j] += -divisor[j] * coef;
            }
        }

        int separator = out.length - (divisor.length - 1);

        return new int[][]{
            Arrays.copyOfRange(out, 0, separator),
            Arrays.copyOfRange(out, separator, out.length)
        };
    }
}
Task: Earliest difference between prime gaps




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    limit := int(1e9)
    gapStarts := make(map[int]int)
    primes := rcu.Primes(limit * 5)
    for i := 1; i < len(primes); i++ {
        gap := primes[i] - primes[i-1]
        if _, ok := gapStarts[gap]; !ok {
            gapStarts[gap] = primes[i-1]
        }
    }
    pm := 10
    gap1 := 2
    for {
        for _, ok := gapStarts[gap1]; !ok; {
            gap1 += 2
        }
        start1 := gapStarts[gap1]
        gap2 := gap1 + 2
        if _, ok := gapStarts[gap2]; !ok {
            gap1 = gap2 + 2
            continue
        }
        start2 := gapStarts[gap2]
        diff := start2 - start1
        if diff < 0 {
            diff = -diff
        }
        if diff > pm {
            cpm := rcu.Commatize(pm)
            cst1 := rcu.Commatize(start1)
            cst2 := rcu.Commatize(start2)
            cd := rcu.Commatize(diff)
            fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm)
            fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd)
            if pm == limit {
                break
            }
            pm *= 10
        } else {
            gap1 = gap2
        }
    }
}


Java: import java.util.HashMap;
import java.util.Map;

public class PrimeGaps {
    private Map<Integer, Integer> gapStarts = new HashMap<>();
    private int lastPrime;
    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);

    public static void main(String[] args) {
        final int limit = 100000000;
        PrimeGaps pg = new PrimeGaps();
        for (int pm = 10, gap1 = 2;;) {
            int start1 = pg.findGapStart(gap1);
            int gap2 = gap1 + 2;
            int start2 = pg.findGapStart(gap2);
            int diff = start2 > start1 ? start2 - start1 : start1 - start2;
            if (diff > pm) {
                System.out.printf(
                    "Earliest difference > %,d between adjacent prime gap starting primes:\n"
                    + "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n",
                    pm, gap1, start1, gap2, start2, diff);
                if (pm == limit)
                    break;
                pm *= 10;
            } else {
                gap1 = gap2;
            }
        }
    }

    private int findGapStart(int gap) {
        Integer start = gapStarts.get(gap);
        if (start != null)
            return start;
        for (;;) {
            int prev = lastPrime;
            lastPrime = primeGenerator.nextPrime();
            int diff = lastPrime - prev;
            gapStarts.putIfAbsent(diff, prev);
            if (diff == gap)
                return prev;
        }
    }
}
Task: Inheritance_Single




Go: package main

type animal struct {
    alive bool
}

type dog struct {
    animal
    obedienceTrained bool
}

type cat struct {
    animal
    litterBoxTrained bool
}

type lab struct {
    dog
    color string
}

type collie struct {
    dog
    catchesFrisbee bool
}

func main() {
    var pet lab
    pet.alive = true
    pet.obedienceTrained = false
    pet.color = "yellow"
}


Java: public class Animal{
   
}
Task: Associative array_Creation




Go: 
var x map[string]int


x = make(map[string]int)


x = make(map[string]int, 42)


x["foo"] = 3


y1 := x["bar"]     
y2, ok := x["bar"] 


delete(x, "foo")


x = map[string]int{
	"foo": 2, "bar": 42, "baz": -1,
}


Java: Map<String, Int> map = new HashMap();
map["foo"] = 5;      
map["bar"] = 10;
map["baz"] = 15;
map["foo"] = 6;
Task: Wilson primes of order n




Go: package main

import (
    "fmt"
    "math/big"
    "rcu"
)

func main() {
    const LIMIT = 11000
    primes := rcu.Primes(LIMIT)
    facts := make([]*big.Int, LIMIT)
    facts[0] = big.NewInt(1)
    for i := int64(1); i < LIMIT; i++ {
        facts[i] = new(big.Int)
        facts[i].Mul(facts[i-1], big.NewInt(i))
    }
    sign := int64(1)
    f := new(big.Int)
    zero := new(big.Int)
    fmt.Println(" n:  Wilson primes")
    fmt.Println("--------------------")
    for n := 1; n < 12; n++ {
        fmt.Printf("%2d:  ", n)
        sign = -sign
        for _, p := range primes {
            if p < n {
                continue
            }
            f.Mul(facts[n-1], facts[p-n])
            f.Sub(f, big.NewInt(sign))
            p2 := int64(p * p)
            bp2 := big.NewInt(p2)
            if f.Rem(f, bp2).Cmp(zero) == 0 {
                fmt.Printf("%d ", p)
            }
        }
        fmt.Println()
    }
}


Java: import java.math.BigInteger;
import java.util.*;

public class WilsonPrimes {
    public static void main(String[] args) {
        final int limit = 11000;
        BigInteger[] f = new BigInteger[limit];
        f[0] = BigInteger.ONE;
        BigInteger factorial = BigInteger.ONE;
        for (int i = 1; i < limit; ++i) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
            f[i] = factorial;
        }
        List<Integer> primes = generatePrimes(limit);
        System.out.printf(" n | Wilson primes\n--------------------\n");
        BigInteger s = BigInteger.valueOf(-1);
        for (int n = 1; n <= 11; ++n) {
            System.out.printf("%2d |", n);
            for (int p : primes) {
                if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)
                        .mod(BigInteger.valueOf(p * p))
                        .equals(BigInteger.ZERO))
                    System.out.printf(" %d", p);
            }
            s = s.negate();
            System.out.println();
        }
    }

    private static List<Integer> generatePrimes(int limit) {
        boolean[] sieve = new boolean[limit >> 1];
        Arrays.fill(sieve, true);
        for (int p = 3, s = 9; s < limit; p += 2) {
            if (sieve[p >> 1]) {
                for (int q = s; q < limit; q += p << 1)
                    sieve[q >> 1] = false;
            }
            s += (p + 1) << 2;
        }
        List<Integer> primes = new ArrayList<>();
        if (limit > 2)
            primes.add(2);
        for (int i = 1; i < sieve.length; ++i) {
            if (sieve[i])
                primes.add((i << 1) + 1);
        } 
        return primes;
    }
}
Task: Polymorphism




Go: package main

import "fmt"

type point struct {
    x, y float64
}

type circle struct {
    x, y, r float64
}

type printer interface {
    print()
}

func (p *point) print() {
    fmt.Println(p.x, p.y)
}

func (c *circle) print() {
    fmt.Println(c.x, c.y, c.r)
}

func main() {
    var i printer            
    i = newPoint(3, 4)       
    i.print()                
    i = newCircle(5, 12, 13) 
    i.print()                
}












func (p *point) getX() float64  { return p.x }
func (p *point) getY() float64  { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }

func (c *circle) getX() float64  { return c.x }
func (c *circle) getY() float64  { return c.y }
func (c *circle) getR() float64  { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }



func (p *point) clone() *point   { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }


func (p *point) set(q *point)   { *p = *q }
func (c *circle) set(d *circle) { *c = *d }










func newPoint(x, y float64) *point {
    return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
    return &circle{x, y, r}
}




Java: class Point {
   protected int x, y;
   public Point() { this(0); }
   public Point(int x) { this(x, 0); }
   public Point(int x, int y) { this.x = x; this.y = y; }
   public Point(Point p) { this(p.x, p.y); }
   public int getX() { return this.x; }
   public int getY() { return this.y; }
   public void setX(int x) { this.x = x; }
   public void setY(int y) { this.y = y; }
   public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); }
}

class Circle extends Point {
   private int r;
   public Circle(Point p) { this(p, 0); }
   public Circle(Point p, int r) { super(p); this.r = r; }
   public Circle() { this(0); }
   public Circle(int x) { this(x, 0); }
   public Circle(int x, int y) { this(x, y, 0); }
   public Circle(int x, int y, int r) { super(x, y); this.r = r; }
   public Circle(Circle c) { this(c.x, c.y, c.r); }
   public int getR() { return this.r; }
   public void setR(int r) { this.r = r; }
   public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); }
}

public class test {
  public static void main(String args[]) {
    Point p = new Point();
    Point c = new Circle();
    p.print();
    c.print();     
  }
}
Task: Create an object_Native demonstration




Go: package romap

type Romap struct{ imap map[byte]int }


func New(m map[byte]int) *Romap {
    if m == nil {
        return nil
    }
    return &Romap{m}
}


func (rom *Romap) Get(key byte) (int, bool) {
    i, ok := rom.imap[key]
    return i, ok
}


func (rom *Romap) Reset(key byte) {
    _, ok := rom.imap[key]
    if ok {
        rom.imap[key] = 0 
    }
}


Java: import java.util.Collections;
import java.util.HashMap;
import java.util.Map;



public class ImmutableMap {

    public static void main(String[] args) {
        Map<String,Integer> hashMap = getImmutableMap();
        try {
            hashMap.put("Test", 23);
        }
        catch (UnsupportedOperationException e) {
            System.out.println("ERROR:  Unable to put new value.");
        }
        try {
            hashMap.clear();
        }
        catch (UnsupportedOperationException e) {
            System.out.println("ERROR:  Unable to clear map.");
        }
        try {
            hashMap.putIfAbsent("Test", 23);
        }
        catch (UnsupportedOperationException e) {
            System.out.println("ERROR:  Unable to put if absent.");
        }
        
        for ( String key : hashMap.keySet() ) {
            System.out.printf("key = %s, value = %s%n", key, hashMap.get(key));
        }
    }
    
    private static Map<String,Integer> getImmutableMap() {
        Map<String,Integer> hashMap = new HashMap<>();
        hashMap.put("Key 1", 34);
        hashMap.put("Key 2", 105);
        hashMap.put("Key 3", 144);

        return Collections.unmodifiableMap(hashMap);
    }
    
}