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

typedef struct floatList {
    float *list;
    int   size;
} *FloatList;

int floatcmp( const void *a, const void *b) {
    if (*(const float *)a < *(const float *)b) return -1;
    else return *(const float *)a > *(const float *)b;
}

float median( FloatList fl )
{
    qsort( fl->list, fl->size, sizeof(float), floatcmp);
    return 0.5 * ( fl->list[fl->size/2] + fl->list[(fl->size-1)/2]);
}

int main()
{
    static float floats1[] = { 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 };
    static struct floatList flist1 = { floats1, sizeof(floats1)/sizeof(float) };

    static float floats2[] = { 5.1, 2.6, 8.8, 4.6, 4.1 };
    static struct floatList flist2 = { floats2, sizeof(floats2)/sizeof(float) };

    printf("flist1 median is %7.2f\n", median(&flist1));
    printf("flist2 median is %7.2f\n", median(&flist2));
    return 0;
}


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

typedef struct { double v; int c; } vcount;

int cmp_dbl(const void *a, const void *b)
{
	double x = *(const double*)a - *(const double*)b;
	return x < 0 ? -1 : x > 0;
}

int vc_cmp(const void *a, const void *b)
{
	return ((const vcount*)b)->c - ((const vcount*)a)->c;
}

int get_mode(double* x, int len, vcount **list)
{
	int i, j;
	vcount *vc;

	qsort(x, len, sizeof(double), cmp_dbl);

	for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1]));

	*list = vc = malloc(sizeof(vcount) * j);
	vc[0].v = x[0];
	vc[0].c = 1;

	for (i = j = 0; i < len - 1; i++, vc[j].c++)
		if (x[i] != x[i + 1]) vc[++j].v = x[i + 1];

	qsort(vc, j + 1, sizeof(vcount), vc_cmp);

	for (i = 0; i <= j && vc[i].c == vc[0].c; i++);

	return i;
}

int main()
{
	double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 };
#	define len sizeof(values)/sizeof(double)
	vcount *vc;

	int i, n_modes = get_mode(values, len, &vc);

	printf("got %d modes:\n", n_modes);
	for (i = 0; i < n_modes; i++)
		printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c);

	free(vc);
	return 0;
}

use std::collections::HashMap;

fn main() {
    let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
    let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]);

    println!("Mode of vec1 is: {:?}", mode_vec1);
    println!("Mode of vec2 is: {:?}", mode_vec2);

    assert!( mode_vec1 == [6], "Error in mode calculation");
    assert!( (mode_vec2 == [1, 4]) || (mode_vec2 == [4,1]), "Error in mode calculation" );
}

fn mode(vs: Vec<i32>) -> Vec<i32> {
    let mut vec_mode = Vec::new();
    let mut seen_map = HashMap::new();
    let mut max_val = 0;
    for i in vs{
        let ctr = seen_map.entry(i).or_insert(0);
        *ctr += 1;
        if *ctr > max_val{
            max_val = *ctr;
        }
    }
    for (key, val) in seen_map {
        if val == max_val{
            vec_mode.push(key);
        }
    }
    vec_mode
}


Averages_Pythagorean means

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

int main(int argc, char* argv[])
{
  int i, count=0;
  double f, sum=0.0, prod=1.0, resum=0.0;

  for (i=1; i<argc; ++i) {
    f = atof(argv[i]);
    count++;
    sum += f;
    prod *= f;
    resum += (1.0/f);
  }

  printf("Arithmetic mean = %f\n",sum/count);
  printf("Geometric mean = %f\n",pow(prod,(1.0/count)));
  printf("Harmonic mean = %f\n",count/resum);

  return 0;
}

fn main() {
    let mut sum = 0.0;
    let mut prod = 1;
    let mut recsum = 0.0;
    for i in 1..11{
        sum += i as f32;
        prod *= i;
        recsum += 1.0/(i as f32);
    }
    let avg = sum/10.0;
    let gmean = (prod as f32).powf(0.1);
    let hmean = 10.0/recsum;
    println!("Average: {}, Geometric mean: {}, Harmonic mean: {}", avg, gmean, hmean);
    assert!( ( (avg >= gmean) && (gmean >= hmean) ), "Incorrect calculation");

}


Averages_Root mean square

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

double rms(double *v, int n)
{
  int i;
  double sum = 0.0;
  for(i = 0; i < n; i++)
    sum += v[i] * v[i];
  return sqrt(sum / n);
}

int main(void)
{
  double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
  printf("%f\n", rms(v, sizeof(v)/sizeof(double)));
  return 0;
}

fn root_mean_square(vec: Vec<i32>) -> f32 {
    let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2));
    return ((sum_squares as f32)/(vec.len() as f32)).sqrt();
}

fn main() {
    let vec = (1..11).collect();
    println!("The root mean square is: {}", root_mean_square(vec));
}


Averages_Simple moving average

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

typedef struct sma_obj {
  double sma;
  double sum;
  int period;
  double *values;
  int lv;
} sma_obj_t;

typedef union sma_result {
  sma_obj_t *handle;
  double sma;
  double *values;
} sma_result_t;

enum Action { SMA_NEW, SMA_FREE, SMA_VALUES, SMA_ADD, SMA_MEAN };
sma_result_t sma(enum Action action, ...)
{
  va_list vl;
  sma_result_t r;
  sma_obj_t *o;
  double v;

  va_start(vl, action);
  switch(action) {
  case SMA_NEW:
    r.handle = malloc(sizeof(sma_obj_t));
    r.handle->sma = 0.0;
    r.handle->period = va_arg(vl, int);
    r.handle->values = malloc(r.handle->period * sizeof(double));
    r.handle->lv = 0;
    r.handle->sum = 0.0;
    break;
  case SMA_FREE:
    r.handle = va_arg(vl, sma_obj_t *);
    free(r.handle->values);
    free(r.handle);
    r.handle = NULL;
    break;
  case SMA_VALUES:
    o = va_arg(vl, sma_obj_t *);
    r.values = o->values;
    break;
  case SMA_MEAN:
    o = va_arg(vl, sma_obj_t *);
    r.sma = o->sma;
    break;
  case SMA_ADD:
    o = va_arg(vl, sma_obj_t *);
    v = va_arg(vl, double);
    if ( o->lv < o->period ) {
      o->values[o->lv++] = v;
      o->sum += v;
      o->sma = o->sum / o->lv;
    } else {
      o->sum -= o->values[ o->lv % o->period];
      o->sum += v;
      o->sma = o->sum / o->period;
      o->values[ o->lv % o->period ] = v; o->lv++;
    }
    r.sma = o->sma;
    break;
  }
  va_end(vl);
  return r;
}

struct SimpleMovingAverage {
    period: usize,
    numbers: Vec<usize>
}

impl SimpleMovingAverage {
    fn new(p: usize) -> SimpleMovingAverage {
        SimpleMovingAverage {
            period: p,
            numbers: Vec::new()
        }
    }

    fn add_number(&mut self, number: usize) -> f64 {
        self.numbers.push(number);

        if self.numbers.len() > self.period {
            self.numbers.remove(0);
        }

        if self.numbers.is_empty() {
            return 0f64;
        }else {
            let sum = self.numbers.iter().fold(0, |acc, x| acc+x);
            return sum as f64 / self.numbers.len() as f64;
        }
    }
}

fn main() {
    for period in [3, 5].iter() {
        println!("Moving average with period {}", period);

        let mut sma = SimpleMovingAverage::new(*period);
        for i in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1].iter() {
            println!("Number: {} | Average: {}", i, sma.add_number(*i));
        }
    }
}


Babbage problem

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

int main() {
	int current = 0,
	    square;

	while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) {
		current++;
	}

	if (square>+INT_MAX)
	    printf("Condition not satisfied before INT_MAX reached.");
	else
	    printf ("The smallest number whose square ends in 269696 is %d\n", current);

	return 0 ;
}

fn main() {
    let mut current = 0;
    while (current * current) % 1_000_000 != 269_696 {
        current += 1;
    }
    println!(
        "The smallest number whose square ends in 269696 is {}",
        current
    );
}


Balanced brackets

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

int isBal(const char*s,int l){
    signed c=0;
    while(l--)
	if(s[l]==']') ++c;
	else if(s[l]=='[') if(--c<0) break;
    return !c;
}

void shuffle(char*s,int h){
    int x,t,i=h;
    while(i--){
	t=s[x=rand()%h];
	s[x]=s[i];
	s[i]=t;
    }
}

void genSeq(char*s,int n){
    if(n){
	memset(s,'[',n);
	memset(s+n,']',n);
	shuffle(s,n*2);
    }
    s[n*2]=0;
}

void doSeq(int n){
    char s[64];
    const char *o="False";
    genSeq(s,n);
    if(isBal(s,n*2)) o="True";
    printf("'%s': %s\n",s,o);
}

int main(){
    int n=0;
    while(n<9) doSeq(n++);
    return 0;
}

extern crate rand;

trait Balanced {

    fn is_balanced(&self) -> bool;
}

impl<'a> Balanced for str {
    fn is_balanced(&self) -> bool {
        let mut count = 0;

        for bracket in self.chars() {
            let change = match bracket {
                '[' => 1,
                ']' => -1,
                _ => panic!("Strings should only contain brackets")
            };

            count += change;
            if count < 0 { return false; }
        }

        count == 0
    }
}

fn generate_brackets(num: usize) -> String {
    use rand::random;

    (0..num).map(|_| if random() { '[' } else { ']' }).collect()
}

fn main() {
    for i in (0..10) {
        let brackets = generate_brackets(i);

        println!("{}    {}", brackets, brackets.is_balanced())
    }
}


Balanced ternary

use std::{
    cmp::min,
    convert::{TryFrom, TryInto},
    fmt,
    ops::{Add, Mul, Neg},
    str::FromStr,
};

fn main() -> Result<(), &'static str> {
    let a = BalancedTernary::from_str("+-0++0+")?;
    let b = BalancedTernary::from(-436);
    let c = BalancedTernary::from_str("+-++-")?;
    println!("a = {} = {}", a, i128::try_from(a.clone())?);
    println!("b = {} = {}", b, i128::try_from(b.clone())?);
    println!("c = {} = {}", c, i128::try_from(c.clone())?);

    let d = a * (b + -c);
    println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?);

    let e = BalancedTernary::from_str(
        "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++",
    )?;
    assert_eq!(i128::try_from(e).is_err(), true);

    Ok(())
}

#[derive(Clone, Copy, PartialEq)]
enum Trit {
    Zero,
    Pos,
    Neg,
}

impl TryFrom<char> for Trit {
    type Error = &'static str;

    fn try_from(value: char) -> Result<Self, Self::Error> {
        match value {
            '0' => Ok(Self::Zero),
            '+' => Ok(Self::Pos),
            '-' => Ok(Self::Neg),
            _ => Err("Invalid character for balanced ternary"),
        }
    }
}

impl From<Trit> for char {
    fn from(x: Trit) -> Self {
        match x {
            Trit::Zero => '0',
            Trit::Pos => '+',
            Trit::Neg => '-',
        }
    }
}

impl Add for Trit {

    type Output = (Self, Self);

    fn add(self, rhs: Self) -> Self::Output {
        use Trit::{Neg, Pos, Zero};
        match (self, rhs) {
            (Zero, x) | (x, Zero) => (Zero, x),
            (Pos, Neg) | (Neg, Pos) => (Zero, Zero),
            (Pos, Pos) => (Pos, Neg),
            (Neg, Neg) => (Neg, Pos),
        }
    }
}

impl Mul for Trit {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        use Trit::{Neg, Pos, Zero};
        match (self, rhs) {
            (Zero, _) | (_, Zero) => Zero,
            (Pos, Pos) | (Neg, Neg) => Pos,
            (Pos, Neg) | (Neg, Pos) => Neg,
        }
    }
}

impl Neg for Trit {
    type Output = Self;

    fn neg(self) -> Self::Output {
        match self {
            Trit::Zero => Trit::Zero,
            Trit::Pos => Trit::Neg,
            Trit::Neg => Trit::Pos,
        }
    }
}

#[derive(Clone)]
struct BalancedTernary(Vec<Trit>);

impl fmt::Display for BalancedTernary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.0
                .iter()
                .rev()
                .map(|&d| char::from(d))
                .collect::<String>()
        )
    }
}

impl Add for BalancedTernary {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        use Trit::Zero;

        fn trim(v: &mut Vec<Trit>) {
            while let Some(last_elem) = v.pop() {
                if last_elem != Zero {
                    v.push(last_elem);
                    break;
                }
            }
        }

        if rhs.0.is_empty() {

            if self.0.is_empty() {
                return BalancedTernary(vec![Zero]);
            }
            return self;
        }

