WeixiangYan/CodeTransOcean huggingface dataset:
Task: Extreme floating point values

C: #include <stdio.h>

int main()
{
    double inf = 1/0.0;
    double minus_inf = -1/0.0;
    double minus_zero = -1/ inf ;
    double nan = 0.0/0.0;

    printf("positive infinity: %f\n",inf);
    printf("negative infinity: %f\n",minus_inf);
    printf("negative zero: %f\n",minus_zero);
    printf("not a number: %f\n",nan);

    

    printf("+inf + 2.0 = %f\n",inf + 2.0);
    printf("+inf - 10.1 = %f\n",inf - 10.1);
    printf("+inf + -inf = %f\n",inf + minus_inf);
    printf("0.0 * +inf = %f\n",0.0 * inf);
    printf("1.0/-0.0 = %f\n",1.0/minus_zero);
    printf("NaN + 1.0 = %f\n",nan + 1.0);
    printf("NaN + NaN = %f\n",nan + nan);

    

    printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
    printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");

    return 0;
}




Go: package main

import (
    "fmt"
    "math"
)

func main() {
    
    var zero float64                         
    var negZero, posInf, negInf, nan float64 
    negZero = zero * -1
    posInf = 1 / zero
    negInf = -1 / zero
    nan = zero / zero

    
    fmt.Println(negZero, posInf, negInf, nan)

    
    fmt.Println(math.Float64frombits(1<<63),
        math.Inf(1), math.Inf(-1), math.NaN())

    
    fmt.Println()
    validateNaN(negInf+posInf, "-Inf + Inf")
    validateNaN(0*posInf, "0 * Inf")
    validateNaN(posInf/posInf, "Inf / Inf")
    
    
    validateNaN(math.Mod(posInf, 1), "Inf % 1")
    validateNaN(1+nan, "1 + NaN")
    validateZero(1/posInf, "1 / Inf")
    validateGT(posInf, math.MaxFloat64, "Inf > max value")
    validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
    validateNE(nan, nan, "NaN != NaN")
    validateEQ(negZero, 0, "-0 == 0")
}

func validateNaN(n float64, op string) {
    if math.IsNaN(n) {
        fmt.Println(op, "-> NaN")
    } else {
        fmt.Println("!!! Expected NaN from", op, "  Found", n)
    }
}

func validateZero(n float64, op string) {
    if n == 0 {
        fmt.Println(op, "-> 0")
    } else {
        fmt.Println("!!! Expected 0 from", op, "  Found", n)
    }
}

func validateGT(a, b float64, op string) {
    if a > b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}

func validateNE(a, b float64, op string) {
    if a == b {
        fmt.Println("!!! Expected", op, "  Found not true.")
    } else {
        fmt.Println(op)
    }
}

func validateEQ(a, b float64, op string) {
    if a == b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}
Task: Pseudo-random numbers_Xorshift star

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

static uint64_t state;
static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;

void seed(uint64_t num) {
    state = num;
}

uint32_t next_int() {
    uint64_t x;
    uint32_t answer;

    x = state;
    x = x ^ (x >> 12);
    x = x ^ (x << 25);
    x = x ^ (x >> 27);
    state = x;
    answer = ((x * STATE_MAGIC) >> 32);

    return answer;
}

float next_float() {
    return (float)next_int() / (1LL << 32);
}

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

    seed(1234567);
    printf("%u\n", next_int());
    printf("%u\n", next_int());
    printf("%u\n", next_int());
    printf("%u\n", next_int());
    printf("%u\n", next_int());
    printf("\n");

    seed(987654321);
    for (i = 0; i < 100000; i++) {
        int j = (int)floor(next_float() * 5.0);
        counts[j]++;
    }
    for (i = 0; i < 5; i++) {
        printf("%d: %d\n", i, counts[i]);
    }

    return 0;
}




Go: package main

import (
    "fmt"
    "math"
)

const CONST = 0x2545F4914F6CDD1D

type XorshiftStar struct{ state uint64 }

func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }

func (xor *XorshiftStar) seed(state uint64) { xor.state = state }

func (xor *XorshiftStar) nextInt() uint32 {
    x := xor.state
    x = x ^ (x >> 12)
    x = x ^ (x << 25)
    x = x ^ (x >> 27)
    xor.state = x
    return uint32((x * CONST) >> 32)
}

