WeixiangYan/CodeTransOcean huggingface dataset:
Task: Active Directory_Search for a user

C: #include <ldap.h>

char *name, *password;
...

LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);

LDAPMessage **result;
ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE,
	
	"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))",
	NULL, 
	0,  
	result); 



ldap_msgfree(*result);	
ldap_unbind(ld);	




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) 
}
Task: Singular value decomposition

C: #include <stdio.h>
#include <gsl/gsl_linalg.h>


void gsl_matrix_print(const gsl_matrix *M) {
    int rows = M->size1;
    int cols = M->size2;
    for (int i = 0; i < rows; i++) {
        printf("|");
        for (int j = 0; j < cols; j++) {
            printf("% 12.10f ", gsl_matrix_get(M, i, j));
        }
        printf("\b|\n");
    }
    printf("\n");
}

int main(){
    double a[] = {3, 0, 4, 5};
    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);
    gsl_matrix *V = gsl_matrix_alloc(2, 2);
    gsl_vector *S = gsl_vector_alloc(2);
    gsl_vector *work = gsl_vector_alloc(2);

    
    gsl_linalg_SV_decomp(&A.matrix, V, S, work);
    gsl_matrix_transpose(V);
    double s[] = {S->data[0], 0, 0, S->data[1]};
    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);

    printf("U:\n");
    gsl_matrix_print(&A.matrix);

    printf("S:\n");
    gsl_matrix_print(&SM.matrix);

    printf("VT:\n");
    gsl_matrix_print(V);
    
    gsl_matrix_free(V);
    gsl_vector_free(S);
    gsl_vector_free(work);
    return 0;
}




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)
}
Task: Sum of first n cubes

C: #include <stdio.h>

int main() {
    for (int i = 0, sum = 0; i < 50; ++i) {
        sum += i * i * i;
        printf("%7d%c", sum, (i + 1) % 5 == 0 ? '\n' : ' ');
    }
    return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    fmt.Println("Cumulative sums of the first 50 cubes:")
    sum := 0
    for n := 0; n < 50; n++ {
        sum += n * n * n
        fmt.Printf("%9s ", rcu.Commatize(sum))
        if n%10 == 9 {
            fmt.Println()
        }
    }
    fmt.Println()
Task: IPC via named pipe

C: #include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>



#define WILL_BLOCK_EVERYTHING	0

#if WILL_BLOCK_EVERYTHING
#include <poll.h>
#endif

size_t tally = 0;

void* write_loop(void *a)
{
	int fd;
	char buf[32];
	while (1) {
#if WILL_BLOCK_EVERYTHING
		
		fd = open("out", O_WRONLY|O_NONBLOCK);
		if (fd < 0) { 
			usleep(200000);
			continue;
		}
#else
		
		fd = open("out", O_WRONLY);
#endif
		write(fd, buf, snprintf(buf, 32, "%d\n", tally));
		close(fd);

		
		usleep(10000);
	}
}

void read_loop()
{
	int fd;
	size_t len;
	char buf[PIPE_BUF];
#if WILL_BLOCK_EVERYTHING
	struct pollfd pfd;
	pfd.events = POLLIN;
#endif
	while (1) {
#if WILL_BLOCK_EVERYTHING
		fd = pfd.fd = open("in", O_RDONLY|O_NONBLOCK);
		fcntl(fd, F_SETFL, 0);  
		poll(&pfd, 1, INFTIM);  
#else
		fd = open("in", O_RDONLY);
#endif
		while ((len = read(fd, buf, PIPE_BUF)) > 0) tally += len;
		close(fd);
	}
}

int main()
{
	pthread_t pid;

	
	mkfifo("in", 0666);
	mkfifo("out", 0666);

	
	pthread_create(&pid, 0, write_loop, 0);
	read_loop();

	return 0;
}




Go: package main

import (
        "fmt"
        "io"
        "log"
        "os"
        "sync/atomic"
        "syscall"
)

const (
        inputFifo  = "/tmp/in.fifo"
        outputFifo = "/tmp/out.fifo"
        readsize   = 64 << 10
)

func openFifo(path string, oflag int) (f *os.File, err error) {
        err = syscall.Mkfifo(path, 0660)
        
        if err != nil && !os.IsExist(err) {
                return
        }
        f, err = os.OpenFile(path, oflag, 0660)
        if err != nil {
                return
        }
        
        fi, err := f.Stat()
        if err != nil {
                f.Close()
                return nil, err
        }
        if fi.Mode()&os.ModeType != os.ModeNamedPipe {
                f.Close()
                return nil, os.ErrExist
        }
        return
}

func main() {
        var byteCount int64
        go func() {
                var delta int
                var err error
                buf := make([]byte, readsize)
                for {
                        input, err := openFifo(inputFifo, os.O_RDONLY)
                        if err != nil {
                                break
                        }
                        for err == nil {
                                delta, err = input.Read(buf)
                                atomic.AddInt64(&byteCount, int64(delta))
                        }
                        input.Close()
                        if err != io.EOF {
                                break
                        }
                }
                log.Fatal(err)
        }()

        for {
                output, err := openFifo(outputFifo, os.O_WRONLY)
                if err != nil {
                        log.Fatal(err)
                }
                cnt := atomic.LoadInt64(&byteCount)
                fmt.Fprintln(output, cnt)
                output.Close()
        }
}
Task: Execute a system command

C: #include <stdlib.h>

int main()
{
    system("ls");
    return 0;
}




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)
    }
}
Task: Rodrigues’ rotation formula