        let length = min(self.0.len(), rhs.0.len());
        let mut sum = Vec::new();
        let mut carry = vec![Zero];

        for i in 0..length {
            let (carry_dig, digit) = self.0[i] + rhs.0[i];
            sum.push(digit);
            carry.push(carry_dig);
        }

        for i in length..self.0.len() {
            sum.push(self.0[i]);
        }
        for i in length..rhs.0.len() {
            sum.push(rhs.0[i]);
        }

        trim(&mut sum);
        trim(&mut carry);

        BalancedTernary(sum) + BalancedTernary(carry)
    }
}

impl Mul for BalancedTernary {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        let mut results = Vec::with_capacity(rhs.0.len());
        for i in 0..rhs.0.len() {
            let mut digits = vec![Trit::Zero; i];
            for j in 0..self.0.len() {
                digits.push(self.0[j] * rhs.0[i]);
            }
            results.push(BalancedTernary(digits));
        }
        #[allow(clippy::suspicious_arithmetic_impl)]
        results
            .into_iter()
            .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x)
    }
}

impl Neg for BalancedTernary {
    type Output = Self;

    fn neg(self) -> Self::Output {
        BalancedTernary(self.0.iter().map(|&x| -x).collect())
    }
}

impl FromStr for BalancedTernary {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.chars()
            .rev()
            .map(|c| c.try_into())
            .collect::<Result<_, _>>()
            .map(BalancedTernary)
    }
}

impl From<i128> for BalancedTernary {
    fn from(x: i128) -> Self {
        let mut v = Vec::new();
        let mut curr = x;

        loop {
            let rem = curr % 3;

            match rem {
                0 => v.push(Trit::Zero),
                1 | -2 => v.push(Trit::Pos),
                2 | -1 => v.push(Trit::Neg),
                _ => unreachable!(),
            }

            let offset = (rem as f64 / 3.0).round() as i128;
            curr = curr / 3 + offset;

            if curr == 0 {
                break;
            }
        }

        BalancedTernary(v)
    }
}

impl TryFrom<BalancedTernary> for i128 {
    type Error = &'static str;

    fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> {
        value
            .0
            .iter()
            .enumerate()
            .try_fold(0_i128, |acc, (i, character)| {
                let size_err = "Balanced ternary string is too large to fit into 16 bytes";
                let index: u32 = i.try_into().map_err(|_| size_err)?;

                match character {
                    Trit::Zero => Ok(acc),
                    Trit::Pos => 3_i128
                        .checked_pow(index)
                        .and_then(|x| acc.checked_add(x))
                        .ok_or(size_err),
                    Trit::Neg => 3_i128
                        .checked_pow(index)
                        .and_then(|x| acc.checked_sub(x))
                        .ok_or(size_err),
                }
            })
    }
}


Barnsley fern

#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>

void barnsleyFern(int windowWidth, unsigned long iter){

	double x0=0,y0=0,x1,y1;
	int diceThrow;
	time_t t;
	srand((unsigned)time(&t));

	while(iter>0){
		diceThrow = rand()%100;

		if(diceThrow==0){
			x1 = 0;
			y1 = 0.16*y0;
		}

		else if(diceThrow>=1 && diceThrow<=7){
			x1 = -0.15*x0 + 0.28*y0;
			y1 = 0.26*x0 + 0.24*y0 + 0.44;
		}

		else if(diceThrow>=8 && diceThrow<=15){
			x1 = 0.2*x0 - 0.26*y0;
			y1 = 0.23*x0 + 0.22*y0 + 1.6;
		}

		else{
			x1 = 0.85*x0 + 0.04*y0;
			y1 = -0.04*x0 + 0.85*y0 + 1.6;
		}

		putpixel(30*x1 + windowWidth/2.0,30*y1,GREEN);

		x0 = x1;
		y0 = y1;

		iter--;
	}

}

int main()
{
	unsigned long num;

	printf("Enter number of iterations : ");
	scanf("%ld",&num);

	initwindow(500,500,"Barnsley Fern");

	barnsleyFern(500,num);

	getch();

	closegraph();

	return 0;
}

extern crate rand;
extern crate raster;

use rand::Rng;

fn main() {
    let max_iterations = 200_000u32;
    let height = 640i32;
    let width = 640i32;

    let mut rng = rand::thread_rng();
    let mut image = raster::Image::blank(width, height);
    raster::editor::fill(&mut image, raster::Color::white()).unwrap();

    let mut x = 0.;
    let mut y = 0.;
    for _ in 0..max_iterations {
        let r = rng.gen::<f32>();
        let cx: f64;
        let cy: f64;

        if r <= 0.01 {
            cx = 0f64;
            cy = 0.16 * y as f64;
        } else if r <= 0.08 {
            cx = 0.2 * x as f64 - 0.26 * y as f64;
            cy = 0.23 * x as f64 + 0.22 * y as f64 + 1.6;
        } else if r <= 0.15 {
            cx = -0.15 * x as f64 + 0.28 * y as f64;
            cy = 0.26 * x as f64 + 0.26 * y as f64 + 0.44;
        } else {
            cx = 0.85 * x as f64 + 0.04 * y as f64;
            cy = -0.04 * x as f64 + 0.85 * y as f64 + 1.6;
        }
        x = cx;
        y = cy;

        let _ = image.set_pixel(
            ((width as f64) / 2. + x * (width as f64) / 11.).round() as i32,
            ((height as f64) - y * (height as f64) / 11.).round() as i32,
            raster::Color::rgb(50, 205, 50));
    }

    raster::save(&image, "fractal.png").unwrap();
}


Base64 decode data

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

typedef unsigned char ubyte;
const ubyte BASE64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

int findIndex(const ubyte val) {
    if ('A' <= val && val <= 'Z') {
        return val - 'A';
    }
    if ('a' <= val && val <= 'z') {
        return val - 'a' + 26;
    }
    if ('0' <= val && val <= '9') {
        return val - '0' + 52;
    }
    if (val == '+') {
        return 62;
    }
    if (val == '/') {
        return 63;
    }
    return -1;
}

int decode(const ubyte source[], ubyte sink[]) {
    const size_t length = strlen(source);
    const ubyte *it = source;
    const ubyte *end = source + length;
    int acc;

    if (length % 4 != 0) {
        return 1;
    }

    while (it != end) {
        const ubyte b1 = *it++;
        const ubyte b2 = *it++;
        const ubyte b3 = *it++;
        const ubyte b4 = *it++;

        const int i1 = findIndex(b1);
        const int i2 = findIndex(b2);

        acc = i1 << 2;
        acc |= i2 >> 4;
        *sink++ = acc;

        if (b3 != '=') {
            const int i3 = findIndex(b3);

            acc = (i2 & 0xF) << 4;
            acc += i3 >> 2;
            *sink++ = acc;

            if (b4 != '=') {
                const int i4 = findIndex(b4);

                acc = (i3 & 0x3) << 6;
                acc |= i4;
                *sink++ = acc;
            }
        }
    }

    *sink = '\0';
    return 0;
}

int main() {
    ubyte data[] = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
    ubyte decoded[1024];

    printf("%s\n\n", data);
    decode(data, decoded);
    printf("%s\n\n", decoded);

    return 0;
}

use std::str;

const INPUT: &str = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
const UPPERCASE_OFFSET: i8 = -65;
const LOWERCASE_OFFSET: i8 = 26 - 97;
const NUM_OFFSET: i8 = 52 - 48;

fn main() {
    println!("Input: {}", INPUT);

    let result = INPUT.chars()
        .filter(|&ch| ch != '=')
        .map(|ch| {
            let ascii = ch as i8;
            let convert = match ch {
                '0' ... '9' => ascii + NUM_OFFSET,
                'a' ... 'z' => ascii + LOWERCASE_OFFSET,
                'A' ... 'Z' => ascii + UPPERCASE_OFFSET,
                '+' => 62,
                '/' => 63,
                _ => panic!("Not a valid base64 encoded string")
            };
            format!("{:#08b}", convert)[2..].to_string()
        })
        .collect::<String>()
        .chars()
        .collect::<Vec<char>>()
        .chunks(8)
        .map(|chunk| {
            let num_str = chunk.iter().collect::<String>();
            usize::from_str_radix(&num_str, 2).unwrap() as u8
        })
        .collect::<Vec<_>>();

    let result = str::from_utf8(&result).unwrap();

    println!("Output: {}", result);
}


Bell numbers

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

size_t bellIndex(int row, int col) {
    return row * (row - 1) / 2 + col;
}

int getBell(int *bellTri, int row, int col) {
    size_t index = bellIndex(row, col);
    return bellTri[index];
}

void setBell(int *bellTri, int row, int col, int value) {
    size_t index = bellIndex(row, col);
    bellTri[index] = value;
}

int *bellTriangle(int n) {
    size_t length = n * (n + 1) / 2;
    int *tri = calloc(length, sizeof(int));
    int i, j;

    setBell(tri, 1, 0, 1);
    for (i = 2; i <= n; ++i) {
        setBell(tri, i, 0, getBell(tri, i - 1, i - 2));
        for (j = 1; j < i; ++j) {
            int value = getBell(tri, i, j - 1) + getBell(tri, i - 1, j - 1);
            setBell(tri, i, j, value);
        }
    }

    return tri;
}

int main() {
    const int rows = 15;
    int *bt = bellTriangle(rows);
    int i, j;

    printf("First fifteen Bell numbers:\n");
    for (i = 1; i <= rows; ++i) {
        printf("%2d: %d\n", i, getBell(bt, i, 0));
    }

    printf("\nThe first ten rows of Bell's triangle:\n");
    for (i = 1; i <= 10; ++i) {
        printf("%d", getBell(bt, i, 0));
        for (j = 1; j < i; ++j) {
            printf(", %d", getBell(bt, i, j));
        }
        printf("\n");
    }

    free(bt);
    return 0;
}

use num::BigUint;

fn main() {
    let bt = bell_triangle(51);

    for i in 1..=15 {
        println!("{}: {}", i, bt[i][0]);
    }

    println!("50: {}", bt[50][0])
}

fn bell_triangle(n: usize) -> Vec<Vec<BigUint>> {
    let mut tri: Vec<Vec<BigUint>> = Vec::with_capacity(n);
    for i in 0..n {
        let v = vec![BigUint::from(0u32); i];
        tri.push(v);
    }
    tri[1][0] = BigUint::from(1u32);

    for i in 2..n {
        tri[i][0] = BigUint::from_bytes_be(&tri[i - 1][i - 2].to_bytes_be());
        for j in 1..i {
            let added_big_uint = &tri[i][j - 1] + &tri[i - 1][j - 1];
            tri[i][j] = BigUint::from_bytes_be(&added_big_uint.to_bytes_be());
        }
    }

    tri
}


Bernoulli numbers

#include <stdlib.h>
#include <gmp.h>

#define mpq_for(buf, op, n)\
    do {\
        size_t i;\
        for (i = 0; i < (n); ++i)\
            mpq_##op(buf[i]);\
    } while (0)

void bernoulli(mpq_t rop, unsigned int n)
{
    unsigned int m, j;
    mpq_t *a = malloc(sizeof(mpq_t) * (n + 1));
    mpq_for(a, init, n + 1);

    for (m = 0; m <= n; ++m) {
        mpq_set_ui(a[m], 1, m + 1);
        for (j = m; j > 0; --j) {
            mpq_sub(a[j-1], a[j], a[j-1]);
            mpq_set_ui(rop, j, 1);
            mpq_mul(a[j-1], a[j-1], rop);
        }
    }

    mpq_set(rop, a[0]);
    mpq_for(a, clear, n + 1);
    free(a);
}

int main(void)
{
    mpq_t rop;
    mpz_t n, d;
    mpq_init(rop);
    mpz_inits(n, d, NULL);

    unsigned int i;
    for (i = 0; i <= 60; ++i) {
        bernoulli(rop, i);
        if (mpq_cmp_ui(rop, 0, 1)) {
            mpq_get_num(n, rop);
            mpq_get_den(d, rop);
            gmp_printf("B(%-2u) = %44Zd / %Zd\n", i, n, d);
        }
    }

    mpz_clears(n, d, NULL);
    mpq_clear(rop);
    return 0;
}

#![feature(test)]

extern crate num;
extern crate test;

use num::bigint::{BigInt, ToBigInt};
use num::rational::{BigRational};
use std::cmp::max;
use std::env;
use std::ops::{Mul, Sub};
use std::process;

struct Bn {
    value: BigRational,
    index: i32
}

struct Context {
    bigone_const: BigInt,
    a: Vec<BigRational>,
    index: i32
}

