10001th prime

#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 prime( int n ) {
    int p, pn=1;
    if(n==1) return 2;
    for(p=3;pn<n;p+=2) {
        if(isprime(p)) pn++;
    }
    return p-2;
}

int main(void) {
    printf( "%d\n", prime(10001) );
    return 0;
}

fn main() {
    let p = primal::StreamingSieve::nth_prime(10001);
    println!("The 10001st prime is {}.", p);
}


15 puzzle solver

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

typedef unsigned char u8t;
typedef unsigned short u16t;
enum { NR=4, NC=4, NCELLS = NR*NC };
enum { UP, DOWN, LEFT, RIGHT, NDIRS };
enum { OK = 1<<8, XX = 1<<9, FOUND = 1<<10, zz=0x80 };
enum { MAX_INT=0x7E, MAX_NODES=(16*65536)*90};
enum { BIT_HDR=1<<0, BIT_GRID=1<<1, BIT_OTHER=1<<2 };
enum { PHASE1,PHASE2 };

typedef struct { u16t dn; u16t hn; }HSORT_T;

typedef struct {
   u8t data[NCELLS]; unsigned id; unsigned src;
   u8t h; u8t g; u8t udlr;
}NODE_T;

NODE_T goal44={
   {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,0},0,0,0,0,0};
NODE_T work;

NODE_T G34={
 {13,9,5,4, 15,6,1,8, 0,10,2,11, 14,3,7,12},0,0,0,0,0};

NODE_T G52={
   {15,13,9,5, 14,6,1,4,  10,12,0,8, 3,7,11,2},0,0,0,0,0};

NODE_T G99={
   {15,14,1,6, 9,11,4,12, 0,10,7,3, 13,8,5,2},0,0,0,0,0};

struct {
   unsigned nodes;
   unsigned gfound;
   unsigned root_visits;
   unsigned verbose;
   unsigned locks;
   unsigned phase;
}my;

u16t  HybridIDA_star(NODE_T *pNode);
u16t  make_node(NODE_T *pNode, NODE_T *pNew, u8t udlr );
u16t  search(NODE_T *pNode, u16t bound);
u16t  taxi_dist( NODE_T *pNode);
u16t  tile_home( NODE_T *p44);
void  print_node( NODE_T *pN, const char *pMsg, short force );
u16t  goal_found(NODE_T *pNode);
char  udlr_to_char( char udlr );
void  idx_to_rc( u16t idx, u16t *row, u16t *col );
void  sort_nodes(HSORT_T *p);

int main( )
{
   my.verbose = 0;

   memcpy(&work,  &G99, sizeof(NODE_T));
   if(1){
      printf("Phase1: IDA* search for 1234 permutation..\n");
      my.phase = PHASE1;
      (void) HybridIDA_star(&work);
   }
   printf("Phase2: IDA* search phase1 seed..\n");
   my.phase = PHASE2;
   (void)HybridIDA_star(&work);
   return 0;
}

u16t HybridIDA_star(NODE_T *pN){
   my.nodes = 1;
   my.gfound = 0;
   my.root_visits = 0;
   pN->udlr = NDIRS;
   pN->g = 0;
   pN->h = taxi_dist(pN);
   pN->id = my.nodes;
   pN->src = 0;
   const char *pr = {"Start"};
   print_node( pN,pr,1 );
   u16t depth = pN->h;
   while(1){
      depth = search(pN,depth);
      if( depth & FOUND){
         return FOUND;
      }
      if( depth & 0xFF00 ){
	 printf("..error %x\n",depth);
	 return XX;
      }
      my.root_visits++;
      printf("[root visits: %u, depth %u]\n",my.root_visits,depth);
   }
   return 0;
}

u16t search(NODE_T *pN, u16t bound){
   if(bound & 0xff00){ return bound; }
   u16t f = pN->g + pN->h;
   if( f > bound){ return f; }
   if(goal_found(pN)){
      my.gfound = pN->g;
      memcpy(&work,pN,sizeof(NODE_T));
      printf("total nodes=%d, g=%u \n", my.nodes, my.gfound);
      const char *pr = {"Found.."};
      print_node( &work,pr,1 );
      return FOUND;
   }
   NODE_T news;

   HSORT_T hlist[NDIRS];
   for( short i=0; i<NDIRS; i++ ){
      u16t rv = make_node(pN,&news, i );
      hlist[i].dn = i;
      if( rv & OK ){
	 hlist[i].hn = news.h;
	 continue;
      }
      hlist[i].hn = XX;
   }
   sort_nodes(&hlist[0]);

   u16t temp, min = MAX_INT;
   for( short i=0; i<NDIRS; i++ ){
      if( hlist[i].hn > 0xff ) continue;
      temp = make_node(pN,&news, hlist[i].dn );
      if( temp & XX ) return XX;
      if( temp & OK ){
	 news.id = my.nodes++;
	 print_node(&news," succ",0 );
	 temp = search(&news, bound);
	 if(temp & 0xff00){  return temp;}
	 if(temp < min){ min = temp; }
      }
   }
   return min;
}

void sort_nodes(HSORT_T *p){
   for( short s=0; s<NDIRS-1; s++ ){
      HSORT_T tmp = p[0];
      if( p[1].hn < p[0].hn ){tmp=p[0]; p[0]=p[1]; p[1]=tmp; }
      if( p[2].hn < p[1].hn ){tmp=p[1]; p[1]=p[2]; p[2]=tmp; }
      if( p[3].hn < p[2].hn ){tmp=p[2]; p[2]=p[3]; p[3]=tmp; }
   }
}

u16t tile_home(NODE_T *pN ){
   for( short i=0; i<NCELLS; i++ ){
      if( pN->data[i] == 0 ) return i;
   }
   return XX;
}

void print_node( NODE_T *pN, const char *pMsg, short force ){
   const int tp1 = 0;
   if( my.verbose & BIT_HDR || force || tp1){
      char ch = udlr_to_char(pN->udlr);
      printf("id:%u src:%u; h=%d, g=%u, udlr=%c, %s\n",
	     pN->id, pN->src, pN->h, pN->g, ch, pMsg);
   }
   if(my.verbose & BIT_GRID || force || tp1){
      for(u16t i=0; i<NR; i++ ){
	 for( u16t j=0; j<NC; j++ ){
	    printf("%3d",pN->data[i*NR+j]);
	 }
	 printf("\n");
      }
      printf("\n");
   }

}

u16t goal_found(NODE_T *pN) {
   if(my.phase==PHASE1){
      short tags = 0;
      for( short i=0; i<(NC); i++ ){
	 if( pN->data[i] == i+1 ) tags++;
      }
      if( tags==4 ) return 1;
   }

   for( short i=0; i<(NR*NC); i++ ){
      if( pN->data[i] != goal44.data[i] ) return 0;
   }
   return 1;
}

char udlr_to_char( char udlr ){
   char ch = '?';
   switch(udlr){
   case UP:    ch = 'U'; break;
   case DOWN:  ch = 'D'; break;
   case LEFT:  ch = 'L'; break;
   case RIGHT: ch = 'R'; break;
   default: break;
   }
   return ch;
}

void idx_to_rc( u16t idx, u16t *row, u16t *col ){
   *row = idx/NR; *col = abs( idx - (*row * NR));
}

u16t make_node(NODE_T *pSrc, NODE_T *pNew, u8t udlr ){
   u16t row,col,home_idx,idx2;
   if(udlr>=NDIRS||udlr<0 ){ printf("invalid udlr %u\n",udlr); return XX; }
   if(my.nodes > MAX_NODES ){ printf("excessive nodes %u\n",my.nodes);
      return XX; }
   memcpy(pNew,pSrc,sizeof(NODE_T));
   home_idx = tile_home(pNew);
   idx_to_rc(home_idx, &row, &col );

   if( udlr == LEFT)  { if( col < 1 ) return 0; col--; }
   if( udlr == RIGHT ){ if( col >= (NC-1) ) return 0; col++; }
   if( udlr == DOWN ) { if(row >= (NR-1)) return 0; row++; }
   if( udlr == UP ){	 if(row < 1) return 0; row--; }
   idx2 = row * NR + col;
   if( idx2 < NCELLS ){
      u8t *p = &pNew->data[0];
      p[home_idx] = p[idx2];
      p[idx2]     = 0;
      pNew->src   = pSrc->id;
      pNew->g     = pSrc->g + 1;
      pNew->h     = taxi_dist(pNew);
      pNew->udlr  = udlr;
      return OK;
   }
   return 0;
}

u16t taxi_dist( NODE_T *pN){
   u16t tile,sum = 0, r1,c1,r2,c2;
   u8t *p44 = &pN->data[0];
   for( short i=0; i<(NR*NC); i++ ){
      tile = p44[i];
      if( tile==0 ) continue;
      idx_to_rc(i, &r2, &c2 );
      idx_to_rc(tile-1, &r1, &c1 );
      sum += abs(r1-r2) + abs(c1-c2);
   }
   }
   return sum;
}

const NR: [i32; 16] = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3];
const NC: [i32; 16] = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2];

const I: u8 = 1;
const G: u8 = 8;
const E: u8 = 2;
const L: u8 = 4;

struct FifteenSolver {
    n: usize,
    limit: usize,
    n0: [i32; 85],
    n3: [u8; 85],
    n4: [usize; 85],
    n2: [u64; 85],
}

impl FifteenSolver {
    fn f_y(&mut self) -> bool {
        if self.n2[self.n] == 0x123456789abcdef0 {
            return true;
        }
        if self.n4[self.n] <= self.limit {
            return self.f_n();
        }
        false
    }

    fn f_z(&mut self, w: u8) -> bool {
        if w & I != 0 {
            self.f_i();
            if self.f_y() {
                return true;
            }
            self.n -= 1;
        }
        if w & G != 0 {
            self.f_g();
            if self.f_y() {
                return true;
            }
            self.n -= 1;
        }
        if w & E != 0 {
            self.f_e();
            if self.f_y() {
                return true;
            }
            self.n -= 1;
        }
        if w & L != 0 {
            self.f_l();
            if self.f_y() {
                return true;
            }
            self.n -= 1;
        }
        false
    }

    fn f_n(&mut self) -> bool {
        self.f_z(match self.n0[self.n] {
            0 => match self.n3[self.n] {
                b'l' => I,
                b'u' => E,
                _ => I + E,
            },
            3 => match self.n3[self.n] {
                b'r' => I,
                b'u' => L,
                _ => I + L,
            },
            1 | 2 => match self.n3[self.n] {
                b'l' => I + L,
                b'r' => I + E,
                b'u' => E + L,
                _ => L + E + I,
            },
            12 => match self.n3[self.n] {
                b'l' => G,
                b'd' => E,
                _ => E + G,
            },
            15 => match self.n3[self.n] {
                b'r' => G,
                b'd' => L,
                _ => G + L,
            },
            13 | 14 => match self.n3[self.n] {
                b'l' => G + L,
                b'r' => E + G,
                b'd' => E + L,
                _ => G + E + L,
            },
            4 | 8 => match self.n3[self.n] {
                b'l' => I + G,
                b'u' => G + E,
                b'd' => I + E,
                _ => I + G + E,
            },
            7 | 11 => match self.n3[self.n] {
                b'd' => I + L,
                b'u' => G + L,
                b'r' => I + G,
                _ => I + G + L,
            },
            _ => match self.n3[self.n] {
                b'd' => I + E + L,
                b'l' => I + G + L,
                b'r' => I + G + E,
                b'u' => G + E + L,
                _ => I + G + E + L,
            },
        })
    }

    fn f_i(&mut self) {
        let g = (11 - self.n0[self.n]) * 4;
        let a = self.n2[self.n] & (15u64 << g);
        self.n0[self.n + 1] = self.n0[self.n] + 4;
        self.n2[self.n + 1] = self.n2[self.n] - a + (a << 16);
        self.n3[self.n + 1] = b'd';
        self.n4[self.n + 1] = self.n4[self.n];
        let cond = NR[(a >> g) as usize] <= self.n0[self.n] / 4;
        if !cond {
            self.n4[self.n + 1] += 1;;
        }
        self.n += 1;
    }

