WeixiangYan/CodeTransOcean huggingface dataset:
Task: Levenshtein distance_Alignment




Go: package main

import (
    "fmt"

    "github.com/biogo/biogo/align"
    ab "github.com/biogo/biogo/alphabet"
    "github.com/biogo/biogo/feat"
    "github.com/biogo/biogo/seq/linear"
)

func main() {
    
    
    lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz",
        feat.Undefined, '-', 0, true))
    
    
    
    
    nw := make(align.NW, lc.Len())
    for i := range nw {
        r := make([]int, lc.Len())
        nw[i] = r
        for j := range r {
            if j != i {
                r[j] = -1
            }
        }
    }
    
    a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))}
    a.Alpha = lc
    b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))}
    b.Alpha = lc
    
    aln, err := nw.Align(a, b)
    
    if err != nil {
        fmt.Println(err)
        return
    }
    fa := align.Format(a, b, aln, '-')
    fmt.Printf("%s\n%s\n", fa[0], fa[1])
    aa := fmt.Sprint(fa[0])
    ba := fmt.Sprint(fa[1])
    ma := make([]byte, len(aa))
    for i := range ma {
        if aa[i] == ba[i] {
            ma[i] = ' '
        } else {
            ma[i] = '|'
        }
    }
    fmt.Println(string(ma))
}


Java: public class LevenshteinAlignment {

    public static String[] alignment(String a, String b) {
        a = a.toLowerCase();
        b = b.toLowerCase();
        
        int[][] costs = new int[a.length()+1][b.length()+1];
        for (int j = 0; j <= b.length(); j++)
            costs[0][j] = j;
        for (int i = 1; i <= a.length(); i++) {
            costs[i][0] = i;
            for (int j = 1; j <= b.length(); j++) {
                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);
            }
        }

	
	StringBuilder aPathRev = new StringBuilder();
	StringBuilder bPathRev = new StringBuilder();
	for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {
	    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {
		aPathRev.append(a.charAt(--i));
		bPathRev.append(b.charAt(--j));
	    } else if (costs[i][j] == 1 + costs[i-1][j]) {
		aPathRev.append(a.charAt(--i));
		bPathRev.append('-');
	    } else if (costs[i][j] == 1 + costs[i][j-1]) {
		aPathRev.append('-');
		bPathRev.append(b.charAt(--j));
	    }
	}
        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};
    }

    public static void main(String[] args) {
	String[] result = alignment("rosettacode", "raisethysword");
	System.out.println(result[0]);
	System.out.println(result[1]);
    }
}
Task: Simulate input_Keyboard




Go: package main

import (
    "github.com/micmonay/keybd_event"
    "log"
    "runtime"
    "time"
)

func main() {
    kb, err := keybd_event.NewKeyBonding()
    if err != nil {
        log.Fatal(err)
    }

    
    if runtime.GOOS == "linux" {
        time.Sleep(2 * time.Second)
    }

    
    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)

    
    err = kb.Launching()
    if err != nil {
        log.Fatal(err)
    }
}


Java: import java.awt.Robot
public static void type(String str){
   Robot robot = new Robot();
   for(char ch:str.toCharArray()){
      if(Character.isUpperCase(ch)){
         robot.keyPress(KeyEvent.VK_SHIFT);
         robot.keyPress((int)ch);
         robot.keyRelease((int)ch);
         robot.keyRelease(KeyEvent.VK_SHIFT);
      }else{
         char upCh = Character.toUpperCase(ch);
         robot.keyPress((int)upCh);
         robot.keyRelease((int)upCh);
      }
   }
}
Task: Loops_Infinite




Go: package main

import "fmt"

func main() {
	for {
		fmt.Printf("SPAM\n")
	}
}


Java: while (true) {
   System.out.println("SPAM");
}
Task: Move-to-front algorithm




Go: package main

import (
	"bytes"
	"fmt"
)

type symbolTable string