C: #include <stdio.h>
#include <math.h>

typedef struct {
    double x, y, z;
} vector;

typedef struct {
    vector i, j, k;
} matrix;

double norm(vector v) {
    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
}

vector normalize(vector v){
    double length = norm(v);
    vector n = {v.x / length, v.y / length, v.z / length};
    return n;
}

double dotProduct(vector v1, vector v2) {
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

vector crossProduct(vector v1, vector v2) {
    vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x};
    return cp;
}

double getAngle(vector v1, vector v2) {
    return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2)));
}

vector matrixMultiply(matrix m ,vector v) {
    vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)};
    return mm;
}

vector aRotate(vector p, vector v, double a) {
    double ca = cos(a), sa = sin(a);
    double t = 1.0 - ca;
    double x = v.x, y = v.y, z = v.z;
    matrix r = {
        {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);
}

int main() {
    vector v1 = {5, -6, 4}, v2 = {8, 5, -30};
    double a = getAngle(v1, v2);
    vector cp = crossProduct(v1, v2);
    vector ncp = normalize(cp);
    vector np = aRotate(v1, ncp, a);
    printf("[%.13f, %.13f, %.13f]\n", np.x, np.y, np.z);
    return 0;
}




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)
}
Task: XML validation

C: #include <libxml/xmlschemastypes.h>

int main(int argC, char** argV)
{
	if (argC <= 2) {
		printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]);
		return 0;
	}
	
	xmlDocPtr doc;
	xmlSchemaPtr schema = NULL;
	xmlSchemaParserCtxtPtr ctxt;
	char *XMLFileName = argV[1];
	char *XSDFileName = argV[2];
	int ret;

	xmlLineNumbersDefault(1);

	ctxt = xmlSchemaNewParserCtxt(XSDFileName);

	xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
	schema = xmlSchemaParse(ctxt);
	xmlSchemaFreeParserCtxt(ctxt);


	doc = xmlReadFile(XMLFileName, NULL, 0);

	if (doc == NULL){
		fprintf(stderr, "Could not parse %s\n", XMLFileName);
	}
	else{
		xmlSchemaValidCtxtPtr ctxt;

		ctxt = xmlSchemaNewValidCtxt(schema);
		xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
		ret = xmlSchemaValidateDoc(ctxt, doc);
		
		if (ret == 0){
			printf("%s validates\n", XMLFileName);
		}
		else if (ret > 0){
			printf("%s fails to validate\n", XMLFileName);
		}
		else{
			printf("%s validation generated an internal error\n", XMLFileName);
		}
		xmlSchemaFreeValidCtxt(ctxt);
		xmlFreeDoc(doc);
	}


	if(schema != NULL)
		xmlSchemaFree(schema);

	xmlSchemaCleanupTypes();
	xmlCleanupParser();
	xmlMemoryDump();

	return 0;
}




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!")
}
Task: Longest increasing subsequence