    fn f_g(&mut self) {
        let g = (19 - self.n0[self.n]) * 4;
        let a = self.n2[self.n] & (15u64 << g);
        self.n0[self.n + 1] = self.n0[self.n] - 4;
        self.n2[self.n + 1] = self.n2[self.n] - a + (a >> 16);
        self.n3[self.n + 1] = b'u';
        self.n4[self.n + 1] = self.n4[self.n];
        let cond = NR[(a >> g) as usize] >= self.n0[self.n] / 4;
        if !cond {
            self.n4[self.n + 1] += 1;
        }
        self.n += 1;
    }

    fn f_e(&mut self) {
        let g = (14 - self.n0[self.n]) * 4;
        let a = self.n2[self.n] & (15u64 << g);
        self.n0[self.n + 1] = self.n0[self.n] + 1;
        self.n2[self.n + 1] = self.n2[self.n] - a + (a << 4);
        self.n3[self.n + 1] = b'r';
        self.n4[self.n + 1] = self.n4[self.n];
        let cond = NC[(a >> g) as usize] <= self.n0[self.n] % 4;
        if !cond {
            self.n4[self.n + 1] += 1;
        }
        self.n += 1;
    }

    fn f_l(&mut self) {
        let g = (16 - self.n0[self.n]) * 4;
        let a = self.n2[self.n] & (15u64 << g);
        self.n0[self.n + 1] = self.n0[self.n] - 1;
        self.n2[self.n + 1] = self.n2[self.n] - a + (a >> 4);
        self.n3[self.n + 1] = b'l';
        self.n4[self.n + 1] = self.n4[self.n];
        let cond = NC[(a >> g) as usize] >= self.n0[self.n] % 4;
        if !cond {
            self.n4[self.n + 1] += 1;
        }
        self.n += 1;
    }

    fn new(n: i32, g: u64) -> Self {
        let mut solver = FifteenSolver {
            n: 0,
            limit: 0,
            n0: [0; 85],
            n3: [0; 85],
            n4: [0; 85],
            n2: [0; 85],
        };
        solver.n0[0] = n;
        solver.n2[0] = g;
        solver
    }

    fn solve(&mut self) {
        while !self.f_n() {
            self.n = 0;
            self.limit += 1;
        }
        println!(
            "Solution found in {} moves: {}",
            self.n,
            std::str::from_utf8(&self.n3[1..=self.n]).unwrap()
        );
    }
}

fn main() {
    FifteenSolver::new(8, 0xfe169b4c0a73d852).solve();
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

#define D_INVALID -1
#define D_UP       1
#define D_DOWN     2
#define D_RIGHT    3
#define D_LEFT     4

const long values[] = {
    0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048
};

const char *colors[] = {
    "39", "31", "32", "33", "34", "35", "36", "37", "91", "92", "93", "94"
};

struct gamestate_struct__ {
    int grid[4][4];
    int have_moved;
    long total_score;
    long score_last_move;
    int blocks_in_play;
} game;

struct termios oldt, newt;

void do_draw(void)
{
    printf("\033[2J\033[HScore: %ld", game.total_score);
    if (game.score_last_move)
        printf(" (+%ld)", game.score_last_move);
    printf("\n");

    for (int i = 0; i < 25; ++i)
        printf("-");
    printf("\n");

    for (int y = 0; y < 4; ++y) {
        printf("|");
        for (int x = 0; x < 4; ++x) {
            if (game.grid[x][y])
                printf("\033[7m\033[%sm%*zd \033[0m|", colors[game.grid[x][y]],
                        4, values[game.grid[x][y]]);
            else
                printf("%*s |", 4, "");
        }
        printf("\n");
    }

    for (int i = 0; i < 25; ++i) {
        printf("-");
    }
    printf("\n");
}

void do_merge(int d)
{

#define MERGE_DIRECTION(_v1, _v2, _xs, _xc, _xi, _ys, _yc, _yi, _x, _y)     \
    do {                                                                    \
        for (int _v1 = _xs; _v1 _xc; _v1 += _xi) {                          \
            for (int _v2 = _ys; _v2 _yc; _v2 += _yi) {                      \
                if (game.grid[x][y] && (game.grid[x][y] ==                  \
                                    game.grid[x + _x][y + _y])) {           \
                    game.grid[x][y] += (game.have_moved = 1);               \
                    game.grid[x + _x][y + _y] = (0 * game.blocks_in_play--);\
                    game.score_last_move += values[game.grid[x][y]];        \
                    game.total_score += values[game.grid[x][y]];            \
                }                                                           \
            }                                                               \
        }                                                                   \
    } while (0)

    game.score_last_move = 0;

    switch (d) {
        case D_LEFT:
            MERGE_DIRECTION(x, y, 0, < 3, 1, 0, < 4, 1, 1, 0);
            break;
        case D_RIGHT:
            MERGE_DIRECTION(x, y, 3, > 0, -1, 0, < 4, 1, -1, 0);
            break;
        case D_DOWN:
            MERGE_DIRECTION(y, x, 3, > 0, -1, 0, < 4, 1, 0, -1);
            break;
        case D_UP:
            MERGE_DIRECTION(y, x, 0, < 3, 1, 0, < 4, 1, 0, 1);
            break;
    }

#undef MERGE_DIRECTION
}

void do_gravity(int d)
{
#define GRAVITATE_DIRECTION(_v1, _v2, _xs, _xc, _xi, _ys, _yc, _yi, _x, _y) \
    do {                                                                    \
        int break_cond = 0;                                                 \
        while (!break_cond) {                                               \
            break_cond = 1;                                                 \
            for (int _v1 = _xs; _v1 _xc; _v1 += _xi) {                      \
                for (int _v2 = _ys; _v2 _yc; _v2 += _yi) {                  \
                    if (!game.grid[x][y] && game.grid[x + _x][y + _y]) {    \
                        game.grid[x][y] = game.grid[x + _x][y + _y];        \
                        game.grid[x + _x][y + _y] = break_cond = 0;         \
                        game.have_moved = 1;                                \
                    }                                                       \
                }                                                           \
            }                                                               \
            do_draw(); usleep(40000);                                       \
        }                                                                   \
    } while (0)

    switch (d) {
        case D_LEFT:
            GRAVITATE_DIRECTION(x, y, 0, < 3, 1, 0, < 4, 1, 1, 0);
            break;
        case D_RIGHT:
            GRAVITATE_DIRECTION(x, y, 3, > 0, -1, 0, < 4, 1, -1, 0);
            break;
        case D_DOWN:
            GRAVITATE_DIRECTION(y, x, 3, > 0, -1, 0, < 4, 1, 0, -1);
            break;
        case D_UP:
            GRAVITATE_DIRECTION(y, x, 0, < 3, 1, 0, < 4, 1, 0, 1);
            break;
    }

#undef GRAVITATE_DIRECTION
}

int do_check_end_condition(void)
{
    int ret = -1;
    for (int x = 0; x < 4; ++x) {
        for (int y = 0; y < 4; ++y) {
            if (values[game.grid[x][y]] == 2048)
                return 1;
            if (!game.grid[x][y] ||
                  ((x + 1 < 4) && (game.grid[x][y] == game.grid[x + 1][y])) ||
                  ((y + 1 < 4) && (game.grid[x][y] == game.grid[x][y + 1])))
                ret = 0;
        }
    }
    return ret;
}

int do_tick(int d)
{
    game.have_moved = 0;
    do_gravity(d);
    do_merge(d);
    do_gravity(d);
    return game.have_moved;
}

void do_newblock(void) {
    if (game.blocks_in_play >= 16) return;

    int bn = rand() % (16 - game.blocks_in_play);
    int pn = 0;

    for (int x = 0; x < 4; ++x) {
        for (int y = 0; y < 4; ++y) {
            if (game.grid[x][y])
                continue;

            if (pn == bn){
                game.grid[x][y] = rand() % 10 ? 1 : 2;
                game.blocks_in_play += 1;
                return;
            }
            else {
                ++pn;
            }
        }
    }
}

int main(void)
{

    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    srand(time(NULL));
    memset(&game, 0, sizeof(game));
    do_newblock();
    do_newblock();
    do_draw();

    while (1) {
        int found_valid_key, direction, value;
        do {
            found_valid_key = 1;
            direction       = D_INVALID;
            value           = getchar();
            switch (value) {
                case 'h': case 'a':
                    direction = D_LEFT;
                    break;
                case 'l': case 'd':
                    direction = D_RIGHT;
                    break;
                case 'j': case 's':
                    direction = D_DOWN;
                    break;
                case 'k': case 'w':
                    direction = D_UP;
                    break;
                case 'q':
                    goto game_quit;
                    break;
                case 27:
                    if (getchar() == 91) {
                        value = getchar();
                        switch (value) {
                            case 65:
                                direction = D_UP;
                                break;
                            case 66:
                                direction = D_DOWN;
                                break;
                            case 67:
                                direction = D_RIGHT;
                                break;
                            case 68:
                                direction = D_LEFT;
                                break;
                            default:
                                found_valid_key = 0;
                                break;
                        }
                    }
                    break;
                default:
                    found_valid_key = 0;
                    break;
            }
        }  while (!found_valid_key);

        do_tick(direction);
        if (game.have_moved != 0){
                do_newblock();
        }
        do_draw();

        switch (do_check_end_condition()) {
            case -1:
                goto game_lose;
            case 1:
                goto game_win;
            case 0:
                break;
        }
    }

    if (0)
game_lose:
    printf("You lose!\n");
    goto game_quit;
    if (0)
game_win:
    printf("You win!\n");
    goto game_quit;
    if (0)
game_quit:

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return 0;
}

use std::io::{self,BufRead};
extern crate rand;

enum Usermove {
    Up,
    Down,
    Left,
    Right,
}

fn print_game(field :& [[u32;4];4] ){
    println!("{:?}",&field[0] );
    println!("{:?}",&field[1] );
    println!("{:?}",&field[2] );
    println!("{:?}",&field[3] );
}

fn get_usermove()-> Usermove {
    let umove: Usermove ;
    loop{
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();

        match input.chars().nth(0){
            Some('a') =>{umove = Usermove::Left ;break },
            Some('w') =>{umove = Usermove::Up   ;break },
            Some('s') =>{umove = Usermove::Down ;break },
            Some('d') =>{umove = Usermove::Right;break },
            _   => {println!("input was {}: invalid character should be a,s,w or d ",input.chars().nth(0).unwrap());} ,
        }
    }
    umove
}

fn do_game_step(step : &Usermove, field:&mut [[u32;4];4]){
    match *step {
        Usermove::Left =>{
            for array in field{
                for  col in 0..4 {
                    for testcol in (col+1)..4 {
                        if array[testcol] != 0 {
                            if array[col] == 0 {
                                array[col] += array[testcol];
                                array[testcol] = 0;
                            }
                            else if array[col] == array[testcol] {
                                array[col] += array[testcol];
                                array[testcol] = 0;
                                break;
                            } else {
                                break
                            }
                        }
                    }
                }
            }
        } ,
        Usermove::Right=>{
            for array in field{
                for  col in (0..4).rev() {
                    for testcol in (0..col).rev() {
                        if array[testcol] != 0 {
                            if array[col] == 0 {
                                array[col] += array[testcol];
                                array[testcol] = 0;
                            }
                            else if array[col] == array[testcol] {
                                array[col] += array[testcol];
                                array[testcol] = 0;
                                break;
                            }else {
                                break;
                            }
                        }
                    }
                }
            }
        } ,
        Usermove::Down   =>{
            for col in 0..4 {
                for row in (0..4).rev() {
                    for testrow in (0..row).rev() {
                        if field[testrow][col] != 0 {
                            if field[row][col] == 0 {
                                field[row][col] += field[testrow][col];
                                field[testrow][col] = 0;
                            } else if field[row][col] == field[testrow][col] {
                                field[row][col] += field[testrow][col];
                                field[testrow][col] = 0;
                                break;
                            }else {
                                break;
                            }

                        }
                    }
                }
            }
        } ,
        Usermove::Up =>{
            for col in 0..4 {
                for row in 0..4{
                    for testrow in (row+1)..4 {
                        if field[testrow][col] != 0 {
                            if field[row][col] == 0 {
                                field[row][col] += field[testrow][col];
                                field[testrow][col] = 0;
                            } else if field[row][col] == field[testrow][col] {
                                field[row][col] += field[testrow][col];
                                field[testrow][col] = 0;
                                break;
                            }else {
                                break;
                            }
                        }
                    }
                }
            }
        },
    }
}

fn spawn( field: &mut  [[u32;4];4]){
    loop{
        let x = rand::random::<usize>();
        if field[x % 4][(x/4)%4] == 0 {
            if x % 10 == 0 {
                field[x % 4][(x/4)%4]= 4;
            }else{
                field[x % 4][(x/4)%4]= 2;
            }
            break;
        }
    }
}

fn main() {
    let mut field : [[u32; 4];4] =  [[0;4];4];
    let mut test : [[u32; 4];4] ;
    'gameloop:loop {

        test=field.clone();
        spawn(&mut field);

        for i in [Usermove::Up,Usermove::Down,Usermove::Left,Usermove::Right].into_iter(){
            do_game_step(i, &mut test);
            if test != field{
                break;
            }
            match *i{
                Usermove::Right=> {
                    println!("No more valid move, you lose");
                    break 'gameloop;
                },
                _=>{},
            }
        }
        print_game(&field);
        println!("move the blocks");

        test=field.clone();
        while test==field {
            do_game_step(&get_usermove(), &mut field);
        }

        for row in field.iter(){
            if row.iter().any(|x| *x == 2048){
                print_game(&field );
                println!("You Won!!");
                break;
            }
        }
    }
}


