WeixiangYan/CodeTransOcean huggingface dataset:
Task: Words from neighbour ones

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

#define MAX_WORD_SIZE 80
#define MIN_LENGTH 9
#define WORD_SIZE (MIN_LENGTH + 1)

void fatal(const char* message) {
    fprintf(stderr, "%s\n", message);
    exit(1);
}

void* xmalloc(size_t n) {
    void* ptr = malloc(n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

void* xrealloc(void* p, size_t n) {
    void* ptr = realloc(p, n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

int word_compare(const void* p1, const void* p2) {
    return memcmp(p1, p2, WORD_SIZE);
}

int main(int argc, char** argv) {
    const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
    FILE* in = fopen(filename, "r");
    if (!in) {
        perror(filename);
        return EXIT_FAILURE;
    }
    char line[MAX_WORD_SIZE];
    size_t size = 0, capacity = 1024;
    char* words = xmalloc(WORD_SIZE * capacity);
    while (fgets(line, sizeof(line), in)) {
        size_t len = strlen(line) - 1; 
        if (len < MIN_LENGTH)
            continue;
        line[len] = '\0';
        if (size == capacity) {
            capacity *= 2;
            words = xrealloc(words, WORD_SIZE * capacity);
        }
        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);
        ++size;
    }
    fclose(in);
    qsort(words, size, WORD_SIZE, word_compare);
    int count = 0;
    char prev_word[WORD_SIZE] = { 0 };
    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {
        char word[WORD_SIZE] = { 0 };
        for (size_t j = 0; j < MIN_LENGTH; ++j)
            word[j] = words[(i + j) * WORD_SIZE + j];
        if (word_compare(word, prev_word) == 0)
            continue;
        if (bsearch(word, words, size, WORD_SIZE, word_compare))
            printf("%2d. %s\n", ++count, word);
        memcpy(prev_word, word, WORD_SIZE);
    }
    free(words);
    return EXIT_SUCCESS;
}




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "sort"
    "strings"
    "unicode/utf8"
)

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    var words []string
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) >= 9 {
            words = append(words, s)
        }
    }
    count := 0
    var alreadyFound []string
    le := len(words)
    var sb strings.Builder
    for i := 0; i < le-9; i++ {
        sb.Reset()
        for j := i; j < i+9; j++ {
            sb.WriteByte(words[j][j-i])
        }
        word := sb.String()
        ix := sort.SearchStrings(words, word)
        if ix < le && word == words[ix] {
            ix2 := sort.SearchStrings(alreadyFound, word)
            if ix2 == len(alreadyFound) {
                count++
                fmt.Printf("%2d: %s\n", count, word)
                alreadyFound = append(alreadyFound, word)
            }
        }
    }
}
Task: Numbers divisible by their individual digits, but not by the product of their digits.

C: #include <stdio.h>

int divisible(int n) {
    int p = 1;
    int c, d;
    
    for (c=n; c; c /= 10) {
        d = c % 10;
        if (!d || n % d) return 0;
        p *= d;
    }
    
    return n % p;
}

int main() {
    int n, c=0;
    
    for (n=1; n<1000; n++) {
        if (divisible(n)) {
            printf("%5d", n);
            if (!(++c % 10)) printf("\n");
        }
    }
    printf("\n");
    
    return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    var res []int
    for n := 1; n < 1000; n++ {
        digits := rcu.Digits(n, 10)
        var all = true
        for _, d := range digits {
            if d == 0 || n%d != 0 {
                all = false
                break
            }
        }
        if all {
            prod := 1
            for _, d := range digits {
                prod *= d
            }
            if prod > 0 && n%prod != 0 {
                res = append(res, n)
            }
        }
    }
    fmt.Println("Numbers < 1000 divisible by their digits, but not by the product thereof:")
    for i, n := range res {
        fmt.Printf("%4d", n)
        if (i+1)%9 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n%d such numbers found\n", len(res))
}
Task: Four bit adder

C: #include <stdio.h>

typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))


#define NOT(X) (~(X)&1)


#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))

void halfadder(IN a, IN b, OUT s, OUT c)
{
  V(s) = XOR(V(a), V(b));
  V(c) = V(a) & V(b);
}

