WeixiangYan/CodeTransOcean huggingface dataset:
Task: Call a foreign-language function




Go: package main



import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    
    go1 := "hello C"
    
    c1 := C.CString(go1)
    
    go1 = ""
    
    c2 := C.strdup(c1)
    
    C.free(unsafe.Pointer(c1))
    
    go2 := C.GoString(c2)
    
    C.free(unsafe.Pointer(c2))
    
    fmt.Println(go2)
}


Java: public class JNIDemo
{
  static
  {  System.loadLibrary("JNIDemo");  }
  
  public static void main(String[] args)
  {
    System.out.println(callStrdup("Hello World!"));
  }
  
  private static native String callStrdup(String s);
}
Task: Knuth's algorithm S




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

func sOfNCreator(n int) func(byte) []byte {
    s := make([]byte, 0, n)
    m := n
    return func(item byte) []byte {
        if len(s) < n {
            s = append(s, item)
        } else {
            m++
            if rand.Intn(m) < n {
                s[rand.Intn(n)] = item
            }
        }
        return s
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    var freq [10]int
    for r := 0; r < 1e5; r++ {
        sOfN := sOfNCreator(3)
        for d := byte('0'); d < '9'; d++ {
            sOfN(d)
        }
        for _, d := range sOfN('9') {
            freq[d-'0']++
        }
    }
    fmt.Println(freq)
}


Java: import java.util.*;
 
class SOfN<T> {
    private static final Random rand = new Random();
 
    private List<T> sample;
    private int i = 0;
    private int n;

    public SOfN(int _n) {
        n = _n;
        sample = new ArrayList<T>(n);
    }

    public List<T> process(T item) {
        if (++i <= n) {
            sample.add(item);
        } else if (rand.nextInt(i) < n) {
            sample.set(rand.nextInt(n), item);
        }
        return sample;
    }
}
 
public class AlgorithmS {
    public static void main(String[] args) {
        int[] bin = new int[10];
        for (int trial = 0; trial < 100000; trial++) {
            SOfN<Integer> s_of_n = new SOfN<Integer>(3);
            for (int i = 0; i < 9; i++) s_of_n.process(i);
            for (int s : s_of_n.process(9)) bin[s]++;
        }
        System.out.println(Arrays.toString(bin));
    }
}
Task: Command-line arguments




Go: package main
import (
	"fmt"
	"os"
)

func main() {
	for i, x := range os.Args[1:] {
		fmt.Printf("the argument #%d is %s\n", i, x)
	}
}


Java: public class Arguments {
  public static void main(String[] args) {
     System.out.println("There are " + args.length + " arguments given.");
     for(int i = 0; i < args.length; i++) 
        System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
  }
}
Task: Array concatenation




Go: package main

import "fmt"

func main() {
    
    
    a := []int{1, 2, 3}
    b := []int{7, 12, 60} 
    c := append(a, b...)
    fmt.Println(c)

    
    
    
    i := []interface{}{1, 2, 3}
    j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
    k := append(i, j...) 
    fmt.Println(k)

    
    
    
    
    
    
    
    l := [...]int{1, 2, 3}
    m := [...]int{7, 12, 60} 
    var n [len(l) + len(m)]int
    copy(n[:], l[:]) 
    copy(n[len(l):], m[:])
    fmt.Println(n)

}


Java: String[] fruits = ["apples", "oranges"];
String[] grains = ["wheat", "corn"];
String[] all    = fruits + grains;
Task: User input_Text




Go: package main

import "fmt"

func main() {
    var s string
    var i int
    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
        fmt.Println("good")
    } else {
        fmt.Println("wrong")
    }
}


Java: import java.util.Scanner;

public class GetInput {
    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = s.nextLine();
        System.out.print("Enter an integer: ");
        int i = Integer.parseInt(s.next());
    }
}
Task: Musical scale




Go: package main

import (
    "encoding/binary"
    "log"
    "math"
    "os"
    "strings"
)