24 game

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>

jmp_buf ctx;
const char *msg;

enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };

typedef struct expr_t *expr, expr_t;
struct expr_t {
	int op, val, used;
	expr left, right;
};

#define N_DIGITS 4
expr_t digits[N_DIGITS];

void gen_digits()
{
	int i;
	for (i = 0; i < N_DIGITS; i++)
		digits[i].val = 1 + rand() % 9;
}

#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;

#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;

void reset()
{
	int i;
	msg = 0;
	pool_ptr = pos = 0;
	for (i = 0; i < POOL_SIZE; i++) {
		pool[i].op = OP_NONE;
		pool[i].left = pool[i].right = 0;
	}
	for (i = 0; i < N_DIGITS; i++)
		digits[i].used = 0;
}

void bail(const char *s)
{
	msg = s;
	longjmp(ctx, 1);
}

expr new_expr()
{
	if (pool_ptr < POOL_SIZE)
		return pool + pool_ptr++;
	return 0;
}

int next_tok()
{
	while (isspace(str[pos])) pos++;
	return str[pos];
}

int take()
{
	if (str[pos] != '\0') return ++pos;
	return 0;
}

expr get_fact();
expr get_term();
expr get_expr();

expr get_expr()
{
	int c;
	expr l, r, ret;
	if (!(ret = get_term())) bail("Expected term");
	while ((c = next_tok()) == '+' || c == '-') {
		if (!take()) bail("Unexpected end of input");
		if (!(r = get_term())) bail("Expected term");

		l = ret;
		ret = new_expr();
		ret->op = (c == '+') ? OP_ADD : OP_SUB;
		ret->left = l;
		ret->right = r;
	}
	return ret;
}

expr get_term()
{
	int c;
	expr l, r, ret;
	ret = get_fact();
	while((c = next_tok()) == '*' || c == '/') {
		if (!take()) bail("Unexpected end of input");

		r = get_fact();
		l = ret;
		ret = new_expr();
		ret->op = (c == '*') ? OP_MUL : OP_DIV;
		ret->left = l;
		ret->right = r;
	}
	return ret;
}

expr get_digit()
{
	int i, c = next_tok();
	expr ret;
	if (c >= '0' && c <= '9') {
		take();
		ret = new_expr();
		ret->op = OP_NUM;
		ret->val = c - '0';
		for (i = 0; i < N_DIGITS; i++)
			if (digits[i].val == ret->val && !digits[i].used) {
				digits[i].used = 1;
				return ret;
			}
		bail("Invalid digit");
	}
	return 0;
}

expr get_fact()
{
	int c;
	expr l = get_digit();
	if (l) return l;
	if ((c = next_tok()) == '(') {
		take();
		l = get_expr();
		if (next_tok() != ')') bail("Unbalanced parens");
		take();
		return l;
	}
	return 0;
}

expr parse()
{
	int i;
	expr ret = get_expr();
	if (next_tok() != '\0')
		bail("Trailing garbage");
	for (i = 0; i < N_DIGITS; i++)
		if (!digits[i].used)
			bail("Not all digits are used");
	return ret;
}

typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };

int gcd(int m, int n)
{
	int t;
	while (m) {
		t = m; m = n % m; n = t;
	}
	return n;
}

void eval_tree(expr e, frac res)
{
	frac_t l, r;
	int t;
	if (e->op == OP_NUM) {
		res->num = e->val;
		res->denom = 1;
		return;
	}

	eval_tree(e->left, &l);
	eval_tree(e->right, &r);

	switch(e->op) {
	case OP_ADD:
		res->num = l.num * r.denom + l.denom * r.num;
		res->denom = l.denom * r.denom;
		break;
	case OP_SUB:
		res->num = l.num * r.denom - l.denom * r.num;
		res->denom = l.denom * r.denom;
		break;
	case OP_MUL:
		res->num = l.num * r.num;
		res->denom = l.denom * r.denom;
		break;
	case OP_DIV:
		res->num = l.num * r.denom;
		res->denom = l.denom * r.num;
		break;
	}
	if ((t = gcd(res->denom, res->num))) {
		res->denom /= t;
		res->num /= t;
	}
}

void get_input()
{
	int i;
reinput:
	reset();
	printf("\nAvailable digits are:");
	for (i = 0; i < N_DIGITS; i++)
		printf(" %d", digits[i].val);
	printf(". Type an expression and I'll check it for you, or make new numbers.\n"
		"Your choice? [Expr/n/q] ");

	while (1) {
		for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
		fgets(str, MAX_INPUT, stdin);
		if (*str == '\0') goto reinput;
		if (str[MAX_INPUT - 1] != '\n')
			bail("string too long");

		for (i = 0; i < MAX_INPUT; i++)
			if (str[i] == '\n') str[i] = '\0';
		if (str[0] == 'q') {
			printf("Bye\n");
			exit(0);
		}
		if (str[0] == 'n') {
			gen_digits();
			goto reinput;
		}
		return;
	}
}

int main()
{
	frac_t f;
	srand(time(0));

	gen_digits();
	while(1) {
		get_input();
		setjmp(ctx);
		if (msg) {

			printf("%s at '%.*s'\n", msg, pos, str);
			continue;
		}

		eval_tree(parse(), &f);

		if (f.denom == 0) bail("Divide by zero");
		if (f.denom == 1 && f.num == 24)
			printf("You got 24.  Very good.\n");
		else {
			if (f.denom == 1)
				printf("Eval to: %d, ", f.num);
			else
				printf("Eval to: %d/%d, ", f.num, f.denom);
			printf("no good.  Try again.\n");
		}
	}
	return 0;
}

use std::io::{self,BufRead};
extern crate rand;
use rand::Rng;

fn op_type(x: char) -> i32{
    match x {
        '-' | '+' => return 1,
        '/' | '*' => return 2,
        '(' | ')' => return -1,
        _   => return 0,
    }
}

fn to_rpn(input: &mut String){

    let mut rpn_string : String = String::new();
    let mut rpn_stack : String = String::new();
    let mut last_token = '#';
    for token in input.chars(){
        if token.is_digit(10) {
            rpn_string.push(token);
        }
        else if op_type(token) == 0 {
            continue;
        }
        else if op_type(token) > op_type(last_token) || token == '(' {
                rpn_stack.push(token);
                last_token=token;
        }
        else {
            while let Some(top) = rpn_stack.pop() {
                if top=='(' {
                    break;
                }
                rpn_string.push(top);
            }
            if token != ')'{
                rpn_stack.push(token);
            }
        }
    }
    while let Some(top) = rpn_stack.pop() {
        rpn_string.push(top);
    }

    println!("you formula results in {}", rpn_string);

    *input=rpn_string;
}

fn calculate(input: &String, list : &mut [u32;4]) -> f32{
    let mut stack : Vec<f32> = Vec::new();
    let mut accumulator : f32 = 0.0;

    for token in input.chars(){
        if token.is_digit(10) {
            let test = token.to_digit(10).unwrap() as u32;
            match list.iter().position(|&x| x == test){
                Some(idx) => list[idx]=10 ,
                _         => println!(" invalid digit: {} ",test),
            }
            stack.push(accumulator);
            accumulator = test as f32;
        }else{
            let a = stack.pop().unwrap();
            accumulator = match token {
                '-' => a-accumulator,
                '+' => a+accumulator,
                '/' => a/accumulator,
                '*' => a*accumulator,
                _ => {accumulator},
            };
        }
    }
    println!("you formula results in {}",accumulator);
    accumulator
}

fn main() {

    let mut rng = rand::thread_rng();
    let mut list :[u32;4]=[rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10];

    println!("form 24 with using + - / * {:?}",list);

    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();

    to_rpn(&mut input);
    let result = calculate(&input, &mut list);

    if list.iter().any(|&list| list !=10){
        println!("and you used all numbers");
        match result {
            24.0 => println!("you won"),
            _ => println!("but your formulla doesn't result in 24"),
        }
    }else{
        println!("you didn't use all the numbers");
    }

}


24 game_Solve

#include <stdio.h>

typedef struct {int val, op, left, right;} Node;

Node nodes[10000];
int iNodes;

int b;
float eval(Node x){
    if (x.op != -1){
        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
        switch(x.op){
            case 0: return l+r;
            case 1: return l-r;
            case 2: return r-l;
            case 3: return l*r;
            case 4: return r?l/r:(b=1,0);
            case 5: return l?r/l:(b=1,0);
        }
    }
    else return x.val*1.;
}

void show(Node x){
    if (x.op != -1){
        printf("(");
        switch(x.op){
            case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break;
            case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break;
            case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break;
            case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break;
            case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break;
            case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break;
        }
        printf(")");
    }
    else printf("%d", x.val);
}

int float_fix(float x){ return x < 0.00001 && x > -0.00001; }

void solutions(int a[], int n, float t, int s){
    if (s == n){
        b = 0;
        float e = eval(nodes[0]);

        if (!b && float_fix(e-t)){
            show(nodes[0]);
            printf("\n");
        }
    }
    else{
        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};

        for (int op = 0; op < 6; op++){
            int k = iNodes-1;
            for (int i = 0; i < k; i++){
                nodes[iNodes++] = nodes[i];
                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};
                solutions(a, n, t, s+1);
                nodes[i] = nodes[--iNodes];
            }
        }

        iNodes--;
    }
};

int main(){

    int a[4] = {8, 3, 8, 3};
    float t = 24;

    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};
    iNodes = 1;

    solutions(a, sizeof(a)/sizeof(int), t, 1);

    return 0;
}

#[derive(Clone, Copy, Debug)]
enum Operator {
    Sub,
    Plus,
    Mul,
    Div,
}

#[derive(Clone, Debug)]
struct Factor {
    content: String,
    value: i32,
}

fn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec<Factor> {
    let mut ret = Vec::new();
    for l in left.iter() {
        for r in right.iter() {
            use Operator::*;
            ret.push(match op {
                Sub if l.value > r.value => Factor {
                    content: format!("({} - {})", l.content, r.content),
                    value: l.value - r.value,
                },
                Plus => Factor {
                    content: format!("({} + {})", l.content, r.content),
                    value: l.value + r.value,
                },
                Mul => Factor {
                    content: format!("({} x {})", l.content, r.content),
                    value: l.value * r.value,
                },
                Div if l.value >= r.value && r.value > 0 && l.value % r.value == 0 => Factor {
                    content: format!("({} / {})", l.content, r.content),
                    value: l.value / r.value,
                },
                _ => continue,
            })
        }
    }
    ret
}