impl Context {
    pub fn new() -> Context {
        let bigone = 1.to_bigint().unwrap();
        let a_vec: Vec<BigRational> = vec![];
        Context {
            bigone_const: bigone,
            a: a_vec,
            index: -1
        }
    }
}

impl Iterator for Context {
    type Item = Bn;

    fn next(&mut self) -> Option<Bn> {
        self.index += 1;
        Some(Bn { value: bernoulli(self.index as usize, self), index: self.index })
    }
}

fn help() {
    println!("Usage: bernoulli_numbers <up_to>");
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut up_to: usize = 60;

    match args.len() {
        1 => {},
        2 => {
            up_to = args[1].parse::<usize>().unwrap();
        },
        _ => {
            help();
            process::exit(0);
        }
    }

    let context = Context::new();

    let res = context.take(up_to + 1).collect::<Vec<_>>();
    let width = res.iter().fold(0, |a, r| max(a, r.value.numer().to_string().len()));

    for r in res.iter().filter(|r| *r.value.numer() != ToBigInt::to_bigint(&0).unwrap()) {
        println!("B({:>2}) = {:>2$} / {denom}", r.index, r.value.numer(), width,
            denom = r.value.denom());
    }
}

fn _bernoulli_naive(n: usize, c: &mut Context) -> BigRational {
    for m in 0..n + 1 {
        c.a.push(BigRational::new(c.bigone_const.clone(), (m + 1).to_bigint().unwrap()));
        for j in (1..m + 1).rev() {
            c.a[j - 1] = (c.a[j - 1].clone().sub(c.a[j].clone())).mul(
                BigRational::new(j.to_bigint().unwrap(), c.bigone_const.clone())
            );
        }
    }
    c.a[0].reduced()
}

fn bernoulli(n: usize, c: &mut Context) -> BigRational {
    for i in 0..n + 1 {
        if i >= c.a.len() {
            c.a.push(BigRational::new(c.bigone_const.clone(), (i + 1).to_bigint().unwrap()));
            for j in (1..i + 1).rev() {
                c.a[j - 1] = (c.a[j - 1].clone().sub(c.a[j].clone())).mul(
                    BigRational::new(j.to_bigint().unwrap(), c.bigone_const.clone())
                );
            }
        }
    }
    c.a[0].reduced()
}

#[cfg(test)]
mod tests {
    use super::{Bn, Context, bernoulli, _bernoulli_naive};
    use num::rational::{BigRational};
    use std::str::FromStr;
    use test::Bencher;

    #[bench]
    fn bench_bernoulli_naive(b: &mut Bencher) {
        let mut context = Context::new();
        b.iter(|| {
            let mut res: Vec<Bn> = vec![];
            for n in 0..30 + 1 {
                let b = _bernoulli_naive(n, &mut context);
                res.push(Bn { value:b.clone(), index: n as i32});
            }
        });
    }

    #[bench]
    fn bench_bernoulli(b: &mut Bencher) {
        let mut context = Context::new();
        b.iter(|| {
            let mut res: Vec<Bn> = vec![];
            for n in 0..30 + 1 {
                let b = bernoulli(n, &mut context);
                res.push(Bn { value:b.clone(), index: n as i32});
            }
        });
    }

    #[bench]
    fn bench_bernoulli_iter(b: &mut Bencher) {
        b.iter(|| {
            let context = Context::new();
            let _res = context.take(30 + 1).collect::<Vec<_>>();
        });
    }
}


Best shuffle

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

#define DEBUG

void best_shuffle(const char* txt, char* result) {
    const size_t len = strlen(txt);
    if (len == 0)
        return;

#ifdef DEBUG

    assert(len == strlen(result));
#endif

    size_t counts[UCHAR_MAX];
    memset(counts, '\0', UCHAR_MAX * sizeof(int));
    size_t fmax = 0;
    for (size_t i = 0; i < len; i++) {
        counts[(unsigned char)txt[i]]++;
        const size_t fnew = counts[(unsigned char)txt[i]];
        if (fmax < fnew)
             fmax = fnew;
    }
    assert(fmax > 0 && fmax <= len);

    size_t *ndx1 = malloc(len * sizeof(size_t));
    if (ndx1 == NULL)
        exit(EXIT_FAILURE);
    for (size_t ch = 0, i = 0; ch < UCHAR_MAX; ch++)
       if (counts[ch])
            for (size_t j = 0; j < len; j++)
                if (ch == (unsigned char)txt[j]) {
                    ndx1[i] = j;
                    i++;
                }

    size_t *ndx2 = malloc(len * sizeof(size_t));
    if (ndx2 == NULL)
        exit(EXIT_FAILURE);
    for (size_t i = 0, n = 0, m = 0; i < len; i++) {
        ndx2[i] = ndx1[n];
        n += fmax;
        if (n >= len) {
            m++;
            n = m;
        }
    }

    const size_t grp = 1 + (len - 1) / fmax;
    assert(grp > 0 && grp <= len);

    const size_t lng = 1 + (len - 1) % fmax;
    assert(lng > 0 && lng <= len);

    for (size_t i = 0, j = 0; i < fmax; i++) {
        const size_t first = ndx2[j];
        const size_t glen = grp - (i < lng ? 0 : 1);
        for (size_t k = 1; k < glen; k++)
            ndx1[j + k - 1] = ndx2[j + k];
        ndx1[j + glen - 1] = first;
        j += glen;
    }

    result[len] = '\0';
    for (size_t i = 0; i < len; i++)
        result[ndx2[i]] = txt[ndx1[i]];

    free(ndx1);
    free(ndx2);
}

void display(const char* txt1, const char* txt2) {
    const size_t len = strlen(txt1);
    assert(len == strlen(txt2));
    int score = 0;
    for (size_t i = 0; i < len; i++)
        if (txt1[i] == txt2[i])
            score++;
    (void)printf("%s, %s, (%u)\n", txt1, txt2, score);
}

int main() {
    const char* data[] = {"abracadabra", "seesaw", "elk", "grrrrrr",
                          "up", "a", "aabbbbaa", "", "xxxxx"};
    const size_t data_len = sizeof(data) / sizeof(data[0]);
    for (size_t i = 0; i < data_len; i++) {
        const size_t shuf_len = strlen(data[i]) + 1;
        char shuf[shuf_len];

#ifdef DEBUG
        memset(shuf, 0xFF, sizeof shuf);
        shuf[shuf_len - 1] = '\0';
#endif

        best_shuffle(data[i], shuf);
        display(data[i], shuf);
    }

    return EXIT_SUCCESS;
}

extern crate permutohedron;
extern crate rand;

use std::cmp::{min, Ordering};
use std::env;
use rand::{thread_rng, Rng};
use std::str;

const WORDS: &'static [&'static str] = &["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"];

#[derive(Eq)]
struct Solution {
    original: String,
    shuffled: String,
    score: usize,
}

impl PartialOrd for Solution {
    fn partial_cmp(&self, other: &Solution) -> Option<Ordering> {
        match (self.score, other.score) {
            (s, o) if s < o => Some(Ordering::Less),
            (s, o) if s > o => Some(Ordering::Greater),
            (s, o) if s == o => Some(Ordering::Equal),
            _ => None,
        }
    }
}

impl PartialEq for Solution {
    fn eq(&self, other: &Solution) -> bool {
        match (self.score, other.score) {
            (s, o) if s == o => true,
            _ => false,
        }
    }
}

impl Ord for Solution {
    fn cmp(&self, other: &Solution) -> Ordering {
        match (self.score, other.score) {
            (s, o) if s < o => Ordering::Less,
            (s, o) if s > o => Ordering::Greater,
            _ => Ordering::Equal,
        }
    }
}

fn _help() {
    println!("Usage: best_shuffle <word1> <word2> ...");
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut words: Vec<String> = vec![];

    match args.len() {
        1 => {
            for w in WORDS.iter() {
                words.push(String::from(*w));
            }
        }
        _ => {
            for w in args.split_at(1).1 {
                words.push(w.clone());
            }
        }
    }

    let solutions = words.iter().map(|w| best_shuffle(w)).collect::<Vec<_>>();

    for s in solutions {
        println!("{}, {}, ({})", s.original, s.shuffled, s.score);
    }
}

fn _best_shuffle_perm(w: &String) -> Solution {
    let mut soln = Solution {
        original: w.clone(),
        shuffled: w.clone(),
        score: w.len(),
    };
    let w_bytes: Vec<u8> = w.clone().into_bytes();
    let mut permutocopy = w_bytes.clone();
    let mut permutations = permutohedron::Heap::new(&mut permutocopy);
    while let Some(p) = permutations.next_permutation() {
        let hamm = hamming(&w_bytes, p);
        soln = min(soln,
                   Solution {
                       original: w.clone(),
                       shuffled: String::from(str::from_utf8(p).unwrap()),
                       score: hamm,
                   });

        if hamm == 0 {
            break;
        }
    }
    soln
}

fn best_shuffle(w: &String) -> Solution {
    let w_bytes: Vec<u8> = w.clone().into_bytes();
    let mut shuffled_bytes: Vec<u8> = w.clone().into_bytes();

    let sh: &mut [u8] = shuffled_bytes.as_mut_slice();
    thread_rng().shuffle(sh);

    for i in 0..sh.len() {
        for j in 0..sh.len() {
            if (i == j) | (sh[i] == w_bytes[j]) | (sh[j] == w_bytes[i]) | (sh[i] == sh[j]) {
                continue;
            }
            sh.swap(i, j);
            break;
        }
    }

    let res = String::from(str::from_utf8(sh).unwrap());
    let res_bytes: Vec<u8> = res.clone().into_bytes();
    Solution {
        original: w.clone(),
        shuffled: res,
        score: hamming(&w_bytes, &res_bytes),
    }
}

fn hamming(w0: &Vec<u8>, w1: &Vec<u8>) -> usize {
    w0.iter().zip(w1.iter()).filter(|z| z.0 == z.1).count()
}


Bin given limits

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

size_t upper_bound(const int* array, size_t n, int value) {
    size_t start = 0;
    while (n > 0) {
        size_t step = n / 2;
        size_t index = start + step;
        if (value >= array[index]) {
            start = index + 1;
            n -= step + 1;
        } else {
            n = step;
        }
    }
    return start;
}

int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
    int* result = calloc(nlimits + 1, sizeof(int));
    if (result == NULL)
        return NULL;
    for (size_t i = 0; i < ndata; ++i)
        ++result[upper_bound(limits, nlimits, data[i])];
    return result;
}

void print_bins(const int* limits, size_t n, const int* bins) {
    if (n == 0)
        return;
    printf("           < %3d: %2d\n", limits[0], bins[0]);
    for (size_t i = 1; i < n; ++i)
        printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
    printf(">= %3d          : %2d\n", limits[n - 1], bins[n]);
}

int main() {
    const int limits1[] = {23, 37, 43, 53, 67, 83};
    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,
                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,
                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};

    printf("Example 1:\n");
    size_t n = sizeof(limits1) / sizeof(int);
    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
    if (b == NULL) {
        fprintf(stderr, "Out of memory\n");
        return EXIT_FAILURE;
    }
    print_bins(limits1, n, b);
    free(b);

    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
    const int data2[] = {
        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,
        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,
        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,
        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,
        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,
        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,
        101, 684, 727, 749};

    printf("\nExample 2:\n");
    n = sizeof(limits2) / sizeof(int);
    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
    if (b == NULL) {
        fprintf(stderr, "Out of memory\n");
        return EXIT_FAILURE;
    }
    print_bins(limits2, n, b);
    free(b);

    return EXIT_SUCCESS;
}


Binary digits

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE

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

char* bin2str(unsigned value, char* buffer)
{

    const unsigned N_DIGITS = sizeof(unsigned) * 8;
    unsigned mask = 1 << (N_DIGITS - 1);
    char* ptr = buffer;

    for (int i = 0; i < N_DIGITS; i++)
    {
        *ptr++ = '0' + !!(value & mask);
        mask >>= 1;
    }
    *ptr = '\0';

    for (ptr = buffer; *ptr == '0'; ptr++)
        ;

    return ptr;
}

char* bin2strNaive(unsigned value, char* buffer)
{

    unsigned n, m, p;

    n = 0;
    p = 1;
    while (p <= value / 2)
    {
        n = n + 1;
        p = p * 2;
    }

    m = 0;
    while (n > 0)
    {
        buffer[m] = '0' + value / p;
        value = value % p;
        m = m + 1;
        n = n - 1;
        p = p / 2;
    }

    buffer[m + 1] = '\0';
    return buffer;
}

