WeixiangYan/CodeTransOcean huggingface dataset:
Task: Permutations by swapping

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

int flag = 1;

void heapPermute(int n, int arr[],int arrLen){
	int temp;
	int i;
	
	if(n==1){
		printf("\n[");
		
		for(i=0;i<arrLen;i++)
			printf("%d,",arr[i]);
		printf("\b] Sign : %d",flag);
		
		flag*=-1;
	}
	else{
		for(i=0;i<n-1;i++){
			heapPermute(n-1,arr,arrLen);
			
			if(n%2==0){
				temp = arr[i];
				arr[i] = arr[n-1];
				arr[n-1] = temp;
			}
			else{
				temp = arr[0];
				arr[0] = arr[n-1];
				arr[n-1] = temp;
			}
		}
		heapPermute(n-1,arr,arrLen);
	}
}

int main(int argC,char* argV[0])
{
	int *arr, i=0, count = 1;
	char* token;
	
	if(argC==1)
		printf("Usage : %s <comma separated list of integers>",argV[0]);
	else{
		while(argV[1][i]!=00){
			if(argV[1][i++]==',')
				count++;
		}
		
		arr = (int*)malloc(count*sizeof(int));
		
		i = 0;
		
		token = strtok(argV[1],",");
		
		while(token!=NULL){
			arr[i++] = atoi(token);
			token = strtok(NULL,",");
		}
		
		heapPermute(i,arr,count);
	}
		
	return 0;
}




Go: package permute




func Iter(p []int) func() int {
    f := pf(len(p))
    return func() int {
        return f(p)
    }
}



func pf(n int) func([]int) int {
    sign := 1
    switch n {
    case 0, 1:
        return func([]int) (s int) {
            s = sign
            sign = 0
            return
        }
    default:
        p0 := pf(n - 1)
        i := n
        var d int
        return func(p []int) int {
            switch {
            case sign == 0:
            case i == n:
                i--
                sign = p0(p[:i])
                d = -1
            case i == 0:
                i++
                sign *= p0(p[1:])
                d = 1
                if sign == 0 {
                    p[0], p[1] = p[1], p[0]
                }
            default:
                p[i], p[i-1] = p[i-1], p[i]
                sign = -sign
                i += d
            }
            return sign
        }
    }
}
Task: Minimum multiple of m where digital sum equals m

C: #include <stdio.h>

unsigned digit_sum(unsigned n) {
    unsigned sum = 0;
    do { sum += n % 10; }
    while(n /= 10);
    return sum;
}

unsigned a131382(unsigned n) {
    unsigned m;
    for (m = 1; n != digit_sum(m*n); m++);
    return m;
}

int main() {
    unsigned n;
    for (n = 1; n <= 70; n++) {
        printf("%9u", a131382(n));
        if (n % 10 == 0) printf("\n");
    }
    return 0;
}




Go: package main

import "rcu"

func main() {
    var res []int
    for n := 1; n <= 70; n++ {
        m := 1
        for rcu.DigitSum(m*n, 10) != n {
            m++
        }
        res = append(res, m)
    }
    rcu.PrintTable(res, 7, 10, true)
}
Task: Pythagorean quadruples

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

#define N 2200

int main(int argc, char **argv){
   int a,b,c,d;
   int r[N+1];
   memset(r,0,sizeof(r));	
   for(a=1; a<=N; a++){
      for(b=a; b<=N; b++){
	 int aabb;
	 if(a&1 && b&1) continue;  
	 aabb=a*a + b*b;
	 for(c=b; c<=N; c++){
	    int aabbcc=aabb + c*c;
	    d=(int)sqrt((float)aabbcc);
	    if(aabbcc == d*d && d<=N) r[d]=1;	
	 }
      }
   }
   for(a=1; a<=N; a++)
      if(!r[a]) printf("%d ",a);	
   printf("\n");
}




Go: package main

import "fmt"

const (
    N = 2200
    N2 = N * N * 2
)