fn calc(op: [Operator; 3], numbers: [i32; 4]) -> Vec<Factor> {
    fn calc(op: &[Operator], numbers: &[i32], acc: &[Factor]) -> Vec<Factor> {
        use Operator::*;
        if op.is_empty() {
            return Vec::from(acc)
        }
        let mut ret = Vec::new();
        let mono_factor = [Factor {
            content: numbers[0].to_string(),
            value: numbers[0],
        }];
        match op[0] {
            Mul => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),
            Div => {
                ret.extend_from_slice(&apply(op[0], acc, &mono_factor));
                ret.extend_from_slice(&apply(op[0], &mono_factor, acc));
            },
            Sub => {
                ret.extend_from_slice(&apply(op[0], acc, &mono_factor));
                ret.extend_from_slice(&apply(op[0], &mono_factor, acc));
            },
            Plus => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),
        }
        calc(&op[1..], &numbers[1..], &ret)
    }
    calc(&op, &numbers[1..], &[Factor { content: numbers[0].to_string(), value: numbers[0] }])
}

fn solutions(numbers: [i32; 4]) -> Vec<Factor> {
    use std::collections::hash_set::HashSet;
    let mut ret = Vec::new();
    let mut hash_set = HashSet::new();

    for ops in OpIter(0) {
        for o in orders().iter() {
            let numbers = apply_order(numbers, o);
            let r = calc(ops, numbers);
            ret.extend(r.into_iter().filter(|&Factor { value, ref content }| value == 24 && hash_set.insert(content.to_owned())))
        }
    }
    ret
}

fn main() {
    let mut numbers = Vec::new();
    if let Some(input) = std::env::args().skip(1).next() {
        for c in input.chars() {
            if let Ok(n) = c.to_string().parse() {
                numbers.push(n)
            }
            if numbers.len() == 4 {
                let numbers = [numbers[0], numbers[1], numbers[2], numbers[3]];
                let solutions = solutions(numbers);
                let len = solutions.len();
                if len == 0 {
                    println!("no solution for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]);
                    return
                }
                println!("solutions for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]);
                for s in solutions {
                    println!("{}", s.content)
                }
                println!("{} solutions found", len);
                return
            }
        }
    } else {
        println!("empty input")
    }
}

struct OpIter (usize);

impl Iterator for OpIter {
    type Item = [Operator; 3];
    fn next(&mut self) -> Option<[Operator; 3]> {
        use Operator::*;
        const OPTIONS: [Operator; 4] = [Mul, Sub, Plus, Div];
        if self.0 >= 1 << 6 {
            return None
        }
        let f1 = OPTIONS[(self.0 & (3 << 4)) >> 4];
        let f2 = OPTIONS[(self.0 & (3 << 2)) >> 2];
        let f3 = OPTIONS[(self.0 & (3 << 0)) >> 0];
        self.0 += 1;
        Some([f1, f2, f3])
    }
}

fn orders() -> [[usize; 4]; 24] {
    [
        [0, 1, 2, 3],
        [0, 1, 3, 2],
        [0, 2, 1, 3],
        [0, 2, 3, 1],
        [0, 3, 1, 2],
        [0, 3, 2, 1],
        [1, 0, 2, 3],
        [1, 0, 3, 2],
        [1, 2, 0, 3],
        [1, 2, 3, 0],
        [1, 3, 0, 2],
        [1, 3, 2, 0],
        [2, 0, 1, 3],
        [2, 0, 3, 1],
        [2, 1, 0, 3],
        [2, 1, 3, 0],
        [2, 3, 0, 1],
        [2, 3, 1, 0],
        [3, 0, 1, 2],
        [3, 0, 2, 1],
        [3, 1, 0, 2],
        [3, 1, 2, 0],
        [3, 2, 0, 1],
        [3, 2, 1, 0]
    ]
}

fn apply_order(numbers: [i32; 4], order: &[usize; 4]) -> [i32; 4] {
    [numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]]
}


Abbreviations, easy

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* command_table =
  "Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy "
  "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
  "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
  "Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO "
  "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT "
  "READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT "
  "RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up";

typedef struct command_tag {
    char* cmd;
    size_t length;
    size_t min_len;
    struct command_tag* next;
} command_t;

bool command_match(const command_t* command, const char* str) {
    size_t olen = strlen(str);
    return olen >= command->min_len && olen <= command->length
        && strncmp(str, command->cmd, olen) == 0;
}

char* uppercase(char* str, size_t n) {
    for (size_t i = 0; i < n; ++i)
        str[i] = toupper((unsigned char)str[i]);
    return str;
}

size_t get_min_length(const char* str, size_t n) {
    size_t len = 0;
    while (len < n && isupper((unsigned char)str[len]))
        ++len;
    return len;
}

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;
}

char** split_into_words(const char* str, size_t* count) {
    size_t size = 0;
    size_t capacity = 16;
    char** words = xmalloc(capacity * sizeof(char*));
    size_t len = strlen(str);
    for (size_t begin = 0; begin < len; ) {
        size_t i = begin;
        for (; i < len && isspace((unsigned char)str[i]); ++i) {}
        begin = i;
        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
        size_t word_len = i - begin;
        if (word_len == 0)
            break;
        char* word = xmalloc(word_len + 1);
        memcpy(word, str + begin, word_len);
        word[word_len] = 0;
        begin += word_len;
        if (capacity == size) {
            capacity *= 2;
            words = xrealloc(words, capacity * sizeof(char*));
        }
        words[size++] = word;
    }
    *count = size;
    return words;
}

command_t* make_command_list(const char* table) {
    command_t* cmd = NULL;
    size_t count = 0;
    char** words = split_into_words(table, &count);
    for (size_t i = 0; i < count; ++i) {
        char* word = words[i];
        command_t* new_cmd = xmalloc(sizeof(command_t));
        size_t word_len = strlen(word);
        new_cmd->length = word_len;
        new_cmd->min_len = get_min_length(word, word_len);
        new_cmd->cmd = uppercase(word, word_len);
        new_cmd->next = cmd;
        cmd = new_cmd;
    }
    free(words);
    return cmd;
}

void free_command_list(command_t* cmd) {
    while (cmd != NULL) {
        command_t* next = cmd->next;
        free(cmd->cmd);
        free(cmd);
        cmd = next;
    }
}

const command_t* find_command(const command_t* commands, const char* word) {
    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
        if (command_match(cmd, word))
            return cmd;
    }
    return NULL;
}

void test(const command_t* commands, const char* input) {
    printf(" input: %s\n", input);
    printf("output:");
    size_t count = 0;
    char** words = split_into_words(input, &count);
    for (size_t i = 0; i < count; ++i) {
        char* word = words[i];
        uppercase(word, strlen(word));
        const command_t* cmd_ptr = find_command(commands, word);
        printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
        free(word);
    }
    free(words);
    printf("\n");
}

int main() {
    command_t* commands = make_command_list(command_table);
    const char* input = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin";
    test(commands, input);
    free_command_list(commands);
    return 0;
}

use std::collections::HashMap;

fn main() {
    let commands = "
        Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \
        COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \
        NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \
        Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \
        MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \
        READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \
        RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \
    ";
    let split = commands.split_ascii_whitespace();
    let count_hashtable: HashMap<&str, usize> = split.map(|word| {
        (word, word.chars().take_while(|c| c.is_ascii_uppercase()).count())
    }).collect();

    let line = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin";
    let mut words_vec: Vec<String> = vec![];
    for word in line.split_ascii_whitespace() {
        let split = commands.split_ascii_whitespace();
        let abbr = split.filter(|x| {
            x.to_ascii_lowercase().starts_with(&word.to_ascii_lowercase()) &&
            word.len() >= *count_hashtable.get(x).unwrap()
        }).next();
        words_vec.push(match abbr {
            Some(word) => word.to_ascii_uppercase(),
            None => String::from("*error*"),
        });
    }
    let corrected_line = words_vec.join(" ");
    println!("{}", corrected_line);
}


Abelian sandpile model

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

int main(int argc, char** argv)
{
	int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right;
	int** sandPile;
	char* fileName;
	static unsigned char colour[3];

	if(argc!=3){
		printf("Usage: %s <Sand pile side> <Center pile height>",argv[0]);
		return 0;
	}

	sandPileEdge = atoi(argv[1]);
	centerPileHeight = atoi(argv[2]);

	if(sandPileEdge<=0 || centerPileHeight<=0){
		printf("Sand pile and center pile dimensions must be positive integers.");
		return 0;
	}

	sandPile = (int**)malloc(sandPileEdge * sizeof(int*));

	for(i=0;i<sandPileEdge;i++){
		sandPile[i] = (int*)calloc(sandPileEdge,sizeof(int));
	}

	sandPile[sandPileEdge/2][sandPileEdge/2] = centerPileHeight;

	printf("Initial sand pile :\n\n");

	for(i=0;i<sandPileEdge;i++){
		for(j=0;j<sandPileEdge;j++){
			printf("%3d",sandPile[i][j]);
		}
		printf("\n");
	}

	while(processAgain == 1){

		processAgain = 0;
		top = 0;
		down = 0;
		left = 0;
		right = 0;

		for(i=0;i<sandPileEdge;i++){
			for(j=0;j<sandPileEdge;j++){
				if(sandPile[i][j]>=4){
					if(i-1>=0){
						top = 1;
						sandPile[i-1][j]+=1;
						if(sandPile[i-1][j]>=4)
							processAgain = 1;
					}
					if(i+1<sandPileEdge){
						down = 1;
						sandPile[i+1][j]+=1;
						if(sandPile[i+1][j]>=4)
							processAgain = 1;
					}
					if(j-1>=0){
						left = 1;
						sandPile[i][j-1]+=1;
						if(sandPile[i][j-1]>=4)
							processAgain = 1;
					}
					if(j+1<sandPileEdge){
						right = 1;
						sandPile[i][j+1]+=1;
						if(sandPile[i][j+1]>=4)
							processAgain = 1;
					}
				sandPile[i][j] -= (top + down + left + right);
				if(sandPile[i][j]>=4)
					processAgain = 1;
				}
			}
		}
	}

	printf("Final sand pile : \n\n");

	for(i=0;i<sandPileEdge;i++){
		for(j=0;j<sandPileEdge;j++){
			printf("%3d",sandPile[i][j]);
		}
		printf("\n");
	}

	fileName = (char*)malloc((strlen(argv[1]) + strlen(argv[2]) + 23)*sizeof(char));

	strcpy(fileName,"Final_Sand_Pile_");
	strcat(fileName,argv[1]);
	strcat(fileName,"_");
	strcat(fileName,argv[2]);
	strcat(fileName,".ppm");

	FILE *fp = fopen(fileName,"wb");

	fprintf(fp,"P6\n%d %d\n255\n",sandPileEdge,sandPileEdge);

	for(i=0;i<sandPileEdge;i++){
		for(j=0;j<sandPileEdge;j++){
			colour[0] = (sandPile[i][j] + i)%256;
			colour[1] = (sandPile[i][j] + j)%256;
			colour[2] = (sandPile[i][j] + i*j)%256;
			fwrite(colour,1,3,fp);
		}
	}

	fclose(fp);

	printf("\nImage file written to %s\n",fileName);

	return 0;
}

fn advance(field: &mut Vec<Vec<usize>>, boundary: &mut [usize; 4]) -> bool
{

    let mut done = false;

    for y in boundary[0]..boundary[2]
    {
        for x in boundary[1]..boundary[3]
        {
            if field[y][x] >= 4
            {

                let rem: usize = field[y][x] / 4;
                field[y][x] %= 4;

                if y as isize - 1 >= 0 {field[y-1][x] += rem; if y == boundary[0] {boundary[0]-=1;}}
                if x as isize - 1 >= 0 {field[y][x-1] += rem; if x == boundary[1] {boundary[1]-=1;}}
                if y+1 < field.len() {field[y+1][x] += rem; if x == boundary[2]-1 {boundary[2]+=1;}}
                if x+1 < field.len() {field[y][x+1] += rem; if y == boundary[3]-1 {boundary[3]+=1;}}

                done = true;
            }
        }
    }

    done
}