void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
  PIN(ps); PIN(pc); PIN(tc);

  halfadder(a, b, ps, pc);
  halfadder(ps, ic, s, tc);
  V(oc) = V(tc) | V(pc);
}

void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
		   IN b0, IN b1, IN b2, IN b3,
		   OUT o0, OUT o1, OUT o2, OUT o3,
		   OUT overflow)
{
  PIN(zero); V(zero) = 0;
  PIN(tc0); PIN(tc1); PIN(tc2);

  fulladder(a0, b0, zero, o0, tc0);
  fulladder(a1, b1, tc0,  o1, tc1);
  fulladder(a2, b2, tc1,  o2, tc2);
  fulladder(a3, b3, tc2,  o3, overflow);
}


int main()
{
  PIN(a0); PIN(a1); PIN(a2); PIN(a3);
  PIN(b0); PIN(b1); PIN(b2); PIN(b3);
  PIN(s0); PIN(s1); PIN(s2); PIN(s3);
  PIN(overflow);

  V(a3) = 0; V(b3) = 1;
  V(a2) = 0; V(b2) = 1;
  V(a1) = 1; V(b1) = 1;
  V(a0) = 0; V(b0) = 0;

  fourbitsadder(a0, a1, a2, a3, 
		b0, b1, b2, b3,
		s0, s1, s2, s3, 
		overflow);

  printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
	 V(a3), V(a2), V(a1), V(a0),
	 V(b3), V(b2), V(b1), V(b0),
	 V(s3), V(s2), V(s1), V(s0),
	 V(overflow));
  
  return 0;
}




Go: package main

import "fmt"

func xor(a, b byte) byte {
    return a&(^b) | b&(^a)
}

func ha(a, b byte) (s, c byte) {
    return xor(a, b), a & b
}

func fa(a, b, c0 byte) (s, c1 byte) {
    sa, ca := ha(a, c0)
    s, cb := ha(sa, b)
    c1 = ca | cb
    return
}

func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {
    s0, c0 := fa(a0, b0, 0)
    s1, c1 := fa(a1, b1, c0)
    s2, c2 := fa(a2, b2, c1)
    s3, v = fa(a3, b3, c2)
    return
}

func main() {
    
    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}
Task: Scope_Function names and labels

C: #include <stdio.h>

#define sqr(x) ((x) * (x))
#define greet printf("Hello There!\n")

int twice(int x)
{
	return 2 * x;
}

int main(void)
{
	int x;

	printf("This will demonstrate function and label scopes.\n");
	printf("All output is happening through printf(), a function declared in the header stdio.h, which is external to this program.\n");
	printf("Enter a number: ");
	if (scanf("%d", &x) != 1)
		return 0;
	
	switch (x % 2) {
	default:
		printf("Case labels in switch statements have scope local to the switch block.\n");
	case 0:
		printf("You entered an even number.\n");
		printf("Its square is %d, which was computed by a macro. It has global scope within the translation unit.\n", sqr(x));
		break;
	case 1:
		printf("You entered an odd number.\n");
		goto sayhello;
	jumpin:
		printf("2 times %d is %d, which was computed by a function defined in this file. It has global scope within the translation unit.\n", x, twice(x));
		printf("Since you jumped in, you will now be greeted, again!\n"); 
	sayhello:
		greet;
		if (x == -1)
			goto scram;   
		break;
	}

	printf("We now come to goto, it's extremely powerful but it's also prone to misuse. Its use is discouraged and it wasn't even adopted by Java and later languages.\n");

	if (x != -1) {
		x = -1;   
	 	goto jumpin;  
	}

scram:
	printf("If you are trying to figure out what happened, you now understand goto.\n");
	return 0;
}




Go: package main

import (
    "fmt"
    "runtime"

    "ex"
)

func main() {
    

    
    f := func() {
        
        
        pc, _, _, _ := runtime.Caller(0)
        fmt.Println(runtime.FuncForPC(pc).Name(), "here!")
    }

    ex.X(f) 

    
}
Task: Generate Chess960 starting position

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

char rank[9];

int pos[8];

