WeixiangYan/CodeTransOcean huggingface dataset:
Task: Terminal control_Dimensions

C: #include <sys/ioctl.h>	
#include <err.h>	
#include <fcntl.h>	
#include <stdio.h>	
#include <unistd.h>	

int
main()
{
	struct winsize ws;
	int fd;

	
	fd = open("/dev/tty", O_RDWR);
	if (fd < 0)
		err(1, "/dev/tty");

	 
	if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
		err(1, "/dev/tty");

	printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
	printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);

	close(fd);	
	return 0;
}




Go: package main

import (
    "fmt"
    "os"

    "golang.org/x/crypto/ssh/terminal"
)

func main() {
    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(h, w)
}
Task: Vibrating rectangles

C: 

#include<graphics.h>

void vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)
{
	int color = 1,i,x = winWidth/2, y = winHeight/2;
	
	while(!kbhit()){
		setcolor(color++);
		for(i=num;i>0;i--){
			rectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);
			delay(msec);
		}

		if(color>MAXCOLORS){
			color = 1;
		}
	}
}

int main()
{
	initwindow(1000,1000,"Vibrating Rectangles...");
	
	vibratingRectangles(1000,1000,30,15,20,500);
	
	closegraph();
	
	return 0;
}




Go: package main

import (
    "image"
    "image/color"
    "image/gif"
    "log"
    "os"
)

var (
    black   = color.RGBA{0, 0, 0, 255}
    red     = color.RGBA{255, 0, 0, 255}
    green   = color.RGBA{0, 255, 0, 255}
    blue    = color.RGBA{0, 0, 255, 255}
    magenta = color.RGBA{255, 0, 255, 255}
    cyan    = color.RGBA{0, 255, 255, 255}
    yellow  = color.RGBA{255, 255, 0, 255}
    white   = color.RGBA{255, 255, 255, 255}
)

var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}

func hline(img *image.Paletted, x1, y, x2 int, ci uint8) {
    for ; x1 <= x2; x1++ {
        img.SetColorIndex(x1, y, ci)
    }
}

func vline(img *image.Paletted, x, y1, y2 int, ci uint8) {
    for ; y1 <= y2; y1++ {
        img.SetColorIndex(x, y1, ci)
    }
}

func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {
    for x := 0; x < w; x++ {
        for y := 0; y < h; y++ {
            img.SetColorIndex(x, y, ci)
        }
    }
}

func drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
    hline(img, x1, y1, x2, ci)
    hline(img, x1, y2, x2, ci)
    vline(img, x1, y1, y2, ci)
    vline(img, x2, y1, y2, ci)
}

func main() {
    const nframes = 140
    const delay = 10 
    width, height := 500, 500
    anim := gif.GIF{LoopCount: nframes}
    rect := image.Rect(0, 0, width, height)
    for c := uint8(0); c < 7; c++ {
        for f := 0; f < 20; f++ {
            img := image.NewPaletted(rect, palette)
            setBackgroundColor(img, width, height, 7) 
            for r := 0; r < 20; r++ {
                ix := c
                if r < f {
                    ix = (ix + 1) % 7
                }
                x := width * (r + 1) / 50
                y := height * (r + 1) / 50
                w := width - x
                h := height - y
                drawRectangle(img, x, y, w, h, ix)
            }
            anim.Delay = append(anim.Delay, delay)
            anim.Image = append(anim.Image, img)
        }
    }
    file, err := os.Create("vibrating.gif")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close() 
    if err2 := gif.EncodeAll(file, &anim); err != nil {
        log.Fatal(err2)
    }   
}
Task: Last list item

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

int compare(const void *a, const void *b) {
    int aa = *(const int *)a;
    int bb = *(const int *)b;
    if (aa < bb) return -1;
    if (aa > bb) return 1;
    return 0;
}

int main() {
    int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};
    int isize = sizeof(int);
    int asize = sizeof(a) / isize;
    int i, sum;
    while (asize > 1) {
        qsort(a, asize, isize, compare);
        printf("Sorted list: ");
        for (i = 0; i < asize; ++i) printf("%d ", a[i]);
        printf("\n");
        sum = a[0] + a[1];
        printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum);
        for (i = 2; i < asize; ++i) a[i-2] = a[i];
        a[asize - 2] = sum;
        asize--;
    }
    printf("Last item is %d.\n", a[0]);
    return 0;
}




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}
    for len(a) > 1 {
        sort.Ints(a)
        fmt.Println("Sorted list:", a)
        sum := a[0] + a[1]
        fmt.Printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum)
        a = append(a, sum)
        a = a[2:]
    }
    fmt.Println("Last item is", a[0], "\b.")
}
Task: Piprimes

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