fn display(field: &Vec<Vec<usize>>)
{
    for row in field
    {
        let char_row = {
            row.iter().map(|c| {match c {
                0 => ' ',
                1 => '░',
                2 => '▒',
                3 => '▓',
                _ => '█'
            }}).collect::<String>()
        };
        println!("{}", char_row);
    }
}

fn write_pile(pile: &Vec<Vec<usize>>) {
    use std::fs::File;
    use std::io::Write;

    let mut file = File::create("./output.ppm").unwrap();

    write!(file, "P3\n{} {}\n255\n", pile.len(), pile.len()).unwrap();

    for row in pile {

        let mut line = String::with_capacity(row.len() * 14);

        for elem in row {
            line.push_str(match elem {
                0 => "100 40 15 ",
                1 => "117 87 30 ",
                2 => "181 134 47 ",
                3 => "245 182 66 ",
                _ => unreachable!(),
            });
        }

        write!(file, "{}\n", line).unwrap();
    }
}

fn main() {

    let field_size = 16;
    let mut playfield = vec![vec![0; field_size]; field_size];

    let mut boundary = [field_size/2-1, field_size/2-1, field_size/2, field_size/2];
    playfield[field_size/2 - 1][field_size/2 - 1] = 16;

    while advance(&mut playfield, &mut boundary) {};

    display(&playfield);

}


Active Directory_Connect

#include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld);

let conn = ldap3::LdapConn::new("ldap:
conn.simple_bind("bind_dn", "bind_pass")?.success()?;


Air mass

#include <math.h>
#include <stdio.h>

#define DEG 0.017453292519943295769236907684886127134
#define RE 6371000.0
#define DD 0.001
#define FIN 10000000.0

static double rho(double a) {

    return exp(-a / 8500.0);
}

static double height(double a, double z, double d) {

    double aa = RE + a;
    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));
    return hh - RE;
}

static double column_density(double a, double z) {

    double sum = 0.0, d = 0.0;
    while (d < FIN) {

        double delta = DD * d;
        if (delta < DD)
            delta = DD;
        sum += rho(height(a, z, d + 0.5 * delta)) * delta;
        d += delta;
    }
    return sum;
}

static double airmass(double a, double z) {
    return column_density(a, z) / column_density(a, 0.0);
}

int main() {
    puts("Angle     0 m              13700 m");
    puts("------------------------------------");
    for (double z = 0; z <= 90; z+= 5) {
        printf("%2.0f      %11.8f      %11.8f\n",
               z, airmass(0.0, z), airmass(13700.0, z));
    }
}


Aliquot sequence classifications

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

unsigned long long bruteForceProperDivisorSum(unsigned long long n){
	unsigned long long i,sum = 0;

	for(i=1;i<(n+1)/2;i++)
		if(n%i==0 && n!=i)
			sum += i;

	return sum;
}

void printSeries(unsigned long long* arr,int size,char* type){
	int i;

	printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type);

	for(i=0;i<size-1;i++)
		printf("%llu, ",arr[i]);
	printf("%llu",arr[i]);
}

void aliquotClassifier(unsigned long long n){
	unsigned long long arr[16];
	int i,j;

	arr[0] = n;

	for(i=1;i<16;i++){
		arr[i] = bruteForceProperDivisorSum(arr[i-1]);

		if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){
			printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable");
			return;
		}

		for(j=1;j<i;j++){
			if(arr[j]==arr[i]){
				printSeries(arr,i+1,"Cyclic");
				return;
			}
		}
	}

	printSeries(arr,i+1,"Non-Terminating");
}

void processFile(char* fileName){
	FILE* fp = fopen(fileName,"r");
	char str[21];

	while(fgets(str,21,fp)!=NULL)
		aliquotClassifier(strtoull(str,(char**)NULL,10));

	fclose(fp);
}

int main(int argC,char* argV[])
{
    if(argC!=2)
		printf("Usage : %s <positive integer>",argV[0]);
	else{
		if(strchr(argV[1],'.')!=NULL)
			processFile(argV[1]);
		else
			aliquotClassifier(strtoull(argV[1],(char**)NULL,10));
	}
	return 0;
}

#[derive(Debug)]
enum AliquotType { Terminating, Perfect, Amicable, Sociable, Aspiring, Cyclic, NonTerminating }

fn classify_aliquot(num: i64) -> (AliquotType, Vec<i64>) {
    let limit = 1i64 << 47;
    let mut terms = Some(num).into_iter().collect::<Vec<_>>();
    for i in 0..16 {
        let n = terms[i];
        let divsum = (1..(n + 1) / 2 + 1).filter(|&x| n % x == 0 && n != x).fold(0, |sum, x| sum + x);
        let classification = if divsum == 0 {
            Some(AliquotType::Terminating)
        }
        else if divsum > limit {
            Some(AliquotType::NonTerminating)
        }
        else if let Some(prev_idx) = terms.iter().position(|&x| x == divsum) {
            let cycle_len = terms.len() - prev_idx;
            Some(if prev_idx == 0 {
                match cycle_len {
                    1 => AliquotType::Perfect,
                    2 => AliquotType::Amicable,
                    _ => AliquotType::Sociable
                }
            }
            else {
                if cycle_len == 1 {AliquotType::Aspiring} else {AliquotType::Cyclic}
            })
        }
        else {
            None
        };
        terms.push(divsum);
        if let Some(result) = classification {
            return (result, terms);
        }
    }
    (AliquotType::NonTerminating, terms)
}

fn main() {
    let nums = [1i64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488];
    for num in &nums {
        println!("{} {:?}", num, classify_aliquot(*num));
    }
}


Angles (geometric), normalization and conversion

#define PI 3.141592653589793
#define TWO_PI 6.283185307179586

double normalize2deg(double a) {
  while (a < 0) a += 360;
  while (a >= 360) a -= 360;
  return a;
}
double normalize2grad(double a) {
  while (a < 0) a += 400;
  while (a >= 400) a -= 400;
  return a;
}
double normalize2mil(double a) {
  while (a < 0) a += 6400;
  while (a >= 6400) a -= 6400;
  return a;
}
double normalize2rad(double a) {
  while (a < 0) a += TWO_PI;
  while (a >= TWO_PI) a -= TWO_PI;
  return a;
}

double deg2grad(double a) {return a * 10 / 9;}
double deg2mil(double a) {return a * 160 / 9;}
double deg2rad(double a) {return a * PI / 180;}

double grad2deg(double a) {return a * 9 / 10;}
double grad2mil(double a) {return a * 16;}
double grad2rad(double a) {return a * PI / 200;}

double mil2deg(double a) {return a * 9 / 160;}
double mil2grad(double a) {return a / 16;}
double mil2rad(double a) {return a * PI / 3200;}

double rad2deg(double a) {return a * 180 / PI;}
double rad2grad(double a) {return a * 200 / PI;}
double rad2mil(double a) {return a * 3200 / PI;}

use std::{
    marker::PhantomData,
    f64::consts::PI,
};

pub trait AngleUnit: Copy {
    const TURN: f64;
    const NAME: &'static str;
}

macro_rules! unit {
    ($name:ident, $value:expr, $string:expr) => (
        #[derive(Debug, Copy, Clone)]
        struct $name;
        impl AngleUnit for $name {
            const TURN: f64 = $value;
            const NAME: &'static str = $string;
        }
    );
}

unit!(Degrees,  360.0,      "Degrees");
unit!(Radians,  PI * 2.0,   "Radians");
unit!(Gradians, 400.0,      "Gradians");
unit!(Mils,     6400.0,     "Mils");

#[derive(Copy, Clone, PartialEq, PartialOrd)]
struct Angle<T: AngleUnit>(f64, PhantomData<T>);

impl<T: AngleUnit> Angle<T> {
    pub fn new(val: f64) -> Self {
        Self(val, PhantomData)
    }

    pub fn normalize(self) -> Self {
        Self(self.0 % T::TURN, PhantomData)
    }

    pub fn val(self) -> f64 {
        self.0
    }

    pub fn convert<U: AngleUnit>(self) -> Angle<U> {
        Angle::new(self.0 * U::TURN / T::TURN)
    }

    pub fn name(self) -> &'static str {
        T::NAME
    }
}

fn print_angles<T: AngleUnit>() {
    let angles = [-2.0, -1.0, 0.0, 1.0, 2.0, 6.2831853, 16.0, 57.2957795, 359.0, 399.0, 6399.0, 1000000.0];
    println!("{:<12} {:<12} {:<12} {:<12} {:<12} {:<12}", "Angle", "Unit", "Degrees", "Gradians", "Mils", "Radians");

    for &angle in &angles {
        let deg = Angle::<T>::new(angle).normalize();
        println!("{:<12} {:<12} {:<12.4} {:<12.4} {:<12.4} {:<12.4}",
                 angle,
                 deg.name(),
                 deg.convert::<Degrees>().val(),
                 deg.convert::<Gradians>().val(),
                 deg.convert::<Mils>().val(),
                 deg.convert::<Radians>().val(),
        );
    }

    println!();
}

fn main() {
    print_angles::<Degrees>();
    print_angles::<Gradians>();
    print_angles::<Mils>();
    print_angles::<Radians>();
}


Arena storage pool

#![feature(rustc_private)]

extern crate arena;

use arena::TypedArena;

fn main() {

    let arena = TypedArena::new();

    let v1 = arena.alloc(1i32);

    let v2 = arena.alloc(3);
    *v2 += 38;
    println!("{}", *v1 + *v2);

}


Arithmetic numbers

#include <stdio.h>

void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
                           unsigned int* psum) {
    unsigned int divisor_count = 1;
    unsigned int divisor_sum = 1;
    unsigned int power = 2;
    for (; (n & 1) == 0; power <<= 1, n >>= 1) {
        ++divisor_count;
        divisor_sum += power;
    }
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1, sum = 1;
        for (power = p; n % p == 0; power *= p, n /= p) {
            ++count;
            sum += power;
        }
        divisor_count *= count;
        divisor_sum *= sum;
    }
    if (n > 1) {
        divisor_count *= 2;
        divisor_sum *= n + 1;
    }
    *pcount = divisor_count;
    *psum = divisor_sum;
}

int main() {
    unsigned int arithmetic_count = 0;
    unsigned int composite_count = 0;

    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
        unsigned int divisor_count;
        unsigned int divisor_sum;
        divisor_count_and_sum(n, &divisor_count, &divisor_sum);
        if (divisor_sum % divisor_count != 0)
            continue;
        ++arithmetic_count;
        if (divisor_count > 2)
            ++composite_count;
        if (arithmetic_count <= 100) {
            printf("%3u ", n);
            if (arithmetic_count % 10 == 0)
                printf("\n");
        }
        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
            arithmetic_count == 100000 || arithmetic_count == 1000000) {
            printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
            printf("Number of composite arithmetic numbers <= %u: %u\n", n,
                   composite_count);
        }
    }
    return 0;
}

fn divisor_count_and_sum(mut n: u32) -> (u32, u32) {
    let mut divisor_count = 1;
    let mut divisor_sum = 1;
    let mut power = 2;
    while (n & 1) == 0 {
        divisor_count += 1;
        divisor_sum += power;
        power <<= 1;
        n >>= 1;
    }
    let mut p = 3;
    while p * p <= n {
        let mut count = 1;
        let mut sum = 1;
        power = p;
        while n % p == 0 {
            count += 1;
            sum += power;
            power *= p;
            n /= p;
        }
        divisor_count *= count;
        divisor_sum *= sum;
        p += 2;
    }
    if n > 1 {
        divisor_count *= 2;
        divisor_sum *= n + 1;
    }
    (divisor_count, divisor_sum)
}

fn main() {
    let mut arithmetic_count = 0;
    let mut composite_count = 0;
    let mut n = 1;
    while arithmetic_count <= 1000000 {
        let (divisor_count, divisor_sum) = divisor_count_and_sum(n);
        if divisor_sum % divisor_count != 0 {
            n += 1;
            continue;
        }
        arithmetic_count += 1;
        if divisor_count > 2 {
            composite_count += 1;
        }
        if arithmetic_count <= 100 {
            print!("{:3} ", n);
            if arithmetic_count % 10 == 0 {
                println!();
            }
        }
        if arithmetic_count == 1000
            || arithmetic_count == 10000
            || arithmetic_count == 100000
            || arithmetic_count == 1000000
        {
            println!("\n{}th arithmetic number is {}", arithmetic_count, n);
            println!(
                "Number of composite arithmetic numbers <= {}: {}",
                n, composite_count
            );
        }
        n += 1;
    }
}