int main(int argc, char* argv[])
{
    const unsigned NUMBERS[] = { 5, 50, 9000 };

    const int RADIX = 2;
    char buffer[(sizeof(unsigned)*8 + 1)];

    for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
    {
        unsigned value = NUMBERS[i];
        itoa(value, buffer, RADIX);
        printf("itoa:          %u decimal = %s binary\n", value, buffer);
    }

    for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
    {
        unsigned value = NUMBERS[i];
        printf("bin2str:       %u decimal = %s binary\n", value, bin2str(value, buffer));
    }

    for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
    {
        unsigned value = NUMBERS[i];
        printf("bin2strNaive:  %u decimal = %s binary\n", value, bin2strNaive(value, buffer));
    }

    return EXIT_SUCCESS;
}

fn main() {
    for i in 0..8 {
        println!("{:b}", i)
    }
}


Binary search

#include <stdio.h>

int bsearch (int *a, int n, int x) {
    int i = 0, j = n - 1;
    while (i <= j) {
        int k = i + ((j - i) / 2);
        if (a[k] == x) {
            return k;
        }
        else if (a[k] < x) {
            i = k + 1;
        }
        else {
            j = k - 1;
        }
    }
    return -1;
}

int bsearch_r (int *a, int x, int i, int j) {
    if (j < i) {
        return -1;
    }
    int k = i + ((j - i) / 2);
    if (a[k] == x) {
        return k;
    }
    else if (a[k] < x) {
        return bsearch_r(a, x, k + 1, j);
    }
    else {
        return bsearch_r(a, x, i, k - 1);
    }
}

int main () {
    int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
    int n = sizeof a / sizeof a[0];
    int x = 2;
    int i = bsearch(a, n, x);
    if (i >= 0)
      printf("%d is at index %d.\n", x, i);
    else
      printf("%d is not found.\n", x);
    x = 5;
    i = bsearch_r(a, x, 0, n - 1);
    if (i >= 0)
      printf("%d is at index %d.\n", x, i);
    else
      printf("%d is not found.\n", x);
    return 0;
}

fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> {
    let mut lower = 0 as usize;
    let mut upper = v.len() - 1;

    while upper >= lower {
        let mid = (upper + lower) / 2;
        if v[mid] == searchvalue {
            return Some(searchvalue);
        } else if searchvalue < v[mid] {
            upper = mid - 1;
        } else {
            lower = mid + 1;
        }
    }

    None
}


Binary strings

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

typedef struct str_t {
	size_t len, alloc;
	unsigned char *s;
} bstr_t, *bstr;

#define str_len(s) ((s)->len)
bstr str_new(size_t len)
{
	bstr s = malloc(sizeof(bstr_t));
	if (len < 8) len = 8;
	s->alloc = len;
	s->s = malloc(len);
	s->len = 0;
	return s;
}

void str_extend(bstr s)
{
	size_t ns = s->alloc * 2;
	if (ns - s->alloc > 1024) ns = s->alloc + 1024;
	s->s = realloc(s->s, ns);
	s->alloc = ns;
}

void str_del(bstr s)
{
	free(s->s), free(s);
}

int str_cmp(bstr l, bstr r)
{
	int res, len = l->len;
	if (len > r->len) len = r->len;

	if ((res = memcmp(l->s, r->s, len))) return res;
	return l->len > r->len ? 1 : -1;
}

bstr str_dup(bstr src)
{
	bstr x = str_new(src->len);
	memcpy(x->s, src->s, src->len);
	x->len = src->len;
	return x;
}

bstr str_from_chars(const char *t)
{
	if (!t) return str_new(0);
	size_t l = strlen(t);
	bstr x = str_new(l + 1);
	x->len = l;
	memcpy(x->s, t, l);
	return x;
}

void str_append(bstr s, unsigned char b)
{
	if (s->len >= s->alloc) str_extend(s);
	s->s[s->len++] = b;
}

bstr str_substr(bstr s, int from, int to)
{
	if (!to) to = s->len;
	if (from < 0) from += s->len;
	if (from < 0 || from >= s->len)
		return 0;
	if (to < from) to = from + 1;
	bstr x = str_new(to - from);
	x->len = to - from;
	memcpy(x->s, s->s + from, x->len);
	return x;
}

bstr str_cat(bstr s, bstr s2)
{
	while (s->alloc < s->len + s2->len) str_extend(s);
	memcpy(s->s + s->len, s2->s, s2->len);
	s->len += s2->len;
	return s;
}

void str_swap(bstr a, bstr b)
{
	size_t tz;
	unsigned char *ts;
	tz = a->alloc; a->alloc = b->alloc; b->alloc = tz;
	tz = a->len; a->len = b->len; b->len = tz;
	ts = a->s; a->s = b->s; b->s = ts;
}

bstr str_subst(bstr tgt, bstr pat, bstr repl)
{
	bstr tmp = str_new(0);
	int i;
	for (i = 0; i + pat->len <= tgt->len;) {
		if (memcmp(tgt->s + i, pat->s, pat->len)) {
			str_append(tmp, tgt->s[i]);
			i++;
		} else {
			str_cat(tmp, repl);
			i += pat->len;
			if (!pat->len) str_append(tmp, tgt->s[i++]);
		}
	}
	while (i < tgt->len) str_append(tmp, tgt->s[i++]);
	str_swap(tmp, tgt);
	str_del(tmp);
	return tgt;
}

void str_set(bstr dest, bstr src)
{
	while (dest->len < src->len) str_extend(dest);
	memcpy(dest->s, src->s, src->len);
	dest->len = src->len;
}

int main()
{
	bstr s = str_from_chars("aaaaHaaaaaFaaaaHa");
	bstr s2 = str_from_chars("___.");
	bstr s3 = str_from_chars("");

	str_subst(s, s3, s2);
	printf("%.*s\n", s->len, s->s);

	str_del(s);
	str_del(s2);
	str_del(s3);

	return 0;
}

use std::str;

fn main() {

    let string = String::from("Hello world!");
    println!("{}", string);
    assert_eq!(string, "Hello world!", "Incorrect string text");

    let mut assigned_str = String::new();
    assert_eq!(assigned_str, "", "Incorrect string creation");
    assigned_str += "Text has been assigned!";
    println!("{}", assigned_str);
    assert_eq!(assigned_str, "Text has been assigned!","Incorrect string text");

    if string == "Hello world!" && assigned_str == "Text has been assigned!" {
        println!("Strings are equal");
    }

    let clone_str = string.clone();
    println!("String is:{}  and  Clone string is: {}", string, clone_str);
    assert_eq!(clone_str, string, "Incorrect string creation");

    let copy_str = string;
    println!("String copied now: {}", copy_str);

    let empty_str = String::new();
    assert!(empty_str.is_empty(), "Error, string should be empty");

    let byte_vec = [65];
    let byte_str = str::from_utf8(&byte_vec).unwrap();
    assert_eq!(byte_str, "A", "Incorrect byte append");

    let test_str = "Blah String";
    let mut sub_str = &test_str[0..11];
    assert_eq!(sub_str, "Blah String", "Error in slicing");
    sub_str = &test_str[1..5];
    assert_eq!(sub_str, "lah ", "Error in slicing");
    sub_str = &test_str[3..];
    assert_eq!(sub_str, "h String", "Error in slicing");
    sub_str = &test_str[..2];
    assert_eq!(sub_str, "Bl", "Error in slicing");

    let org_str = "Hello";
    assert_eq!(org_str.replace("l", "a"), "Heaao", "Error in replacement");
    assert_eq!(org_str.replace("ll", "r"), "Hero", "Error in replacement");

    let str1 = "Hi";
    let str2 = " There";
    let fin_str = str1.to_string() + str2;
    assert_eq!(fin_str, "Hi There", "Error in concatenation");

    let str1 = "Hi";
    let str2 = " There";
    let fin_str = str1.to_string() + str2;
    assert_eq!(fin_str, "Hi There", "Error in concatenation");

    let f_str = "Pooja and Sundar are up in Tumkur";
    let split_str: Vec<_> = f_str.split(' ').collect();
    assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split");
}


Bitcoin_address validation

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

const char *coin_err;
#define bail(s) { coin_err = s; return 0; }

int unbase58(const char *s, unsigned char *out) {
	static const char *tmpl = "123456789"
		"ABCDEFGHJKLMNPQRSTUVWXYZ"
		"abcdefghijkmnopqrstuvwxyz";
	int i, j, c;
	const char *p;

	memset(out, 0, 25);
	for (i = 0; s[i]; i++) {
		if (!(p = strchr(tmpl, s[i])))
			bail("bad char");

		c = p - tmpl;
		for (j = 25; j--; ) {
			c += 58 * out[j];
			out[j] = c % 256;
			c /= 256;
		}

		if (c) bail("address too long");
	}

	return 1;
}

int valid(const char *s) {
	unsigned char dec[32], d1[SHA256_DIGEST_LENGTH], d2[SHA256_DIGEST_LENGTH];

	coin_err = "";
	if (!unbase58(s, dec)) return 0;

	SHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2);

	if (memcmp(dec + 21, d2, 4))
		bail("bad digest");

	return 1;
}

int main (void) {
	const char *s[] = {
		"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",
		"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
		"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9",
		"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I",
		0 };
	int i;
	for (i = 0; s[i]; i++) {
		int status = valid(s[i]);
		printf("%s: %s\n", s[i], status ? "Ok" : coin_err);
	}

	return 0;
}

extern crate crypto;

use crypto::digest::Digest;
use crypto::sha2::Sha256;