int isprime( int n ) {
	int i;
        if (n<2) return 0;
	for(i=2; i*i<=n; i++) {
		if (n % i == 0) {return 0;}
	}
	return 1;
}

int main(void)  {
	int n = 0, p = 1;
	while (n<22) {
		printf( "%d   ", n );
		p++;
		if (isprime(p)) n+=1;
        }
	return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    primes := rcu.Primes(79) 
    ix := 0
    n := 1
    count := 0
    var pi []int
    for {
        if primes[ix] <= n {
            count++
            if count == 22 {
                break
            }
            ix++
        }
        n++
        pi = append(pi, count)
    }
    fmt.Println("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
    for i, n := range pi {
        fmt.Printf("%2d ", n)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
}
Task: Minimum numbers of three lists

C: #include <stdio.h>

int min(int a, int b) {
    if (a < b) return a;
    return b;
}

int main() {
    int n;
    int numbers1[5] = {5, 45, 23, 21, 67};
    int numbers2[5] = {43, 22, 78, 46, 38};
    int numbers3[5] = {9, 98, 12, 98, 53};
    int numbers[5]  = {};
    for (n = 0; n < 5; ++n) {
        numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);
        printf("%d ", numbers[n]);
    }
    printf("\n");
    return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    numbers1 := [5]int{5, 45, 23, 21, 67}
    numbers2 := [5]int{43, 22, 78, 46, 38}
    numbers3 := [5]int{9, 98, 12, 98, 53}
    numbers := [5]int{}
    for n := 0; n < 5; n++ {
        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])
    }
    fmt.Println(numbers)
}
Task: Pseudo-random numbers_PCG32

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

const uint64_t N = 6364136223846793005;

static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;

uint32_t pcg32_int() {
    uint64_t old = state;
    state = old * N + inc;
    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
    uint32_t rot = old >> 59;
    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}

double pcg32_float() {
    return ((double)pcg32_int()) / (1LL << 32);
}

void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
    state = 0;
    inc = (seed_sequence << 1) | 1;
    pcg32_int();
    state = state + seed_state;
    pcg32_int();
}

int main() {
    int counts[5] = { 0, 0, 0, 0, 0 };
    int i;

    pcg32_seed(42, 54);
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("\n");

    pcg32_seed(987654321, 1);
    for (i = 0; i < 100000; i++) {
        int j = (int)floor(pcg32_float() * 5.0);
        counts[j]++;
    }

    printf("The counts for 100,000 repetitions are:\n");
    for (i = 0; i < 5; i++) {
        printf("  %d : %d\n", i, counts[i]);
    }

    return 0;
}




Go: package main

import (
    "fmt"
    "math"
)

const CONST = 6364136223846793005

type Pcg32 struct{ state, inc uint64 }

func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }

func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
    pcg.state = 0
    pcg.inc = (seedSequence << 1) | 1
    pcg.nextInt()
    pcg.state = pcg.state + seedState
    pcg.nextInt()
}

func (pcg *Pcg32) nextInt() uint32 {
    old := pcg.state
    pcg.state = old*CONST + pcg.inc
    pcgshifted := uint32(((old >> 18) ^ old) >> 27)
    rot := uint32(old >> 59)
    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}

func (pcg *Pcg32) nextFloat() float64 {
    return float64(pcg.nextInt()) / (1 << 32)
}

func main() {
    randomGen := Pcg32New()
    randomGen.seed(42, 54)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321, 1)
    for i := 0; i < 1e5; i++ {
        j := int(math.Floor(randomGen.nextFloat() * 5))
        counts[j]++
    }
    fmt.Println("\nThe counts for 100,000 repetitions are:")
    for i := 0; i < 5; i++ {
        fmt.Printf("  %d : %d\n", i, counts[i])
    }
}
Task: Deconvolution_1D

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
 
double PI;
typedef double complex cplx;
 