void swap(int i,int j){
	int temp = pos[i];
	pos[i] = pos[j];
	pos[j] = temp;
}

void generateFirstRank(){
	 int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;
	 
	 for(i=0;i<8;i++){
		 rank[i] = 'e';
		 pos[i] = i;
	 }
		 
	 do{
		 kPos = rand()%8;
		 rPos1 = rand()%8;
		 rPos2 = rand()%8;
	 }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));

	 rank[pos[rPos1]] = 'R';
	 rank[pos[kPos]] = 'K';
	 rank[pos[rPos2]] = 'R';
	 
	 swap(rPos1,7);
	 swap(rPos2,6);
	 swap(kPos,5);
	 
	 do{
		 bPos1 = rand()%5;
		 bPos2 = rand()%5;
	 }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));

	 rank[pos[bPos1]] = 'B';
	 rank[pos[bPos2]] = 'B';
	 
	 swap(bPos1,4);
	 swap(bPos2,3);
	 
	 do{
		 qPos = rand()%3;
		 nPos1 = rand()%3;
	 }while(qPos==nPos1);
	 
	 rank[pos[qPos]] = 'Q';
	 rank[pos[nPos1]] = 'N';
	 
	 for(i=0;i<8;i++)
		 if(rank[i]=='e'){
			 rank[i] = 'N';
			 break;
		 }		
}

void printRank(){
	int i;
	
	#ifdef _WIN32
		printf("%s\n",rank);
	#else
	{
		setlocale(LC_ALL,"");
		printf("\n");
		for(i=0;i<8;i++){
			if(rank[i]=='K')
				printf("%lc",(wint_t)9812);
			else if(rank[i]=='Q')
				printf("%lc",(wint_t)9813);
			else if(rank[i]=='R')
				printf("%lc",(wint_t)9814);
			else if(rank[i]=='B')
				printf("%lc",(wint_t)9815);
			if(rank[i]=='N')
				printf("%lc",(wint_t)9816);
		}
	}
	#endif
}

int main()
{
	int i;
	
	srand((unsigned)time(NULL));
	
	for(i=0;i<9;i++){
		generateFirstRank();
		printRank();
	}
	
	return 0;
}




Go: package main

import (
    "fmt"
    "math/rand"
)

type symbols struct{ k, q, r, b, n rune }

var A = symbols{'K', 'Q', 'R', 'B', 'N'}
var W = symbols{'♔', '♕', '♖', '♗', '♘'}
var B = symbols{'♚', '♛', '♜', '♝', '♞'}

var krn = []string{
    "nnrkr", "nrnkr", "nrknr", "nrkrn",
    "rnnkr", "rnknr", "rnkrn",
    "rknnr", "rknrn",
    "rkrnn"}

func (sym symbols) chess960(id int) string {
    var pos [8]rune
    q, r := id/4, id%4
    pos[r*2+1] = sym.b
    q, r = q/4, q%4
    pos[r*2] = sym.b
    q, r = q/6, q%6
    for i := 0; ; i++ {
        if pos[i] != 0 {
            continue
        }
        if r == 0 {
            pos[i] = sym.q
            break
        }
        r--
    }
    i := 0
    for _, f := range krn[q] {
        for pos[i] != 0 {
            i++
        }
        switch f {
        case 'k':
            pos[i] = sym.k
        case 'r':
            pos[i] = sym.r
        case 'n':
            pos[i] = sym.n
        }
    }
    return string(pos[:])
}

func main() {
    fmt.Println(" ID  Start position")
    for _, id := range []int{0, 518, 959} {
        fmt.Printf("%3d  %s\n", id, A.chess960(id))
    }
    fmt.Println("\nRandom")
    for i := 0; i < 5; i++ {
        fmt.Println(W.chess960(rand.Intn(960)))
    }
}
Task: Modulinos

C: int meaning_of_life();




Go: 
package main

import "fmt"

func MeaningOfLife() int {
    return 42
}

func libMain() {
    fmt.Println("The meaning of life is", MeaningOfLife())
}
Task: Unix_ls

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

int cmpstr(const void *a, const void *b)
{
    return strcmp(*(const char**)a, *(const char**)b);
}