func (xor *XorshiftStar) nextFloat() float64 {
    return float64(xor.nextInt()) / (1 << 32)
}

func main() {
    randomGen := XorshiftStarNew(1234567)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321)
    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: Levenshtein distance_Alignment

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

typedef struct edit_s edit_t, *edit;
struct edit_s {
	char c1, c2;
	int n;
	edit next;
};

void leven(char *a, char *b)
{
	int i, j, la = strlen(a), lb = strlen(b);
	edit *tbl = malloc(sizeof(edit) * (1 + la));
	tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));
	for (i = 1; i <= la; i++)
		tbl[i] = tbl[i-1] + (1+lb);

	for (i = la; i >= 0; i--) {
		char *aa = a + i;
		for (j = lb; j >= 0; j--) {
			char *bb = b + j;
			if (!*aa && !*bb) continue;

			edit e = &tbl[i][j];
			edit repl = &tbl[i+1][j+1];
			edit dela = &tbl[i+1][j];
			edit delb = &tbl[i][j+1];

			e->c1 = *aa;
			e->c2 = *bb;
			if (!*aa) {
				e->next = delb;
				e->n = e->next->n + 1;
				continue;
			}
			if (!*bb) {
				e->next = dela;
				e->n = e->next->n + 1;
				continue;
			}

			e->next = repl;
			if (*aa == *bb) {
				e->n = e->next->n;
				continue;
			}

			if (e->next->n > delb->n) {
				e->next = delb;
				e->c1 = 0;
			}
			if (e->next->n > dela->n) {
				e->next = dela;
				e->c1 = *aa;
				e->c2 = 0;
			}
			e->n = e->next->n + 1;
		}
	}

	edit p = tbl[0];
	printf("%s -> %s: %d edits\n", a, b, p->n);

	while (p->next) {
		if (p->c1 == p->c2)
			printf("%c", p->c1);
		else {
			putchar('(');
			if (p->c1) putchar(p->c1);
			putchar(',');
			if (p->c2) putchar(p->c2);
			putchar(')');
		}

		p = p->next;
	}
	putchar('\n');

	free(tbl[0]);
	free(tbl);
}

int main(void)
{
	leven("raisethysword", "rosettacode");
	return 0;
}




Go: package main

import (
    "fmt"

    "github.com/biogo/biogo/align"
    ab "github.com/biogo/biogo/alphabet"
    "github.com/biogo/biogo/feat"
    "github.com/biogo/biogo/seq/linear"
)

func main() {
    
    
    lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz",
        feat.Undefined, '-', 0, true))
    
    
    
    
    nw := make(align.NW, lc.Len())
    for i := range nw {
        r := make([]int, lc.Len())
        nw[i] = r
        for j := range r {
            if j != i {
                r[j] = -1
            }
        }
    }
    
    a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))}
    a.Alpha = lc
    b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))}
    b.Alpha = lc
    
    aln, err := nw.Align(a, b)
    
    if err != nil {
        fmt.Println(err)
        return
    }
    fa := align.Format(a, b, aln, '-')
    fmt.Printf("%s\n%s\n", fa[0], fa[1])
    aa := fmt.Sprint(fa[0])
    ba := fmt.Sprint(fa[1])
    ma := make([]byte, len(aa))
    for i := range ma {
        if aa[i] == ba[i] {
            ma[i] = ' '
        } else {
            ma[i] = '|'
        }
    }
    fmt.Println(string(ma))
}
Task: Same fringe

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

typedef struct {
	ucontext_t caller, callee;
	char stack[8192];
	void *in, *out;
} co_t;

co_t * co_new(void(*f)(), void *data)
{
	co_t * c = malloc(sizeof(*c));
	getcontext(&c->callee);
	c->in = data;

	c->callee.uc_stack.ss_sp = c->stack;
	c->callee.uc_stack.ss_size = sizeof(c->stack);
	c->callee.uc_link = &c->caller;
	makecontext(&c->callee, f, 1, (int)c);

	return c;
}

void co_del(co_t *c)
{
	free(c);
}

inline void
co_yield(co_t *c, void *data)
{
	c->out = data;
	swapcontext(&c->callee, &c->caller);
}

inline void *
co_collect(co_t *c)
{
	c->out = 0;
	swapcontext(&c->caller, &c->callee);
	return c->out;
}