func main() {
    s  := 3 
    var s1, s2 int    
    var r  [N + 1]bool
    var ab [N2 + 1]bool

    for a := 1; a <= N; a++ {
        a2 := a * a
        for b := a; b <= N; b++ {
            ab[a2 + b * b] = true
        }
    }

    for c := 1; c <= N; c++ {
        s1 = s
        s += 2
        s2 = s
        for d := c + 1; d <= N; d++ {
            if ab[s1] {
                r[d] = true
            }
            s1 += s2
            s2 += 2
        }
    }

    for d := 1; d <= N; d++ {
        if !r[d] {
            fmt.Printf("%d ", d)
        }       
    }
    fmt.Println()
}
Task: Steady squares

C: #include <stdio.h>
#include <stdbool.h>
 
bool steady(int n)
{
    int mask = 1;
    for (int d = n; d != 0; d /= 10) 
        mask *= 10;
    return (n * n) % mask == n;
}
 
int main()
{
    for (int i = 1; i < 10000; i++)
        if (steady(i))
            printf("%4d^2 = %8d\n", i, i * i);
    return 0;
}




Go: package main

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

func contains(list []int, s int) bool {
    for _, e := range list {
        if e == s {
            return true
        }
    }
    return false
}

func main() {
    fmt.Println("Steady squares under 10,000:")
    finalDigits := []int{1, 5, 6}
    for i := 1; i < 10000; i++ {
        if !contains(finalDigits, i%10) {
            continue
        }
        sq := i * i
        sqs := strconv.Itoa(sq)
        is := strconv.Itoa(i)
        if strings.HasSuffix(sqs, is) {
            fmt.Printf("%5s -> %10s\n", rcu.Commatize(i), rcu.Commatize(sq))
        }
    }
}
Task: Numbers in base 10 that are palindromic in bases 2, 4, and 16

C: #include <stdio.h>
#define MAXIMUM 25000

int reverse(int n, int base) {
    int r;
    for (r = 0; n; n /= base)
        r = r*base + n%base;
    return r;
}

int palindrome(int n, int base) {
    return n == reverse(n, base);
}

int main() {
    int i, c = 0;
    
    for (i = 0; i < MAXIMUM; i++) {
        if (palindrome(i, 2) &&
            palindrome(i, 4) &&
            palindrome(i, 16)) {
            printf("%5d%c", i, ++c % 12 ? ' ' : '\n');
        }
    }
    printf("\n");
    return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
    "strconv"
)

func reverse(s string) string {
    chars := []rune(s)
    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
        chars[i], chars[j] = chars[j], chars[i]
    }
    return string(chars)
}