void _fft(cplx buf[], cplx out[], int n, int step)
{
	if (step < n) {
		_fft(out, buf, n, step * 2);
		_fft(out + step, buf + step, n, step * 2);
 
		for (int i = 0; i < n; i += 2 * step) {
			cplx t = cexp(-I * PI * i / n) * out[i + step];
			buf[i / 2]     = out[i] + t;
			buf[(i + n)/2] = out[i] - t;
		}
	}
}
 
void fft(cplx buf[], int n)
{
	cplx out[n];
	for (int i = 0; i < n; i++) out[i] = buf[i];
	_fft(buf, out, n, 1);
}


cplx *pad_two(double g[], int len, int *ns)
{
	int n = 1;
	if (*ns) n = *ns;
	else while (n < len) n *= 2;

	cplx *buf = calloc(sizeof(cplx), n);
	for (int i = 0; i < len; i++) buf[i] = g[i];
	*ns = n;
	return buf;
}

void deconv(double g[], int lg, double f[], int lf, double out[]) {
	int ns = 0;
	cplx *g2 = pad_two(g, lg, &ns);
	cplx *f2 = pad_two(f, lf, &ns);

	fft(g2, ns);
	fft(f2, ns);

	cplx h[ns];
	for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];
	fft(h, ns);

	for (int i = 0; i >= lf - lg; i--)
		out[-i] = h[(i + ns) % ns]/32;
	free(g2);
	free(f2);
}

int main()
{
	PI = atan2(1,1) * 4;
	double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};
	double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };
	double h[] = { -8,-9,-3,-1,-6,7 };

	int lg = sizeof(g)/sizeof(double);
	int lf = sizeof(f)/sizeof(double);
	int lh = sizeof(h)/sizeof(double);

	double h2[lh];
	double f2[lf];

	printf("f[] data is : ");
	for (int i = 0; i < lf; i++) printf(" %g", f[i]);
	printf("\n");

	printf("deconv(g, h): ");
	deconv(g, lg, h, lh, f2);
	for (int i = 0; i < lf; i++) printf(" %g", f2[i]);
	printf("\n");

	printf("h[] data is : ");
	for (int i = 0; i < lh; i++) printf(" %g", h[i]);
	printf("\n");

	printf("deconv(g, f): ");
	deconv(g, lg, f, lf, h2);
	for (int i = 0; i < lh; i++) printf(" %g", h2[i]);
	printf("\n");
}




Go: package main

import "fmt"

func main() {
    h := []float64{-8, -9, -3, -1, -6, 7}
    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
        96, 31, 55, 36, 29, -43, -7}
    fmt.Println(h)
    fmt.Println(deconv(g, f))
    fmt.Println(f)
    fmt.Println(deconv(g, h))
}

func deconv(g, f []float64) []float64 {
    h := make([]float64, len(g)-len(f)+1)
    for n := range h {
        h[n] = g[n]
        var lower int
        if n >= len(f) {
            lower = n - len(f) + 1
        }
        for i := lower; i < n; i++ {
            h[n] -= h[i] * f[n-i]
        }
        h[n] /= f[0]
    }
    return h
}
Task: Bitmap_PPM conversion through a pipe

C: 
void print_jpg(image img, int qual);




Go: package main





import (
    "fmt"
    "math/rand"
    "os/exec"
    "raster"
)

func main() {
    b := raster.NewBitmap(400, 300)
    
    b.FillRgb(0xc08040)
    for i := 0; i < 2000; i++ {
        b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)
    }
    for x := 0; x < 400; x++ {
        for y := 240; y < 245; y++ {
            b.SetPxRgb(x, y, 0x804020)
        }
        for y := 260; y < 265; y++ {
            b.SetPxRgb(x, y, 0x804020)
        }
    }
    for y := 0; y < 300; y++ {
        for x := 80; x < 85; x++ {
            b.SetPxRgb(x, y, 0x804020)
        }
        for x := 95; x < 100; x++ {
            b.SetPxRgb(x, y, 0x804020)
        }
    }

    
    c := exec.Command("cjpeg", "-outfile", "pipeout.jpg")
    pipe, err := c.StdinPipe()
    if err != nil {
        fmt.Println(err)
        return
    }
    err = c.Start()
    if err != nil {
        fmt.Println(err)
        return
    }
    err = b.WritePpmTo(pipe)
    if err != nil {
        fmt.Println(err)
        return
    }
    err = pipe.Close()
    if err != nil {
        fmt.Println(err)
    }
}
Task: OpenGL_Utah teapot