typedef struct node node;
struct node {
	int v;
	node *left, *right;
};

node *newnode(int v)
{
	node *n = malloc(sizeof(node));
	n->left = n->right = 0;
	n->v = v;
	return n;
}

void tree_insert(node **root, node *n)
{
	while (*root) root = ((*root)->v > n->v)
				? &(*root)->left
				: &(*root)->right;
	*root = n;
}

void tree_trav(int x)
{
	co_t *c = (co_t *) x;

	void trav(node *root) {
		if (!root) return;
		trav(root->left);
		co_yield(c, root);
		trav(root->right);
	}

	trav(c->in);
}

int tree_eq(node *t1, node *t2)
{
	co_t *c1 = co_new(tree_trav, t1);
	co_t *c2 = co_new(tree_trav, t2);

	node *p = 0, *q = 0;
	do {
		p = co_collect(c1);
		q = co_collect(c2);
	} while (p && q && (p->v == q->v));

	co_del(c1);
	co_del(c2);
	return !p && !q;
}

int main()
{
	int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
	int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
	int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };

	node *t1 = 0, *t2 = 0, *t3 = 0;

	void mktree(int *buf, node **root) {
		int i;
		for (i = 0; buf[i] >= 0; i++)
			tree_insert(root, newnode(buf[i]));
	}

	mktree(x, &t1); 
	mktree(y, &t2); 
	mktree(z, &t3);

	printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no");
	printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no");

	return 0;
}




Go: package main

import "fmt"

type node struct {
    int
    left, right *node
}



func leaves(t *node) chan int {
    ch := make(chan int)
    
    var f func(*node)
    f = func(n *node) {
        if n == nil {
            return
        }
        
        if n.left == nil && n.right == nil {
            ch <- n.int
        } else {
            f(n.left)
            f(n.right)
        }
    }
    
    
    go func() {
        f(t)
        close(ch)
    }()
    return ch
}

func sameFringe(t1, t2 *node) bool {
    f1 := leaves(t1)
    f2 := leaves(t2)
    for l1 := range f1 {
        
        if l2, ok := <-f2; !ok || l1 != l2 {
            return false
        }
    }
    
    _, ok := <-f2
    return !ok
}

func main() {
    
    
    t1 := &node{3,
        &node{1,
            &node{int: 1},
            &node{int: 2}},
        &node{8,
            &node{int: 5},
            &node{int: 13}}}
    
    
    t2 := &node{-8,
        &node{-3,
            &node{-1,
                &node{int: 1},
                &node{int: 2}},
            &node{int: 5}},
        &node{int: 13}}
    fmt.Println(sameFringe(t1, t2)) 
}
Task: Parse command-line arguments

C: #include <stdio.h>
int main(int argc, char **argv){
    int i;
    const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
    enum {CREATE,PRINT,TITLE,DATE,AUTH};
    if (argc<2) {
usage:   printf ("Usage: %s [commands]\n" 
            "-c  Create new entry.\n" 
            "-p  Print the latest entry.\n" 
            "-t  Sort by title.\n" 
            "-d  Sort by date.\n" 
            "-a  Sort by author.\n",argv[0]);
        return 0;
    }
    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
    switch (i) {
    case CREATE:
...
    break;
    case PRINT:
...
    break;
...
...
    default:
    printf ("Unknown command..." ...);
    goto usage;
    }
    return 0;
}




Go: package main

import (
    "flag"
    "fmt"
)

func main() {
    b := flag.Bool("b", false, "just a boolean")
    s := flag.String("s", "", "any ol' string")
    n := flag.Int("n", 0, "your lucky number")
    flag.Parse()
    fmt.Println("b:", *b)
    fmt.Println("s:", *s)
    fmt.Println("n:", *n)
}
Task: Show the (decimal) value of a number of 1s appended with a 3, then squared

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

uint64_t ones_plus_three(uint64_t ones) {
    uint64_t r = 0;
    while (ones--) r = r*10 + 1;
    return r*10 + 3;
}

int main() {
    uint64_t n;
    for (n=0; n<8; n++) {
        uint64_t x = ones_plus_three(n);
        printf("%8lu^2 = %15lu\n", x, x*x);
    }
    return 0;
}




Go: package main

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