func main() {
    fmt.Println("Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:")
    var numbers []int
    for i := int64(0); i < 25000; i++ {
        b2 := strconv.FormatInt(i, 2)
        if b2 == reverse(b2) {
            b4 := strconv.FormatInt(i, 4)
            if b4 == reverse(b4) {
                b16 := strconv.FormatInt(i, 16)
                if b16 == reverse(b16) {
                    numbers = append(numbers, int(i))
                }
            }
        }
    }
    for i, n := range numbers {
        fmt.Printf("%6s ", rcu.Commatize(n))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\n\nFound", len(numbers), "such numbers.")
}
Task: Long stairs

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

int main(void) {
    int trial, secs_tot=0, steps_tot=0;     
    int sbeh, slen, wiz, secs;              
    time_t t;
    srand((unsigned) time(&t));             
    printf( "Seconds    steps behind    steps ahead\n" );
    for( trial=1;trial<=10000;trial++ ) {   
        sbeh = 0; slen = 100; secs = 0;     
        while(sbeh<slen) {                  
            sbeh+=1;                        
            for(wiz=1;wiz<=5;wiz++) {       
                if(rand()%slen < sbeh)
                    sbeh+=1;                
                slen+=1;                    
            }
            secs+=1;                        
            if(trial==1&&599<secs&&secs<610)
                printf("%d        %d            %d\n", secs, sbeh, slen-sbeh );
            
        }
        secs_tot+=secs;
        steps_tot+=slen;
    }
    printf( "Average secs taken: %f\n", secs_tot/10000.0 );
    printf( "Average final length of staircase: %f\n", steps_tot/10000.0 ); 
    return 0;
}




Go: package main

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

func main() {
    rand.Seed(time.Now().UnixNano())
    totalSecs := 0
    totalSteps := 0
    fmt.Println("Seconds    steps behind    steps ahead")
    fmt.Println("-------    ------------    -----------")
    for trial := 1; trial < 10000; trial++ {
        sbeh := 0
        slen := 100
        secs := 0
        for sbeh < slen {
            sbeh++
            for wiz := 1; wiz < 6; wiz++ {
                if rand.Intn(slen) < sbeh {
                    sbeh++
                }
                slen++
            }
            secs++
            if trial == 1 && secs > 599 && secs < 610 {
                fmt.Printf("%d        %d            %d\n", secs, sbeh, slen-sbeh)
            }
        }
        totalSecs += secs
        totalSteps += slen
    }
    fmt.Println("\nAverage secs taken:", float64(totalSecs)/10000)
    fmt.Println("Average final length of staircase:", float64(totalSteps)/10000)
}
Task: Terminal control_Positional read

C: #include <windows.h>
#include <wchar.h>

int
main()
{
	CONSOLE_SCREEN_BUFFER_INFO info;
	COORD pos;
	HANDLE conout;
	long len;
	wchar_t c;

	
	conout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
	    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
	    0, NULL);
	if (conout == INVALID_HANDLE_VALUE)
		return 1;

	
	if (GetConsoleScreenBufferInfo(conout, &info) == 0)
		return 1;

	
	pos.X = info.srWindow.Left + 3;  
	pos.Y = info.srWindow.Top  + 6;  
	if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||
	    len <= 0)
		return 1;

	wprintf(L"Character at (3, 6) had been '%lc'\n", c);
	return 0;
}




Go: package main


import "C"
import "fmt"

func main() {
    for i := 0; i < 80*25; i++ {
        fmt.Print("A")  
    }
    fmt.Println()
    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)
    info := C.CONSOLE_SCREEN_BUFFER_INFO{}
    pos := C.COORD{}
    C.GetConsoleScreenBufferInfo(conOut, &info)
    pos.X = info.srWindow.Left + 3 
    pos.Y = info.srWindow.Top + 6  
    var c C.wchar_t
    var le C.ulong
    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)
    if ret == 0 || le <= 0 {
        fmt.Println("Something went wrong!")
        return
    }
    fmt.Printf("The character at column 3, row 6 is '%c'\n", c) 
}
Task: Pseudo-random numbers_Middle-square method

C: #include<stdio.h>
long long seed;
long long random(){
        seed = seed * seed / 1000 % 1000000;
        return seed;
}
int main(){
        seed = 675248;
        for(int i=1;i<=5;i++)
                printf("%lld\n",random());
        return 0;
}




Go: package main

import "fmt"

func random(seed int) int {
    return seed * seed / 1e3 % 1e6
}

func main() {
    seed := 675248
    for i := 1; i <= 5; i++ {
        seed = random(seed)
        fmt.Println(seed)
    }
}
Task: Image convolution

C: image filter(image img, double *K, int Ks, double, double);




Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/jpeg"
    "math"
    "os"
)



func kf3(k *[9]float64, src, dst *image.Gray) {
    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {
        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {
            var sum float64
            var i int
            for yo := y - 1; yo <= y+1; yo++ {
                for xo := x - 1; xo <= x+1; xo++ {
                    if (image.Point{xo, yo}).In(src.Rect) {
                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)
                    } else {
                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)
                    }
                    i++
                }
            }
            dst.SetGray(x, y,
                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})
        }
    }
}

var blur = [9]float64{
    1. / 9, 1. / 9, 1. / 9,
    1. / 9, 1. / 9, 1. / 9,
    1. / 9, 1. / 9, 1. / 9}