C: #include <stdio.h>
#include <stdlib.h>

struct node {
	int val, len;
	struct node *next;
};

void lis(int *v, int len)
{
	int i;
	struct node *p, *n = calloc(len, sizeof *n);
	for (i = 0; i < len; i++)
		n[i].val = v[i];

	for (i = len; i--; ) {
		
		for (p = n + i; p++ < n + len; ) {
			if (p->val > n[i].val && p->len >= n[i].len) {
				n[i].next = p;
				n[i].len = p->len + 1;
			}
		}
	}

	
	for (i = 0, p = n; i < len; i++)
		if (n[i].len > p->len) p = n + i;

	do printf(" %d", p->val); while ((p = p->next));
	putchar('\n');

	free(n);
}

int main(void)
{
	int x[] = { 3, 2, 6, 4, 5, 1 };
	int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };

	lis(x, sizeof(x) / sizeof(int));
	lis(y, sizeof(y) / sizeof(int));
	return 0;
}




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))
    }
}
Task: Hough transform

C: #include "SL_Generated.h"
#include "CImg.h"

using namespace cimg_library;

int main( int argc, char** argv )
{
    string fileName = "Pentagon.bmp";
    if(argc > 1) fileName = argv[1];
    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);
    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);
    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);
    int threads = 0; if(argc > 5) threads = atoi(argv[5]);
    char titleBuffer[200];
    SLTimer t;

    CImg<int> image(fileName.c_str());
    int imageDimensions[] = {image.height(), image.width(), 0};
    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);
    Sequence< Sequence<int> > result;

    sl_init(threads);

    t.start();
    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);
    t.stop();
    
    CImg<int> resultImage(result[1].size(), result.size());
    for(int y = 0; y < result.size(); y++)
        for(int x = 0; x < result[y+1].size(); x++)
            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];
    
    sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0", 
                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());
    resultImage.display(titleBuffer);

    sl_done();
    return 0;
}




Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "math"
    "os"
)

func hough(im image.Image, ntx, mry int) draw.Image {
    nimx := im.Bounds().Max.X
    mimy := im.Bounds().Max.Y

    him := image.NewGray(image.Rect(0, 0, ntx, mry))
    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),
        image.Point{}, draw.Src)

    rmax := math.Hypot(float64(nimx), float64(mimy))
    dr := rmax / float64(mry/2)
    dth := math.Pi / float64(ntx)

    for jx := 0; jx < nimx; jx++ {
        for iy := 0; iy < mimy; iy++ {
            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)
            if col.Y == 255 {
                continue
            }
            for jtx := 0; jtx < ntx; jtx++ {
                th := dth * float64(jtx)
                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)
                iry := mry/2 - int(math.Floor(r/dr+.5))
                col = him.At(jtx, iry).(color.Gray)
                if col.Y > 0 {
                    col.Y--
                    him.SetGray(jtx, iry, col)
                }
            }
        }
    }
    return him
}

func main() {
    f, err := os.Open("Pentagon.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    pent, err := png.Decode(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
    h := hough(pent, 460, 360)
    if f, err = os.Create("hough.png"); err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, h); err != nil {
        fmt.Println(err)
    }
    if cErr := f.Close(); cErr != nil && err == nil {
        fmt.Println(err)
    }
}
Task: Call a function

C: 
f();


g(1, 2, 3);


int op_arg();
int main()
{
	op_arg(1);
	op_arg(1, 2);
	op_arg(1, 2, 3);
	return 0;
}
int op_arg(int a, int b)
{
	printf("%d %d %d\n", a, b, (&b)[1]);
	return a;
}  