int main(void)
{
    DIR *basedir;
    char path[PATH_MAX];
    struct dirent *entry;
    char **dirnames;
    int diralloc = 128;
    int dirsize  = 0;
    
    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
        perror("malloc error:");
        return 1;
    }

    if (!getcwd(path, PATH_MAX)) {
        perror("getcwd error:");
        return 1;
    }

    if (!(basedir = opendir(path))) {
        perror("opendir error:");
        return 1;
    }

    while ((entry = readdir(basedir))) {
        if (dirsize >= diralloc) {
            diralloc *= 2;
            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
                perror("realloc error:");
                return 1;
            }
        }
        dirnames[dirsize++] = strdup(entry->d_name);
    }

    qsort(dirnames, dirsize, sizeof(char*), cmpstr);

    int i;
    for (i = 0; i < dirsize; ++i) {
        if (dirnames[i][0] != '.') {
            printf("%s\n", dirnames[i]);
        }
    }

    for (i = 0; i < dirsize; ++i)
        free(dirnames[i]);
    free(dirnames);
    closedir(basedir);
    return 0;
}




Go: package main

import (
	"fmt"
	"log"
	"os"
	"sort"
)

func main() {
	f, err := os.Open(".")
	if err != nil {
		log.Fatal(err)
	}
	files, err := f.Readdirnames(0)
	f.Close()
	if err != nil {
		log.Fatal(err)
	}
	sort.Strings(files)
	for _, n := range files {
		fmt.Println(n)
	}
}
Task: Primes whose first and last number is 3

C: #include<stdio.h>
#include<stdlib.h>
#include<math.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 np = 1, d, i, n;
    printf( "3  " );
    for(d=1; d<6; d++) {
        for(i=3; i<pow(10,d)-1; i+=10) {
            n = i + 3*pow(10,d);
            if(isprime(n)) {
                ++np;
                if(n<4009) {
                    printf("%d  ",n);
                    if(!(np%10)) printf("\n");
                }
            }
        }
    }
    printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np );
    return 0;
}




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    var primes []int
    candidates := []int{3, 33}
    for i := 303; i <= 393; i += 10 {
        candidates = append(candidates, i)
    }
    for i := 3003; i <= 3993; i += 10 {
        candidates = append(candidates, i)
    }
    for _, cand := range candidates {
        if rcu.IsPrime(cand) {
            primes = append(primes, cand)
        }
    }
    fmt.Println("Primes under 4,000 which begin and end in 3:")
    for i, p := range primes {
        fmt.Printf("%5s ", rcu.Commatize(p))
        if (i+1)%11 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\nFound", len(primes), "Such primes.")
    pc := len(primes)
    for i := 30003; i <= 39993; i += 10 {
        if rcu.IsPrime(i) {
            pc++
        }
    }
    for i := 300003; i <= 399993; i += 10 {
        if rcu.IsPrime(i) {
            pc++
        }
    }
    pcc := rcu.Commatize(pc)
    fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.")
}
Task: First class environments

C: #include <stdio.h>

#define JOBS 12
#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a))
typedef struct { int seq, cnt; } env_t;

env_t env[JOBS] = {{0, 0}};
int *seq, *cnt;

void hail()
{
	printf("% 4d", *seq);
	if (*seq == 1) return;
	++*cnt;
	*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;
}

void switch_to(int id)
{
	seq = &env[id].seq;
	cnt = &env[id].cnt;
}

int main()
{
	int i;
	jobs(i) { env[i].seq = i + 1; }

again:	jobs(i) { hail(); }
	jobs(i) { if (1 != *seq) goto again; }

	printf("COUNTS:\n");
	jobs(i) { printf("% 4d", *cnt); }

	return 0;
}




Go: package main

import "fmt"

const jobs = 12

type environment struct{ seq, cnt int }

var (
    env      [jobs]environment
    seq, cnt *int
)

func hail() {
    fmt.Printf("% 4d", *seq)
    if *seq == 1 {
        return
    }
    (*cnt)++
    if *seq&1 != 0 {
        *seq = 3*(*seq) + 1
    } else {
        *seq /= 2
    }
}