func blurY(src *image.YCbCr) *image.YCbCr {
    dst := *src

    
    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {
        return &dst
    }

    
    srcGray := image.Gray{src.Y, src.YStride, src.Rect}
    dstGray := srcGray
    dstGray.Pix = make([]uint8, len(src.Y))
    kf3(&blur, &srcGray, &dstGray) 

    
    dst.Y = dstGray.Pix                   
    dst.Cb = append([]uint8{}, src.Cb...) 
    dst.Cr = append([]uint8{}, src.Cr...)
    return &dst
}

func main() {
    
    
    f, err := os.Open("Lenna100.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    img, err := jpeg.Decode(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    f.Close()
    y, ok := img.(*image.YCbCr)
    if !ok {
        fmt.Println("expected color jpeg")
        return
    }
    f, err = os.Create("blur.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})
    if err != nil {
        fmt.Println(err)
    }
}
Task: Dice game probabilities

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

typedef uint32_t uint;
typedef uint64_t ulong;

ulong ipow(const uint x, const uint y) {
    ulong result = 1;
    for (uint i = 1; i <= y; i++)
        result *= x;
    return result;
}

uint min(const uint x, const uint y) {
    return (x < y) ? x : y;
}

void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {
    if (n_dice == 0) {
        counts[s]++;
        return;
    }

    for (uint i = 1; i < n_sides + 1; i++)
        throw_die(n_sides, n_dice - 1, s + i, counts);
}

double beating_probability(const uint n_sides1, const uint n_dice1,
                           const uint n_sides2, const uint n_dice2) {
    const uint len1 = (n_sides1 + 1) * n_dice1;
    uint C1[len1];
    for (uint i = 0; i < len1; i++)
        C1[i] = 0;
    throw_die(n_sides1, n_dice1, 0, C1);

    const uint len2 = (n_sides2 + 1) * n_dice2;
    uint C2[len2];
    for (uint j = 0; j < len2; j++)
        C2[j] = 0;
    throw_die(n_sides2, n_dice2, 0, C2);

    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));

    double tot = 0;
    for (uint i = 0; i < len1; i++)
        for (uint j = 0; j < min(i, len2); j++)
            tot += (double)C1[i] * C2[j] / p12;
    return tot;
}

int main() {
    printf("%1.16f\n", beating_probability(4, 9, 6, 6));
    printf("%1.16f\n", beating_probability(10, 5, 7, 6));
    return 0;
}




Go: package main

import(
    "math"
    "fmt"
)

func minOf(x, y uint) uint {
    if x < y {
        return x
    }
    return y
}

func throwDie(nSides, nDice, s uint, counts []uint) {
    if nDice == 0 {
        counts[s]++
        return
    }
    for i := uint(1); i <= nSides; i++ {
        throwDie(nSides, nDice - 1, s + i, counts)
    }
}

func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
    len1 := (nSides1 + 1) * nDice1
    c1 := make([]uint, len1)  
    throwDie(nSides1, nDice1, 0, c1)

    len2 := (nSides2 + 1) * nDice2
    c2 := make([]uint, len2)
    throwDie(nSides2, nDice2, 0, c2)
    p12 := math.Pow(float64(nSides1), float64(nDice1)) *
           math.Pow(float64(nSides2), float64(nDice2))

    tot := 0.0
    for i := uint(0); i < len1; i++ {
        for j := uint(0); j < minOf(i, len2); j++ {
            tot += float64(c1[i] * c2[j]) / p12
        }
    }
    return tot
}

func main() {
    fmt.Println(beatingProbability(4, 9, 6, 6))
    fmt.Println(beatingProbability(10, 5, 7, 6))
}
Task: Halt and catch fire

C: int main(){int a=0, b=0, c=a/b;}




Go: package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
Task: Plasma effect

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

#define pi M_PI

int main()
{
	CONSOLE_SCREEN_BUFFER_INFO info;
    int cols, rows;
	time_t t;
	int i,j;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
    cols = info.srWindow.Right - info.srWindow.Left + 1;
    rows = info.srWindow.Bottom - info.srWindow.Top + 1;
	
	HANDLE console;
	
	console = GetStdHandle(STD_OUTPUT_HANDLE);
	
	system("@clear||cls");
	
	srand((unsigned)time(&t));
	
	for(i=0;i<rows;i++)
		for(j=0;j<cols;j++){
			SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);
			printf("%c",219);
		}
		
	getchar();
	
	return 0;
}