func main() {
    const (
        sampleRate = 44100
        duration   = 8
        dataLength = sampleRate * duration
        hdrSize    = 44
        fileLen    = dataLength + hdrSize - 8
    )

    
    buf1 := make([]byte, 1)
    buf2 := make([]byte, 2)
    buf4 := make([]byte, 4)

    
    var sb strings.Builder
    sb.WriteString("RIFF")
    binary.LittleEndian.PutUint32(buf4, fileLen)
    sb.Write(buf4) 
    sb.WriteString("WAVE")
    sb.WriteString("fmt ")
    binary.LittleEndian.PutUint32(buf4, 16)
    sb.Write(buf4) 
    binary.LittleEndian.PutUint16(buf2, 1)
    sb.Write(buf2) 
    sb.Write(buf2) 
    binary.LittleEndian.PutUint32(buf4, sampleRate)
    sb.Write(buf4) 
    sb.Write(buf4) 
    sb.Write(buf2) 
    binary.LittleEndian.PutUint16(buf2, 8)
    sb.Write(buf2) 
    sb.WriteString("data")
    binary.LittleEndian.PutUint32(buf4, dataLength)
    sb.Write(buf4) 
    wavhdr := []byte(sb.String())

    
    f, err := os.Create("notes.wav")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    f.Write(wavhdr)

    
    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
    for j := 0; j < duration; j++ {
        freq := freqs[j]
        omega := 2 * math.Pi * freq
        for i := 0; i < dataLength/duration; i++ {
            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
            buf1[0] = byte(math.Round(y))
            f.Write(buf1)
        }
    }
}


Java: 

import processing.sound.*;

float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};

SinOsc sine;

size(500,500);

sine = new SinOsc(this);

for(int i=0;i<frequencies.length;i++){
   sine.freq(frequencies[i]);
   sine.play();

   delay(500);
}
Task: Cartesian product of two or more lists




Go: package main

import "fmt"

type pair [2]int

func cart2(a, b []int) []pair {
    p := make([]pair, len(a)*len(b))
    i := 0
    for _, a := range a {
        for _, b := range b {
            p[i] = pair{a, b}
            i++
        }
    }
    return p
}

func main() {
    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
    fmt.Println(cart2([]int{1, 2}, nil))
    fmt.Println(cart2(nil, []int{1, 2}))
}


Java: import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;

import java.util.List;

public class CartesianProduct {

    public List<?> product(List<?>... a) {
        if (a.length >= 2) {
            List<?> product = a[0];
            for (int i = 1; i < a.length; i++) {
                product = product(product, a[i]);
            }
            return product;
        }

        return emptyList();
    }

    private <A, B> List<?> product(List<A> a, List<B> b) {
        return of(a.stream()
                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
                .flatMap(List::stream)
                .collect(toList())).orElse(emptyList());
    }
}
Task: First-class functions




Go: package main

import "math"
import "fmt"


func cube(x float64) float64 { return math.Pow(x, 3) }


type ffType func(float64) float64

func compose(f, g ffType) ffType {
    return func(x float64) float64 {
        return f(g(x))
    }
}

func main() {
    
    funclist := []ffType{math.Sin, math.Cos, cube}
    
    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
    for i := 0; i < 3; i++ {
        
        fmt.Println(compose(funclisti[i], funclist[i])(.5))
    }
}


Java: import java.util.ArrayList;

public class FirstClass{
	
	public interface Function<A,B>{
		B apply(A x);
	}
	
	public static <A,B,C> Function<A, C> compose(
			final Function<B, C> f, final Function<A, B> g) {
		return new Function<A, C>() {
			@Override public C apply(A x) {
				return f.apply(g.apply(x));
			}
		};
	}
	 
	public static void main(String[] args){
		ArrayList<Function<Double, Double>> functions =
			new ArrayList<Function<Double,Double>>();
		
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.cos(x);
					}
				});
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.tan(x);
					}
				});
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return x * x;
					}
				});
		
		ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
		
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.acos(x);
					}
				});
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.atan(x);
					}
				});
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.sqrt(x);
					}
				});
		System.out.println("Compositions:");
		for(int i = 0; i < functions.size(); i++){
			System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
		}
		System.out.println("Hard-coded compositions:");
		System.out.println(Math.cos(Math.acos(0.5)));
		System.out.println(Math.tan(Math.atan(0.5)));
		System.out.println(Math.pow(Math.sqrt(0.5), 2));
	}
}
Task: Proper divisors