func (symbols symbolTable) encode(s string) []byte {
	seq := make([]byte, len(s))
	pad := []byte(symbols)
	for i, c := range []byte(s) {
		x := bytes.IndexByte(pad, c)
		seq[i] = byte(x)
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return seq
}

func (symbols symbolTable) decode(seq []byte) string {
	chars := make([]byte, len(seq))
	pad := []byte(symbols)
	for i, x := range seq {
		c := pad[x]
		chars[i] = c
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return string(chars)
}

func main() {
	m := symbolTable("abcdefghijklmnopqrstuvwxyz")
	for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
		enc := m.encode(s)
		dec := m.decode(enc)
		fmt.Println(s, enc, dec)
		if dec != s {
			panic("Whoops!")
		}
	}
}


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

public class MTF{
	public static List<Integer> encode(String msg, String symTable){
		List<Integer> output = new LinkedList<Integer>();
		StringBuilder s = new StringBuilder(symTable);
		for(char c : msg.toCharArray()){
			int idx = s.indexOf("" + c);
			output.add(idx);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output;
	}
	
	public static String decode(List<Integer> idxs, String symTable){
		StringBuilder output = new StringBuilder();
		StringBuilder s = new StringBuilder(symTable);
		for(int idx : idxs){
			char c = s.charAt(idx);
			output = output.append(c);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output.toString();
	}
	
	private static void test(String toEncode, String symTable){
		List<Integer> encoded = encode(toEncode, symTable);
		System.out.println(toEncode + ": " + encoded);
		String decoded = decode(encoded, symTable);
		System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
	}
	
	public static void main(String[] args){
		String symTable = "abcdefghijklmnopqrstuvwxyz";
		test("broood", symTable);
		test("bananaaa", symTable);
		test("hiphophiphop", symTable);
	}
}
Task: Active Directory_Search for a user




Go: package main

import (
    "log"
    "github.com/jtblin/go-ldap-client"
)

func main() {
    client := &ldap.LDAPClient{
        Base:        "dc=example,dc=com",
        Host:        "ldap.example.com",
        Port:        389,
        GroupFilter: "(memberUid=%s)",
    }
    defer client.Close()
    err := client.Connect()
    if err != nil { 
        log.Fatalf("Failed to connect : %+v", err)
    }
    groups, err := client.GetGroupsOfUser("username")
    if err != nil {
        log.Fatalf("Error getting groups for user %s: %+v", "username", err)
    }
    log.Printf("Groups: %+v", groups) 
}


Java: import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;

public class LdapSearchDemo {

    public static void main(String[] args) throws IOException, LdapException, CursorException {
        new LdapSearchDemo().demonstrateSearch();
    }

    private void demonstrateSearch() throws IOException, LdapException, CursorException {
        try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) {
            conn.bind("uid=admin,ou=system", "********");
            search(conn, "*mil*");
            conn.unBind();
        }
    }

    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {
        String baseDn = "ou=users,o=mojo";
        String filter = "(&(objectClass=person)(&(uid=" + uid + ")))";
        SearchScope scope = SearchScope.SUBTREE;
        String[] attributes = {"dn", "cn", "sn", "uid"};
        int ksearch = 0;

        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);
        while (cursor.next()) {
            ksearch++;
            Entry entry = cursor.get();
            System.out.printf("Search entry %d = %s%n", ksearch, entry);
        }
    }
}
Task: Singular value decomposition




Go: <package main

import (
    "fmt"
    "gonum.org/v1/gonum/mat"
    "log"
)

func matPrint(m mat.Matrix) {
    fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze())
    fmt.Printf("%13.10f\n", fa)
}

func main() {
    var svd mat.SVD
    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})
    ok := svd.Factorize(a, mat.SVDFull)
    if !ok {
        log.Fatal("Something went wrong!")
    }
    u := mat.NewDense(2, 2, nil)
    svd.UTo(u)
    fmt.Println("U:")
    matPrint(u)
    values := svd.Values(nil)
    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})
    fmt.Println("\nΣ:")
    matPrint(sigma)
    vt := mat.NewDense(2, 2, nil)
    svd.VTo(vt)
    fmt.Println("\nVT:")
    matPrint(vt)
}


Java: import Jama.Matrix;
public class SingularValueDecomposition {
    public static void main(String[] args) {
        double[][] matrixArray = {{3, 0}, {4, 5}};
        var matrix = new Matrix(matrixArray);
        var svd = matrix.svd();
        svd.getU().print(0, 10); 
        svd.getS().print(0, 10);
        svd.getV().print(0, 10);
    }
}
Task: Execute a system command