C: #include<gl/freeglut.h>

double rot = 0;
float matCol[] = {1,0,0,0};

void display(){
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glPushMatrix();
	glRotatef(30,1,1,0);
	glRotatef(rot,0,1,1);
	glMaterialfv(GL_FRONT,GL_DIFFUSE,matCol);
	glutWireTeapot(0.5);
	glPopMatrix();
	glFlush();
}


void onIdle(){
	rot += 0.01;
	glutPostRedisplay();
}

void init(){
	float pos[] = {1,1,1,0};
	float white[] = {1,1,1,0};
	float shini[] = {70};
	
	glClearColor(.5,.5,.5,0);
	glShadeModel(GL_SMOOTH);
	glLightfv(GL_LIGHT0,GL_AMBIENT,white);
	glLightfv(GL_LIGHT0,GL_DIFFUSE,white);
	glMaterialfv(GL_FRONT,GL_SHININESS,shini);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_DEPTH_TEST);
}

int main(int argC, char* argV[])
{
	glutInit(&argC,argV);
	glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
	glutInitWindowSize(900,700);
	glutCreateWindow("The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.");
	init();
	glutDisplayFunc(display);
	glutIdleFunc(onIdle);
	glutMainLoop();
	return 0;
}




Go: package main


import "C"
import "unsafe"

var rot = 0.0
var matCol = [4]C.float{1, 0, 0, 0}


func display() {
    C.glClear(C.GL_COLOR_BUFFER_BIT | C.GL_DEPTH_BUFFER_BIT)
    C.glPushMatrix()
    C.glRotatef(30, 1, 1, 0)
    C.glRotatef(C.float(rot), 0, 1, 1)
    C.glMaterialfv(C.GL_FRONT, C.GL_DIFFUSE, &matCol[0])
    C.glutWireTeapot(0.5)
    C.glPopMatrix()
    C.glFlush()
}


func onIdle() {
    rot += 0.01
    C.glutPostRedisplay()
}

func initialize() {
    white := [4]C.float{1, 1, 1, 0}
    shini := [1]C.float{70}
    C.glClearColor(0.5, 0.5, 0.5, 0)
    C.glShadeModel(C.GL_SMOOTH)
    C.glLightfv(C.GL_LIGHT0, C.GL_AMBIENT, &white[0])
    C.glLightfv(C.GL_LIGHT0, C.GL_DIFFUSE, &white[0])
    C.glMaterialfv(C.GL_FRONT, C.GL_SHININESS, &shini[0])
    C.glEnable(C.GL_LIGHTING)
    C.glEnable(C.GL_LIGHT0)
    C.glEnable(C.GL_DEPTH_TEST)
}

func main() {
    argc := C.int(0)
    C.glutInit(&argc, nil)
    C.glutInitDisplayMode(C.GLUT_SINGLE | C.GLUT_RGB | C.GLUT_DEPTH)
    C.glutInitWindowSize(900, 700)
    tl := "The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut."
    tlc := C.CString(tl)
    C.glutCreateWindow(tlc)
    initialize()
    C.glutDisplayFunc(C.displayFunc())
    C.glutIdleFunc(C.idleFunc())
    C.glutMainLoop()
    C.free(unsafe.Pointer(tlc))
}
Task: Sierpinski pentagon

C: #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>

#define pi M_PI

int main(){
	
	time_t t;
	double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
	int i,iter,choice,numSides;
	
	printf("Enter number of sides : ");
	scanf("%d",&numSides);
	
	printf("Enter polygon side length : ");
	scanf("%lf",&side);
	
	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	initwindow(windowSide,windowSide,"Polygon Chaos");
	
	vertices = (double**)malloc(numSides*sizeof(double*));
	
	for(i=0;i<numSides;i++){
		vertices[i] = (double*)malloc(2 * sizeof(double));
		
		vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
		vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
		sumX+= vertices[i][0];
		sumY+= vertices[i][1];
		putpixel(vertices[i][0],vertices[i][1],15);
	}
	
	srand((unsigned)time(&t));
	
	seedX = sumX/numSides;
	seedY = sumY/numSides;
	
	putpixel(seedX,seedY,15);
	
	for(i=0;i<iter;i++){
		choice = rand()%numSides;
		
		seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
		seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
		
		putpixel(seedX,seedY,15);
	}
	
	free(vertices);
	
	getch();
	
	closegraph();
	
	return 0;
}