Go: package main

import (
    "fmt"
    "strconv"
)

func listProperDivisors(limit int) {
    if limit < 1 {
        return
    }
    width := len(strconv.Itoa(limit))
    for i := 1; i <= limit; i++ {
        fmt.Printf("%*d -> ", width, i)
        if i == 1 {
            fmt.Println("(None)")
            continue
        }
        for j := 1; j <= i/2; j++ {
            if i%j == 0 {
                fmt.Printf(" %d", j)
            }
        }
        fmt.Println()
    }
}

func countProperDivisors(n int) int {
    if n < 2 {
        return 0
    }
    count := 0
    for i := 1; i <= n/2; i++ {
        if n%i == 0 {
            count++
        }
    }
    return count
}

func main() {
    fmt.Println("The proper divisors of the following numbers are :\n")
    listProperDivisors(10)
    fmt.Println()
    maxCount := 0
    most := []int{1}
    for n := 2; n <= 20000; n++ {
        count := countProperDivisors(n)
        if count == maxCount {
            most = append(most, n)
        } else if count > maxCount {
            maxCount = count
            most = most[0:1]
            most[0] = n
        }
    }
    fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
    fmt.Println("namely", maxCount, "\b\n")
    for _, n := range most {
        fmt.Println(n)
    }
}


Java: import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Proper{
    public static List<Integer> properDivs(int n){
        List<Integer> divs = new LinkedList<Integer>();
        if(n == 1) return divs;
        divs.add(1);
        for(int x = 2; x < n; x++){
            if(n % x == 0) divs.add(x);
        }
        
        Collections.sort(divs);
        
        return divs;
    }
    
    public static void main(String[] args){
        for(int x = 1; x <= 10; x++){
            System.out.println(x + ": " + properDivs(x));
        }
        
        int x = 0, count = 0;
        for(int n = 1; n <= 20000; n++){
            if(properDivs(n).size() > count){
                x = n;
                count = properDivs(n).size();
            }
        }
        System.out.println(x + ": " + count);
    }
}
Task: XML_Output




Go: package main

import (
    "encoding/xml"
    "fmt"
)


func xRemarks(r CharacterRemarks) (string, error) {
    b, err := xml.MarshalIndent(r, "", "    ")
    return string(b), err
}



type CharacterRemarks struct {
    Character []crm
}

type crm struct {
    Name   string `xml:"name,attr"`
    Remark string `xml:",chardata"`
}