Go: package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls", "-l")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}


Java: import java.util.Scanner;
import java.io.*;

public class Program {
    public static void main(String[] args) {    	
    	try {
    		Process p = Runtime.getRuntime().exec("cmd /C dir");
    		Scanner sc = new Scanner(p.getInputStream());    		
    		while (sc.hasNext()) System.out.println(sc.nextLine());
    	}
    	catch (IOException e) {
    		System.out.println(e.getMessage());
    	}
    }
}
Task: Rodrigues’ rotation formula




Go: package main

import (
    "fmt"
    "math"
)

type vector [3]float64
type matrix [3]vector

func norm(v vector) float64 {
    return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
}

func normalize(v vector) vector {
    length := norm(v)
    return vector{v[0] / length, v[1] / length, v[2] / length}
}

func dotProduct(v1, v2 vector) float64 {
    return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}

func crossProduct(v1, v2 vector) vector {
    return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}
}

func getAngle(v1, v2 vector) float64 {
    return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))
}

func matrixMultiply(m matrix, v vector) vector {
    return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}
}

func aRotate(p, v vector, a float64) vector {
    ca, sa := math.Cos(a), math.Sin(a)
    t := 1 - ca
    x, y, z := v[0], v[1], v[2]
    r := matrix{
        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},
        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},
        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},
    }
    return matrixMultiply(r, p)
}

func main() {
    v1 := vector{5, -6, 4}
    v2 := vector{8, 5, -30}
    a := getAngle(v1, v2)
    cp := crossProduct(v1, v2)
    ncp := normalize(cp)
    np := aRotate(v1, ncp, a)
    fmt.Println(np)
}


Java: 

class Vector{
  private double x, y, z;

  public Vector(double x1,double y1,double z1){
    x = x1;
    y = y1;
    z = z1;
  }
  
  void printVector(int x,int y){
    text("( " + this.x + " )  \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y);
  }

  public double norm() {
    return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
  }
  
  public Vector normalize(){
    double length = this.norm();
    return new Vector(this.x / length, this.y / length, this.z / length);
  }
  
  public double dotProduct(Vector v2) {
    return this.x*v2.x + this.y*v2.y + this.z*v2.z;
  }
  
  public Vector crossProduct(Vector v2) {
    return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);
  }
  
  public double getAngle(Vector v2) {
    return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));
  }
  
  public Vector aRotate(Vector v, double a) {
    double ca = Math.cos(a), sa = Math.sin(a);
    double t = 1.0 - ca;
    double x = v.x, y = v.y, z = v.z;
    Vector[] r = {
        new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),
        new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),
        new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)
    };
    return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));
  }
}

void setup(){
  Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);
  double a = v1.getAngle(v2);
  Vector cp = v1.crossProduct(v2);
  Vector normCP = cp.normalize();
  Vector np = v1.aRotate(normCP,a);
  
  size(1200,600);
  fill(#000000);
  textSize(30);
  
  text("v1 = ",10,100);
  v1.printVector(60,100);
  text("v2 = ",10,150);
  v2.printVector(60,150);
  text("rV = ",10,200);
  np.printVector(60,200);
}
Task: XML validation




Go: package main

import (
    "fmt"
    "github.com/lestrrat-go/libxml2"
    "github.com/lestrrat-go/libxml2/xsd"
    "io/ioutil"
    "log"
    "os"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    xsdfile := "shiporder.xsd"
    f, err := os.Open(xsdfile)
    check(err)
    defer f.Close()

    buf, err := ioutil.ReadAll(f)
    check(err)

    s, err := xsd.Parse(buf)
    check(err)
    defer s.Free()

    xmlfile := "shiporder.xml"
    f2, err := os.Open(xmlfile)
    check(err)
    defer f2.Close()

    buf2, err := ioutil.ReadAll(f2)
    check(err)

    d, err := libxml2.Parse(buf2)
    check(err)

    if err := s.Validate(d); err != nil {
        for _, e := range err.(xsd.SchemaValidationError).Errors() {
            log.Printf("error: %s", e.Error())
        }
        return
    }

    fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!")
}


