WeixiangYan/CodeTransOcean huggingface dataset:
Task: Paraffins

C: #include <stdio.h>

#define MAX_N 33	
#define BRANCH 4	



typedef unsigned long long xint;
#define FMT "llu"

xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};


xint choose(xint m, xint k)
{
	xint i, r;

	if (k == 1) return m;
	for (r = m, i = 1; i < k; i++)
		r = r * (m + i) / (i + 1);
	return r;
}


void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
	xint b, c, m, s;

	for (b = br + 1; b <= BRANCH; b++) {
		s = sum + (b - br) * n;
		if (s >= MAX_N) return;

		
		c = choose(rooted[n], b - br) * cnt;

		
		if (l * 2 < s) unrooted[s] += c;

		
		if (b == BRANCH) return;
		rooted[s] += c;

		
		for (m = n; --m; ) tree(b, m, c, s, l);
	}
}

void bicenter(int s)
{
	if (s & 1) return;

	
	unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}

int main()
{
	xint n;
	for (n = 1; n < MAX_N; n++) {
		tree(0, n, 1, 1, n);
		bicenter(n);
		printf("%"FMT": %"FMT"\n", n, unrooted[n]);
	}

	return 0;
}




Go: package main

import (
    "fmt"
    "math/big"
)

const branches = 4
const nMax = 500

var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)

func tree(br, n, l, sum int, cnt *big.Int) {
    for b := br + 1; b <= branches; b++ {
        sum += n
        if sum > nMax {
            return
        }
        if l*2 >= sum && b >= branches {
            return
        }
        if b == br+1 {
            c[br].Mul(&rooted[n], cnt)
        } else {
            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
            c[br].Mul(&c[br], tmp)
            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
        }
        if l*2 < sum {
            unrooted[sum].Add(&unrooted[sum], &c[br])
        }
        if b < branches {
            rooted[sum].Add(&rooted[sum], &c[br])
        }
        for m := n - 1; m > 0; m-- {
            tree(b, m, l, sum, &c[br])
        }
    }
}

func bicenter(s int) {
    if s&1 == 0 {
        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
        unrooted[s].Add(&unrooted[s], tmp)
    }
}

func main() {
    rooted[0].SetInt64(1)
    rooted[1].SetInt64(1)
    unrooted[0].SetInt64(1)
    unrooted[1].SetInt64(1)
    for n := 1; n <= nMax; n++ {
        tree(0, n, n, 1, big.NewInt(1))
        bicenter(n)
        fmt.Printf("%d: %d\n", n, &unrooted[n])
    }
}
Task: Minimum number of cells after, before, above and below NxN squares

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

#define min(a, b) (a<=b?a:b)

void minab( unsigned int n ) {
    int i, j;
    for(i=0;i<n;i++) {
        for(j=0;j<n;j++) {
            printf( "%2d  ", min( min(i, n-1-i), min(j, n-1-j) ));
        }
        printf( "\n" );
    }
    return;
}

int main(void) {
    minab(10);
    return 0;
}




Go: package main

import "fmt"

func printMinCells(n int) {
    fmt.Printf("Minimum number of cells after, before, above and below %d x %d square:\n", n, n)
    p := 1
    if n > 20 {
        p = 2
    }
    for r := 0; r < n; r++ {
        cells := make([]int, n)
        for c := 0; c < n; c++ {
            nums := []int{n - r - 1, r, c, n - c - 1}
            min := n
            for _, num := range nums {
                if num < min {
                    min = num
                }
            }
            cells[c] = min
        }
        fmt.Printf("%*d \n", p, cells)
    }
}

func main() {
    for _, n := range []int{23, 10, 9, 2, 1} {
        printMinCells(n)
        fmt.Println()
    }
}
Task: Pentagram

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

#define pi M_PI