const DIGITS58: [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 main() {
    println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i"));
    println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"));
    println!("{}", validate_address("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j"));
    println!("{}", validate_address("17NdbrSGoUotzeGCcMMC?nFkEvLymoou9j"));
}

fn validate_address(address: &str) -> bool {
    let decoded = match from_base58(address, 25) {
        Ok(x) => x,
        Err(_) => return false
    };
    if decoded[0] != 0 {
        return false;
    }
    let mut sha = Sha256::new();
    sha.input(&decoded[0..21]);
    let mut first_round = vec![0u8; sha.output_bytes()];
    sha.result(&mut first_round);
    sha.reset();

    sha.input(&first_round);
    let mut second_round = vec![0u8; sha.output_bytes()];
    sha.result(&mut second_round);
    if second_round[0..4] != decoded[21..25] {
        return false
    }
    true
}

fn from_base58(encoded: &str, size: usize) -> Result<Vec<u8>, String> {
    let mut res: Vec<u8> = vec![0; size];
    for base58_value in encoded.chars() {
        let mut value: u32 = match DIGITS58
            .iter()
            .position(|x| *x == base58_value){
            Some(x) => x as u32,
            None => return Err(String::from("Invalid character found in encoded string."))
        };
        for result_index in (0..size).rev() {
            value += 58 * res[result_index] as u32;
            res[result_index] = (value % 256) as u8;
            value /= 256;
        }
    }
    Ok(res)
}


Bitmap

#ifndef _IMGLIB_0
#define _IMGLIB_0

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <math.h>
#include <sys/queue.h>

typedef unsigned char color_component;
typedef color_component pixel[3];
typedef struct {
    unsigned int width;
    unsigned int height;
    pixel * buf;
} image_t;
typedef image_t * image;

image alloc_img(unsigned int width, unsigned int height);
void free_img(image);
void fill_img(image img,
        color_component r,
        color_component g,
        color_component b );
void put_pixel_unsafe(
       	image img,
        unsigned int x,
        unsigned int y,
        color_component r,
        color_component g,
        color_component b );
void put_pixel_clip(
       	image img,
        unsigned int x,
        unsigned int y,
        color_component r,
        color_component g,
        color_component b );
#define GET_PIXEL(IMG, X, Y) (IMG->buf[ ((Y) * IMG->width + (X)) ])
#endif

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Rgb {
    pub fn new(r: u8, g: u8, b: u8) -> Self {
        Rgb { r, g, b }
    }

    pub const BLACK: Rgb = Rgb { r: 0, g: 0, b: 0 };
    pub const RED: Rgb = Rgb { r: 255, g: 0, b: 0 };
    pub const GREEN: Rgb = Rgb { r: 0, g: 255, b: 0 };
    pub const BLUE: Rgb = Rgb { r: 0, g: 0, b: 255 };
}

#[derive(Clone, Debug)]
pub struct Image {
    width: usize,
    height: usize,
    pixels: Vec<Rgb>,
}

impl Image {
    pub fn new(width: usize, height: usize) -> Self {
        Image {
            width,
            height,
            pixels: vec![Rgb::BLACK; width * height],
        }
    }

    pub fn width(&self) -> usize {
        self.width
    }

    pub fn height(&self) -> usize {
        self.height
    }

    pub fn fill(&mut self, color: Rgb) {
        for pixel in &mut self.pixels {
            *pixel = color;
        }
    }

    pub fn get(&self, row: usize, col: usize) -> Option<&Rgb> {
        if row >= self.width {
            return None;
        }
        self.pixels.get(row * self.width + col)
    }

    pub fn get_mut(&mut self, row: usize, col: usize) -> Option<&mut Rgb> {
        if row >= self.width {
            return None;
        }
        self.pixels.get_mut(row * self.width + col)
    }
}

fn main() {
    let mut image = Image::new(16, 9);
    assert_eq!(Some(&Rgb::BLACK), image.get(3, 4));
    assert!(image.get(22, 3).is_none());

    image.fill(Rgb::RED);
    assert_eq!(Some(&Rgb::RED), image.get(3, 4));

    if let Some(pixel) = image.get_mut(3, 4) {
        *pixel = Rgb::GREEN;
    }
    assert_eq!(Some(&Rgb::GREEN), image.get(3, 4));

    if let Some(pixel) = image.get_mut(3, 4) {
        pixel.g -= 100;
        pixel.b = 20;
    }
    assert_eq!(Some(&Rgb::new(0, 155, 20)), image.get(3, 4));
}


Bitmap_Bresenham's line algorithm

void line(int x0, int y0, int x1, int y1) {

  int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
  int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;
  int err = (dx>dy ? dx : -dy)/2, e2;

  for(;;){
    setPixel(x0,y0);
    if (x0==x1 && y0==y1) break;
    e2 = err;
    if (e2 >-dx) { err -= dy; x0 += sx; }
    if (e2 < dy) { err += dx; y0 += sy; }
  }
}

struct Point {
    x: i32,
    y: i32
}

fn main() {
    let mut points: Vec<Point> = Vec::new();
    points.append(&mut get_coordinates(1, 20, 20, 28));
    points.append(&mut get_coordinates(20, 28, 69, 0));
    draw_line(points, 70, 30);
}

fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<Point> {
    let mut coordinates: Vec<Point> = vec![];
    let dx:i32 = i32::abs(x2 - x1);
    let dy:i32 = i32::abs(y2 - y1);
    let sx:i32 = { if x1 < x2 { 1 } else { -1 } };
    let sy:i32 = { if y1 < y2 { 1 } else { -1 } };

    let mut error:i32 = (if dx > dy  { dx } else { -dy }) / 2 ;
    let mut current_x:i32 = x1;
    let mut current_y:i32 = y1;
    loop {
        coordinates.push(Point { x : current_x, y: current_y });

        if current_x == x2 && current_y == y2 { break; }

        let error2:i32 = error;

        if error2 > -dx {
            error -= dy;
            current_x += sx;
        }
        if error2 < dy {
            error += dx;
            current_y += sy;
        }
    }
    coordinates
}

fn draw_line(line: std::vec::Vec<Point>, width: i32, height: i32) {
    for col in 0..height {
        for row in 0..width {
            let is_point_in_line = line.iter().any(| point| point.x == row && point.y == col);
            match is_point_in_line {
                true => print!("@"),
                _ => print!(".")
            };
        }
        print!("\n");
    }
}


Bitmap_Flood fill

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 2048
#define BYTE unsigned char

static int width, height;
static BYTE bitmap[MAXSIZE][MAXSIZE];
static BYTE oldColor;
static BYTE newColor;

void floodFill(int i, int j)
{
    if ( 0 <= i && i < height
    &&   0 <= j && j < width
    &&   bitmap[i][j] == oldColor )
    {
        bitmap[i][j] = newColor;
        floodFill(i-1,j);
        floodFill(i+1,j);
        floodFill(i,j-1);
        floodFill(i,j+1);
    }
}

void skipLine(FILE* file)
{
    while(!ferror(file) && !feof(file) && fgetc(file) != '\n')
        ;
}

void skipCommentLines(FILE* file)
{
    int c;
    int comment = '#';

    while ((c = fgetc(file)) == comment)
        skipLine(file);
    ungetc(c,file);
}

readPortableBitMap(FILE* file)
{
    int i,j;

    skipLine(file);
    skipCommentLines(file);  fscanf(file,"%d",&width);
    skipCommentLines(file);  fscanf(file,"%d",&height);
    skipCommentLines(file);

    if ( width <= MAXSIZE && height <= MAXSIZE )
        for ( i = 0; i < height; i++ )
            for ( j = 0; j < width; j++ )
                fscanf(file,"%1d",&(bitmap[i][j]));
    else exit(EXIT_FAILURE);
}

void writePortableBitMap(FILE* file)
{
    int i,j;
    fprintf(file,"P1\n");
    fprintf(file,"%d %d\n", width, height);
    for ( i = 0; i < height; i++ )
    {
        for ( j = 0; j < width; j++ )
            fprintf(file,"%1d", bitmap[i][j]);
        fprintf(file,"\n");
    }
}

int main(void)
{
    oldColor = 1;
    newColor = oldColor ? 0 : 1;
    readPortableBitMap(stdin);
    floodFill(height/2,width/2);
    writePortableBitMap(stdout);
    return EXIT_SUCCESS;
}

use std::fs::File;
use std::io::{BufReader, BufRead, Write};

fn read_image(filename: String) -> Vec<Vec<(u8,u8,u8)>> {
    let file = File::open(filename).unwrap();
    let reader = BufReader::new(file);
    let mut lines = reader.lines();

    let _ = lines.next().unwrap();
    let _ = lines.next().unwrap();

    let dimensions: (usize, usize) = {
        let line = lines.next().unwrap().unwrap();
        let values = line.split_whitespace().collect::<Vec<&str>>();

        (values[0].parse::<usize>().unwrap(),values[1].parse::<usize>().unwrap())
    };

    let _ = lines.next().unwrap();

    let mut image_data = Vec::with_capacity(dimensions.1);

    for y in 0..dimensions.1 {
        image_data.push(Vec::new());
        for _ in 0..dimensions.0 {

            image_data[y].push((lines.next().unwrap().unwrap().parse::<u8>().unwrap(),
                                lines.next().unwrap().unwrap().parse::<u8>().unwrap(),
                                lines.next().unwrap().unwrap().parse::<u8>().unwrap()));
        }
    }

    image_data
}

fn write_image(image_data: Vec<Vec<(u8,u8,u8)>>) {
    let mut file = File::create(format!("./output.ppm")).unwrap();

    write!(file, "P3\n{} {}\n255\n", image_data.len(), image_data[0].len()).unwrap();

    for row in &image_data {

        let mut line = String::with_capacity(row.len()*6);
        for (r,g,b) in row {

            line.push_str(&*format!("{} {} {} ", r,g,b));
        }

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

}

fn flood_fill(x: usize, y: usize, target: &(u8,u8,u8), replacement: &(u8,u8,u8), image_data: &mut Vec<Vec<(u8,u8,u8)>>) {
    if &image_data[y][x] == target {
        image_data[y][x] = *replacement;

        if y > 0 {flood_fill(x,y-1, &target, &replacement, image_data);}
        if x > 0 {flood_fill(x-1,y, &target, &replacement, image_data);}
        if y < image_data.len()-1 {flood_fill(x,y+1, &target, &replacement, image_data);}
        if x < image_data[0].len()-1 {flood_fill(x+1,y, &target, &replacement, image_data);}
    }
}

fn main() {
    let mut data = read_image(String::from("./input.ppm"));

    flood_fill(1,50, &(255,255,255), &(0,255,0), &mut data);
    flood_fill(40,35, &(0,0,0), &(255,0,0), &mut data);

    write_image(data);

}


Bitmap_Read a PPM file

parser.rs:
use super::{Color, ImageFormat};
use std::str::from_utf8;
use std::str::FromStr;

pub fn parse_version(input: &[u8]) -> nom::IResult<&[u8], ImageFormat> {
    use nom::branch::alt;
    use nom::bytes::complete::tag;
    use nom::character::complete::line_ending;
    use nom::combinator::map;
    use nom::sequence::terminated;

    terminated(
        alt((
            map(tag("P3".as_bytes()), |_| ImageFormat::P3),
            map(tag("P6".as_bytes()), |_| ImageFormat::P6),
        )),
        line_ending,
    )(input)
}

pub fn parse_image_attributes(input: &[u8]) -> nom::IResult<&[u8], (usize, usize, usize)> {
    use nom::character::complete::line_ending;
    use nom::character::complete::{digit1, space1};
    use nom::sequence::terminated;
    use nom::sequence::tuple;

    terminated(tuple((digit1, space1, digit1, space1, digit1)), line_ending)(input).map(
        |(next_input, result)| {
            (
                next_input,
                (
                    usize::from_str_radix(from_utf8(result.0).unwrap(), 10).unwrap(),
                    usize::from_str_radix(from_utf8(result.2).unwrap(), 10).unwrap(),
                    usize::from_str_radix(from_utf8(result.4).unwrap(), 10).unwrap(),
                ),
            )
        },
    )
}

pub fn parse_color_binary(input: &[u8]) -> nom::IResult<&[u8], Color> {
    use nom::number::complete::u8 as nom_u8;
    use nom::sequence::tuple;

    tuple((nom_u8, nom_u8, nom_u8))(input).map(|(next_input, res)| {
        (
            next_input,
            Color {
                red: res.0,
                green: res.1,
                blue: res.2,
            },
        )
    })
}

pub fn parse_data_binary(input: &[u8]) -> nom::IResult<&[u8], Vec<Color>> {
    use nom::multi::many0;
    many0(parse_color_binary)(input)
}

pub fn parse_color_ascii(input: &[u8]) -> nom::IResult<&[u8], Color> {
    use nom::character::complete::{digit1, space0, space1};
    use nom::sequence::tuple;

    tuple((digit1, space1, digit1, space1, digit1, space0))(input).map(|(next_input, res)| {
        (
            next_input,
            Color {
                red: u8::from_str(from_utf8(res.0).unwrap()).unwrap(),
                green: u8::from_str(from_utf8(res.2).unwrap()).unwrap(),
                blue: u8::from_str(from_utf8(res.4).unwrap()).unwrap(),
            },
        )
    })
}

pub fn parse_data_ascii(input: &[u8]) -> nom::IResult<&[u8], Vec<Color>> {
    use nom::multi::many0;
    many0(parse_color_ascii)(input)
}

lib.rs:
extern crate nom;
extern crate thiserror;
mod parser;

use std::default::Default;
use std::fmt;
use std::io::{BufWriter, Error, Write};
use std::ops::{Index, IndexMut};
use std::{fs::File, io::Read};
use thiserror::Error;

#[derive(Copy, Clone, Default, PartialEq, Debug)]
pub struct Color {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ImageFormat {
    P3,
    P6,
}

impl From<&str> for ImageFormat {
    fn from(i: &str) -> Self {
        match i.to_lowercase().as_str() {
            "p3" => ImageFormat::P3,
            "p6" => ImageFormat::P6,
            _ => unimplemented!("no other formats supported"),
        }
    }
}

impl fmt::Display for ImageFormat {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ImageFormat::P3 => {
                write!(f, "P3")
            }
            ImageFormat::P6 => {
                write!(f, "P6")
            }
        }
    }
}

#[derive(Error, Debug)]
pub enum ImageError {
    #[error("File not found")]
    FileNotFound,
    #[error("File not readable")]
    FileNotReadable,
    #[error("Invalid header information")]
    InvalidHeader,
    #[error("Invalid information in the data block")]
    InvalidData,
    #[error("Invalid max color information")]
    InvalidMaxColor,
    #[error("File is incomplete")]
    IncompleteFile,
    #[error("unknown data store error")]
    Unknown,
}
pub struct Image {
    pub format: ImageFormat,
    pub width: usize,
    pub height: usize,
    pub data: Vec<Color>,
}

impl Image {
    #[must_use]
    pub fn new(width: usize, height: usize) -> Self {
        Self {
            format: ImageFormat::P6,
            width,
            height,
            data: vec![Color::default(); width * height],
        }
    }

    pub fn fill(&mut self, color: Color) {
        for elem in &mut self.data {
            *elem = color;
        }
    }

    pub fn write_ppm(&self, filename: &str) -> Result<(), Error> {
        let file = File::create(filename)?;
        let mut writer = BufWriter::new(file);
        writeln!(&mut writer, "{}", self.format.to_string())?;
        writeln!(&mut writer, "{} {} 255", self.width, self.height)?;
        match self.format {
            ImageFormat::P3 => {
                writer.write_all(
                    &self
                        .data
                        .iter()
                        .flat_map(|color| {
                            vec![
                                color.red.to_string(),
                                color.green.to_string(),
                                color.blue.to_string(),
                            ]
                        })
                        .collect::<Vec<String>>()
                        .join(" ")
                        .as_bytes(),
                )?;
            }
            ImageFormat::P6 => {
                writer.write_all(
                    &self
                        .data
                        .iter()
                        .flat_map(|color| vec![color.red, color.green, color.blue])
                        .collect::<Vec<u8>>(),
                )?;
            }
        }
        Ok(())
    }

    pub fn read_ppm(filename: &str) -> Result<Image, ImageError> {
        let mut file = File::open(filename).map_err(|_| ImageError::FileNotFound)?;
        let mut data: Vec<u8> = Vec::new();
        file.read_to_end(&mut data)
            .map_err(|_| ImageError::FileNotReadable)?;

        let (i, format) = parser::parse_version(&data).map_err(|_| ImageError::InvalidHeader)?;
        let (i, (width, height, max_color)) =
            parser::parse_image_attributes(i).map_err(|_| ImageError::InvalidHeader)?;

        if max_color != 255 {
            return Err(ImageError::InvalidMaxColor);
        }

        let (_, data) = match format {
            ImageFormat::P3 => parser::parse_data_ascii(i).map_err(|_| ImageError::InvalidData)?,
            ImageFormat::P6 => parser::parse_data_binary(i).map_err(|_| ImageError::InvalidData)?,
        };

        if data.len() != height * width {
            return Err(ImageError::IncompleteFile);
        };

        Ok(Image {
            format,
            width,
            height,
            data,
        })
    }
}

impl Index<(usize, usize)> for Image {
    type Output = Color;

    fn index(&self, (x, y): (usize, usize)) -> &Color {
        &self.data[x + y * self.width]
    }
}

impl IndexMut<(usize, usize)> for Image {
    fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Color {
        &mut self.data[x + y * self.width]
    }
}

use bitmap::Image;

pub fn main() {

    let image = Image::read_ppm("./test_image.ppm").unwrap();

    println!("Read using nom parsing:");
    println!("Format: {:?}", image.format);
    println!("Dimensions: {} x {}", image.height, image.width);
}


Bitmap_Write a PPM file

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

int main(void)
{
  const int dimx = 800, dimy = 800;
  int i, j;
  FILE *fp = fopen("first.ppm", "wb");
  (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
  for (j = 0; j < dimy; ++j)
  {
    for (i = 0; i < dimx; ++i)
    {
      static unsigned char color[3];
      color[0] = i % 256;
      color[1] = j % 256;
      color[2] = (i * j) % 256;
      (void) fwrite(color, 1, 3, fp);
    }
  }
  (void) fclose(fp);
  return EXIT_SUCCESS;
}

use std::path::Path;
use std::io::Write;
use std::fs::File;

pub struct RGB {
    r: u8,
    g: u8,
    b: u8,
}

pub struct PPM {
    height: u32,
    width: u32,
    data: Vec<u8>,
}

impl PPM {
    pub fn new(height: u32, width: u32) -> PPM {
        let size = 3 * height * width;
        let buffer = vec![0; size as usize];
        PPM { height: height, width: width, data: buffer }
    }

    fn buffer_size(&self) -> u32 {
        3 * self.height * self.width
    }

    fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
        let offset = (y * self.width * 3) + (x * 3);
        if offset < self.buffer_size() {
            Some(offset as usize)
        } else {
            None
        }
    }

    pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
        match self.get_offset(x, y) {
            Some(offset) => {
                let r = self.data[offset];
                let g = self.data[offset + 1];
                let b = self.data[offset + 2];
                Some(RGB {r: r, g: g, b: b})
            },
            None => None
        }
    }

    pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
        match self.get_offset(x, y) {
            Some(offset) => {
                self.data[offset] = color.r;
                self.data[offset + 1] = color.g;
                self.data[offset + 2] = color.b;
                true
            },
            None => false
        }
    }

    pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
        let path = Path::new(filename);
        let mut file = File::create(&path)?;
        let header = format!("P6 {} {} 255\n", self.width, self.height);
        file.write(header.as_bytes())?;
        file.write(&self.data)?;
        Ok(())
    }
}