func a(n int) {
    s, _ := strconv.Atoi(strings.Repeat("1", n) + "3")
    t := s * s
    fmt.Printf("%d %d\n", s, t)
}

func main() {
    for n := 0; n <= 7; n++ {
        a(n)
    }
}
Task: Simulate input_Keyboard

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

int main(int argc, char *argv[])
{
  Display *dpy;
  Window win;
  GC gc;
  int scr;
  Atom WM_DELETE_WINDOW;
  XEvent ev;
  XEvent ev2;
  KeySym keysym;
  int loop;

  
  dpy = XOpenDisplay(NULL);
  if (dpy == NULL) {
    fputs("Cannot open display", stderr);
    exit(1);
  }
  scr = XDefaultScreen(dpy);

  
  win = XCreateSimpleWindow(dpy,
          XRootWindow(dpy, scr),
          
          10, 10, 300, 200, 1,
          
          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));

  
  XStoreName(dpy, win, argv[0]);

  
  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);

  
  XMapWindow(dpy, win);
  XFlush(dpy);

  
  gc = XDefaultGC(dpy, scr);

  
  WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True);
  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);

  
  loop = 1;
  while (loop) {
    XNextEvent(dpy, &ev);
    switch (ev.type)
    {
      case Expose:
        
        {
          char msg1[] = "Clic in the window to generate";
          char msg2[] = "a key press event";
          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);
          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);
        }
        break;

      case ButtonPress:
        puts("ButtonPress event received");
        
        ev2.type = KeyPress;
        ev2.xkey.state = ShiftMask;
        ev2.xkey.keycode = 24 + (rand() % 33);
        ev2.xkey.same_screen = True;
        XSendEvent(dpy, win, True, KeyPressMask, &ev2);
        break;
   
      case ClientMessage:
        
        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)
          loop = 0;
        break;
   
      case KeyPress:
        
        puts("KeyPress event received");
        printf("> keycode: %d\n", ev.xkey.keycode);
        
        keysym = XLookupKeysym(&(ev.xkey), 0);
        if (keysym == XK_q ||
            keysym == XK_Escape) {
          loop = 0;
        } else {
          char buffer[] = "  ";
          int nchars = XLookupString(
                &(ev.xkey),
                buffer,
                2,  
                &keysym,
                NULL );
          if (nchars == 1)
            printf("> Key '%c' pressed\n", buffer[0]);
        }
        break;
    }
  }
  XDestroyWindow(dpy, win);
  
  XCloseDisplay(dpy);
  return 1;
}




Go: package main

import (
    "github.com/micmonay/keybd_event"
    "log"
    "runtime"
    "time"
)

func main() {
    kb, err := keybd_event.NewKeyBonding()
    if err != nil {
        log.Fatal(err)
    }

    
    if runtime.GOOS == "linux" {
        time.Sleep(2 * time.Second)
    }

    
    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)

    
    err = kb.Launching()
    if err != nil {
        log.Fatal(err)
    }
}
Task: Loops_Infinite

C: while(1) puts("SPAM");




Go: package main

import "fmt"

func main() {
	for {
		fmt.Printf("SPAM\n")
	}
}
Task: Metaprogramming

C: 
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]

#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)
#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)
#define COMPILE_TIME_ASSERT(X)    COMPILE_TIME_ASSERT2(X,__LINE__)

COMPILE_TIME_ASSERT(sizeof(long)==8); 
int main()
{
    COMPILE_TIME_ASSERT(sizeof(int)==4); 
}




Go: package main

import "fmt"

type person struct{
    name string
    age int
}

func copy(p person) person {
    return person{p.name, p.age}
}

func main() {
    p := person{"Dave", 40}
    fmt.Println(p)
    q := copy(p)
    fmt.Println(q)
     
}
Task: Numbers with same digit set in base 10 and base 16

C: #include <stdio.h>
#define LIMIT 100000

int digitset(int num, int base) {
    int set;
    for (set = 0; num; num /= base)
        set |= 1 << num % base;
    return set;
}

int main() {
    int i, c = 0;
    for (i = 0; i < LIMIT; i++)
        if (digitset(i,10) == digitset(i,16))
            printf("%6d%c", i, ++c%10 ? ' ' : '\n');
    printf("\n");
    return 0;
}




Go: package main

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