func main() {
    x, err := xRemarks(CharacterRemarks{[]crm{
        {`April`, `Bubbly: I'm > Tam and <= Emily`},
        {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
        {`Emily`, `Short & shrift`},
    }})
    if err != nil {
        x = err.Error()
    }
    fmt.Println(x)
}


Java: import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlCreation {

  private static final String[] names = {"April", "Tam O'Shanter", "Emily"};
  private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily",
    "Burns: \"When chapman billies leave the street ...\"",
      "Short & shrift"};
  
  public static void main(String[] args) {
    try {
      
      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      
      
      final Element root = doc.createElement("CharacterRemarks");
      doc.appendChild(root);
      
      
      for(int i = 0; i < names.length; i++) {
        final Element character = doc.createElement("Character");
        root.appendChild(character);
        character.setAttribute("name", names[i]);
        character.appendChild(doc.createTextNode(remarks[i]));
      }
      
      
      
      final Source source = new DOMSource(doc);
      
      
      final StringWriter buffer = new StringWriter();
      
      
      final Result result = new StreamResult(buffer);
      
      
      final Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty("indent", "yes");
      transformer.transform(source, result);
      
      
      
      System.out.println(buffer.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
}
Task: Regular expressions




Go: package main
import "fmt"
import "regexp"

func main() {
  str := "I am the original string"

  
  matched, _ := regexp.MatchString(".*string$", str)
  if matched { fmt.Println("ends with 'string'") }

  
  pattern := regexp.MustCompile("original")
  result := pattern.ReplaceAllString(str, "modified")
  fmt.Println(result)
}


Java: String str = "I am a string";
if (str.matches(".*string")) { 
  System.out.println("ends with 'string'");
}
Task: Guess the number_With feedback (player)




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    lower, upper := 0, 100
    fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
    answer := sort.Search(upper-lower, func (i int) bool {
        fmt.Printf("Is your number less than or equal to %d? ", lower+i)
        s := ""
        fmt.Scanf("%s", &s)
        return s != "" && s[0] == 'y'
    })
    fmt.Printf("Your number is %d.\n", lower+answer)
}


Java: import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;

public class GuessNumber {
    public static final int LOWER = 0, UPPER = 100;
    public static void main(String[] args) {
	System.out.printf("Instructions:\n" +
			  "Think of integer number from %d (inclusive) to %d (exclusive) and\n" +
			  "I will guess it. After each guess, you respond with L, H, or C depending\n" +
			  "on if my guess was too low, too high, or correct.\n",
			  LOWER, UPPER);
	int result = Collections.binarySearch(new AbstractList<Integer>() {
		private final Scanner in = new Scanner(System.in);
		public int size() { return UPPER - LOWER; }
		public Integer get(int i) {
		    System.out.printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i);
		    String s = in.nextLine();
		    assert s.length() > 0;
		    switch (Character.toLowerCase(s.charAt(0))) {
		    case 'l':
			return -1;
		    case 'h':
			return 1;
		    case 'c':
			return 0;
		    }
		    return -1;
		}
	    }, 0);
	if (result < 0)
	    System.out.println("That is impossible.");
	else
	    System.out.printf("Your number is %d.\n", result);
    }
}
Task: Hash from two arrays




Go: package main

import "fmt"

func main() {
    keys := []string{"a", "b", "c"}
    vals := []int{1, 2, 3}
    hash := map[string]int{}
    for i, key := range keys {
        hash[key] = vals[i]
    }
    fmt.Println(hash)
}


Java: import java.util.HashMap;
public static void main(String[] args){
	String[] keys= {"a", "b", "c"};
	int[] vals= {1, 2, 3};
	HashMap<String, Integer> hash= new HashMap<String, Integer>();

	for(int i= 0; i < keys.length; i++){
	   hash.put(keys[i], vals[i]);
	}
}
Task: Fractal tree




Go: package main







import (
    "math"
    "raster"
)

const (
    width  = 400
    height = 300
    depth  = 8
    angle  = 12
    length = 50
    frac   = .8
)

func main() {
    g := raster.NewGrmap(width, height)
    ftree(g, width/2, height*9/10, length, 0, depth)
    g.Bitmap().WritePpmFile("ftree.ppm")
}

func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
    x2 := x + distance*math.Sin(direction*math.Pi/180)
    y2 := y - distance*math.Cos(direction*math.Pi/180)
    g.AaLine(x, y, x2, y2)
    if depth > 0 {
        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
    }
}


Java: import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class FractalTree extends JFrame {

    public FractalTree() {
        super("Fractal Tree");
        setBounds(100, 100, 800, 600);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {
        if (depth == 0) return;
        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
        g.drawLine(x1, y1, x2, y2);
        drawTree(g, x2, y2, angle - 20, depth - 1);
        drawTree(g, x2, y2, angle + 20, depth - 1);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        drawTree(g, 400, 500, -90, 9);
    }

    public static void main(String[] args) {
        new FractalTree().setVisible(true);
    }
}
Task: Colour pinstripe_Display




Go: package main

import "github.com/fogleman/gg"

var palette = [8]string{
    "000000", 
    "FF0000", 
    "00FF00", 
    "0000FF", 
    "FF00FF", 
    "00FFFF", 
    "FFFF00", 
    "FFFFFF", 
}

func pinstripe(dc *gg.Context) {
    w := dc.Width()
    h := dc.Height() / 4
    for b := 1; b <= 4; b++ {
        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
            dc.SetHexColor(palette[ci%8])
            y := h * (b - 1)
            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
            dc.Fill()
        }
    }
}