Bitwise IO

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

typedef uint8_t byte;
typedef struct {
    FILE *fp;
    uint32_t accu;
    int bits;
} bit_io_t, *bit_filter;

bit_filter b_attach(FILE *f)
{
    bit_filter b = malloc(sizeof(bit_io_t));
    b->bits = b->accu = 0;
    b->fp = f;
    return b;
}

void b_write(byte *buf, size_t n_bits, size_t shift, bit_filter bf)
{
    uint32_t accu = bf->accu;
    int bits = bf->bits;

    buf += shift / 8;
    shift %= 8;

    while (n_bits || bits >= 8) {
        while (bits >= 8) {
            bits -= 8;
            fputc(accu >> bits, bf->fp);
            accu &= (1 << bits) - 1;
        }
        while (bits < 8 && n_bits) {
            accu = (accu << 1) | (((128 >> shift) & *buf) >> (7 - shift));
            --n_bits;
            bits++;
            if (++shift == 8) {
                shift = 0;
                buf++;
            }
        }
    }
    bf->accu = accu;
    bf->bits = bits;
}

size_t b_read(byte *buf, size_t n_bits, size_t shift, bit_filter bf)
{
    uint32_t accu = bf->accu;
    int bits = bf->bits;
    int mask, i = 0;

    buf += shift / 8;
    shift %= 8;

    while (n_bits) {
        while (bits && n_bits) {
            mask = 128 >> shift;
            if (accu & (1 << (bits - 1))) *buf |= mask;
            else *buf &= ~mask;

            n_bits--;
            bits--;

            if (++shift >= 8) {
                shift = 0;
                buf++;
            }
        }
        if (!n_bits) break;
        accu = (accu << 8) | fgetc(bf->fp);
        bits += 8;
    }
    bf->accu = accu;
    bf->bits = bits;

    return i;
}

void b_detach(bit_filter bf)
{
    if (bf->bits) {
        bf->accu <<= 8 - bf->bits;
        fputc(bf->accu, bf->fp);
    }
    free(bf);
}

int main()
{
    unsigned char s[] = "abcdefghijk";
    unsigned char s2[11] = {0};
    int i;

    FILE *f = fopen("test.bin", "wb");
    bit_filter b = b_attach(f);

    for (i = 0; i < 10; i++) b_write(s + i, 7, 1, b);
    b_detach(b);
    fclose(f);

    f = fopen("test.bin", "rb");
    b = b_attach(f);
    for (i = 0; i < 10; i++) b_read(s2 + i, 7, 1, b);
    b_detach(b);
    fclose(f);

    printf("%10s\n", s2);

    return 0;
}

pub trait Codec<Input = u8> {
    type Output: Iterator<Item = u8>;

    fn accept(&mut self, input: Input) -> Self::Output;
    fn finish(self) -> Self::Output;
}

#[derive(Debug)]
pub struct BitDiscard {
    buf: u16,
    buf_bits: u8,
    valid_len: u8,
    shift_len: u8,
}

impl BitDiscard {
    pub fn new(discard: u8) -> Self {
        assert!(discard < 8);

        BitDiscard {
            buf: 0,
            buf_bits: 0,
            valid_len: 8 - discard,
            shift_len: 8 + discard,
        }
    }
}

impl Codec<u8> for BitDiscard {
    type Output = std::option::IntoIter<u8>;

    fn accept(&mut self, input: u8) -> Self::Output {
        let add = ((input as u16) << self.shift_len) >> self.buf_bits;
        self.buf |= add;
        self.buf_bits += self.valid_len;

        let result = if self.buf_bits >= 8 {
            let result = (self.buf >> 8) as u8;
            self.buf <<= 8;
            self.buf_bits -= 8;
            Some(result)
        } else {
            None
        };

        result.into_iter()
    }

    fn finish(self) -> Self::Output {
        let result = if self.buf_bits > 0 {
            Some((self.buf >> 8) as u8)
        } else {
            None
        };

        result.into_iter()
    }
}

#[derive(Debug)]
pub struct BitExpand {
    buf: u16,
    buf_bits: u8,
    valid_len: u8,
    shift_len: u8,
}

impl BitExpand {
    pub fn new(expand: u8) -> Self {
        assert!(expand < 8);

        Self {
            buf: 0,
            buf_bits: 0,
            valid_len: 8 - expand,
            shift_len: 8 + expand,
        }
    }
}

impl Codec<u8> for BitExpand {
    type Output = BitExpandIter;

    fn accept(&mut self, input: u8) -> Self::Output {
        let add = ((input as u16) << 8) >> self.buf_bits;
        self.buf |= add;
        self.buf_bits += 8;
        let buf = self.buf;
        let leftover = self.buf_bits % self.valid_len;
        let buf_bits = self.buf_bits - leftover;
        self.buf <<= buf_bits;
        self.buf_bits = leftover;

        Self::Output {
            buf,
            buf_bits,
            shift_len: self.shift_len,
            valid_len: self.valid_len,
        }
    }

    fn finish(self) -> Self::Output {
        Self::Output {
            buf: 0,
            buf_bits: 0,
            shift_len: 0,
            valid_len: self.valid_len,
        }
    }
}

#[derive(Debug)]
pub struct BitExpandIter {
    buf: u16,
    buf_bits: u8,
    valid_len: u8,
    shift_len: u8,
}

impl Iterator for BitExpandIter {
    type Item = u8;

    fn next(&mut self) -> Option<u8> {
        if self.buf_bits < self.valid_len {
            None
        } else {
            let result = (self.buf >> self.shift_len) as u8;
            self.buf <<= self.valid_len;
            self.buf_bits -= self.valid_len;
            Some(result)
        }
    }
}

fn process_bytes<C: Codec>(mut codec: C, bytes: &[u8]) -> Vec<u8> {
    let mut result: Vec<u8> = bytes.iter().flat_map(|byte| codec.accept(*byte)).collect();
    codec.finish().for_each(|byte| result.push(byte));
    result
}

fn print_bytes(bytes: &[u8]) {
    for byte in bytes {
        print!("{:08b} ", byte);
    }
    println!();

    for byte in bytes {
        print!("{:02x} ", byte);
    }
    println!();
}

fn main() {
    let original = b"STRINGIFY!";
    let discard = 1;
    print_bytes(&original[..]);
    let compressed = process_bytes(BitDiscard::new(discard), &original[..]);
    print_bytes(&compressed);
    let decompressed = process_bytes(BitExpand::new(discard), &compressed);
    print_bytes(&decompressed);
}


Bitwise operations

void bitwise(int a, int b)
{
  printf("a and b: %d\n", a & b);
  printf("a or b: %d\n", a | b);
  printf("a xor b: %d\n", a ^ b);
  printf("not a: %d\n", ~a);
  printf("a << n: %d\n", a << b);
  printf("a >> n: %d\n", a >> b);

  unsigned int c = a;
  printf("c >> b: %d\n", c >> b);

  return 0;
}


Box the compass

#include <stdio.h>

int main()
{
        int i, j;
        double degrees[] = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5,
                84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88,
                168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12,
                253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5,
                354.37, 354.38 };
        const char * names =  "North                 "
                              "North by east         "
                              "North-northeast       "
                              "Northeast by north    "
                              "Northeast             "
                              "Northeast by east     "
                              "East-northeast        "
                              "East by north         "
                              "East                  "
                              "East by south         "
                              "East-southeast        "
                              "Southeast by east     "
                              "Southeast             "
                              "Southeast by south    "
                              "South-southeast       "
                              "South by east         "
                              "South                 "
                              "South by west         "
                              "South-southwest       "
                              "Southwest by south    "
                              "Southwest             "
                              "Southwest by west     "
                              "West-southwest        "
                              "West by south         "
                              "West                  "
                              "West by north         "
                              "West-northwest        "
                              "Northwest by west     "
                              "Northwest             "
                              "Northwest by north    "
                              "North-northwest       "
                              "North by west         "
                              "North                 ";

        for (i = 0; i < 33; i++) {
                j = .5 + degrees[i] * 32 / 360;

                printf("%2d  %.22s  %6.2f\n", (j % 32) + 1, names + (j % 32) * 22,
                        degrees[i]);
        }

        return 0;
}

fn expand(cp: &str) -> String {
    let mut out = String::new();
    for c in cp.chars() {
        out.push_str(match c {
            'N' => "north",
            'E' => "east",
            'S' => "south",
            'W' => "west",
            'b' => " by ",
            _ => "-",
        });
    }
    out
}

fn main() {
    let cp = [
        "N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN",
        "E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE",
        "S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS",
        "W", "WbN", "W-NW", "NWbW", "NW", "NWbN", "N-NW", "NbW"
    ];
    println!("Index  Degrees  Compass point");
    println!("-----  -------  -------------");
    for i in 0..=32 {
        let index = i % 32;
        let heading = i as f32 * 11.25
            + match i % 3 {
                1 => 5.62,
                2 => -5.62,
                _ => 0.0,
            };
        println!(
            "{:2}     {:6.2}   {}",
            index + 1,
            heading,
            expand(cp[index])
        );
    }
}