Java: import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.ws.Holder;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XmlValidation {
	public static void main(String... args) throws MalformedURLException {
		URL schemaLocation = new URL("http:
		URL documentLocation = new URL("http:
		if (validate(schemaLocation, documentLocation)) {
			System.out.println("document is valid");
		} else {
			System.out.println("document is invalid");
		}
	}

	
	public static boolean minimalValidate(URL schemaLocation, URL documentLocation) {
		SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
		try {
			Validator validator = factory.newSchema(schemaLocation).newValidator();
			validator.validate(new StreamSource(documentLocation.toString()));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	
	public static boolean validate(URL schemaLocation, URL documentLocation) {
		SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
		final Holder<Boolean> valid = new Holder<>(true);
		try {
			Validator validator = factory.newSchema(schemaLocation).newValidator();
			
			validator.setErrorHandler(new ErrorHandler(){
				@Override
				public void warning(SAXParseException exception) {
					System.out.println("warning: " + exception.getMessage());
				}

				@Override
				public void error(SAXParseException exception) {
					System.out.println("error: " + exception.getMessage());
					valid.value = false;
				}

				@Override
				public void fatalError(SAXParseException exception) throws SAXException {
					System.out.println("fatal error: " + exception.getMessage());
					throw exception;
				}});
			validator.validate(new StreamSource(documentLocation.toString()));
			return valid.value;
		} catch (SAXException e) {
			
			return false;
		} catch (Exception e) {
			
			System.err.println(e);
			return false;
		}
	}
}
Task: Longest increasing subsequence




Go: package main

import (
  "fmt"
  "sort"
)

type Node struct {
    val int
    back *Node
}

func lis (n []int) (result []int) {
  var pileTops []*Node
  
  for _, x := range n {
    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
    node := &Node{ x, nil }
    if j != 0 { node.back = pileTops[j-1] }
    if j != len(pileTops) {
      pileTops[j] = node
    } else {
      pileTops = append(pileTops, node)
    }
  }

  if len(pileTops) == 0 { return []int{} }
  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
    result = append(result, node.val)
  }
  
  for i := 0; i < len(result)/2; i++ {
    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
  }
  return
}

func main() {
    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
        fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
    }
}


Java: import java.util.*;

public class LIS {
    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {
        List<Node<E>> pileTops = new ArrayList<Node<E>>();
        
        for (E x : n) {
	    Node<E> node = new Node<E>();
	    node.value = x;
            int i = Collections.binarySearch(pileTops, node);
            if (i < 0) i = ~i;
	    if (i != 0)
		node.pointer = pileTops.get(i-1);
            if (i != pileTops.size())
                pileTops.set(i, node);
            else
                pileTops.add(node);
        }
	
	List<E> result = new ArrayList<E>();
	for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);
                node != null; node = node.pointer)
	    result.add(node.value);
	Collections.reverse(result);
	return result;
    }

    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {
	public E value;
	public Node<E> pointer;
        public int compareTo(Node<E> y) { return value.compareTo(y.value); }
    }

    public static void main(String[] args) {
	List<Integer> d = Arrays.asList(3,2,6,4,5,1);
	System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);
	System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
    }
}
Task: Call a function




Go: import (
	"image"
	"image/gif"
	"io/ioutil"
	"strings"
	"unicode"
)

func f() (int, float64)  { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int)   {}


Java: foo();             
Int x = bar();
Task: Superpermutation minimisation




Go: package main

import "fmt"

const max = 12

var (
    super []byte
    pos   int
    cnt   [max]int
)


func factSum(n int) int {
    s := 0
    for x, f := 0, 1; x < n; {
        x++
        f *= x
        s += f
    }
    return s
}

func r(n int) bool {
    if n == 0 {
        return false
    }
    c := super[pos-n]
    cnt[n]--
    if cnt[n] == 0 {
        cnt[n] = n
        if !r(n - 1) {
            return false
        }
    }
    super[pos] = c
    pos++
    return true
}

func superperm(n int) {
    pos = n
    le := factSum(n)
    super = make([]byte, le)
    for i := 0; i <= n; i++ {
        cnt[i] = i
    }
    for i := 1; i <= n; i++ {
        super[i-1] = byte(i) + '0'
    }

    for r(n) {
    }
}