int main(){
	
	char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
              "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
			  
	int stroke=0,fill=0,back=0,i;
	
	double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
	
	printf("Enter core pentagon side length : ");
	scanf("%lf",&coreSide);
	
	printf("Enter pentagram arm length : ");
	scanf("%lf",&armLength);
	
	printf("Available colours are :\n");
	
	for(i=0;i<16;i++){
		printf("%d. %s\t",i+1,colourNames[i]);
		if((i+1) % 3 == 0){
			printf("\n");
		}
	}
	
	while(stroke==fill && fill==back){
		printf("\nEnter three diffrenet options for stroke, fill and background : ");
		scanf("%d%d%d",&stroke,&fill,&back);
	}
	
	pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
	
	initwindow(2*centerX,2*centerY,"Pentagram");
		
	setcolor(stroke-1);
	
	setfillstyle(SOLID_FILL,back-1);
	
	bar(0,0,2*centerX,2*centerY);
	
	floodfill(centerX,centerY,back-1);
	
	setfillstyle(SOLID_FILL,fill-1);

	for(i=0;i<5;i++){
		line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
		line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
		line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
		
		floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
	}
	
	floodfill(centerX,centerY,stroke-1);
	
	getch();
	
	closegraph();
}




Go: package main

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

func Pentagram(x, y, r float64) []gg.Point {
    points := make([]gg.Point, 5)
    for i := 0; i < 5; i++ {
        fi := float64(i)
        angle := 2*math.Pi*fi/5 - math.Pi/2
        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
    }
    return points
}

func main() {
    points := Pentagram(320, 320, 250)
    dc := gg.NewContext(640, 640)
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    for i := 0; i <= 5; i++ {
        index := (i * 2) % 5
        p := points[index]
        dc.LineTo(p.X, p.Y)
    }
    dc.SetHexColor("#6495ED") 
    dc.SetFillRule(gg.FillRuleWinding)
    dc.FillPreserve()
    dc.SetRGB(0, 0, 0) 
    dc.SetLineWidth(5)
    dc.Stroke()
    dc.SavePNG("pentagram.png")
}
Task: Knapsack problem_Unbounded

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

typedef struct {
    char *name;
    double value;
    double weight;
    double volume;
} item_t;

item_t items[] = {
    {"panacea", 3000.0, 0.3, 0.025},
    {"ichor",   1800.0, 0.2, 0.015},
    {"gold",    2500.0, 2.0, 0.002},
};

int n = sizeof (items) / sizeof (item_t);
int *count;
int *best;
double best_value;

void knapsack (int i, double value, double weight, double volume) {
    int j, m1, m2, m;
    if (i == n) {
        if (value > best_value) {
            best_value = value;
            for (j = 0; j < n; j++) {
                best[j] = count[j];
            }
        }
        return;
    }
    m1 = weight / items[i].weight;
    m2 = volume / items[i].volume;
    m = m1 < m2 ? m1 : m2;
    for (count[i] = m; count[i] >= 0; count[i]--) {
        knapsack(
            i + 1,
            value + count[i] * items[i].value,
            weight - count[i] * items[i].weight,
            volume - count[i] * items[i].volume
        );
    }
}

int main () {
    count = malloc(n * sizeof (int));
    best = malloc(n * sizeof (int));
    best_value = 0;
    knapsack(0, 0.0, 25.0, 0.25);
    int i;
    for (i = 0; i < n; i++) {
        printf("%d %s\n", best[i], items[i].name);
    }
    printf("best value: %.0f\n", best_value);
    free(count); free(best);
    return 0;
}




Go: package main

import "fmt"

type Item struct {
	Name           string
	Value          int
	Weight, Volume float64
}

type Result struct {
	Counts []int
	Sum    int
}

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

func Knapsack(items []Item, weight, volume float64) (best Result) {
	if len(items) == 0 {
		return
	}
	n := len(items) - 1
	maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))
	for count := 0; count <= maxCount; count++ {
		sol := Knapsack(items[:n],
			weight-float64(count)*items[n].Weight,
			volume-float64(count)*items[n].Volume)
		sol.Sum += items[n].Value * count
		if sol.Sum > best.Sum {
			sol.Counts = append(sol.Counts, count)
			best = sol
		}
	}
	return
}