Go: package main

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

var (
    red     = color.RGBA{255, 0, 0, 255}
    green   = color.RGBA{0, 255, 0, 255}
    blue    = color.RGBA{0, 0, 255, 255}
    magenta = color.RGBA{255, 0, 255, 255}
    cyan    = color.RGBA{0, 255, 255, 255}
)

var (
    w, h        = 640, 640
    dc          = gg.NewContext(w, h)
    deg72       = gg.Radians(72)
    scaleFactor = 1 / (2 + math.Cos(deg72)*2)
    palette     = [5]color.Color{red, green, blue, magenta, cyan}
    colorIndex  = 0
)

func drawPentagon(x, y, side float64, depth int) {
    angle := 3 * deg72
    if depth == 0 {
        dc.MoveTo(x, y)
        for i := 0; i < 5; i++ {
            x += math.Cos(angle) * side
            y -= math.Sin(angle) * side
            dc.LineTo(x, y)
            angle += deg72
        }
        dc.SetColor(palette[colorIndex])
        dc.Fill()
        colorIndex = (colorIndex + 1) % 5
    } else {
        side *= scaleFactor
        dist := side * (1 + math.Cos(deg72)*2)
        for i := 0; i < 5; i++ {
            x += math.Cos(angle) * dist
            y -= math.Sin(angle) * dist
            drawPentagon(x, y, side, depth-1)
            angle += deg72
        }
    }
}

func main() {
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    order := 5 
    hw := float64(w / 2)
    margin := 20.0
    radius := hw - 2*margin
    side := radius * math.Sin(math.Pi/5) * 2
    drawPentagon(hw, 3*margin, side, order-1)
    dc.SavePNG("sierpinski_pentagon.png")
}
Task: Minimum primes

C: #include <stdio.h>

#define TRUE 1
#define FALSE 0

int isPrime(int n) {
    int d;
    if (n < 2) return FALSE;
    if (n%2 == 0) return n == 2;
    if (n%3 == 0) return n == 3;
    d = 5;
    while (d*d <= n) {
        if (!(n%d)) return FALSE;
        d += 2;
        if (!(n%d)) return FALSE;
        d += 4;
    }
    return TRUE;
}

int max(int a, int b) {
    if (a > b) return a;
    return b;
}

int main() {
    int n, m;
    int numbers1[5] = { 5, 45, 23, 21, 67};
    int numbers2[5] = {43, 22, 78, 46, 38};
    int numbers3[5] = { 9, 98, 12, 54, 53};
    int primes[5]   = {};
    for (n = 0; n < 5; ++n) {
        m = max(max(numbers1[n], numbers2[n]), numbers3[n]);
        if (!(m % 2)) m++;
        while (!isPrime(m)) m += 2;
        primes[n] = m;
        printf("%d ", primes[n]);
    }
    printf("\n");
    return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    numbers1 := [5]int{5, 45, 23, 21, 67}
    numbers2 := [5]int{43, 22, 78, 46, 38}
    numbers3 := [5]int{9, 98, 12, 54, 53}
    primes := [5]int{}
    for n := 0; n < 5; n++ {
        max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])
        if max % 2 == 0 {
            max++
        }
        for !rcu.IsPrime(max) {
            max += 2
        }
        primes[n] = max
    }
    fmt.Println(primes)
}
Task: Bitmap_Histogram

C: typedef unsigned int histogram_t;
typedef histogram_t *histogram;

#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )

histogram get_histogram(grayimage im);
luminance histogram_median(histogram h);




Go: package raster

import "math"

func (g *Grmap) Histogram(bins int) []int {
    if bins <= 0 {
        bins = g.cols
    }
    h := make([]int, bins)
    for _, p := range g.px {
        h[int(p)*(bins-1)/math.MaxUint16]++
    }
    return h
}

func (g *Grmap) Threshold(t uint16) {
    for i, p := range g.px {
        if p < t {
            g.px[i] = 0
        } else {
            g.px[i] = math.MaxUint16
        }
    }
}
Task: Padovan n-step number sequences