func switchTo(id int) {
    seq = &env[id].seq
    cnt = &env[id].cnt
}

func main() {
    for i := 0; i < jobs; i++ {
        switchTo(i)
        env[i].seq = i + 1
    }

again:
    for i := 0; i < jobs; i++ {
        switchTo(i)
        hail()
    }
    fmt.Println()

    for j := 0; j < jobs; j++ {
        switchTo(j)
        if *seq != 1 {
            goto again
        }
    }
    fmt.Println()

    fmt.Println("COUNTS:")
    for i := 0; i < jobs; i++ {
        switchTo(i)
        fmt.Printf("% 4d", *cnt)
    }
    fmt.Println()
}
Task: Xiaolin Wu's line algorithm

C: void draw_line_antialias(
        image img,
        unsigned int x0, unsigned int y0,
        unsigned int x1, unsigned int y1,
        color_component r,
        color_component g,
        color_component b );




Go: package raster

import "math"

func ipart(x float64) float64 {
    return math.Floor(x)
}

func round(x float64) float64 {
    return ipart(x + .5)
}

func fpart(x float64) float64 {
    return x - ipart(x)
}

func rfpart(x float64) float64 {
    return 1 - fpart(x)
}


func (g *Grmap) AaLine(x1, y1, x2, y2 float64) {
    
    dx := x2 - x1
    dy := y2 - y1
    ax := dx
    if ax < 0 {
        ax = -ax
    }
    ay := dy
    if ay < 0 {
        ay = -ay
    }
    
    var plot func(int, int, float64)
    if ax < ay {
        x1, y1 = y1, x1
        x2, y2 = y2, x2
        dx, dy = dy, dx
        plot = func(x, y int, c float64) {
            g.SetPx(y, x, uint16(c*math.MaxUint16))
        }
    } else {
        plot = func(x, y int, c float64) {
            g.SetPx(x, y, uint16(c*math.MaxUint16))
        }
    }
    if x2 < x1 {
        x1, x2 = x2, x1
        y1, y2 = y2, y1
    }
    gradient := dy / dx

    
    xend := round(x1)
    yend := y1 + gradient*(xend-x1)
    xgap := rfpart(x1 + .5)
    xpxl1 := int(xend) 
    ypxl1 := int(ipart(yend))
    plot(xpxl1, ypxl1, rfpart(yend)*xgap)
    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)
    intery := yend + gradient 

    
    xend = round(x2)
    yend = y2 + gradient*(xend-x2)
    xgap = fpart(x2 + 0.5)
    xpxl2 := int(xend) 
    ypxl2 := int(ipart(yend))
    plot(xpxl2, ypxl2, rfpart(yend)*xgap)
    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)

    
    for x := xpxl1 + 1; x <= xpxl2-1; x++ {
        plot(x, int(ipart(intery)), rfpart(intery))
        plot(x, int(ipart(intery))+1, fpart(intery))
        intery = intery + gradient
    }
}
Task: Keyboard macros

C: #include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>

int main()
{
  Display *d;
  XEvent event;
  
  d = XOpenDisplay(NULL);
  if ( d != NULL ) {
                
    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), 
	     Mod1Mask,  
	     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), 
	     Mod1Mask, 
	     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);

    for(;;)
    {
      XNextEvent(d, &event);
      if ( event.type == KeyPress ) {
	KeySym s = XLookupKeysym(&event.xkey, 0);
	if ( s == XK_F7 ) {
	  printf("something's happened\n");
	} else if ( s == XK_F6 ) {
	  break;
	}
      }
    }

    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d));
    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d));
  }
  return EXIT_SUCCESS;
}




Go: package main


import "C"
import "fmt"
import "unsafe"

func main() {
    d := C.XOpenDisplay(nil)
    f7, f6 := C.CString("F7"), C.CString("F6")
    defer C.free(unsafe.Pointer(f7))
    defer C.free(unsafe.Pointer(f6))

    if d != nil {
        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
            C.Mod1Mask, 
            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),
            C.Mod1Mask,
            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)

        var event C.XEvent
        for {
            C.XNextEvent(d, &event)
            if C.getXEvent_type(event) == C.KeyPress {
                xkeyEvent := C.getXEvent_xkey(event)
                s := C.XLookupKeysym(&xkeyEvent, 0)
                if s == C.XK_F7 {
                    fmt.Println("something's happened")
                } else if s == C.XK_F6 {
                    break
                }
            }
        }

        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
    } else {
        fmt.Println("XOpenDisplay did not succeed")
    }
}
Task: McNuggets problem