func main() {
	items := []Item{
		{"Panacea", 3000, 0.3, 0.025},
		{"Ichor", 1800, 0.2, 0.015},
		{"Gold", 2500, 2.0, 0.002},
	}
	var sumCount, sumValue int
	var sumWeight, sumVolume float64

	result := Knapsack(items, 25, 0.25)

	for i := range result.Counts {
		fmt.Printf("%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\n",
			items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),
			items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])

		sumCount += result.Counts[i]
		sumValue += items[i].Value * result.Counts[i]
		sumWeight += items[i].Weight * float64(result.Counts[i])
		sumVolume += items[i].Volume * float64(result.Counts[i])
	}

	fmt.Printf("TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\n",
		sumCount, sumWeight, sumVolume, sumValue)
}
Task: Bitmap_Bézier curves_Quadratic

C: void quad_bezier(
        image img,
        unsigned int x1, unsigned int y1,
        unsigned int x2, unsigned int y2,
        unsigned int x3, unsigned int y3,
        color_component r,
        color_component g,
        color_component b );




Go: package raster

const b2Seg = 20

func (b *Bitmap) Bézier2(x1, y1, x2, y2, x3, y3 int, p Pixel) {
    var px, py [b2Seg + 1]int
    fx1, fy1 := float64(x1), float64(y1)
    fx2, fy2 := float64(x2), float64(y2)
    fx3, fy3 := float64(x3), float64(y3)
    for i := range px {
        c := float64(i) / b2Seg
        a := 1 - c
        a, b, c := a*a, 2 * c * a, c*c
        px[i] = int(a*fx1 + b*fx2 + c*fx3)
        py[i] = int(a*fy1 + b*fy2 + c*fy3)
    }
    x0, y0 := px[0], py[0]
    for i := 1; i <= b2Seg; i++ {
        x1, y1 := px[i], py[i]
        b.Line(x0, y0, x1, y1, p)
        x0, y0 = x1, y1
    }
}

func (b *Bitmap) Bézier2Rgb(x1, y1, x2, y2, x3, y3 int, c Rgb) {
    b.Bézier2(x1, y1, x2, y2, x3, y3, c.Pixel())
}
Task: Increasing gaps between consecutive Niven numbers

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



uint64_t digit_sum(uint64_t n, uint64_t sum) {
    ++sum;
    while (n > 0 && n % 10 == 0) {
        sum -= 9;
        n /= 10;
    }
    return sum;
}

inline bool divisible(uint64_t n, uint64_t d) {
    if ((d & 1) == 0 && (n & 1) == 1)
        return false;
    return n % d == 0;
}

int main() {
    setlocale(LC_ALL, "");

    uint64_t previous = 1, gap = 0, sum = 0;
    int niven_index = 0, gap_index = 1;

    printf("Gap index  Gap    Niven index    Niven number\n");
    for (uint64_t niven = 1; gap_index <= 32; ++niven) {
        sum = digit_sum(niven, sum);
        if (divisible(niven, sum)) {
            if (niven > previous + gap) {
                gap = niven - previous;
                printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
                       gap, niven_index, previous);
            }
            previous = niven;
            ++niven_index;
        }
    }
    return 0;
}




Go: package main

import "fmt"

type is func() uint64

func newSum() is {
    var ms is
    ms = func() uint64 {
        ms = newSum()
        return ms()
    }
    var msd, d uint64
    return func() uint64 {
        if d < 9 {
            d++
        } else {
            d = 0
            msd = ms()
        }
        return msd + d
    }
}

func newHarshard() is {
    i := uint64(0)
    sum := newSum()
    return func() uint64 {
        for i++; i%sum() != 0; i++ {
        }
        return i
    }
}