C: #include <stdio.h>

void padovanN(int n, size_t t, int *p) {
    int i, j;
    if (n < 2 || t < 3) {
        for (i = 0; i < t; ++i) p[i] = 1;
        return;
    }
    padovanN(n-1, t, p);
    for (i = n + 1; i < t; ++i) {
        p[i] = 0;
        for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
    }
}

int main() {
    int n, i;
    const size_t t = 15;
    int p[t];
    printf("First %ld terms of the Padovan n-step number sequences:\n", t);
    for (n = 2; n <= 8; ++n) {
        for (i = 0; i < t; ++i) p[i] = 0;
        padovanN(n, t, p);
        printf("%d: ", n);
        for (i = 0; i < t; ++i) printf("%3d ", p[i]);
        printf("\n");
    }
    return 0;
}




Go: package main

import "fmt"

func padovanN(n, t int) []int {
    if n < 2 || t < 3 {
        ones := make([]int, t)
        for i := 0; i < t; i++ {
            ones[i] = 1
        }
        return ones
    }
    p := padovanN(n-1, t)
    for i := n + 1; i < t; i++ {
        p[i] = 0
        for j := i - 2; j >= i-n-1; j-- {
            p[i] += p[j]
        }
    }
    return p
}

func main() {
    t := 15
    fmt.Println("First", t, "terms of the Padovan n-step number sequences:")
    for n := 2; n <= 8; n++ {
        fmt.Printf("%d: %3d\n", n, padovanN(n, t))
    }
}
Task: Mutex

C: HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);




Go: package main

import (
    "fmt"
    "sync"
    "time"
)

var value int
var m sync.Mutex
var wg sync.WaitGroup

func slowInc() {
    m.Lock()
    v := value
    time.Sleep(1e8)
    value = v+1
    m.Unlock()
    wg.Done()
}

func main() {
    wg.Add(2)
    go slowInc()
    go slowInc()
    wg.Wait()
    fmt.Println(value)
}
Task: Metronome

C: #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>

struct timeval start, last;

inline int64_t tv_to_u(struct timeval s)
{
	return s.tv_sec * 1000000 + s.tv_usec;
}

inline struct timeval u_to_tv(int64_t x)
{
	struct timeval s;
	s.tv_sec = x / 1000000;
	s.tv_usec = x % 1000000;
	return s;
}

void draw(int dir, int64_t period, int64_t cur, int64_t next)
{
	int len = 40 * (next - cur) / period;
	int s, i;

	if (len > 20) len = 40 - len;
	s = 20 + (dir ? len : -len);

	printf("\033[H");
	for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');
}

void beat(int delay)
{
	struct timeval tv = start;
	int dir = 0;
	int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;
	int64_t draw_interval = 20000;
	printf("\033[H\033[J");
	while (1) {
		gettimeofday(&tv, 0);
		slp = next - tv_to_u(tv) - corr;
		usleep(slp);
		gettimeofday(&tv, 0);

		putchar(7); 
		fflush(stdout);

		printf("\033[5;1Hdrift: %d compensate: %d (usec)   ",
			(int)d, (int)corr);
		dir = !dir;

		cur = tv_to_u(tv);
		d = cur - next;
		corr = (corr + d) / 2;
		next += delay;

		while (cur + d + draw_interval < next) {
			usleep(draw_interval);
			gettimeofday(&tv, 0);
			cur = tv_to_u(tv);
			draw(dir, delay, cur, next);
			fflush(stdout);
		}
	}
}

int main(int c, char**v)
{
	int bpm;

	if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;
	if (bpm > 600) {
		fprintf(stderr, "frequency %d too high\n", bpm);
		exit(1);
	}

	gettimeofday(&start, 0);
	last = start;
	beat(60 * 1000000 / bpm);

	return 0;
}




Go: package main

import (
	"fmt"
	"time"
)

func main() {
	var bpm = 72.0 
	var bpb = 4    

	d := time.Duration(float64(time.Minute) / bpm)
	fmt.Println("Delay:", d)
	t := time.NewTicker(d)
	i := 1
	for _ = range t.C {
		i--
		if i == 0 {
			i = bpb
			fmt.Printf("\nTICK ")
		} else {
			fmt.Printf("tick ")
		}
	}
}