C: #include <stdio.h>

int
main() {
    int max = 0, i = 0, sixes, nines, twenties;

loopstart: while (i < 100) {
        for (sixes = 0; sixes*6 < i; sixes++) {
            if (sixes*6 == i) {
                i++;
                goto loopstart;
            }

            for (nines = 0; nines*9 < i; nines++) {
                if (sixes*6 + nines*9 == i) {
                    i++;
                    goto loopstart;
                }

                for (twenties = 0; twenties*20 < i; twenties++) {
                    if (sixes*6 + nines*9 + twenties*20 == i) {
                        i++;
                        goto loopstart;
                    }
                }
            }
        }
        max = i;
        i++;
    }

    printf("Maximum non-McNuggets number is %d\n", max);

    return 0;
}




Go: package main

import "fmt"

func mcnugget(limit int) {
    sv := make([]bool, limit+1) 
    for s := 0; s <= limit; s += 6 {
        for n := s; n <= limit; n += 9 {
            for t := n; t <= limit; t += 20 {
                sv[t] = true
            }
        }
    }
    for i := limit; i >= 0; i-- {
        if !sv[i] {
            fmt.Println("Maximum non-McNuggets number is", i)
            return
        }
    }
}

func main() {
    mcnugget(100)
}
Task: Magic squares of doubly even order

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

int** doublyEvenMagicSquare(int n) {
	if (n < 4 || n % 4 != 0)
		return NULL;

	int bits = 38505;
	int size = n * n;
	int mult = n / 4,i,r,c,bitPos;

	int** result = (int**)malloc(n*sizeof(int*));
	
	for(i=0;i<n;i++)
		result[i] = (int*)malloc(n*sizeof(int));

	for (r = 0, i = 0; r < n; r++) {
		for (c = 0; c < n; c++, i++) {
			bitPos = c / mult + (r / mult) * 4;
			result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
		}
	}
	return result;
}

int numDigits(int n){
	int count = 1;
	
	while(n>=10){
		n /= 10;
		count++;
	}
	
	return count;
}

void printMagicSquare(int** square,int rows){
	int i,j,baseWidth = numDigits(rows*rows) + 3;
	
	printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
	
	for(i=0;i<rows;i++){
		for(j=0;j<rows;j++){
			printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
		}
		printf("\n");
	}
}

int main(int argC,char* argV[])
{
	int n;
	
	if(argC!=2||isdigit(argV[1][0])==0)
		printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
	else{
		n = atoi(argV[1]);
		printMagicSquare(doublyEvenMagicSquare(n),n);
	}
	return 0;
}




Go: package main

import (
	"fmt"
	"log"
	"strings"
)

const dimensions int = 8

func setupMagicSquareData(d int) ([][]int, error) {
	var output [][]int
	if d < 4 || d%4 != 0 {
		return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
	}
	var bits uint = 0x9669 
	size := d * d
	mult := d / 4
	for i, r := 0, 0; r < d; r++ {
		output = append(output, []int{})
		for c := 0; c < d; i, c = i+1, c+1 {
			bitPos := c/mult + (r/mult)*4
			if (bits & (1 << uint(bitPos))) != 0 {
				output[r] = append(output[r], i+1)
			} else {
				output[r] = append(output[r], size-i)
			}
		}
	}
	return output, nil
}

func arrayItoa(input []int) []string {
	var output []string
	for _, i := range input {
		output = append(output, fmt.Sprintf("%4d", i))
	}
	return output
}

func main() {
	data, err := setupMagicSquareData(dimensions)
	if err != nil {
		log.Fatal(err)
	}
	magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2
	for _, row := range data {
		fmt.Println(strings.Join(arrayItoa(row), " "))
	}
	fmt.Printf("\nMagic Constant: %d\n", magicConstant)
}