func main() {
    dc := gg.NewContext(900, 600)
    pinstripe(dc)
    dc.SavePNG("color_pinstripe.png")
}


Java: import java.awt.*;
import static java.awt.Color.*;
import javax.swing.*;

public class ColourPinstripeDisplay extends JPanel {
    final static Color[] palette = {black, red, green, blue, magenta,cyan,
        yellow, white};

    final int bands = 4;

    public ColourPinstripeDisplay() {
        setPreferredSize(new Dimension(900, 600));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int h = getHeight();
        for (int b = 1; b <= bands; b++) {
            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {
                g.setColor(palette[colIndex % palette.length]);
                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("ColourPinstripeDisplay");
            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}
Task: Doomsday rule




Go: package main

import (
    "fmt"
    "strconv"
)

var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

func anchorDay(y int) int {
    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}

func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }

var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}

func main() {
    dates := []string{
        "1800-01-06",
        "1875-03-29",
        "1915-12-07",
        "1970-12-23",
        "2043-05-14",
        "2077-02-12",
        "2101-04-02",
    }

    fmt.Println("Days of week given by Doomsday rule:")
    for _, date := range dates {
        y, _ := strconv.Atoi(date[0:4])
        m, _ := strconv.Atoi(date[5:7])
        m--
        d, _ := strconv.Atoi(date[8:10])
        a := anchorDay(y)
        f := firstDaysCommon[m]
        if isLeapYear(y) {
            f = firstDaysLeap[m]
        }
        w := d - f
        if w < 0 {
            w = 7 + w
        }
        dow := (a + w) % 7
        fmt.Printf("%s -> %s\n", date, days[dow])
    }
}


Java: class Doom {
    public static void main(String[] args) {
        final Date[] dates = {
            new Date(1800,1,6),
            new Date(1875,3,29),
            new Date(1915,12,7),
            new Date(1970,12,23),
            new Date(2043,5,14),
            new Date(2077,2,12),
            new Date(2101,4,2)
        };
        
        for (Date d : dates)
            System.out.println(
                String.format("%s: %s", d.format(), d.weekday()));
    }
}

class Date {
    private int year, month, day;
    
    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};
    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};
    public static final String[] weekdays = {
        "Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"
    };
    
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    
    public boolean isLeapYear() {
        return year%4 == 0 && (year%100 != 0 || year%400 == 0);
    }
    
    public String format() {
        return String.format("%02d/%02d/%04d", month, day, year);
    }
    
    public String weekday() {
        final int c = year/100;
        final int r = year%100;
        final int s = r/12;
        final int t = r%12;
        
        final int c_anchor = (5 * (c%4) + 2) % 7;
        final int doom = (s + t + t/4 + c_anchor) % 7;
        final int anchor = 
            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];
        
        return weekdays[(doom + day - anchor + 7) % 7];
    }
}
Task: Gray code




Go: package main

import "fmt"

func enc(b int) int {
    return b ^ b>>1
}

func dec(g int) (b int) {
    for ; g != 0; g >>= 1 {
        b ^= g
    }
    return
}

func main() {
    fmt.Println("decimal  binary   gray    decoded")
    for b := 0; b < 32; b++ {
        g := enc(b)
        d := dec(g)
        fmt.Printf("  %2d     %05b   %05b   %05b  %2d\n", b, b, g, d, d)
    }
}


Java: public class Gray {
	public static long grayEncode(long n){
		return n ^ (n >>> 1);
	}
	
	public static long grayDecode(long n) {
		long p = n;
		while ((n >>>= 1) != 0)
			p ^= n;
		return p;
	}
	public static void main(String[] args){
		System.out.println("i\tBinary\tGray\tDecoded");
		for(int i = -1; i < 32;i++){
			System.out.print(i +"\t");
			System.out.print(Integer.toBinaryString(i) + "\t");
			System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
			System.out.println(grayDecode(grayEncode(i)));
		}
	}
}