Arithmetic-geometric mean_Calculate Pi

#include "gmp.h"

void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {
	mpf_add (out1, in1, in2);
	mpf_div_ui (out1, out1, 2);
	mpf_mul (out2, in1, in2);
	mpf_sqrt (out2, out2);
}

int main (void) {
	mpf_set_default_prec (300000);
	mpf_t x0, y0, resA, resB, Z, var;

	mpf_init_set_ui (x0, 1);
	mpf_init_set_d (y0, 0.5);
	mpf_sqrt (y0, y0);
	mpf_init (resA);
	mpf_init (resB);
	mpf_init_set_d (Z, 0.25);
	mpf_init (var);

	int n = 1;
        int i;
	for(i=0; i<8; i++){
		agm(x0, y0, resA, resB);
		mpf_sub(var, resA, x0);
		mpf_mul(var, var, var);
		mpf_mul_ui(var, var, n);
		mpf_sub(Z, Z, var);
		n += n;
		agm(resA, resB, x0, y0);
		mpf_sub(var, x0, resA);
		mpf_mul(var, var, var);
		mpf_mul_ui(var, var, n);
		mpf_sub(Z, Z, var);
		n += n;
	}
	mpf_mul(x0, x0, x0);
	mpf_div(x0, x0, Z);
	gmp_printf ("%.100000Ff\n", x0);
	return 0;
}

pub fn pi(n: usize) -> f64 {
    let mut a : f64 = 1.0;
    let two : f64= 2.0;
    let mut g = 1.0 / two.sqrt();
    let mut s = 0.0;
    let mut k = 1;
    while k<=n  {

        let a1 = (a+g)/two;
        let g1 = (a*g).sqrt();
        a = a1;
        g = g1;
        s += (a.powi(2)-g.powi(2)) * two.powi((k+1) as i32);
        k += 1;

    }

    4.0 * a.powi(2) / (1.0-s)
}


Banker's algorithm

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

int main() {
    int curr[5][5];
    int max_claim[5][5];
    int avl[5];
    int alloc[5] = {0, 0, 0, 0, 0};
    int max_res[5];
    int running[5];

    int i, j, exec, r, p;
    int count = 0;
    bool safe = false;

    printf("\nEnter the number of resources: ");
    scanf("%d", &r);

    printf("\nEnter the number of processes: ");
    scanf("%d", &p);
    for (i = 0; i < p; i++) {
        running[i] = 1;
        count++;
    }

    printf("\nEnter Claim Vector: ");
    for (i = 0; i < r; i++)
        scanf("%d", &max_res[i]);

    printf("\nEnter Allocated Resource Table: ");
    for (i = 0; i < p; i++) {
        for (j = 0; j < r; j++)
            scanf("%d", &curr[i][j]);
    }

    printf("\nEnter Maximum Claim table: ");
    for (i = 0; i < p; i++) {
        for (j = 0; j < r; j++)
            scanf("%d", &max_claim[i][j]);
    }

    printf("\nThe Claim Vector is: ");
    for (i = 0; i < r; i++)
        printf("%d ", max_res[i]);

    printf("\nThe Allocated Resource Table:\n");
    for (i = 0; i < p; i++) {
        for (j = 0; j < r; j++)
            printf("\t%d", curr[i][j]);
        printf("\n");
    }

    printf("\nThe Maximum Claim Table:\n");
    for (i = 0; i < p; i++) {
        for (j = 0; j < r; j++)
            printf("\t%d", max_claim[i][j]);
        printf("\n");
    }

    for (i = 0; i < p; i++)
        for (j = 0; j < r; j++)
            alloc[j] += curr[i][j];

    printf("\nAllocated resources: ");
    for (i = 0; i < r; i++)
        printf("%d ", alloc[i]);
    for (i = 0; i < r; i++)
        avl[i] = max_res[i] - alloc[i];

    printf("\nAvailable resources: ");
    for (i = 0; i < r; i++)
        printf("%d ", avl[i]);
    printf("\n");

    while (count != 0) {
        safe = false;
        for (i = 0; i < p; i++) {
            if (running[i]) {
                exec = 1;
                for (j = 0; j < r; j++) {
                    if (max_claim[i][j] - curr[i][j] > avl[j]) {
                        exec = 0;
                        break;
                    }
                }

                if (exec) {
                    printf("\nProcess%d is executing.\n", i + 1);
                    running[i] = 0;
                    count--;
                    safe = true;
                    for (j = 0; j < r; j++)
                        avl[j] += curr[i][j];
                    break;
                }
            }
        }

        if (!safe) {
            printf("\nThe processes are in unsafe state.");
            break;
        }

        if (safe)
            printf("\nThe process is in safe state.");

        printf("\nAvailable vector: ");
        for (i = 0; i < r; i++)
            printf("%d ", avl[i]);
    }

    return 0;
}

fn read_numbers<T>() -> Vec<T>
where T: std::str::FromStr {
    use std::io::Write;
    std::io::stdout().flush().unwrap();

    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line.split(" ").map(|word| word.trim().parse::<T>().ok().unwrap()).collect()
}

fn main() {
    print!("Enter the number of resources: ");
    let r = read_numbers()[0];

    print!("Enter the number of processes: ");
    let p = read_numbers()[0];
    let mut running = vec![true; p];
    let mut count = p;

    print!("Enter the {}-item claim vector: ", r);
    let max_res = read_numbers::<u32>();

    println!("Enter the {}-line {}-column allocated-resource table:", p, r);
    let mut curr = vec![vec![0; 0]; p];
    for i in 0..p {
        curr[i] = read_numbers::<u32>();
    }

    println!("Enter the {}-line {}-column maximum-claim table:", p, r);
    let mut max_claim = vec![vec![0; 0]; p];
    for i in 0..p {
        max_claim[i] = read_numbers::<u32>();
    }

    print!("The claim vector is: ");
    for i in 0..r {
        print!("{} ", max_res[i]);
    }
    println!();

    println!("The allocated resources table is:");
    for i in 0..p {
        for j in 0..r {
            print!("\t{}", curr[i][j]);
        }
        println!();
    }

    println!("The maximum claims table is:");
    for i in 0..p {
        for j in 0..r {
            print!("\t{}", max_claim[i][j]);
        }
        println!();
    }

    let mut alloc = vec![0; r];
    for i in 0..p {
        for j in 0..r {
            alloc[j] += curr[i][j];
        }
    }

    print!("The allocated resources are: ");
    for i in 0..r {
        print!("{} ", alloc[i]);
    }
    println!();
    let mut avl = vec![0; r];
    for i in 0..r {
        avl[i] = max_res[i] - alloc[i];
    }

    print!("The available resources are: ");
    for i in 0..r {
        print!("{} ", avl[i]);
    }
    println!();

    while count != 0 {
        let mut safe = false;
        for i in 0..p {
            if running[i] {
                let mut exec = true;
                for j in 0..r {
                    if max_claim[i][j] - curr[i][j] > avl[j] {
                        exec = false;
                        break;
                    }
                }

                if exec {
                    println!("Process {} is executing.", i + 1);
                    running[i] = false;
                    count -= 1;
                    safe = true;
                    for j in 0..r {
                        avl[j] += curr[i][j];
                    }
                    break;
                }
            }
        }

        if safe {
            println!("The process is in safe state.");
        }
        else {
            println!("The processes are in unsafe state.");
            break;
        }

        print!("The available vector is: ");
        for i in 0..r {
            print!("{} ", avl[i]);
        }
        println!();
    }
}


Benford's law

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

float *benford_distribution(void)
{
    static float prob[9];
    for (int i = 1; i < 10; i++)
        prob[i - 1] = log10f(1 + 1.0 / i);

    return prob;
}

float *get_actual_distribution(char *fn)
{
    FILE *input = fopen(fn, "r");
    if (!input)
    {
        perror("Can't open file");
        exit(EXIT_FAILURE);
    }

    int tally[9] = { 0 };
    char c;
    int total = 0;
    while ((c = getc(input)) != EOF)
    {

        while (c < '1' || c > '9')
            c = getc(input);

        tally[c - '1']++;
        total++;

        while ((c = getc(input)) != '\n' && c != EOF)
            ;
    }
    fclose(input);

    static float freq[9];
    for (int i = 0; i < 9; i++)
        freq[i] = tally[i] / (float) total;

    return freq;
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        printf("Usage: benford <file>\n");
        return EXIT_FAILURE;
    }

    float *actual = get_actual_distribution(argv[1]);
    float *expected = benford_distribution();

    puts("digit\tactual\texpected");
    for (int i = 0; i < 9; i++)
        printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]);

    return EXIT_SUCCESS;
}

extern crate num_traits;
extern crate num;

use num::bigint::{BigInt, ToBigInt};
use num_traits::{Zero, One};
use std::collections::HashMap;

fn fib(n: usize) -> Vec<BigInt> {
    let mut result = Vec::with_capacity(n);
    let mut a = BigInt::zero();
    let mut b = BigInt::one();

    result.push(b.clone());

    for i in 1..n {
        let t = b.clone();
        b = a+b;
        a = t;
        result.push(b.clone());
    }

    result
}

fn first_digit(x: &BigInt) -> u8 {
    let zero = BigInt::zero();
    assert!(x > &zero);

    let s = x.to_str_radix(10);

    *&s[..1].parse::<u8>().unwrap()
}

fn main() {
    const N: usize = 1000;
    let mut counter: HashMap<u8, u32> = HashMap::new();
    for x in fib(N) {
        let d = first_digit(&x);
        *counter.entry(d).or_insert(0) += 1;
    }

    println!("{:>13}    {:>10}", "real", "predicted");
    for y in 1..10 {
        println!("{}: {:10.3} v. {:10.3}", y, *counter.get(&y).unwrap_or(&0) as f32 / N as f32,
        (1.0 + 1.0 / (y as f32)).log10());
    }

}


Bitcoin_public point to address

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>

#define COIN_VER 0
const char *coin_err;

typedef unsigned char byte;

int is_hex(const char *s) {
	int i;
	for (i = 0; i < 64; i++)
		if (!isxdigit(s[i])) return 0;
	return 1;
}

void str_to_byte(const char *src, byte *dst, int n) {
	while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}

char* base58(byte *s, char *out) {
	static const char *tmpl = "123456789"
		"ABCDEFGHJKLMNPQRSTUVWXYZ"
		"abcdefghijkmnopqrstuvwxyz";
	static char buf[40];

	int c, i, n;
	if (!out) out = buf;

	out[n = 34] = 0;
	while (n--) {
		for (c = i = 0; i < 25; i++) {
			c = c * 256 + s[i];
			s[i] = c / 58;
			c %= 58;
		}
		out[n] = tmpl[c];
	}

	for (n = 0; out[n] == '1'; n++);
	memmove(out, out + n, 34 - n);

	return out;
}

char *coin_encode(const char *x, const char *y, char *out) {
	byte s[65];
	byte rmd[5 + RIPEMD160_DIGEST_LENGTH];

	if (!is_hex(x) || !(is_hex(y))) {
		coin_err = "bad public point string";
		return 0;
	}

	s[0] = 4;
	str_to_byte(x, s + 1, 32);
	str_to_byte(y, s + 33, 32);

	rmd[0] = COIN_VER;
	RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);

	memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);

	return base58(rmd, out);
}

int main(void) {
	puts(coin_encode(
		"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
		"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
		0));
	return 0;
}

use ring::digest::{digest, SHA256};
use ripemd160::{Digest, Ripemd160};

use hex::FromHex;

static X: &str = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352";
static Y: &str = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6";
static ALPHABET: [char; 58] = [
    '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
    'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e',
    'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
    'z',
];