Brownian tree

#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <FreeImage.h>

#define NUM_PARTICLES  1000
#define SIZE           800

void draw_brownian_tree(int world[SIZE][SIZE]){
  int px, py;
  int dx, dy;
  int i;

  world[rand() % SIZE][rand() % SIZE] = 1;

  for (i = 0; i < NUM_PARTICLES; i++){

    px = rand() % SIZE;
    py = rand() % SIZE;

    while (1){

      dx = rand() % 3 - 1;
      dy = rand() % 3 - 1;

      if (dx + px < 0 || dx + px >= SIZE || dy + py < 0 || dy + py >= SIZE){

        px = rand() % SIZE;
        py = rand() % SIZE;
      }else if (world[py + dy][px + dx] != 0){

        world[py][px] = 1;
        break;
      }else{
        py += dy;
        px += dx;
      }
    }
  }
}

int main(){
  int world[SIZE][SIZE];
  FIBITMAP * img;
  RGBQUAD rgb;
  int x, y;

  memset(world, 0, sizeof world);
  srand((unsigned)time(NULL));

  draw_brownian_tree(world);

  img = FreeImage_Allocate(SIZE, SIZE, 32, 0, 0, 0);

  for (y = 0; y < SIZE; y++){
    for (x = 0; x < SIZE; x++){
      rgb.rgbRed = rgb.rgbGreen = rgb.rgbBlue = (world[y][x] ? 255 : 0);
      FreeImage_SetPixelColor(img, x, y, &rgb);
    }
  }
  FreeImage_Save(FIF_BMP, img, "brownian_tree.bmp", 0);
  FreeImage_Unload(img);
}

extern crate image;
extern crate rand;

use image::ColorType;

use std::cmp::{min, max};
use std::env;
use std::path::Path;
use std::process;
use rand::Rng;

fn help() {
    println!("Usage: brownian_tree <output_path> <mote_count> <edge_length>");
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut output_path = Path::new("out.png");
    let mut mote_count: u32 = 10000;
    let mut width: usize = 512;
    let mut height: usize = 512;

    match args.len() {
        1 => {}
        4 => {
            output_path = Path::new(&args[1]);
            mote_count = args[2].parse::<u32>().unwrap();
            width = args[3].parse::<usize>().unwrap();
            height = width;
        }
        _ => {
            help();
            process::exit(0);
        }
    }

    assert!(width >= 2);

    let mut field_raw = vec![0u8; width * height];
    populate_tree(&mut field_raw, width, height, mote_count);

    let our_max = field_raw.iter().fold(0u8, |champ, e| max(champ, *e));
    let fudge = std::u8::MAX / our_max;
    let balanced: Vec<u8> = field_raw.iter().map(|e| e * fudge).collect();

    match image::save_buffer(output_path,
                             &balanced,
                             width as u32,
                             height as u32,
                             ColorType::L8) {
        Err(e) => println!("Error writing output image:\n{}", e),
        Ok(_) => println!("Output written to:\n{}", output_path.to_str().unwrap()),
    }
}

fn populate_tree(raw: &mut Vec<u8>, width: usize, height: usize, mc: u32) {

    let mut field_base: Vec<_> = raw.as_mut_slice().chunks_mut(width).collect();

    let field: &mut [&mut [u8]] = field_base.as_mut_slice();

    field[width / 2][height / 2] = 1;

    let mut rng = rand::thread_rng();

    for i in 0..mc {
        if i % 100 == 0 {
            println!("{}", i)
        }

        let mut x=rng.gen_range(1usize..width-1);
        let mut y=rng.gen_range(1usize..height-1);

        if field[x][y] > 0 {
            field[x][y] = min(field[x][y] as u32 + 1, std::u8::MAX as u32) as u8;
            continue;
        }

        loop {
            let contacts = field[x - 1][y - 1] + field[x][y - 1] + field[x + 1][y - 1] +
                field[x - 1][y] + field[x + 1][y] +
                field[x - 1][y + 1] + field[x][y + 1] +
                field[x + 1][y + 1];

            if contacts > 0 {
                field[x][y] = 1;
                break;
            } else {
                let xw = rng.gen_range(-1..2) + x as i32;
                let yw = rng.gen_range(-1..2) + y as i32;
                if xw < 1 || xw >= (width as i32 - 1) || yw < 1 || yw >= (height as i32 - 1) {
                    break;
                }
                x = xw as usize;
                y = yw as usize;
            }
        }
    }
}


Bulls and cows

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

#define MAX_NUM_TRIES 72
#define LINE_BEGIN 7
#define LAST_LINE 18

int yp=LINE_BEGIN, xp=0;

char number[5];
char guess[5];

#define MAX_STR 256
void mvaddstrf(int y, int x, const char *fmt, ...)
{
  va_list args;
  char buf[MAX_STR];

  va_start(args, fmt);
  vsprintf(buf, fmt, args);
  move(y, x);
  clrtoeol();
  addstr(buf);
  va_end(args);
}

void ask_for_a_number()
{
  int i=0;
  char symbols[] = "123456789";

  move(5,0); clrtoeol();
  addstr("Enter four digits: ");
  while(i<4) {
    int c = getch();
    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
      addch(c);
      symbols[c-'1'] = 0;
      guess[i++] = c;
    }
  }
}

void choose_the_number()
{
  int i=0, j;
  char symbols[] = "123456789";

  while(i<4) {
    j = rand() % 9;
    if ( symbols[j] != 0 ) {
      number[i++] = symbols[j];
      symbols[j] = 0;
    }
  }
}

use std::io;
use rand::{Rng,thread_rng};

extern crate rand;

const NUMBER_OF_DIGITS: usize = 4;

static DIGITS: [char; 9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

fn generate_digits() -> Vec<char> {
    let mut temp_digits: Vec<_> = (&DIGITS[..]).into();
    thread_rng().shuffle(&mut temp_digits);
    return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect();
}

fn parse_guess_string(guess: &str) -> Result<Vec<char>, String> {
    let chars: Vec<char> = (&guess).chars().collect();

    if !chars.iter().all(|c| DIGITS.contains(c)) {
        return Err("only digits, please".to_string());
    }

    if chars.len() != NUMBER_OF_DIGITS {
        return Err(format!("you need to guess with {} digits", NUMBER_OF_DIGITS));
    }

    let mut uniques: Vec<char> = chars.clone();
    uniques.dedup();
    if uniques.len() != chars.len() {
        return Err("no duplicates, please".to_string());
    }

    return Ok(chars);
}

fn calculate_score(given_digits: &[char], guessed_digits: &[char]) -> (usize, usize) {
    let mut bulls = 0;
    let mut cows = 0;
    for i in 0..NUMBER_OF_DIGITS {
        let pos: Option<usize> = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]});
        match pos {
            None              => (),
            Some(p) if p == i => bulls += 1,
            Some(_)           => cows += 1
        }
    }
    return (bulls, cows);
}

fn main() {
    let reader = io::stdin();

    loop {
        let given_digits = generate_digits();
        println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS);

        loop {
            let guess_string: String = {
                let mut buf = String::new();
                reader.read_line(&mut buf).unwrap();
                buf.trim().into()
            };

            let digits_maybe = parse_guess_string(&guess_string);
            match digits_maybe {
                Err(msg) => {
                    println!("{}", msg);
                    continue;
                },
                Ok(guess_digits) => {
                    match calculate_score(&given_digits, &guess_digits) {
                        (NUMBER_OF_DIGITS, _) => {
                            println!("you win!");
                            break;
                        },
                        (bulls, cows) => println!("bulls: {}, cows: {}", bulls, cows)
                    }
                }
            }
        }
    }
}


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

int main()
{
	const char *s = "The quick brown fox jumps over the lazy dog";
	printf("%lX\n", crc32(0, (const void*)s, strlen(s)));

	return 0;
}

fn crc32_compute_table() -> [u32; 256] {
    let mut crc32_table = [0; 256];

    for n in 0..256 {
        crc32_table[n as usize] = (0..8).fold(n as u32, |acc, _| {
            match acc & 1 {
                1 => 0xedb88320 ^ (acc >> 1),
                _ => acc >> 1,
            }
        });
    }

    crc32_table
}

fn crc32(buf: &str) -> u32 {
    let crc_table = crc32_compute_table();

    !buf.bytes().fold(!0, |acc, octet| {
        (acc >> 8) ^ crc_table[((acc & 0xff) ^ octet as u32) as usize]
    })
}

fn main() {
    println!("{:x}", crc32("The quick brown fox jumps over the lazy dog"));
}


CSV data manipulation

#define TITLE "CSV data manipulation"
#define URL "http:

#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

typedef struct {
	char * delim;
	unsigned int rows;
	unsigned int cols;
	char ** table;
} CSV;

int trim(char ** str) {
	int trimmed;
	int n;
	int len;

	len = strlen(*str);
	n = len - 1;

	while((n>=0) && isspace((*str)[n])) {
		(*str)[n] = '\0';
		trimmed += 1;
		n--;
	}

	n = 0;
	while((n < len) && (isspace((*str)[0]))) {
		(*str)[0] = '\0';
		*str = (*str)+1;
		trimmed += 1;
		n++;
	}
	return trimmed;
}

int csv_destroy(CSV * csv) {
	if (csv == NULL) { return 0; }
	if (csv->table != NULL) { free(csv->table); }
	if (csv->delim != NULL) { free(csv->delim); }
	free(csv);
	return 0;
}

CSV * csv_create(unsigned int cols, unsigned int rows) {
	CSV * csv;

	csv = malloc(sizeof(CSV));
	csv->rows = rows;
	csv->cols = cols;
	csv->delim = strdup(",");

	csv->table = malloc(sizeof(char *) * cols * rows);
	if (csv->table == NULL) { goto error; }

	memset(csv->table, 0, sizeof(char *) * cols * rows);

	return csv;

error:
	csv_destroy(csv);
	return NULL;
}

char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
	unsigned int idx;
	idx = col + (row * csv->cols);
	return csv->table[idx];
}

int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
	unsigned int idx;
	idx = col + (row * csv->cols);
	csv->table[idx] = value;
	return 0;
}

void csv_display(CSV * csv) {
	int row, col;
	char * content;
	if ((csv->rows == 0) || (csv->cols==0)) {
		printf("[Empty table]\n");
		return ;
	}

	printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
	for (row=0; row<csv->rows; row++) {
		printf("[|");
		for (col=0; col<csv->cols; col++) {
			content = csv_get(csv, col, row);
            printf("%s\t|", content);
		}
        printf("]\n");
	}
	printf("\n");
}

int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
	unsigned int cur_col,
				 cur_row,
				 max_cols,
				 max_rows;
	CSV * new_csv;
	char * content;
	bool in_old, in_new;

	new_csv = csv_create(new_cols, new_rows);
	if (new_csv == NULL) { goto error; }

	new_csv->rows = new_rows;
	new_csv->cols = new_cols;

	max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
	max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;

	for (cur_col=0; cur_col<max_cols; cur_col++) {
		for (cur_row=0; cur_row<max_rows; cur_row++) {
			in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
			in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);

			if (in_old && in_new) {

				content = csv_get(old_csv, cur_col, cur_row);
				csv_set(new_csv, cur_col, cur_row, content);
			} else if (in_old) {

				content = csv_get(old_csv, cur_col, cur_row);
				free(content);
			} else {  }
		}
	}

	free(old_csv->table);
	old_csv->rows = new_rows;
	old_csv->cols = new_cols;
	old_csv->table = new_csv->table;
	new_csv->table = NULL;
	csv_destroy(new_csv);

	return 0;

error:
	printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
	return -1;
}

int csv_open(CSV * csv, char * filename) {
	FILE * fp;
	unsigned int m_rows;
	unsigned int m_cols, cols;
	char line[2048];
	char * lineptr;
	char * token;

	fp = fopen(filename, "r");
	if (fp == NULL) { goto error; }

	m_rows = 0;
	m_cols = 0;
	while(fgets(line, sizeof(line), fp) != NULL) {
 		m_rows += 1;
 		cols = 0;
 		lineptr = line;
 		while ((token = strtok(lineptr, csv->delim)) != NULL) {
 			lineptr = NULL;
 			trim(&token);
            cols += 1;
        	if (cols > m_cols) { m_cols = cols; }
            csv_resize(csv, m_cols, m_rows);
            csv_set(csv, cols-1, m_rows-1, strdup(token));
        }
	}

	fclose(fp);
	csv->rows = m_rows;
	csv->cols = m_cols;
	return 0;

error:
	fclose(fp);
	printf("Unable to open %s for reading.", filename);
	return -1;
}