func main() {
    for n := 0; n < max; n++ {
        fmt.Printf("superperm(%2d) ", n)
        superperm(n)
        fmt.Printf("len = %d\n", len(super))
    }
}


Java: import static java.util.stream.IntStream.rangeClosed;

public class Test {
    final static int nMax = 12;

    static char[] superperm;
    static int pos;
    static int[] count = new int[nMax];

    static int factSum(int n) {
        return rangeClosed(1, n)
                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();
    }

    static boolean r(int n) {
        if (n == 0)
            return false;

        char c = superperm[pos - n];
        if (--count[n] == 0) {
            count[n] = n;
            if (!r(n - 1))
                return false;
        }
        superperm[pos++] = c;
        return true;
    }

    static void superPerm(int n) {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        pos = n;
        superperm = new char[factSum(n)];

        for (int i = 0; i < n + 1; i++)
            count[i] = i;
        for (int i = 1; i < n + 1; i++)
            superperm[i - 1] = chars.charAt(i);

        while (r(n)) {
        }
    }

    public static void main(String[] args) {
        for (int n = 0; n < nMax; n++) {
            superPerm(n);
            System.out.printf("superPerm(%2d) len = %d", n, superperm.length);
            System.out.println();
        }
    }
}
Task: One of n lines in a file




Go: package main

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







func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
    br := bufio.NewReader(r)
    s, err = br.ReadString('\n')
    if err != nil {
        return
    }
    ln = 1
    lnLast := 1.
    var sLast string
    for {
        
        
        sLast, err = br.ReadString('\n')
        if err == io.EOF {
            return s, ln, nil 
        }
        if err != nil {
            break
        }
        lnLast++
        if rand.Float64() < 1/lnLast {
            s = sLast
            ln = int(lnLast)
        }
    }
    return 
}





func oneOfN(n int, file io.Reader) int {
    _, ln, err := choseLineRandomly(file)
    if err != nil {
        panic(err)
    }
    return ln
}


type simReader int

func (r *simReader) Read(b []byte) (int, error) {
    if *r <= 0 {
        return 0, io.EOF
    }
    b[0] = '\n'
    *r--
    return 1, nil
}

func main() {
    
    
    n := 10
    freq := make([]int, n)
    rand.Seed(time.Now().UnixNano())
    for times := 0; times < 1e6; times++ {
        sr := simReader(n)
        freq[oneOfN(n, &sr)-1]++
    }

    
    fmt.Println(freq)
}


Java: import java.util.Arrays;
import java.util.Random;

public class OneOfNLines {

	static Random rand;
	
	public static int oneOfN(int n) {
		int choice = 0;
		
		for(int i = 1; i < n; i++) {
			if(rand.nextInt(i+1) == 0)
				choice = i;
		}
		
		return choice;
	}
	
	public static void main(String[] args) {
		int n = 10;
		int trials = 1000000;
		int[] bins = new int[n];
		rand = new Random();
		
		for(int i = 0; i < trials; i++)
			bins[oneOfN(n)]++;
		
		
		System.out.println(Arrays.toString(bins));
	}
}
Task: Self-describing numbers




Go: package main

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


func sdn(n int64) bool {
    if n >= 1e10 {
        return false
    }
    s := strconv.FormatInt(n, 10)
    for d, p := range s {
        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
            return false
        }
    }
    return true
}


func main() {
    for n := int64(0); n < 1e10; n++ {
        if sdn(n) {
            fmt.Println(n)
        }
    }
}


Java: public class SelfDescribingNumbers{
    public static boolean isSelfDescribing(int a){
        String s = Integer.toString(a);
        for(int i = 0; i < s.length(); i++){
            String s0 = s.charAt(i) + "";
            int b = Integer.parseInt(s0); 
            int count = 0;
            for(int j = 0; j < s.length(); j++){
                int temp = Integer.parseInt(s.charAt(j) + "");
                if(temp == i){
                    count++;
                }
                if (count > b) return false;
            }
            if(count != b) return false;
        }
        return true;
    }

    public static void main(String[] args){
        for(int i = 0; i < 100000000; i++){
            if(isSelfDescribing(i)){
                System.out.println(i);
             }
        }
    }
}