Go: package main

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

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 hsb2rgb(hue, sat, bri float64) (r, g, b int) {
    u := int(bri*255 + 0.5)
    if sat == 0 {
        r, g, b = u, u, u
    } else {
        h := (hue - math.Floor(hue)) * 6
        f := h - math.Floor(h)
        p := int(bri*(1-sat)*255 + 0.5)
        q := int(bri*(1-sat*f)*255 + 0.5)
        t := int(bri*(1-sat*(1-f))*255 + 0.5)
        switch int(h) {
        case 0:
            r, g, b = u, t, p
        case 1:
            r, g, b = q, u, p
        case 2:
            r, g, b = p, u, t
        case 3:
            r, g, b = p, q, u
        case 4:
            r, g, b = t, p, u
        case 5:
            r, g, b = u, p, q
        }
    }
    return
}

func main() {
    const degToRad = math.Pi / 180
    const nframes = 100
    const delay = 4 
    w, h := 640, 640
    anim := gif.GIF{LoopCount: nframes}
    rect := image.Rect(0, 0, w, h)
    palette := make([]color.Color, nframes+1)
    palette[0] = color.White
    for i := 1; i <= nframes; i++ {
        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)
        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}
    }
    for f := 1; f <= nframes; f++ {
        img := image.NewPaletted(rect, palette)
        setBackgroundColor(img, w, h, 0) 
        for y := 0; y < h; y++ {
            for x := 0; x < w; x++ {
                fx, fy := float64(x), float64(y)
                value := math.Sin(fx / 16)
                value += math.Sin(fy / 8)
                value += math.Sin((fx + fy) / 16)
                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)
                value += 4 
                value /= 8 
                _, rem := math.Modf(value + float64(f)/float64(nframes))
                ci := uint8(nframes*rem) + 1
                img.SetColorIndex(x, y, ci)
            }
        }
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }
    file, err := os.Create("plasma.gif")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close() 
    if err2 := gif.EncodeAll(file, &anim); err != nil {
        log.Fatal(err2)
    }    
}
Task: Wordle comparison

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

void wordle(const char *answer, const char *guess, int *result) {
    int i, ix, n = strlen(guess);
    char *ptr;
    if (n != strlen(answer)) {
        printf("The words must be of the same length.\n");
        exit(1);
    }
    char answer2[n+1];
    strcpy(answer2, answer);
    for (i = 0; i < n; ++i) {
        if (guess[i] == answer2[i]) {
            answer2[i] = '\v';
            result[i] = 2;
        }
    }
    for (i = 0; i < n; ++i) {
        if ((ptr = strchr(answer2, guess[i])) != NULL) {
            ix = ptr - answer2;
            answer2[ix] = '\v';
            result[i] = 1;
        }
    }
}

int main() {
    int i, j;
    const char *answer, *guess;
    int res[5];
    const char *res2[5];
    const char *colors[3] = {"grey", "yellow", "green"};
    const char *pairs[5][2] = {
        {"ALLOW", "LOLLY"},
        {"BULLY", "LOLLY"},
        {"ROBIN", "ALERT"},
        {"ROBIN", "SONIC"},
        {"ROBIN", "ROBIN"}
    };
    for (i = 0; i < 5; ++i) {
        answer = pairs[i][0];
        guess  = pairs[i][1];
        for (j = 0; j < 5; ++j) res[j] = 0;
        wordle(answer, guess, res);
        for (j = 0; j < 5; ++j) res2[j] = colors[res[j]];
        printf("%s v %s => { ", answer, guess);
        for (j = 0; j < 5; ++j) printf("%d ", res[j]);
        printf("} => { ");
        for (j = 0; j < 5; ++j) printf("%s ", res2[j]);
        printf("}\n");
    }
    return 0;
}




Go: package main