func commatize(n uint64) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    fmt.Println("Gap    Index of gap   Starting Niven")
    fmt.Println("===   =============   ==============")
    h := newHarshard()
    pg := uint64(0) 
    pn := h()       
    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {
        g := n - pn
        if g > pg {
            fmt.Printf("%3d   %13s   %14s\n", g, commatize(i), commatize(pn))
            pg = g
        }
        pn = n
    }
}
Task: Print debugging statement

C: #include <stdio.h>

#define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x)

int add(int x, int y) {
  int result = x + y;
  DEBUG_INT(x);
  DEBUG_INT(y);
  DEBUG_INT(result);
  DEBUG_INT(result+1);
  return result;
}

int main() {
  add(2, 7);
  return 0;
}




Go: package main

import (
    "fmt"
    "runtime"
)

type point struct {
    x, y float64
}

func add(x, y int) int {
    result := x + y
    debug("x", x)
    debug("y", y)
    debug("result", result)
    debug("result+1", result+1)
    return result
}

func debug(s string, x interface{}) {
    _, _, lineNo, _ := runtime.Caller(1)
    fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x)
}

func main() {
    add(2, 7)
    b := true
    debug("b", b)
    s := "Hello"
    debug("s", s)
    p := point{2, 3}
    debug("p", p)
    q := &p
    debug("q", q)
}
Task: Find prime n such that reversed n is also prime

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

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

unsigned int reverse(unsigned int n) {
    unsigned int rev = 0;
    for (; n > 0; n /= 10)
        rev = rev * 10 + n % 10;
    return rev;
}

int main() {
    unsigned int count = 0;
    for (unsigned int n = 1; n < 500; ++n) {
        if (is_prime(n) && is_prime(reverse(n)))
            printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
    }
    printf("\nCount = %u\n", count);
    return 0;
}




Go: package main

import "fmt"