func equalSets(s1, s2 map[rune]bool) bool {
    if len(s1) != len(s2) {
        return false
    }
    for k, _ := range s1 {
        _, ok := s2[k]
        if !ok {
            return false
        }
    }
    return true
}

func main() {
    const limit = 100_000
    count := 0
    fmt.Println("Numbers under 100,000 which use the same digits in decimal or hex:")
    for n := 0; n < limit; n++ {
        h := strconv.FormatInt(int64(n), 16)
        hs := make(map[rune]bool)
        for _, c := range h {
            hs[c] = true
        }
        ns := make(map[rune]bool)
        for _, c := range strconv.Itoa(n) {
            ns[c] = true
        }
        if equalSets(hs, ns) {
            count++
            fmt.Printf("%6s ", rcu.Commatize(n))
            if count%10 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Printf("\n\n%d such numbers found.\n", count)
}
Task: Largest prime factor

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

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

int main(void) {
    long int n=600851475143, j=3;

    while(!isprime(n)) {
        if(!(n%j)) n/=j;
        j+=2;
    }
    printf( "%ld\n", n );
    return 0;
}




Go: package main

import "fmt"

func largestPrimeFactor(n uint64) uint64 {
    if n < 2 {
        return 1
    }
    inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6}
    max := uint64(1)
    for n%2 == 0 {
        max = 2
        n /= 2
    }
    for n%3 == 0 {
        max = 3
        n /= 3
    }
    for n%5 == 0 {
        max = 5
        n /= 5
    }
    k := uint64(7)
    i := 0
    for k*k <= n {
        if n%k == 0 {
            max = k
            n /= k
        } else {
            k += inc[i]
            i = (i + 1) % 8
        }
    }
    if n > 1 {
        return n
    }
    return max
}

func main() {
    n := uint64(600851475143)
    fmt.Println("The largest prime factor of", n, "is", largestPrimeFactor(n), "\b.")
}
Task: Largest proper divisor of n

C: #include <stdio.h>

unsigned int lpd(unsigned int n) {
    if (n<=1) return 1;
    int i;
    for (i=n-1; i>0; i--)
        if (n%i == 0) return i;   
}

int main() {
    int i;
    for (i=1; i<=100; i++) {
        printf("%3d", lpd(i));
        if (i % 10 == 0) printf("\n");
    }
    return 0;
}




Go: package main

import "fmt"

func largestProperDivisor(n int) int {
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            return n / i
        }
    }
    return 1
}

func main() {
    fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
    fmt.Print(" 1  ")
    for n := 2; n <= 100; n++ {
        if n%2 == 0 {
            fmt.Printf("%2d  ", n/2)
        } else {
            fmt.Printf("%2d  ", largestProperDivisor(n))
        }
        if n%10 == 0 {
            fmt.Println()
        }
    }
}
Task: Three word location

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

typedef long long int64;
 
void to_word(char *ws, int64 w) {
    sprintf(ws, "W%05lld", w);
}

int64 from_word(char *ws) {
    return atoi(++ws);
}

int main() {
    double lat, lon;
    int64 latlon, ilat, ilon, w1, w2, w3;
    char w1s[7], w2s[7], w3s[7];
    printf("Starting figures:\n");
    lat = 28.3852;
    lon = -81.5638;
    printf("  latitude = %0.4f, longitude = %0.4f\n", lat, lon);
 
    
    ilat = (int64)(lat*10000 + 900000);
    ilon = (int64)(lon*10000 + 1800000);
 
    
    latlon = (ilat << 22) + ilon;

    
    w1 = (latlon >> 28) & 0x7fff;
    w2 = (latlon >> 14) & 0x3fff;
    w3 = latlon & 0x3fff;

    
    to_word(w1s, w1);
    to_word(w2s, w2);
    to_word(w3s, w3);
 
    
    printf("\nThree word location is:\n");
    printf("  %s %s %s\n", w1s, w2s, w3s);

    
    w1 = from_word(w1s);
    w2 = from_word(w2s);
    w3 = from_word(w3s);

    latlon = (w1 << 28) | (w2 << 14) | w3;
    ilat = latlon >> 22;
    ilon = latlon & 0x3fffff;
    lat = (double)(ilat-900000) / 10000;
    lon = (double)(ilon-1800000) / 10000;

    
    printf("\nAfter reversing the procedure:\n");
    printf("  latitude = %0.4f, longitude = %0.4f\n", lat, lon);
    return 0;
}