import (
    "bytes"
    "fmt"
    "log"
)

func wordle(answer, guess string) []int {
    n := len(guess)
    if n != len(answer) {
        log.Fatal("The words must be of the same length.")
    }
    answerBytes := []byte(answer)
    result := make([]int, n) 
    for i := 0; i < n; i++ {
        if guess[i] == answerBytes[i] {
            answerBytes[i] = '\000'
            result[i] = 2
        }
    }
    for i := 0; i < n; i++ {
        ix := bytes.IndexByte(answerBytes, guess[i])
        if ix >= 0 {
            answerBytes[ix] = '\000'
            result[i] = 1
        }
    }
    return result
}

func main() {
    colors := []string{"grey", "yellow", "green"}
    pairs := [][]string{
        {"ALLOW", "LOLLY"},
        {"BULLY", "LOLLY"},
        {"ROBIN", "ALERT"},
        {"ROBIN", "SONIC"},
        {"ROBIN", "ROBIN"},
    }
    for _, pair := range pairs {
        res := wordle(pair[0], pair[1])
        res2 := make([]string, len(res))
        for i := 0; i < len(res); i++ {
            res2[i] = colors[res[i]]
        }
        fmt.Printf("%s v %s => %v => %v\n", pair[0], pair[1], res, res2)
    }
}
Task: Unicode strings

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


wchar_t poker[] = L"♥♦♣♠";
wchar_t four_two[] = L"\x56db\x5341\x4e8c";

int main() {
    
    if (!setlocale(LC_CTYPE, "")) {
        fprintf(stderr, "Locale failure, check your env vars\n");
        return 1;
    }

#ifdef __STDC_ISO_10646__
    
    printf("%lc\n", 0x2708);    
    printf("%ls\n", poker);     
    printf("%ls\n", four_two);  
#else
    
    printf("airplane\n");
    printf("club diamond club spade\n");
    printf("for ty two\n");
#endif
    return 0;
}




Go:     var i int
    var u rune
    for i, u = range "voilà" {
        fmt.Println(i, u)
    }
Task: Bitmap_Read an image through a pipe

C: image read_image(const char *name);




Go: package main






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

func main() {
    c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-")
    pipe, err := c.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }
    if err = c.Start(); err != nil {
        log.Fatal(err)
    }
    b, err := raster.ReadPpmFrom(pipe)
    if err != nil {
        log.Fatal(err)
    }
    if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil {
        log.Fatal(err)
    }
}
Task: Memory layout of a data structure

C: struct RS232_data
{
  unsigned carrier_detect        : 1;
  unsigned received_data         : 1;
  unsigned transmitted_data      : 1;
  unsigned data_terminal_ready   : 1;
  unsigned signal_ground         : 1;
  unsigned data_set_ready        : 1;
  unsigned request_to_send       : 1;
  unsigned clear_to_send         : 1;
  unsigned ring_indicator        : 1;
};




Go: package main

import "fmt"

type rs232p9 uint16

const (
	CD9  rs232p9 = 1 << iota 
	RD9                      
	TD9                      
	DTR9                     
	SG9                      
	DSR9                     
	RTS9                     
	CTS9                     
	RI9                      
)

func main() {
	
	p := RI9 | TD9 | CD9
	fmt.Printf("Type=%T value=%#04x\n", p, p)
}
Task: Sum of primes in odd positions is prime

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

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

int main( void ) {
   int s=0, p, i=1;
   for(p=2;p<=999;p++) {
       if(isprime(p)) {
           if(i%2) {
               s+=p;
               if(isprime(s)) printf( "%d       %d       %d\n", i, p, s );
           }
           i+=1;
       }
   }
   return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    primes := rcu.Primes(999)
    sum := 0
    fmt.Println(" i   p[i]  Σp[i]")
    fmt.Println("----------------")
    for i := 0; i < len(primes); i += 2 {
        sum += primes[i]
        if rcu.IsPrime(sum) {
            fmt.Printf("%3d  %3d  %6s\n", i+1, primes[i], rcu.Commatize(sum))
        }
    }
}