func sieve(limit int) []bool {
    limit++
    
    c := make([]bool, limit) 
    c[0] = true
    c[1] = true
    for i := 4; i < limit; i += 2 {
        c[i] = true
    }
    p := 3 
    for {
        p2 := p * p
        if p2 >= limit {
            break
        }
        for i := p2; i < limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    return c
}

func reversed(n int) int {
    rev := 0
    for n > 0 {
        rev = rev*10 + n%10
        n /= 10
    }
    return rev
}

func main() {
    c := sieve(999)
    reversedPrimes := []int{2}
    for i := 3; i < 500; i += 2 {
        if !c[i] && !c[reversed(i)] {
            reversedPrimes = append(reversedPrimes, i)
        }
    }
    fmt.Println("Primes under 500 which are also primes when the digits are reversed:")
    for i, p := range reversedPrimes {
        fmt.Printf("%5d", p)
        if (i+1) % 10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\n%d such primes found.\n", len(reversedPrimes))
}
Task: Superellipse

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

#define pi M_PI

int main(){
	
	double a,b,n,i,incr = 0.0001;
	
	printf("Enter major and minor axes of the SuperEllipse : ");
	scanf("%lf%lf",&a,&b);
	
	printf("Enter n : ");
	scanf("%lf",&n);
	
	initwindow(500,500,"Superellipse");
	
	for(i=0;i<2*pi;i+=incr){
		putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
	}
	
	printf("Done. %lf",i);
	
	getch();
	
	closegraph();
}




Go: package main

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


func superEllipse(dc *gg.Context, n float64, a int) {
    hw := float64(dc.Width() / 2)
    hh := float64(dc.Height() / 2)

    
    y := make([]float64, a+1)
    for x := 0; x <= a; x++ {
        aa := math.Pow(float64(a), n)
        xx := math.Pow(float64(x), n)
        y[x] = math.Pow(aa-xx, 1.0/n)
    }

    
    for x := a; x >= 0; x-- {
        dc.LineTo(hw+float64(x), hh-y[x])
    }
    for x := 0; x <= a; x++ {
        dc.LineTo(hw+float64(x), hh+y[x])
    }
    for x := a; x >= 0; x-- {
        dc.LineTo(hw-float64(x), hh+y[x])
    }
    for x := 0; x <= a; x++ {
        dc.LineTo(hw-float64(x), hh-y[x])
    }

    dc.SetRGB(1, 1, 1) 
    dc.Fill()
}

func main() {
    dc := gg.NewContext(500, 500)
    dc.SetRGB(0, 0, 0) 
    dc.Clear()
    superEllipse(dc, 2.5, 200)
    dc.SavePNG("superellipse.png")
}
Task: Permutations_Rank of a permutation

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

#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)

void _mr_unrank1(int rank, int n, int *vec) {
    int t, q, r;
    if (n < 1) return;

    q = rank / n;
    r = rank % n;
    SWAP(vec[r], vec[n-1]);
    _mr_unrank1(q, n-1, vec);
}

int _mr_rank1(int n, int *vec, int *inv) {
    int s, t;
    if (n < 2) return 0;

    s = vec[n-1];
    SWAP(vec[n-1], vec[inv[n-1]]);
    SWAP(inv[s], inv[n-1]);
    return s + n * _mr_rank1(n-1, vec, inv);
}


void get_permutation(int rank, int n, int *vec) {
    int i;
    for (i = 0; i < n; ++i) vec[i] = i;
    _mr_unrank1(rank, n, vec);
}


int get_rank(int n, int *vec) {
    int i, r, *v, *inv;

    v = malloc(n * sizeof(int));
    inv = malloc(n * sizeof(int));

    for (i = 0; i < n; ++i) {
        v[i] = vec[i];
        inv[vec[i]] = i;
    }
    r = _mr_rank1(n, v, inv);
    free(inv);
    free(v);
    return r;
}

int main(int argc, char *argv[]) {
    int i, r, tv[4];

    for (r = 0; r < 24; ++r) {
        printf("%3d: ", r);
        get_permutation(r, 4, tv);

        for (i = 0; i < 4; ++i) {
            if (0 == i) printf("[ ");
            else printf(", ");
            printf("%d", tv[i]);
        }
        printf(" ] = %d\n", get_rank(4, tv));
    }
}




Go: package main

import (
    "fmt"
    "math/rand"
)


func MRPerm(q, n int) []int {
    p := ident(n)
    var r int
    for n > 0 {
        q, r = q/n, q%n
        n--
        p[n], p[r] = p[r], p[n]
    }
    return p
}


func ident(n int) []int {
    p := make([]int, n)
    for i := range p {
        p[i] = i
    }
    return p
}


func MRRank(p []int) (r int) {
    p = append([]int{}, p...)
    inv := inverse(p)
    for i := len(p) - 1; i > 0; i-- {
        s := p[i]
        p[inv[i]] = s
        inv[s] = inv[i]
    }
    for i := 1; i < len(p); i++ {
        r = r*(i+1) + p[i]
    }
    return
}


func inverse(p []int) []int {
    r := make([]int, len(p))
    for i, x := range p {
        r[x] = i
    }
    return r
}


func fact(n int) (f int) {
    for f = n; n > 2; {
        n--
        f *= n
    }
    return
}

func main() {
    n := 3
    fmt.Println("permutations of", n, "items")
    f := fact(n)
    for i := 0; i < f; i++ {
        p := MRPerm(i, n)
        fmt.Println(i, p, MRRank(p))
    }
    n = 12
    fmt.Println("permutations of", n, "items")
    f = fact(n)
    m := map[int]bool{}
    for len(m) < 4 {
        r := rand.Intn(f)
        if m[r] {
            continue
        }
        m[r] = true
        fmt.Println(r, MRPerm(r, n))
    }
}
Task: Range extraction

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

size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "") 
#define ol (s ? 100 : 0)       
	int i, j;
	char *a = s;
	for (i = j = 0; i < len; i = ++j) {
		for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);

		if (i + 1 < j)
			a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
		else
			while (i <= j)
				a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
	}
	return a - s;