Go: package main

import (
    "fmt"
    "strconv"
)

func toWord(w int64) string { return fmt.Sprintf("W%05d", w) }

func fromWord(ws string) int64 {
    var u, _ = strconv.ParseUint(ws[1:], 10, 64)
    return int64(u)
}

func main() {
    fmt.Println("Starting figures:")
    lat := 28.3852
    lon := -81.5638
    fmt.Printf("  latitude = %0.4f, longitude = %0.4f\n", lat, lon)

    
    ilat := int64(lat*10000 + 900000)
    ilon := int64(lon*10000 + 1800000)

    
    latlon := (ilat << 22) + ilon

    
    w1 := (latlon >> 28) & 0x7fff
    w2 := (latlon >> 14) & 0x3fff
    w3 := latlon & 0x3fff

    
    w1s := toWord(w1)
    w2s := toWord(w2)
    w3s := toWord(w3)

    
    fmt.Println("\nThree word location is:")
    fmt.Printf("  %s %s %s\n", w1s, w2s, w3s)

    
    w1 = fromWord(w1s)
    w2 = fromWord(w2s)
    w3 = fromWord(w3s)

    latlon = (w1 << 28) | (w2 << 14) | w3
    ilat = latlon >> 22
    ilon = latlon & 0x3fffff
    lat = float64(ilat-900000) / 10000
    lon = float64(ilon-1800000) / 10000

    
    fmt.Println("\nAfter reversing the procedure:")
    fmt.Printf("  latitude = %0.4f, longitude = %0.4f\n", lat, lon)
}
Task: Move-to-front algorithm

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

#define MAX_SIZE 100

int move_to_front(char *str,char c)
{
    char *q,*p;
    int shift=0;
    p=(char *)malloc(strlen(str)+1);
    strcpy(p,str);
    q=strchr(p,c); 
    shift=q-p;      
    strncpy(str+1,p,shift);
    str[0]=c;
    free(p);
  
    return shift;
}

void decode(int* pass,int size,char *sym)
{
    int i,index;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=table[pass[i]];
        index=move_to_front(table,c);
        if(pass[i]!=index) printf("there is an error");
        sym[i]=c;
    }
    sym[size]='\0';
}

void encode(char *sym,int size,int *pass)
{
    int i=0;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=sym[i];
        pass[i]=move_to_front(table,c);
    }
}

int check(char *sym,int size,int *pass)
{
    int *pass2=malloc(sizeof(int)*size);
    char *sym2=malloc(sizeof(char)*size);
    int i,val=1;

    encode(sym,size,pass2);
    i=0;
    while(i<size && pass[i]==pass2[i])i++;
    if(i!=size)val=0;

    decode(pass,size,sym2);
    if(strcmp(sym,sym2)!=0)val=0;

    free(sym2);
    free(pass2);

    return val;
}

int main()
{
    char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
    int pass[MAX_SIZE]={0};
    int i,len,j;
    for(i=0;i<3;i++)
    {
        len=strlen(sym[i]);
        encode(sym[i],len,pass);
        printf("%s : [",sym[i]);
        for(j=0;j<len;j++)
            printf("%d ",pass[j]);
        printf("]\n");
        if(check(sym[i],len,pass))
            printf("Correct :)\n");
        else
            printf("Incorrect :(\n");
    }
    return 0;
}




Go: package main

import (
	"bytes"
	"fmt"
)

type symbolTable string

func (symbols symbolTable) encode(s string) []byte {
	seq := make([]byte, len(s))
	pad := []byte(symbols)
	for i, c := range []byte(s) {
		x := bytes.IndexByte(pad, c)
		seq[i] = byte(x)
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return seq
}

func (symbols symbolTable) decode(seq []byte) string {
	chars := make([]byte, len(seq))
	pad := []byte(symbols)
	for i, x := range seq {
		c := pad[x]
		chars[i] = c
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return string(chars)
}

func main() {
	m := symbolTable("abcdefghijklmnopqrstuvwxyz")
	for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
		enc := m.encode(s)
		dec := m.decode(enc)
		fmt.Println(s, enc, dec)
		if dec != s {
			panic("Whoops!")
		}
	}
}