int csv_save(CSV * csv, char * filename) {
	FILE * fp;
	int row, col;
	char * content;

	fp = fopen(filename, "w");
	for (row=0; row<csv->rows; row++) {
		for (col=0; col<csv->cols; col++) {
			content = csv_get(csv, col, row);
            fprintf(fp, "%s%s", content,
            		((col == csv->cols-1) ? "" : csv->delim) );
		}
        fprintf(fp, "\n");
	}

	fclose(fp);
	return 0;
}

int main(int argc, char ** argv) {
	CSV * csv;

	printf("%s\n%s\n\n",TITLE, URL);

	csv = csv_create(0, 0);
	csv_open(csv, "fixtures/csv-data-manipulation.csv");
	csv_display(csv);

	csv_set(csv, 0, 0, "Column0");
	csv_set(csv, 1, 1, "100");
	csv_set(csv, 2, 2, "200");
	csv_set(csv, 3, 3, "300");
	csv_set(csv, 4, 4, "400");
	csv_display(csv);

	csv_save(csv, "tmp/csv-data-manipulation.result.csv");
	csv_destroy(csv);

	return 0;
}

use std::error::Error;
use std::num::ParseIntError;
use csv::{Reader, Writer};

fn main() -> Result<(), Box<dyn Error>> {
    let mut reader = Reader::from_path("data.csv")?;
    let mut writer = Writer::from_path("output.csv")?;

    let mut headers = reader.headers()?.clone();
    headers.push_field("SUM");
    writer.write_record(headers.iter())?;

    for row in reader.records() {
        let mut row = row?;

        let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| {
            Ok(accum + s.parse::<i64>()?)
        });

        row.push_field(&sum?.to_string());
        writer.write_record(row.iter())?;
    }

    writer.flush()?;
    Ok(())
}


CUSIP

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

int cusipCheck(char str[10]){
	int sum=0,i,v;

	for(i=0;i<8;i++){
		if(str[i]>='0'&&str[i]<='9')
			v = str[i]-'0';
		else if(str[i]>='A'&&str[i]<='Z')
			v = (str[i] - 'A' + 10);
		else if(str[i]=='*')
			v = 36;
		else if(str[i]=='@')
			v = 37;
		else if(str[i]=='#')
			v = 38;
		if(i%2!=0)
			v*=2;

		sum += ((int)(v/10) + v%10);
	}
	return ((10 - (sum%10))%10);
}

int main(int argC,char* argV[])
{
	char cusipStr[10];

	int i,numLines;

	if(argC==1)
		printf("Usage : %s <full path of CUSIP Data file>",argV[0]);

	else{
		FILE* fp = fopen(argV[1],"r");

		fscanf(fp,"%d",&numLines);

		printf("CUSIP       Verdict\n");
		printf("-------------------");

		for(i=0;i<numLines;i++){

			fscanf(fp,"%s",cusipStr);

			printf("\n%s : %s",cusipStr,(cusipCheck(cusipStr)==(cusipStr[8]-'0'))?"Valid":"Invalid");
		}

		fclose(fp);
	}
	return 0;
}

fn cusip_check(cusip: &str) -> bool {
    if cusip.len() != 9 {
        return false;
    }

    let mut v = 0;
    let capital_cusip = cusip.to_uppercase();
    let char_indices = capital_cusip.as_str().char_indices().take(7);

    let total = char_indices.fold(0, |total, (i, c)| {
        v = match c {
            '*' => 36,
            '@' => 37,
            '#' => 38,
            _ if c.is_digit(10) => c.to_digit(10).unwrap() as u8,
            _ if c.is_alphabetic() => (c as u8) - b'A' + 1 + 9,
            _ => v,
        };

        if i % 2 != 0 {
            v *= 2
        }
        total + (v / 10) + v % 10
    });

    let check = (10 - (total % 10)) % 10;
    (check.to_string().chars().nth(0).unwrap()) == cusip.chars().nth(cusip.len() - 1).unwrap()
}

fn main() {
    let codes = [
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105",
    ];
    for code in &codes {
        println!("{} -> {}", code, cusip_check(code))
    }
}


Caesar cipher

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

#define caesar(x) rot(13, x)
#define decaesar(x) rot(13, x)
#define decrypt_rot(x, y) rot((26-x), y)

void rot(int c, char *str)
{
	int l = strlen(str);

        const char*  alpha_low  = "abcdefghijklmnopqrstuvwxyz";

        const char*  alpha_high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

       char subst;
       int idx;

         int i;

	for (i = 0; i < l; i++)
	{
		if( 0 == isalpha(str[i]) )  continue;

                idx = (int) (tolower(str[i]) - 'a') + c) % 26;

		if( isupper(str[i]) )
                    subst = alpha_high[idx];
                else
                    subst = alpha_low[idx];

               str[i] = subst;

	}
}

int main(int argc, char** argv)
{
	char str[] = "This is a top secret text message!";

	printf("Original: %s\n", str);
	caesar(str);
	printf("Encrypted: %s\n", str);
	decaesar(str);
	printf("Decrypted: %s\n", str);

	return 0;
}

use std::io::{self, Write};
use std::fmt::Display;
use std::{env, process};

fn main() {
    let shift: u8 = env::args().nth(1)
        .unwrap_or_else(|| exit_err("No shift provided", 2))
        .parse()
        .unwrap_or_else(|e| exit_err(e, 3));

    let plain = get_input()
        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));

    let cipher = plain.chars()
        .map(|c| {
            let case = if c.is_uppercase() {'A'} else {'a'} as u8;
            if c.is_alphabetic() { (((c as u8 - case + shift) % 26) + case) as char } else { c }
        }).collect::<String>();

    println!("Cipher text: {}", cipher.trim());
}

fn get_input() -> io::Result<String> {
    print!("Plain text:  ");
    try!(io::stdout().flush());

    let mut buf = String::new();
    try!(io::stdin().read_line(&mut buf));
    Ok(buf)
}

fn exit_err<T: Display>(msg: T, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
    process::exit(code);
}


Calculating the value of e

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

int main(void)
{
    double e;

    puts("The double precision in C give about 15 significant digits.\n"
         "Values below are presented with 16 digits after the decimal point.\n");

    e = exp(1);
    printf("Euler constant e = %.16lf\n", e);

    e = 1.0 + 0x1p-26;
    for (int i = 0; i < 26; i++)
        e *= e;
    printf("Euler constant e = %.16lf\n", e);

    const int N = 1000;
    double a[1000];
    a[0] = 1.0;
    for (int i = 1; i < N; i++)
    {
        a[i] = a[i-1] / i;
    }
    e = 1.;
    for (int i = N - 1; i > 0; i--)
        e += a[i];
    printf("Euler constant e = %.16lf\n", e);

    return 0;
}

const EPSILON: f64 = 1e-15;

fn main() {
    let mut fact: u64 = 1;
    let mut e: f64 = 2.0;
    let mut n: u64 = 2;
    loop {
        let e0 = e;
        fact *= n;
        n += 1;
        e += 1.0 / fact as f64;
        if (e - e0).abs() < EPSILON {
            break;
        }
    }
    println!("e = {:.15}", e);
}


Calendar

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

int width = 80, year = 1969;
int cols, lead, gap;

const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" };
struct months {
	const char *name;
	int days, start_wday, at;
} months[12] = {
	{ "January",	31, 0, 0 },
	{ "February",	28, 0, 0 },
	{ "March",	31, 0, 0 },
	{ "April",	30, 0, 0 },
	{ "May",	31, 0, 0 },
	{ "June",	30, 0, 0 },
	{ "July",	31, 0, 0 },
	{ "August",	31, 0, 0 },
	{ "September",	30, 0, 0 },
	{ "October",	31, 0, 0 },
	{ "November",	30, 0, 0 },
	{ "December",	31, 0, 0 }
};

void space(int n) { while (n-- > 0) putchar(' '); }

void init_months()
{
	int i;

	if ((!(year % 4) && (year % 100)) || !(year % 400))
		months[1].days = 29;

	year--;
	months[0].start_wday
		= (year * 365 + year/4 - year/100 + year/400 + 1) % 7;

	for (i = 1; i < 12; i++)
		months[i].start_wday =
			(months[i-1].start_wday + months[i-1].days) % 7;

	cols = (width + 2) / 22;
	while (12 % cols) cols--;
	gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0;
	if (gap > 4) gap = 4;
	lead = (width - (20 + gap) * cols + gap + 1) / 2;
        year++;
}

void print_row(int row)
{
	int c, i, from = row * cols, to = from + cols;
	space(lead);
	for (c = from; c < to; c++) {
		i = strlen(months[c].name);
		space((20 - i)/2);
		printf("%s", months[c].name);
		space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap));
	}
	putchar('\n');

	space(lead);
	for (c = from; c < to; c++) {
		for (i = 0; i < 7; i++)
			printf("%s%s", wdays[i], i == 6 ? "" : " ");
		if (c < to - 1) space(gap);
		else putchar('\n');
	}

	while (1) {
		for (c = from; c < to; c++)
			if (months[c].at < months[c].days) break;
		if (c == to) break;

		space(lead);
		for (c = from; c < to; c++) {
			for (i = 0; i < months[c].start_wday; i++) space(3);
			while(i++ < 7 && months[c].at < months[c].days) {
				printf("%2d", ++months[c].at);
				if (i < 7 || c < to - 1) putchar(' ');
			}
			while (i++ <= 7 && c < to - 1) space(3);
			if (c < to - 1) space(gap - 1);
			months[c].start_wday = 0;
		}
		putchar('\n');
	}
	putchar('\n');
}

void print_year()
{
	int row;
	char buf[32];
	sprintf(buf, "%d", year);
	space((width - strlen(buf)) / 2);
	printf("%s\n\n", buf);
	for (row = 0; row * cols < 12; row++)
		print_row(row);
}

int main(int c, char **v)
{
	int i, year_set = 0;
	for (i = 1; i < c; i++) {
		if (!strcmp(v[i], "-w")) {
			if (++i == c || (width = atoi(v[i])) < 20)
				goto bail;
		} else if (!year_set) {
			if (!sscanf(v[i], "%d", &year) || year <= 0)
				year = 1969;
			year_set = 1;
		} else
			goto bail;
	}

	init_months();
	print_year();
	return 0;

bail:	fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]);
	exit(1);
}

extern crate chrono;

use std::{env, cmp};
use chrono::{NaiveDate, Datelike};

const MONTH_WIDTH: usize = 22;

fn print_header(months: &[&str]) {
    const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA  ";
    println!();
    for m in months {
        print!("{:^20}  ", m);
    }
    println!("\n{}", DAYS_OF_WEEK.repeat(months.len()));
}

fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> {
    let start = week_num * 7 - start_day_of_week + 1;
    let end = (week_num + 1) * 7 - start_day_of_week;
    let mut ret = String::with_capacity(MONTH_WIDTH);
    if start > days {
        None
    } else {
        for i in start..(end + 1) {
            if i <= 0 || i > days {
                ret.push_str("  ");
            } else {
                if i < 10 {
                    ret.push_str(" ");
                }
                ret.push_str(&i.to_string());
            }
            ret.push_str(" ");
        }
        ret.push_str(" ");
        Some(ret)
    }
}

fn main() {
    const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
                                     "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
    const DEFAULT_TEXT_WIDTH: usize = 100;

    let args: Vec<String> = env::args().collect();
    let year: i32 = args[1].parse().expect("The first argument must be a year");
    let width: usize = if args.len() > 2 {
        cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width"))
    } else {
        DEFAULT_TEXT_WIDTH
    };
    let months_in_row = width / MONTH_WIDTH;
    let month_rows = if MONTH_NAMES.len() % months_in_row == 0 {
        MONTH_NAMES.len() / months_in_row
    } else {
        MONTH_NAMES.len() / months_in_row + 1
    };

    let start_days_of_week: Vec<i32> =
        (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect();

    let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };

    println!("{year:^w$}", w=width, year=year.to_string());
    for i in 0..month_rows {
        let start = i * months_in_row;
        let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len());
        print_header(&MONTH_NAMES[start..end]);
        let mut count = 0;
        let mut row_num = 0;
        while count < months_in_row {
            let mut row_str = String::with_capacity(width);
            for j in start..end {
                match get_week_str(month_days[j], row_num, start_days_of_week[j]) {
                    None => {
                        count += 1;
                        row_str.push_str(&" ".repeat(MONTH_WIDTH));
                    },
                    Some(week_str) => row_str.push_str(&week_str)
                }
            }
            if count < months_in_row {
                println!("{}", row_str);
            }
            row_num += 1;
        }
    }
}