#undef sep
#undef ol
}

int main()
{
	int x[] = {	0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
			15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
			25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
			37, 38, 39 };

	char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
	rprint(s, x, sizeof(x) / sizeof(int));
	printf("%s\n", s);

	return 0;
}




Go: package main

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

func main() {
    rf, err := rangeFormat([]int{
        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
        37, 38, 39,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("range format:", rf)
}

func rangeFormat(a []int) (string, error) {
    if len(a) == 0 {
        return "", nil
    }
    var parts []string
    for n1 := 0; ; {
        n2 := n1 + 1
        for n2 < len(a) && a[n2] == a[n2-1]+1 {
            n2++
        }
        s := strconv.Itoa(a[n1])
        if n2 == n1+2 {
            s += "," + strconv.Itoa(a[n2-1])
        } else if n2 > n1+2 {
            s += "-" + strconv.Itoa(a[n2-1])
        }
        parts = append(parts, s)
        if n2 == len(a) {
            break
        }
        if a[n2] == a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence repeats value %d", a[n2]))
        }
        if a[n2] < a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence not ordered: %d < %d", a[n2], a[n2-1]))
        }
        n1 = n2
    }
    return strings.Join(parts, ","), nil
}
Task: Machine code

C: #include <stdio.h>
#include <sys/mman.h>
#include <string.h>

int test (int a, int b)
{
  
  char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
  void *buf;
  int c;
  
  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
             MAP_PRIVATE|MAP_ANON,-1,0);

  memcpy (buf, code, sizeof(code));
  
  c = ((int (*) (int, int))buf)(a, b);
  
  munmap (buf, sizeof(code));
  return c;
}

int main ()
{
  printf("%d\n", test(7,12));
  return 0;
}




Go: package main

import "fmt"


import "C"

func main() {
    code := []byte{
        0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
        0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
        0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
        0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,
    }
    le := len(code)
    buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,
        C.MAP_PRIVATE|C.MAP_ANON, -1, 0)
    codePtr := C.CBytes(code)
    C.memcpy(buf, codePtr, C.size_t(le))
    var a, b byte = 7, 12
    fmt.Printf("%d + %d = ", a, b)
    C.runMachineCode(buf, C.byte(a), C.byte(b))
    C.munmap(buf, C.size_t(le))
    C.free(codePtr)
}
Task: Type detection

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

void typeDetector(char* str){	
	if(isalnum(str[0])!=0)
		printf("\n%c is alphanumeric",str[0]);
	if(isalpha(str[0])!=0)
		printf("\n%c is alphabetic",str[0]);
	if(iscntrl(str[0])!=0)
		printf("\n%c is a control character",str[0]);
	if(isdigit(str[0])!=0)
		printf("\n%c is a digit",str[0]);
	if(isprint(str[0])!=0)
		printf("\n%c is printable",str[0]);
	if(ispunct(str[0])!=0)
		printf("\n%c is a punctuation character",str[0]);
	if(isxdigit(str[0])!=0)
		printf("\n%c is a hexadecimal digit",str[0]);
}

int main(int argC, char* argV[])
{
	int i;
	
	if(argC==1)
		printf("Usage : %s <followed by ASCII characters>");
	else{
		for(i=1;i<argC;i++)
			typeDetector(argV[i]);
	}
	return 0;
}




Go: package main

import "fmt"

type any = interface{}

func showType(a any) {
    switch a.(type) {
    case rune:
        fmt.Printf("The type of '%c' is %T\n", a, a)
    default:
        fmt.Printf("The type of '%v' is %T\n", a, a)
    }
}

func main() {
    values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"}
    for _, value := range values {
        showType(value)
    }
}