fn base58_encode(bytes: &mut [u8]) -> String {
    let base = ALPHABET.len();
    if bytes.is_empty() {
        return String::from("");
    }
    let mut output: Vec<u8> = Vec::new();
    let mut num: usize;
    for _ in 0..33 {
        num = 0;
        for byte in bytes.iter_mut() {
            num = num * 256 + *byte as usize;
            *byte = (num / base) as u8;
            num %= base;
        }
        output.push(num as u8);
    }
    let mut string = String::new();
    for b in output.iter().rev() {
        string.push(ALPHABET[*b as usize]);
    }
    string
}

fn double_sha256(bytes: &[u8]) -> Vec<u8> {
    let digest_1 = digest(&SHA256, bytes);

    let digest_2 = digest(&SHA256, digest_1.as_ref());
    digest_2.as_ref().to_vec()
}

fn point_to_address(x: &str, y: &str) -> String {
    let mut addrv: Vec<u8> = Vec::with_capacity(65);
    addrv.push(4u8);
    addrv.append(&mut <Vec<u8>>::from_hex(x).unwrap());
    addrv.append(&mut <Vec<u8>>::from_hex(y).unwrap());

    let sha_digest = digest(&SHA256, &addrv);
    let mut ripemd_digest = Ripemd160::digest(&sha_digest.as_ref()).as_slice().to_vec();

    ripemd_digest.insert(0, 0);

    let checksum = double_sha256(&ripemd_digest);
    ripemd_digest.extend_from_slice(&checksum[..4]);
    base58_encode(&mut ripemd_digest)
}

fn main() {
    println!("{}", point_to_address(X, Y));
}


Brace expansion

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 128

typedef unsigned char character;
typedef character *string;

typedef struct node_t node;
struct node_t {
    enum tag_t {
        NODE_LEAF,
        NODE_TREE,
        NODE_SEQ,
    } tag;

    union {
        string str;
        node *root;
    } data;

    node *next;
};

node *allocate_node(enum tag_t tag) {
    node *n = malloc(sizeof(node));
    if (n == NULL) {
        fprintf(stderr, "Failed to allocate node for tag: %d\n", tag);
        exit(1);
    }
    n->tag = tag;
    n->next = NULL;
    return n;
}

node *make_leaf(string str) {
    node *n = allocate_node(NODE_LEAF);
    n->data.str = str;
    return n;
}

node *make_tree() {
    node *n = allocate_node(NODE_TREE);
    n->data.root = NULL;
    return n;
}

node *make_seq() {
    node *n = allocate_node(NODE_SEQ);
    n->data.root = NULL;
    return n;
}

void deallocate_node(node *n) {
    if (n == NULL) {
        return;
    }

    deallocate_node(n->next);
    n->next = NULL;

    if (n->tag == NODE_LEAF) {
        free(n->data.str);
        n->data.str = NULL;
    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {
        deallocate_node(n->data.root);
        n->data.root = NULL;
    } else {
        fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag);
        exit(1);
    }

    free(n);
}

void append(node *root, node *elem) {
    if (root == NULL) {
        fprintf(stderr, "Cannot append to uninitialized node.");
        exit(1);
    }
    if (elem == NULL) {
        return;
    }

    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {
        if (root->data.root == NULL) {
            root->data.root = elem;
        } else {
            node *it = root->data.root;
            while (it->next != NULL) {
                it = it->next;
            }
            it->next = elem;
        }
    } else {
        fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag);
        exit(1);
    }
}

size_t count(node *n) {
    if (n == NULL) {
        return 0;
    }

    if (n->tag == NODE_LEAF) {
        return 1;
    }
    if (n->tag == NODE_TREE) {
        size_t sum = 0;
        node *it = n->data.root;
        while (it != NULL) {
            sum += count(it);
            it = it->next;
        }
        return sum;
    }
    if (n->tag == NODE_SEQ) {
        size_t prod = 1;
        node *it = n->data.root;
        while (it != NULL) {
            prod *= count(it);
            it = it->next;
        }
        return prod;
    }

    fprintf(stderr, "Cannot count node with tag: %d\n", n->tag);
    exit(1);
}

void expand(node *n, size_t pos) {
    if (n == NULL) {
        return;
    }

    if (n->tag == NODE_LEAF) {
        printf(n->data.str);
    } else if (n->tag == NODE_TREE) {
        node *it = n->data.root;
        while (true) {
            size_t cnt = count(it);
            if (pos < cnt) {
                expand(it, pos);
                break;
            }
            pos -= cnt;
            it = it->next;
        }
    } else if (n->tag == NODE_SEQ) {
        size_t prod = pos;
        node *it = n->data.root;
        while (it != NULL) {
            size_t cnt = count(it);

            size_t rem = prod % cnt;
            expand(it, rem);

            it = it->next;
        }
    } else {
        fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag);
        exit(1);
    }
}

string allocate_string(string src) {
    size_t len = strlen(src);
    string out = calloc(len + 1, sizeof(character));
    if (out == NULL) {
        fprintf(stderr, "Failed to allocate a copy of the string.");
        exit(1);
    }
    strcpy(out, src);
    return out;
}

node *parse_seq(string input, size_t *pos);

node *parse_tree(string input, size_t *pos) {
    node *root = make_tree();

    character buffer[BUFFER_SIZE] = { 0 };
    size_t bufpos = 0;
    size_t depth = 0;
    bool asSeq = false;
    bool allow = false;

    while (input[*pos] != 0) {
        character c = input[(*pos)++];
        if (c == '\\') {
            c = input[(*pos)++];
            if (c == 0) {
                break;
            }
            buffer[bufpos++] = '\\';
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        } else if (c == '{') {
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
            asSeq = true;
            depth++;
        } else if (c == '}') {
            if (depth-- > 0) {
                buffer[bufpos++] = c;
                buffer[bufpos] = 0;
            } else {
                if (asSeq) {
                    size_t new_pos = 0;
                    node *seq = parse_seq(buffer, &new_pos);
                    append(root, seq);
                } else {
                    append(root, make_leaf(allocate_string(buffer)));
                }
                break;
            }
        } else if (c == ',') {
            if (depth == 0) {
                if (asSeq) {
                    size_t new_pos = 0;
                    node *seq = parse_seq(buffer, &new_pos);
                    append(root, seq);
                    bufpos = 0;
                    buffer[bufpos] = 0;
                    asSeq = false;
                } else {
                    append(root, make_leaf(allocate_string(buffer)));
                    bufpos = 0;
                    buffer[bufpos] = 0;
                }
            } else {
                buffer[bufpos++] = c;
                buffer[bufpos] = 0;
            }
        } else {
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        }
    }

    return root;
}

node *parse_seq(string input, size_t *pos) {
    node *root = make_seq();

    character buffer[BUFFER_SIZE] = { 0 };
    size_t bufpos = 0;

    while (input[*pos] != 0) {
        character c = input[(*pos)++];
        if (c == '\\') {
            c = input[(*pos)++];
            if (c == 0) {
                break;
            }
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        } else if (c == '{') {
            node *tree = parse_tree(input, pos);
            if (bufpos > 0) {
                append(root, make_leaf(allocate_string(buffer)));
                bufpos = 0;
                buffer[bufpos] = 0;
            }
            append(root, tree);
        } else {
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        }
    }

    if (bufpos > 0) {
        append(root, make_leaf(allocate_string(buffer)));
        bufpos = 0;
        buffer[bufpos] = 0;
    }

    return root;
}

void test(string input) {
    size_t pos = 0;
    node *n = parse_seq(input, &pos);
    size_t cnt = count(n);
    size_t i;

    printf("Pattern: %s\n", input);

    for (i = 0; i < cnt; i++) {
        expand(n, i);
        printf("\n");
    }
    printf("\n");

    deallocate_node(n);
}

int main() {
    test("~/{Downloads,Pictures}/*.{jpg,gif,png}");
    test("It{{em,alic}iz,erat}e{d,}, please.");
    test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!");

    return 0;
}

const OPEN_CHAR: char = '{';
const CLOSE_CHAR: char = '}';
const SEPARATOR: char = ',';
const ESCAPE: char = '\\';

#[derive(Debug, PartialEq, Clone)]
enum Token {
    Open,
    Close,
    Separator,
    Payload(String),
    Branches(Branches),
}