void h(int a, ...)
{
	va_list ap;
	va_start(ap);
	...
}

h(1, 2, 3, 4, "abcd", (void*)0);


struct v_args {
    int arg1;
    int arg2;
    char _sentinel;
};

void _v(struct v_args args)
{
    printf("%d, %d\n", args.arg1, args.arg2);
}

#define v(...) _v((struct v_args){__VA_ARGS__})

v(.arg2 = 5, .arg1 = 17); 

v(.arg2=1); 
v();  


printf("%p", f); 


double a = asin(1);











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)   {}
Task: Superpermutation minimisation

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 12
char *super = 0;
int pos, cnt[MAX];


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

int r(int n)
{
	if (!n) return 0;

	char c = super[pos - n];
	if (!--cnt[n]) {
		cnt[n] = n;
		if (!r(n-1)) return 0;
	}
	super[pos++] = c;
	return 1;
}

void superperm(int n)
{
	int i, len;

	pos = n;
	len = fact_sum(n);
	super = realloc(super, len + 1);
	super[len] = '\0';

	for (i = 0; i <= n; i++) cnt[i] = i;
	for (i = 1; i <= n; i++) super[i - 1] = i + '0';

	while (r(n));
}

int main(void)
{
	int n;
	for (n = 0; n < MAX; n++) {
		printf("superperm(%2d) ", n);
		superperm(n);
		printf("len = %d", (int)strlen(super));
		
		
		putchar('\n');
	}

	return 0;
}




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))
    }
}
Task: One of n lines in a file

C: #include <stdio.h>
#include <stdlib.h>

inline int irand(int n)
{
	int r, randmax = RAND_MAX/n * n;
	while ((r = rand()) >= randmax);
	return r / (randmax / n);
}

inline int one_of_n(int n)
{
	int i, r = 0;
	for (i = 1; i < n; i++) if (!irand(i + 1)) r = i;
	return r;
}

int main(void)
{
	int i, r[10] = {0};

	for (i = 0; i < 1000000; i++, r[one_of_n(10)]++);
	for (i = 0; i < 10; i++)
		printf("%d%c", r[i], i == 9 ? '\n':' ');

	return 0;
}




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)
}
Task: Self-describing numbers

C: #include <stdio.h>

inline int self_desc(unsigned long long xx)
{
	register unsigned int d, x;
	unsigned char cnt[10] = {0}, dig[10] = {0};
 
	for (d = 0; xx > ~0U; xx /= 10)
		cnt[ dig[d++] = xx % 10 ]++;
 
	for (x = xx; x; x /= 10)
		cnt[ dig[d++] = x % 10 ]++;
 
	while(d-- && dig[x++] == cnt[d]);
 
	return d == -1;
}
 
int main()
{
	int i;
	for (i = 1; i < 100000000; i++) 
		if (self_desc(i)) printf("%d\n", i);
 
	return 0;
}




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)
        }
    }
}
Task: Numeric separator syntax

C: #include <locale.h>
#include <stdio.h>

int main()
{
  unsigned long long int trillion = 1000000000000;

  setlocale(LC_NUMERIC,"");

  printf("Locale : %s, One Trillion : %'llu\n", setlocale(LC_CTYPE,NULL),trillion);

  return 0;
}




Go: package main

import "fmt"

func main() {
    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}
    for _, integer := range integers {
        fmt.Printf("%d  ", integer)
    }
    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}
    for _, float := range floats {
        fmt.Printf("%g  ", float)
    }
    fmt.Println()
    
    
}
Task: Repeat

C: #include <stdio.h>

void repeat(void (*f)(void), unsigned int n) {
 while (n-->0)
  (*f)(); 
}

void example() {
 printf("Example\n");
}

int main(int argc, char *argv[]) {
 repeat(example, 4);
 return 0;
}




Go: package main

import "fmt"

func repeat(n int, f func()) {
  for i := 0; i < n; i++ {
    f()
  }
}

func fn() {
  fmt.Println("Example")
}

func main() {
  repeat(4, fn)
}