impl From<char> for Token {
    fn from(ch: char) -> Token {
        match ch {
            OPEN_CHAR => Token::Open,
            CLOSE_CHAR => Token::Close,
            SEPARATOR => Token::Separator,
            _ => panic!("Non tokenizable char!"),
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
struct Branches {
    tokens: Vec<Vec<Token>>,
}

impl Branches {
    fn new() -> Branches {
        Branches{
            tokens: Vec::new(),
        }
    }

    fn add_branch(&mut self, branch: Vec<Token>) {
        self.tokens.push(branch);
    }

    fn from(tokens: &Vec<Token>) -> Branches {
        let mut branches = Branches::new();
        let mut tail = tokens.clone();
        while let Some(pos) = tail.iter().position(|token| { *token == Token::Separator }) {
            let mut rest = tail.split_off(pos);
            branches.add_branch(tail);
            rest.remove(0);
            tail = rest;
        }
        branches.add_branch(tail);
        branches
    }
}

impl From<Branches> for Token {
    fn from(branches: Branches) -> Token {
        Token::Branches(branches)
    }
}

impl From<Vec<Token>> for Branches {
    fn from(tokens: Vec<Token>) -> Branches {
        Branches::from(&tokens)
    }
}

impl From<Token> for String {
    fn from(token: Token) -> String {
        match token {
            Token::Branches(_) => panic!("Cannot convert to String!"),
            Token::Payload(text) => text,
            Token::Open => OPEN_CHAR.to_string(),
            Token::Close => CLOSE_CHAR.to_string(),
            Token::Separator => SEPARATOR.to_string(),
        }
    }
}

impl From<Branches> for Vec<String> {
    fn from(branches: Branches) -> Vec<String> {
        let Branches{ tokens: token_lines } = branches;
        let mut vec: Vec<String> = Vec::new();
        let braces = { if token_lines.len() == 1 { true } else { false } };
        for tokens in token_lines {
            let mut vec_string = output(tokens);
            vec.append(&mut vec_string);
        }
        if braces {
            vec.iter()
                .map(|line| {
                    format!("{}{}{}", OPEN_CHAR, line, CLOSE_CHAR)
                }).
                collect::<Vec<String>>()
        } else {
            vec
        }
    }
}

impl From<Token> for Vec<String> {
    fn from(token: Token) -> Vec<String> {
        match token {
            Token::Branches(branches) => {
                branches.into()
            },
            _ => {
                let frag: String = token.into();
                vec![frag]
            },
        }
    }
}

fn tokenize(string: &str) -> Vec<Token> {
    let mut tokens: Vec<Token> = Vec::new();
    let mut chars = string.chars();
    let mut payload = String::new();
    while let Some(ch) = chars.next() {
        match ch {
            OPEN_CHAR | SEPARATOR | CLOSE_CHAR => {
                if payload.len() > 0 {
                    tokens.push(Token::Payload(payload));
                }
                payload = String::new();
                if ch == CLOSE_CHAR {
                    let pos = tokens.iter().rposition(|token| *token == Token::Open);
                    if let Some(pos) = pos {
                        let branches: Branches = {
                            let mut to_branches = tokens.split_off(pos);
                            to_branches.remove(0);
                            to_branches
                        }.into();
                        tokens.push(branches.into());
                    } else {
                        tokens.push(ch.into());
                    }
                } else {
                    tokens.push(ch.into());
                }
            },
            ESCAPE => {
                payload.push(ch);
                if let Some(next_char) = chars.next() {
                    payload.push(next_char);
                }
            },
            _ => payload.push(ch),
        }
    }
    let payload = payload.trim_end();
    if payload.len() > 0 {
        tokens.push(Token::Payload(payload.into()));
    }
    tokens
}

fn output(tokens: Vec<Token>) -> Vec<String> {
    let mut output: Vec<String> = vec![String::new()];
    for token in tokens {
        let mut aux: Vec<String> = Vec::new();
        let strings: Vec<String> = token.into();
        for root in &output {
            for string in &strings {
                aux.push({format!("{}{}", root, string)});
            }
        }
        output = aux;
    }
    output
}

fn main() {
    let mut input: String = String::new();
    std::io::stdin().read_line(&mut input).unwrap();

    let tokens: Vec<Token> = tokenize(&input);

    let output = output(tokens);
    for line in &output {
        println!("{}", line);
    }
}


Brazilian numbers

#include <stdio.h>

typedef char bool;

#define TRUE 1
#define FALSE 0

bool same_digits(int n, int b) {
    int f = n % b;
    n /= b;
    while (n > 0) {
        if (n % b != f) return FALSE;
        n /= b;
    }
    return TRUE;
}

bool is_brazilian(int n) {
    int b;
    if (n < 7) return FALSE;
    if (!(n % 2) && n >= 8) return TRUE;
    for (b = 2; b < n - 1; ++b) {
        if (same_digits(n, b)) return TRUE;
    }
    return FALSE;
}

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

int main() {
    int i, c, n;
    const char *kinds[3] = {" ", " odd ", " prime "};
    for (i = 0; i < 3; ++i) {
        printf("First 20%sBrazilian numbers:\n", kinds[i]);
        c = 0;
        n = 7;
        while (TRUE) {
            if (is_brazilian(n)) {
                printf("%d ", n);
                if (++c == 20) {
                    printf("\n\n");
                    break;
                }
            }
            switch (i) {
                case 0: n++; break;
                case 1: n += 2; break;
                case 2:
                    do {
                        n += 2;
                    } while (!is_prime(n));
                    break;
            }
        }
    }

    for (n = 7, c = 0; c < 100000; ++n) {
        if (is_brazilian(n)) c++;
    }
    printf("The 100,000th Brazilian number: %d\n", n - 1);
    return 0;
}

fn same_digits(x: u64, base: u64) -> bool {
    let f = x % base;
    let mut n = x;
    while n > 0 {
        if n % base != f {
            return false;
        }
        n /= base;
    }

    true
}
fn is_brazilian(x: u64) -> bool {
    if x < 7 {
        return false;
    };
    if x % 2 == 0 {
        return true;
    };

    for base in 2..(x - 1) {
        if same_digits(x, base) {
            return true;
        }
    }
    false
}

fn main() {
    let mut counter = 0;
    let limit = 20;
    let big_limit = 100_000;
    let mut big_result: u64 = 0;
    let mut br: Vec<u64> = Vec::new();
    let mut o: Vec<u64> = Vec::new();
    let mut p: Vec<u64> = Vec::new();

    for x in 7.. {
        if is_brazilian(x) {
            counter += 1;
            if br.len() < limit {
                br.push(x);
            }
            if o.len() < limit && x % 2 == 1 {
                o.push(x);
            }
            if p.len() < limit && primes::is_prime(x) {
                p.push(x);
            }
            if counter == big_limit {
                big_result = x;
                break;
            }
        }
    }
    println!("First {} Brazilian numbers:", limit);
    println!("{:?}", br);
    println!("\nFirst {} odd Brazilian numbers:", limit);
    println!("{:?}", o);
    println!("\nFirst {} prime Brazilian numbers:", limit);
    println!("{:?}", p);

    println!("\nThe {}th Brazilian number: {}", big_limit, big_result);
}


Burrows–Wheeler transform

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

const char STX = '\002', ETX = '\003';

int compareStrings(const void *a, const void *b) {
    char *aa = *(char **)a;
    char *bb = *(char **)b;
    return strcmp(aa, bb);
}

int bwt(const char *s, char r[]) {
    int i, len = strlen(s) + 2;
    char *ss, *str;
    char **table;
    if (strchr(s, STX) || strchr(s, ETX)) return 1;
    ss = calloc(len + 1, sizeof(char));
    sprintf(ss, "%c%s%c", STX, s, ETX);
    table = malloc(len * sizeof(const char *));
    for (i = 0; i < len; ++i) {
        str = calloc(len + 1, sizeof(char));
        strcpy(str, ss + i);
        if (i > 0) strncat(str, ss, i);
        table[i] = str;
    }
    qsort(table, len, sizeof(const char *), compareStrings);
    for(i = 0; i < len; ++i) {
        r[i] = table[i][len - 1];
        free(table[i]);
    }
    free(table);
    free(ss);
    return 0;
}

void ibwt(const char *r, char s[]) {
    int i, j, len = strlen(r);
    char **table = malloc(len * sizeof(const char *));
    for (i = 0; i < len; ++i) table[i] = calloc(len + 1, sizeof(char));
    for (i = 0; i < len; ++i) {
        for (j = 0; j < len; ++j) {
            memmove(table[j] + 1, table[j], len);
            table[j][0] = r[j];
        }
        qsort(table, len, sizeof(const char *), compareStrings);
    }
    for (i = 0; i < len; ++i) {
        if (table[i][len - 1] == ETX) {
            strncpy(s, table[i] + 1, len - 2);
            break;
        }
    }
    for (i = 0; i < len; ++i) free(table[i]);
    free(table);
}

void makePrintable(const char *s, char t[]) {
    strcpy(t, s);
    for ( ; *t != '\0'; ++t) {
        if (*t == STX) *t = '^';
        else if (*t == ETX) *t = '|';
    }
}

int main() {
    int i, res, len;
    char *tests[6], *t, *r, *s;
    tests[0] = "banana";
    tests[1] = "appellee";
    tests[2] = "dogwood";
    tests[3] = "TO BE OR NOT TO BE OR WANT TO BE OR NOT?";
    tests[4] = "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
    tests[5] = "\002ABC\003";
    for (i = 0; i < 6; ++i) {
        len = strlen(tests[i]);
        t = calloc(len + 1, sizeof(char));
        makePrintable(tests[i], t);
        printf("%s\n", t);
        printf(" --> ");
        r = calloc(len + 3, sizeof(char));
        res = bwt(tests[i], r);
        if (res == 1) {
            printf("ERROR: String can't contain STX or ETX\n");
        }
        else {
            makePrintable(r, t);
            printf("%s\n", t);
        }
        s = calloc(len + 1, sizeof(char));
        ibwt(r, s);
        makePrintable(s, t);
        printf(" --> %s\n\n", t);
        free(t);
        free(r);
        free(s);
    }
    return 0;
}

use core::cmp::Ordering;

const STX: char = '\u{0002}';
const ETX: char = '\u{0003}';

pub fn special_cmp(lhs: &str, rhs: &str) -> Ordering {
    let mut iter1 = lhs.chars();
    let mut iter2 = rhs.chars();

    loop {
        match (iter1.next(), iter2.next()) {
            (Some(lhs), Some(rhs)) => {
                if lhs != rhs {
                    let is_lhs_special = lhs == ETX || lhs == STX;
                    let is_rhs_special = rhs == ETX || rhs == STX;

                    let result = if is_lhs_special == is_rhs_special {
                        lhs.cmp(&rhs)
                    } else if is_lhs_special {
                        Ordering::Greater
                    } else {
                        Ordering::Less
                    };

                    return result;
                }
            }
            (Some(_), None) => return Ordering::Greater,
            (None, Some(_)) => return Ordering::Less,
            (None, None) => return lhs.cmp(&rhs),
        }
    }
}

fn burrows_wheeler_transform(input: &str) -> String {
    let mut table: Vec<String> = vec![];

    let input_string = format!("{}{}{}", STX, input, ETX);

    for (i, _) in input_string.char_indices() {
        table.push(format!(
            "{}{}",
            &input_string[input_string.len() - 1 - i..],
            &input_string[0..input_string.len() - 1 - i]
        ));
    }

    table.sort_unstable_by(|lhs, rhs| special_cmp(&lhs, &rhs));

    table
        .iter()
        .map(|s| s.chars().nth_back(0).unwrap())
        .collect::<String>()
}

fn inverse_burrows_wheeler_transform(input: &str) -> String {
    let mut table: Vec<String> = vec![String::new(); input.len()];
    for _ in 0..input.len() {

        for (j, s) in table.iter_mut().enumerate() {
            *s = format!("{}{}", input.chars().nth(j).unwrap(), s);
        }

        table.sort_unstable_by(|lhs, rhs| special_cmp(&lhs, &rhs));
    }

    table
        .into_iter()
        .filter(|s| s.ends_with(ETX))
        .collect::<String>()

        .replace(STX, "")
        .replace(ETX, "")
}

fn main() {
    let input = [
        "banana",
        "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
        "TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
    ];
    for s in input.iter() {
        let bwt = burrows_wheeler_transform(s);
        let ibwt = inverse_burrows_wheeler_transform(&bwt);
        println!("Input: {}", s);
        println!("\tBWT: {}", bwt.replace(STX, "^").replace(ETX, "|"));
        println!("\tInverse BWT: {}", ibwt);
    }
}


Canonicalize CIDR

#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>

typedef struct cidr_tag {
    uint32_t address;
    unsigned int mask_length;
} cidr_t;

bool cidr_parse(const char* str, cidr_t* cidr) {
    int a, b, c, d, m;
    if (sscanf(str, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &m) != 5)
        return false;
    if (m < 1 || m > 32
        || a < 0 || a > UINT8_MAX
        || b < 0 || b > UINT8_MAX
        || c < 0 || c > UINT8_MAX
        || d < 0 || d > UINT8_MAX)
        return false;
    uint32_t mask = ~((1 << (32 - m)) - 1);
    uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;
    address &= mask;
    cidr->address = address;
    cidr->mask_length = m;
    return true;
}

void cidr_format(const cidr_t* cidr, char* str, size_t size) {
    uint32_t address = cidr->address;
    unsigned int d = address & UINT8_MAX;
    address >>= 8;
    unsigned int c = address & UINT8_MAX;
    address >>= 8;
    unsigned int b = address & UINT8_MAX;
    address >>= 8;
    unsigned int a = address & UINT8_MAX;
    snprintf(str, size, "%u.%u.%u.%u/%u", a, b, c, d,
             cidr->mask_length);
}

int main(int argc, char** argv) {
    const char* tests[] = {
        "87.70.141.1/22",
        "36.18.154.103/12",
        "62.62.197.11/29",
        "67.137.119.181/4",
        "161.214.74.21/24",
        "184.232.176.184/18"
    };
    for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {
        cidr_t cidr;
        if (cidr_parse(tests[i], &cidr)) {
            char out[32];
            cidr_format(&cidr, out, sizeof(out));
            printf("%-18s -> %s\n", tests[i], out);
        } else {
            fprintf(stderr, "%s: invalid CIDR\n", tests[i]);
        }
    }
    return 0;
}


Case-sensitivity of identifiers

#include <stdio.h>

static const char *dog = "Benjamin";
static const char *Dog = "Samba";
static const char *DOG = "Bernie";

int main()
{
    printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG);
    return 0;
}

fn main() {
    let dog = "Benjamin";
    let Dog = "Samba";
    let DOG = "Bernie";
    println!("The three dogs are named {}, {} and {}.", dog, Dog, DOG);
}


Casting out nines

#include <stdio.h>
#include <math.h>

int main() {
    const int N = 2;
    int base = 10;
    int c1 = 0;
    int c2 = 0;
    int k;

    for (k = 1; k < pow(base, N); k++) {
        c1++;
        if (k % (base - 1) == (k * k) % (base - 1)) {
            c2++;
            printf("%d ", k);
        }
    }

    printf("\nTring %d numbers instead of %d numbers saves %f%%\n", c2, c1, 100.0 - 100.0 * c2 / c1);
    return 0;
}

fn compare_co9_efficiency(base: u64, upto: u64) {
    let naive_candidates: Vec<u64> = (1u64..upto).collect();
    let co9_candidates: Vec<u64> = naive_candidates.iter().cloned()
        .filter(|&x| x % (base - 1) == (x * x) % (base - 1))
        .collect();
    for candidate in &co9_candidates {
        print!("{} ", candidate);
    }
    println!();
    println!(
        "Trying {} numbers instead of {} saves {:.2}%",
        co9_candidates.len(),
        naive_candidates.len(),
        100.0 - 100.0 * (co9_candidates.len() as f64 / naive_candidates.len() as f64)
    );
}

fn main() {
    compare_co9_efficiency(10, 100);
    compare_co9_efficiency(16, 256);
}