Call a function in a shared library

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

int myopenimage(const char *in)
{
  static int handle=0;
  fprintf(stderr, "internal openimage opens %s...\n", in);
  return handle++;
}

int main()
{
  void *imglib;
  int (*extopenimage)(const char *);
  int imghandle;

  imglib = dlopen("./fakeimglib.so", RTLD_LAZY);
  if ( imglib != NULL ) {

    *(void **)(&extopenimage) = dlsym(imglib, "openimage");

    imghandle = extopenimage("fake.img");
  } else {
    imghandle = myopenimage("fake.img");
  }
  printf("opened with handle %d\n", imghandle);

  if (imglib != NULL ) dlclose(imglib);
  return EXIT_SUCCESS;
}

#![allow(unused_unsafe)]
extern crate libc;

use std::io::{self,Write};
use std::{mem,ffi,process};

use libc::{c_double, RTLD_NOW};

macro_rules! to_cstr {
    ($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}

macro_rules! from_cstr {
    ($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}

fn main() {
    unsafe {
        let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);

        if handle.is_null() {
            writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
            process::exit(1);
        }

        let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
                .as_ref()
                .map(mem::transmute::<_,fn (c_double) -> c_double)
                .unwrap_or(builtin_cos);
        println!("{}", extern_cos(4.0));
    }
}

fn builtin_cos(x: c_double) -> c_double {
    x.cos()
}


Call an object method

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

typedef struct{
        int x;
        int (*funcPtr)(int);
}functionPair;

int factorial(int num){
        if(num==0||num==1)
                return 1;
        else
                return num*factorial(num-1);
}

int main(int argc,char** argv)
{
        functionPair response;

        if(argc!=2)
                return printf("Usage : %s <non negative integer>",argv[0]);
        else{
                response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
                printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
        }
        return 0;
}

struct Foo;

impl Foo {

    fn get_the_answer_to_life(&self) -> i32 {
        42
    }

    fn new() -> Foo {
        println!("Hello, world!");
        Foo
    }
}

fn main() {

    let foo = Foo::new();

    println!("The answer to life is {}.", foo.get_the_answer_to_life());

    let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;
    println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
}


Cantor set

#include <stdio.h>

#define WIDTH 81
#define HEIGHT 5

char lines[HEIGHT][WIDTH];

void init() {
    int i, j;
    for (i = 0; i < HEIGHT; ++i) {
        for (j = 0; j < WIDTH; ++j) lines[i][j] = '*';
    }
}

void cantor(int start, int len, int index) {
    int i, j, seg = len / 3;
    if (seg == 0) return;
    for (i = index; i < HEIGHT; ++i) {
        for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' ';
    }
    cantor(start, seg, index + 1);
    cantor(start + seg * 2, seg, index + 1);
}

void print() {
    int i, j;
    for (i = 0; i < HEIGHT; ++i) {
        for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]);
        printf("\n");
    }
}

int main() {
    init();
    cantor(0, WIDTH, 1);
    print();
    return 0;
}

use convert_base::Convert;
use std::fmt;

struct CantorSet {
    cells: Vec<Vec<bool>>,
}
fn number_to_vec(n: usize) -> Vec<u32> {

    n.to_string()
        .chars()
        .rev()
        .map(|c| c.to_digit(10).unwrap())
        .collect()
}

impl CantorSet {
    fn new(lines: usize) -> CantorSet {

        let mut base = Convert::new(10, 3);
        let mut cells: Vec<Vec<bool>> = vec![];

        for line in 0..lines {

            let segment_size = 3_usize.pow((lines - line - 1) as u32);
            let segment: Vec<bool> = (0..3_usize.pow(line as u32))
                .map(|n| {
                    let output = base.convert::<u32, u32>(&number_to_vec(n));

                    !output.contains(&1)
                })
                .collect();

            let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size);
            for c in segment.iter() {
                accum.extend(std::iter::repeat(*c).take(segment_size))
            }

            cells.push(accum);
        }

        CantorSet { cells }
    }
}

impl fmt::Display for CantorSet {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for line in self.cells.iter() {
            for c in line {
                write!(f, "{}", if *c { "█" } else { " " })?
            }
            writeln!(f)?;
        }

        Ok(())
    }
}
fn main() {
    let cs = CantorSet::new(5);
    println!("Cantor set:");
    println!("{}", cs);
}


Cartesian product of two or more lists

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

void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
	int i,j;

	if(times==numSets){
		printf("(");
		for(i=0;i<times;i++){
			printf("%d,",currentSet[i]);
		}
		printf("\b),");
	}
	else{
		for(j=0;j<setLengths[times];j++){
			currentSet[times] = sets[times][j];
			cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
		}
	}
}

void printSets(int** sets, int* setLengths, int numSets){
	int i,j;

	printf("\nNumber of sets : %d",numSets);

	for(i=0;i<numSets+1;i++){
		printf("\nSet %d : ",i+1);
		for(j=0;j<setLengths[i];j++){
			printf(" %d ",sets[i][j]);
		}
	}
}

void processInputString(char* str){
	int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
	char *token,*holder,*holderToken;

	for(i=0;str[i]!=00;i++)
		if(str[i]=='x')
			numSets++;

	if(numSets==0){
			printf("\n%s",str);
			return;
	}

	currentSet = (int*)calloc(sizeof(int),numSets + 1);

	setLengths = (int*)calloc(sizeof(int),numSets + 1);

	sets = (int**)malloc((numSets + 1)*sizeof(int*));

	token = strtok(str,"x");

	while(token!=NULL){
		holder = (char*)malloc(strlen(token)*sizeof(char));

		j = 0;

		for(i=0;token[i]!=00;i++){
			if(token[i]>='0' && token[i]<='9')
				holder[j++] = token[i];
			else if(token[i]==',')
				holder[j++] = ' ';
		}
		holder[j] = 00;

		setLength = 0;

		for(i=0;holder[i]!=00;i++)
			if(holder[i]==' ')
				setLength++;

		if(setLength==0 && strlen(holder)==0){
			printf("\n{}");
			return;
		}

		setLengths[counter] = setLength+1;

		sets[counter] = (int*)malloc((1+setLength)*sizeof(int));

		k = 0;

		start = 0;

		for(l=0;holder[l]!=00;l++){
			if(holder[l+1]==' '||holder[l+1]==00){
				holderToken = (char*)malloc((l+1-start)*sizeof(char));
				strncpy(holderToken,holder + start,l+1-start);
				sets[counter][k++] = atoi(holderToken);
				start = l+2;
			}
		}

		counter++;
		token = strtok(NULL,"x");
	}

	printf("\n{");
	cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
	printf("\b}");

}

int main(int argC,char* argV[])
{
	if(argC!=2)
		printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
	else
		processInputString(argV[1]);

	return 0;
}

fn cartesian_product(lists: &Vec<Vec<u32>>) -> Vec<Vec<u32>> {
    let mut res = vec![];

    let mut list_iter = lists.iter();
    if let Some(first_list) = list_iter.next() {
        for &i in first_list {
            res.push(vec![i]);
        }
    }
    for l in list_iter {
        let mut tmp = vec![];
        for r in res {
            for &el in l {
                let mut tmp_el = r.clone();
                tmp_el.push(el);
                tmp.push(tmp_el);
            }
        }
        res = tmp;
    }
    res
}

fn main() {
    let cases = vec![
        vec![vec![1, 2], vec![3, 4]],
        vec![vec![3, 4], vec![1, 2]],
        vec![vec![1, 2], vec![]],
        vec![vec![], vec![1, 2]],
        vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]],
        vec![vec![1, 2, 3], vec![30], vec![500, 100]],
        vec![vec![1, 2, 3], vec![], vec![500, 100]],
    ];
    for case in cases {
        println!(
            "{}\n{:?}\n",
            case.iter().map(|c| format!("{:?}", c)).collect::<Vec<_>>().join(" × "),
            cartesian_product(&case)
        )
    }
}


Catalan numbers

#include <stdio.h>

typedef unsigned long long ull;

ull binomial(ull m, ull n)
{
	ull r = 1, d = m - n;
	if (d > n) { n = d; d = m - n; }

	while (m > n) {
		r *= m--;
		while (d > 1 && ! (r%d) ) r /= d--;
	}

	return r;
}

ull catalan1(int n) {
	return binomial(2 * n, n) / (1 + n);
}

ull catalan2(int n) {
	int i;
	ull r = !n;

	for (i = 0; i < n; i++)
		r += catalan2(i) * catalan2(n - 1 - i);
	return r;
}

ull catalan3(int n)
{
	return n ? 2 * (2 * n - 1) * catalan3(n - 1) / (1 + n) : 1;
}

int main(void)
{
	int i;
	puts("\tdirect\tsumming\tfrac");
	for (i = 0; i < 16; i++) {
		printf("%d\t%llu\t%llu\t%llu\n", i,
			catalan1(i), catalan2(i), catalan3(i));
	}

	return 0;
}


Catalan numbers_Pascal's triangle

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

const int N = 15;

int main()
{

    register int k, n;

    unsigned long long int num, den;

    int catalan;

    printf("1 ");

    for (n=2; n<=N; ++n) {

        num = den = 1;

        for (k=2; k<=n; ++k) {
            num *= (n+k);
            den *= k;
            catalan = num /den;
        }

        printf("%d ", catalan);
    }

    printf("\n");
    return 0;
}


Catamorphism

#include <stdio.h>

typedef int (*intFn)(int, int);

int reduce(intFn fn, int size, int *elms)
{
    int i, val = *elms;
    for (i = 1; i < size; ++i)
        val = fn(val, elms[i]);
    return val;
}

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }

int main(void)
{
    int nums[] = {1, 2, 3, 4, 5};
    printf("%d\n", reduce(add, 5, nums));
    printf("%d\n", reduce(sub, 5, nums));
    printf("%d\n", reduce(mul, 5, nums));
    return 0;
}

fn main() {
    println!("Sum: {}", (1..10).fold(0, |acc, n| acc + n));
    println!("Product: {}", (1..10).fold(1, |acc, n| acc * n));
    let chars = ['a', 'b', 'c', 'd', 'e'];
    println!("Concatenation: {}",
             chars.iter().map(|&c| (c as u8 + 1) as char).collect::<String>());
}


Chaocipher

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

#define TRUE 1
#define FALSE 0

typedef int bool;
typedef enum { ENCRYPT, DECRYPT } cmode;

const char *l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const char *r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

void chao(const char *in, char *out, cmode mode, bool show_steps) {
    int i, j, index;
    char store;
    size_t len = strlen(in);
    char left[27], right[27], temp[27];
    strcpy(left, l_alphabet);
    strcpy(right, r_alphabet);
    temp[26] = '\0';

    for (i = 0; i < len; ++i ) {
        if (show_steps) printf("%s  %s\n", left, right);
        if (mode == ENCRYPT) {
            index = strchr(right, in[i]) - right;
            out[i] = left[index];
        }
        else {
            index = strchr(left, in[i]) - left;
            out[i] = right[index];
        }
        if (i == len - 1) break;

        for (j = index; j < 26; ++j) temp[j - index] = left[j];
        for (j = 0; j < index; ++j) temp[26 - index + j] = left[j];
        store = temp[1];
        for (j = 2; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        strcpy(left, temp);

        for (j = index; j < 26; ++j) temp[j - index] = right[j];
        for (j = 0; j < index; ++j) temp[26 - index + j] = right[j];
        store = temp[0];
        for (j = 1; j < 26; ++j) temp[j - 1] = temp[j];
        temp[25] = store;
        store = temp[2];
        for (j = 3; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        strcpy(right, temp);
    }
}

int main() {
    const char *plain_text = "WELLDONEISBETTERTHANWELLSAID";
    char *cipher_text = malloc(strlen(plain_text) + 1);
    char *plain_text2 = malloc(strlen(plain_text) + 1);
    printf("The original plaintext is : %s\n", plain_text);
    printf("\nThe left and right alphabets after each permutation"
           " during encryption are :\n\n");
    chao(plain_text, cipher_text, ENCRYPT, TRUE);
    printf("\nThe ciphertext is : %s\n", cipher_text);
    chao(cipher_text, plain_text2, DECRYPT, FALSE);
    printf("\nThe recovered plaintext is : %s\n", plain_text2);
    free(cipher_text);
    free(plain_text2);
    return 0;
}

const LEFT_ALPHABET_CT: &str = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const RIGHT_ALPHABET_PT: &str = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
const ZENITH: usize = 0;
const NADIR: usize = 12;
const SEQUENCE: &str = "WELLDONEISBETTERTHANWELLSAID";

fn cipher(letter: &char, left: &String, right: &String) -> (usize, char) {
    let pos = right.find(*letter).unwrap();
    let cipher = left.chars().nth(pos).unwrap();
    (pos, cipher)
}

fn main() {
    let mut left = LEFT_ALPHABET_CT.to_string();
    let mut right = RIGHT_ALPHABET_PT.to_string();

    let ciphertext = SEQUENCE.chars()
        .map(|letter| {
            let (pos, cipher_char) = cipher(&letter, &left, &right);
            left = format!("{}{}", &left[pos..], &left[..pos]);
            left = format!("{}{}{}{}", &left[ZENITH..1], &left[2..NADIR+2], &left[1..2], &left[NADIR+2..]);
            if pos != right.len() - 1 {
                right = format!("{}{}", &right[pos + 1..], &right[..pos + 1]);
            }
            right = format!("{}{}{}{}", &right[ZENITH..2], &right[3..NADIR+2], &right[2..3], &right[NADIR+2..]);
            cipher_char
        })
        .collect::<String>();

    println!("Plaintext: {}", SEQUENCE);
    println!("Ciphertext: {}", ciphertext);
}


Character codes

#include <stdio.h>

int main() {
  printf("%d\n", 'a');
  printf("%c\n", 97);
  return 0;
}

use std::char::from_u32;

fn main() {

    println!("{}", 'a' as u8);
    println!("{}", 97 as char);

    println!("{}", 'π' as u32);
    println!("{}", from_u32(960).unwrap());
}


Chat server

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h>

int tsocket;
struct sockaddr_in tsockinfo;
fd_set status, current;
void ClientText(int handle, char *buf, int buf_len);

struct client
{
    char buffer[4096];
    int pos;
    char name[32];
} *connections[FD_SETSIZE];

void AddConnection(int handle)
{
    connections[handle] = malloc(sizeof(struct client));
    connections[handle]->buffer[0] = '\0';
    connections[handle]->pos = 0;
    connections[handle]->name[0] = '\0';
}

void CloseConnection(int handle)
{
    char buf[512];
    int j;

    FD_CLR(handle, &status);

    if (connections[handle]->name[0])
    {
        sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name);

        for (j = 0; j < FD_SETSIZE; j++)
        {
            if (handle != j && j != tsocket && FD_ISSET(j, &status))
            {
                if (write(j, buf, strlen(buf)) < 0)
                {
                    CloseConnection(j);
                }
            }
        }
    } else
    {
        printf ("-- Connection %d disconnected\n", handle);
    }
    if (connections[handle])
    {
        free(connections[handle]);
    }
    close(handle);
}

void strip(char *buf)
{
    char *x;

    x = strchr(buf, '\n');
    if (x) { *x='\0'; }
    x = strchr(buf, '\r');
    if (x) { *x='\0'; }
}

int RelayText(int handle)
{
    char *begin, *end;
    int ret = 0;
    begin = connections[handle]->buffer;
    if (connections[handle]->pos == 4000)
    {
        if (begin[3999] != '\n')
            begin[4000] = '\0';
        else {
            begin[4000] = '\n';
            begin[4001] = '\0';
        }
    } else {
        begin[connections[handle]->pos] = '\0';
    }

    end = strchr(begin, '\n');
    while (end != NULL)
    {
        char output[8000];
        output[0] = '\0';
        if (!connections[handle]->name[0])
        {
            strncpy(connections[handle]->name, begin, 31);
            connections[handle]->name[31] = '\0';

            strip(connections[handle]->name);
            sprintf(output, "* Connected: %s\r\n", connections[handle]->name);
            ret = 1;
        } else
        {
            sprintf(output, "%s: %.*s\r\n", connections[handle]->name,
                    end-begin, begin);
            ret = 1;
        }

        if (output[0])
        {
            int j;
            for (j = 0; j < FD_SETSIZE; j++)
            {
                if (handle != j && j != tsocket && FD_ISSET(j, &status))
                {
                    if (write(j, output, strlen(output)) < 0)
                    {
                        CloseConnection(j);
                    }
                }
            }
        }
        begin = end+1;
        end = strchr(begin, '\n');
    }

    strcpy(connections[handle]->buffer, begin);
    connections[handle]->pos -= begin - connections[handle]->buffer;
    return ret;
}

void ClientText(int handle, char *buf, int buf_len)
{
    int i, j;
    if (!connections[handle])
        return;
    j = connections[handle]->pos;

    for (i = 0; i < buf_len; ++i, ++j)
    {
        connections[handle]->buffer[j] = buf[i];

        if (j == 4000)
        {
            while (RelayText(handle));
            j = connections[handle]->pos;
        }
    }
    connections[handle]->pos = j;

    while (RelayText(handle));
}

int ChatLoop()
{
    int i, j;
    FD_ZERO(&status);

    FD_SET(tsocket, &status);
    FD_SET(0, &status);

    while(1)
    {
        current = status;
        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)
        {
            perror("Select");
            return 0;
        }
        for (i = 0; i < FD_SETSIZE; ++i)
        {
            if (FD_ISSET(i, &current))
            {
                if (i == tsocket)
                {
                    struct sockaddr_in cliinfo;
                    socklen_t addrlen = sizeof(cliinfo);
                    int handle;
                    handle = accept(tsocket, &cliinfo, &addrlen);
                    if (handle == -1)
                    {
                        perror ("Couldn't accept connection");
                    } else if (handle > FD_SETSIZE)
                    {
                        printf ("Unable to accept new connection.\n");
                        close(handle);
                    }
                    else
                    {
                        if (write(handle, "Enter name: ", 12) >= 0)
                        {
                            printf("-- New connection %d from %s:%hu\n",
                                handle,
                                inet_ntoa (cliinfo.sin_addr),
                                ntohs(cliinfo.sin_port));
                            FD_SET(handle, &status);

                            AddConnection(handle);
                        }
                    }
                }
                else
                {
                    char buf[512];
                    int b;

                    b = read(i, buf, 500);
                    if (b <= 0)
                    {
                        CloseConnection(i);
                    }
                    else
                    {
                        ClientText(i, buf, b);
                    }
                }
            }
        }
    }
}

int main (int argc, char*argv[])
{
    tsocket = socket(PF_INET, SOCK_STREAM, 0);

    tsockinfo.sin_family = AF_INET;
    tsockinfo.sin_port = htons(7070);
    if (argc > 1)
    {
        tsockinfo.sin_port = htons(atoi(argv[1]));
    }
    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);
    printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));

    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)
    {
        perror("Couldn't bind socket");
        return -1;
    }

    if (listen(tsocket, 10) == -1)
    {
        perror("Couldn't listen to port");
    }

    ChatLoop();

    return 0;
}

use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, RwLock};
use std::thread;

type Username = String;

fn broadcast_message(
    user: &str,
    clients: &mut HashMap<String, TcpStream>,
    message: &str,
) -> io::Result<()> {
    for (client, stream) in clients.iter_mut() {
        if client != user {
            writeln!(stream, "{}", message)?;
        }
    }

    Ok(())
}

fn chat_loop(listener: &TcpListener) -> io::Result<()> {
    let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> =
        Arc::new(RwLock::new(HashMap::new()));

    println!("Accepting connections on {}", listener.local_addr()?.port());

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                let client_clients = Arc::clone(&local_clients);
                thread::spawn(move || -> io::Result<()> {
                    let mut reader = BufReader::new(stream.try_clone()?);
                    let mut writer = stream;

                    let mut name = String::new();
                    loop {
                        write!(writer, "Please enter a username: ")?;
                        reader.read_line(&mut name)?;
                        name = name.trim().to_owned();

                        let clients = client_clients.read().unwrap();
                        if !clients.contains_key(&name) {
                            writeln!(writer, "Welcome, {}!", &name)?;
                            break;
                        }

                        writeln!(writer, "That username is taken.")?;
                        name.clear();
                    }

                    {
                        let mut clients = client_clients.write().unwrap();
                        clients.insert(name.clone(), writer);
                        broadcast_message(
                            &name,
                            &mut *clients,
                            &format!("{} has joined the chat room.", &name),
                        )?;
                    }

                    for line in reader.lines() {
                        let mut clients = client_clients.write().unwrap();
                        broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?;
                    }

                    {
                        let mut clients = client_clients.write().unwrap();
                        clients.remove(&name);
                        broadcast_message(
                            &name,
                            &mut *clients,
                            &format!("{} has left the chat room.", &name),
                        )?;
                    }

                    Ok(())
                });
            }
            Err(e) => {
                println!("Connection failed: {}", e);
            }
        }
    }

    Ok(())
}

fn main() {
    let listener = TcpListener::bind(("localhost", 7000)).unwrap();
    chat_loop(&listener).unwrap();
}


Check output device is a terminal

#include <unistd.h>
#include <stdio.h>

int main()
{
    puts(isatty(fileno(stdout))
          ? "stdout is tty"
          : "stdout is not tty");
    return 0;
}

f = File.open("test.txt")
p f.isatty          # => false
p STDOUT.isatty     # => true


Check that file exists

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>

int check_reg(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISREG(sb.st_mode);
}

int check_dir(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);
}

int main() {
	printf("input.txt is a regular file? %s\n",
	    check_reg("input.txt") ? "yes" : "no");
	printf("docs is a directory? %s\n",
	    check_dir("docs") ? "yes" : "no");
	printf("/input.txt is a regular file? %s\n",
	    check_reg("/input.txt") ? "yes" : "no");
	printf("/docs is a directory? %s\n",
	    check_dir("/docs") ? "yes" : "no");
	return 0;
}

use std::fs;

fn main() {
    for file in ["input.txt", "docs", "/input.txt", "/docs"].iter() {
        match fs::metadata(file) {
            Ok(attr) => {
                if attr.is_dir() {
                    println!("{} is a directory", file);
                }else {
                    println!("{} is a file", file);
                }
            },
            Err(_) => {
                println!("{} does not exist", file);
            }
        };
    }
}


Checkpoint synchronization

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

int main()
{
        int jobs = 41, tid;
        omp_set_num_threads(5);

        #pragma omp parallel shared(jobs) private(tid)
        {
                tid = omp_get_thread_num();
                while (jobs > 0) {

                        #pragma omp barrier
                        if (!jobs) break;

                        printf("%d: taking job %d\n", tid, jobs--);
                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);
                        printf("%d: done job\n", tid);
                }

                printf("[%d] leaving\n", tid);

                #pragma omp barrier
        }

        return 0;
}

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::thread::spawn;

use array_init::array_init;

pub fn checkpoint() {
    const NUM_TASKS: usize = 10;
    const NUM_ITERATIONS: u8 = 10;

    let barrier = Barrier::new(NUM_TASKS);
    let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));

    let arc = Arc::new((barrier, events));

    let (tx, rx) = channel();
    for i in 0..NUM_TASKS {
        let arc = Arc::clone(&arc);
        let tx = tx.clone();

        spawn(move || {
            let (ref barrier, ref events) = *arc;

            let event = &events[i];

            for _ in 0..NUM_ITERATIONS {

                event.store(true, Ordering::Release);

                barrier.wait();

                assert!(events.iter().all(|e| e.load(Ordering::Acquire)));

                barrier.wait();

                event.store(false, Ordering::Release);

                barrier.wait();

                assert!(events.iter().all(|e| !e.load(Ordering::Acquire)));

                barrier.wait();
            }

            tx.send(()).unwrap();
        });
    }
    drop(tx);

    for _ in 0..NUM_TASKS {
        rx.recv().unwrap();
    }
}

fn main() {
    checkpoint();
}


Cheryl's birthday

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

char *months[] = {
    "ERR", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

struct Date {
    int month, day;
    bool active;
} dates[] = {
    {5,15,true}, {5,16,true}, {5,19,true},
    {6,17,true}, {6,18,true},
    {7,14,true}, {7,16,true},
    {8,14,true}, {8,15,true}, {8,17,true}
};
#define UPPER_BOUND (sizeof(dates) / sizeof(struct Date))

void printRemaining() {
    int i, c;
    for (i = 0, c = 0; i < UPPER_BOUND; i++) {
        if (dates[i].active) {
            c++;
        }
    }
    printf("%d remaining.\n", c);
}

void printAnswer() {
    int i;
    for (i = 0; i < UPPER_BOUND; i++) {
        if (dates[i].active) {
            printf("%s, %d\n", months[dates[i].month], dates[i].day);
        }
    }
}

void firstPass() {

    int i, j, c;
    for (i = 0; i < UPPER_BOUND; i++) {
        c = 0;

        for (j = 0; j < UPPER_BOUND; j++) {
            if (dates[j].day == dates[i].day) {
                c++;
            }
        }

        if (c == 1) {
            for (j = 0; j < UPPER_BOUND; j++) {
                if (!dates[j].active) continue;
                if (dates[j].month == dates[i].month) {
                    dates[j].active = false;
                }
            }
        }
    }
}

void secondPass() {

    int i, j, c;
    for (i = 0; i < UPPER_BOUND; i++) {
        if (!dates[i].active) continue;
        c = 0;

        for (j = 0; j < UPPER_BOUND; j++) {
            if (!dates[j].active) continue;
            if (dates[j].day == dates[i].day) {
                c++;
            }
        }

        if (c > 1) {
            for (j = 0; j < UPPER_BOUND; j++) {
                if (!dates[j].active) continue;
                if (dates[j].day == dates[i].day) {
                    dates[j].active = false;
                }
            }
        }
    }
}

void thirdPass() {

    int i, j, c;
    for (i = 0; i < UPPER_BOUND; i++) {
        if (!dates[i].active) continue;
        c = 0;

        for (j = 0; j < UPPER_BOUND; j++) {
            if (!dates[j].active) continue;
            if (dates[j].month == dates[i].month) {
                c++;
            }
        }

        if (c > 1) {
            for (j = 0; j < UPPER_BOUND; j++) {
                if (!dates[j].active) continue;
                if (dates[j].month == dates[i].month) {
                    dates[j].active = false;
                }
            }
        }
    }
}

int main() {
    printRemaining();

    firstPass();

    printRemaining();

    secondPass();

    printRemaining();

    thirdPass();

    printAnswer();
    return 0;
}

#[derive(PartialEq, Debug, Copy, Clone)]
enum Month {
    May,
    June,
    July,
    August,
}

#[derive(PartialEq, Debug, Copy, Clone)]
struct Birthday {
    month: Month,
    day: u8,
}

impl Birthday {
    fn month_unique_in(&self, birthdays: &[Birthday]) -> bool {
        birthdays
            .iter()
            .filter(|birthday| birthday.month == self.month)
            .count()
            == 1
    }

    fn day_unique_in(&self, birthdays: &[Birthday]) -> bool {
        birthdays
            .iter()
            .filter(|birthday| birthday.day == self.day)
            .count()
            == 1
    }

    fn month_with_unique_day_in(&self, birthdays: &[Birthday]) -> bool {
        birthdays
            .iter()
            .any(|birthday| self.month == birthday.month && birthday.day_unique_in(birthdays))
    }
}

fn solution() -> Option<Birthday> {
    let mut choices: Vec<Birthday> = vec![
        Birthday {
            month: Month::May,
            day: 15,
        },
        Birthday {
            month: Month::May,
            day: 16,
        },
        Birthday {
            month: Month::May,
            day: 19,
        },
        Birthday {
            month: Month::June,
            day: 17,
        },
        Birthday {
            month: Month::June,
            day: 18,
        },
        Birthday {
            month: Month::July,
            day: 14,
        },
        Birthday {
            month: Month::July,
            day: 16,
        },
        Birthday {
            month: Month::August,
            day: 14,
        },
        Birthday {
            month: Month::August,
            day: 15,
        },
        Birthday {
            month: Month::August,
            day: 17,
        },
    ];

    let choices_copy = choices.clone();
    choices.retain(|birthday| !(&birthday.month_unique_in(&choices_copy)));

    let choices_copy = choices.clone();
    choices.retain(|birthday| !(birthday.month_with_unique_day_in(&choices_copy)));

    let choices_copy = choices.clone();
    choices.retain(|birthday| birthday.day_unique_in(&choices_copy));

    let choices_copy = choices.clone();
    choices.retain(|birthday| birthday.month_unique_in(&choices_copy));

    if choices.len() == 1 {
        Some(choices[0])
    } else {
        None
    }
}

fn main() {
    match solution() {
        Some(solution) => println!("Cheryl's birthday is {:?}", solution),
        None => panic!("Didn't work!"),
    }
}


Chinese remainder theorem

#include <stdio.h>

int mul_inv(int a, int b)
{
	int b0 = b, t, q;
	int x0 = 0, x1 = 1;
	if (b == 1) return 1;
	while (a > 1) {
		q = a / b;
		t = b, b = a % b, a = t;
		t = x0, x0 = x1 - q * x0, x1 = t;
	}
	if (x1 < 0) x1 += b0;
	return x1;
}

int chinese_remainder(int *n, int *a, int len)
{
	int p, i, prod = 1, sum = 0;

	for (i = 0; i < len; i++) prod *= n[i];

	for (i = 0; i < len; i++) {
		p = prod / n[i];
		sum += a[i] * mul_inv(p, n[i]) * p;
	}

	return sum % prod;
}

int main(void)
{
	int n[] = { 3, 5, 7 };
	int a[] = { 2, 3, 2 };

	printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
	return 0;
}

fn egcd(a: i64, b: i64) -> (i64, i64, i64) {
    if a == 0 {
        (b, 0, 1)
    } else {
        let (g, x, y) = egcd(b % a, a);
        (g, y - (b / a) * x, x)
    }
}

fn mod_inv(x: i64, n: i64) -> Option<i64> {
    let (g, x, _) = egcd(x, n);
    if g == 1 {
        Some((x % n + n) % n)
    } else {
        None
    }
}

fn chinese_remainder(residues: &[i64], modulii: &[i64]) -> Option<i64> {
    let prod = modulii.iter().product::<i64>();

    let mut sum = 0;

    for (&residue, &modulus) in residues.iter().zip(modulii) {
        let p = prod / modulus;
        sum += residue * mod_inv(p, modulus)? * p
    }

    Some(sum % prod)
}

fn main() {
    let modulii = [3,5,7];
    let residues = [2,3,2];

    match chinese_remainder(&residues, &modulii) {
        Some(sol) => println!("{}", sol),
        None      => println!("modulii not pairwise coprime")
    }

}


Chinese zodiac

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

const char* animals[] = { "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig" };
const char* elements[] = { "Wood","Fire","Earth","Metal","Water" };

const char* getElement(int year) {
    int element = (int)floor((year - 4) % 10 / 2);
    return elements[element];
}

const char* getAnimal(int year) {
    return animals[(year - 4) % 12];
}

const char* getYY(int year) {
    if (year % 2 == 0) {
        return "yang";
    } else {
        return "yin";
    }
}

int main() {
    int years[] = { 1935, 1938, 1968, 1972, 1976, 2017 };
    int i;

    for (i = 0; i < 6; ++i) {
        int year = years[i];
        printf("%d is the year of the %s %s (%s).\n", year, getElement(year), getAnimal(year), getYY(year));
    }

    return 0;
}

fn chinese_zodiac(year: usize) -> String {
    static ANIMALS: [&str; 12] = [
        "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
        "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig",
    ];
    static ASPECTS: [&str; 2] = ["Yang", "Yin"];
    static ELEMENTS: [&str; 5] = ["Wood", "Fire", "Earth", "Metal", "Water"];
    static STEMS: [char; 10] = [
        '甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸',
    ];
    static BRANCHES: [char; 12] = [
        '子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥',
    ];
    static S_NAMES: [&str; 10] = [
        "jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi",
    ];
    static B_NAMES: [&str; 12] = [
        "zĭ", "chŏu", "yín", "măo", "chén", "sì",
        "wŭ", "wèi", "shēn", "yŏu", "xū", "hài",
    ];

    let y = year - 4;
    let s = y % 10;
    let b = y % 12;

    let stem = STEMS[s];
    let branch = BRANCHES[b];
    let s_name = S_NAMES[s];
    let b_name = B_NAMES[b];
    let element = ELEMENTS[s / 2];
    let animal = ANIMALS[b];
    let aspect = ASPECTS[s % 2];
    let cycle = y % 60 + 1;

    format!(
        "{}    {}{}    {:9}  {:7}  {:7}  {:6}  {:02}/60",
        year,
        stem,
        branch,
        format!("{}-{}", s_name, b_name),
        element,
        animal,
        aspect,
        cycle
    )
}

fn main() {
    let years = [1935, 1938, 1968, 1972, 1976, 1984, 2017];
    println!("Year  Chinese  Pinyin     Element  Animal   Aspect  Cycle");
    println!("----  -------  ---------  -------  -------  ------  -----");
    for &year in &years {
        println!("{}", chinese_zodiac(year));
    }
}


Cholesky decomposition

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

double *cholesky(double *A, int n) {
    double *L = (double*)calloc(n * n, sizeof(double));
    if (L == NULL)
        exit(EXIT_FAILURE);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < (i+1); j++) {
            double s = 0;
            for (int k = 0; k < j; k++)
                s += L[i * n + k] * L[j * n + k];
            L[i * n + j] = (i == j) ?
                           sqrt(A[i * n + i] - s) :
                           (1.0 / L[j * n + j] * (A[i * n + j] - s));
        }

    return L;
}

void show_matrix(double *A, int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%2.5f ", A[i * n + j]);
        printf("\n");
    }
}

int main() {
    int n = 3;
    double m1[] = {25, 15, -5,
                   15, 18,  0,
                   -5,  0, 11};
    double *c1 = cholesky(m1, n);
    show_matrix(c1, n);
    printf("\n");
    free(c1);

    n = 4;
    double m2[] = {18, 22,  54,  42,
                   22, 70,  86,  62,
                   54, 86, 174, 134,
                   42, 62, 134, 106};
    double *c2 = cholesky(m2, n);
    show_matrix(c2, n);
    free(c2);

    return 0;
}

fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
    let mut res = vec![0.0; mat.len()];
    for i in 0..n {
        for j in 0..(i+1){
            let mut s = 0.0;
            for k in 0..j {
                s += res[i * n + k] * res[j * n + k];
            }
            res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
        }
    }
    res
}

fn show_matrix(matrix: Vec<f64>, n: usize){
    for i in 0..n {
        for j in 0..n {
            print!("{:.4}\t", matrix[i * n + j]);
        }
        println!("");
    }
    println!("");
}

fn main(){
    let dimension = 3 as usize;
    let m1 = vec![25.0, 15.0, -5.0,
                  15.0, 18.0,  0.0,
                  -5.0,  0.0, 11.0];
    let res1 = cholesky(m1, dimension);
    show_matrix(res1, dimension);

    let dimension = 4 as usize;
    let m2 = vec![18.0, 22.0,  54.0,  42.0,
                  22.0, 70.0,  86.0,  62.0,
                  54.0, 86.0, 174.0, 134.0,
                  42.0, 62.0, 134.0, 106.0];
    let res2 = cholesky(m2, dimension);
    show_matrix(res2, dimension);
}


Classes

#include <stdlib.h>

typedef struct sMyClass
{
  int variable;
} *MyClass;

MyClass  MyClass_new()
{
  MyClass pthis = malloc(sizeof *pthis);
  pthis->variable = 0;
  return pthis;
}

void MyClass_delete(MyClass* pthis)
{
  if (pthis)
  {
    free(*pthis);
    *pthis = NULL;
  }
}

void MyClass_someMethod(MyClass pthis)
{
  pthis->variable = 1;
}

MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);

struct MyClass {
    variable: i32,
}

impl MyClass {

    fn some_method(&mut self) {
        self.variable = 1;
    }

    fn new() -> MyClass {

        MyClass { variable: 0 }
    }
}

fn main () {

    let mut instance = MyClass::new();

    let mut p_instance = Box::new(MyClass::new());

    instance.some_method();
    p_instance.some_method();

}


Closures_Value capture

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>

typedef int (*f_int)();

#define TAG 0xdeadbeef
int _tmpl() {
	volatile int x = TAG;
	return x * x;
}

#define PROT (PROT_EXEC | PROT_WRITE)
#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS)
f_int dupf(int v)
{
	size_t len = (void*)dupf - (void*)_tmpl;
	f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);
	char *p;
	if(ret == MAP_FAILED) {
		perror("mmap");
		exit(-1);
	}
	memcpy(ret, _tmpl, len);
	for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)
		if (*(int *)p == TAG) *(int *)p = v;
	return ret;
}

int main()
{
	f_int funcs[10];
	int i;
	for (i = 0; i < 10; i++) funcs[i] = dupf(i);

	for (i = 0; i < 9; i++)
		printf("func[%d]: %d\n", i, funcs[i]());

	return 0;
}


Collections

#define cSize( a )  ( sizeof(a)/sizeof(a[0]) )
int ar[10];
ar[0] = 1;
ar[1] = 2;

int* p;
for (p=ar;
       p<(ar+cSize(ar));
       p++) {
  printf("%d\n",*p);
}


Combinations

#include <stdio.h>

typedef unsigned long marker;
marker one = 1;

void comb(int pool, int need, marker chosen, int at)
{
	if (pool < need + at) return;

	if (!need) {

		for (at = 0; at < pool; at++)
			if (chosen & (one << at)) printf("%d ", at);
		printf("\n");
		return;
	}

	comb(pool, need - 1, chosen | (one << at), at + 1);
	comb(pool, need, chosen, at + 1);
}

int main()
{
	comb(5, 3, 0, 0);
	return 0;
}

fn comb<T: std::fmt::Default>(arr: &[T], n: uint) {
  let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false);
  comb_intern(arr, n, incl_arr, 0);
}

fn comb_intern<T: std::fmt::Default>(arr: &[T], n: uint, incl_arr: &mut [bool], index: uint) {
  if (arr.len() < n + index) { return; }
  if (n == 0) {
    let mut it = arr.iter().zip(incl_arr.iter()).filter_map(|(val, incl)|
      if (*incl) { Some(val) } else { None }
    );
    for val in it { print!("{} ", *val); }
    print("\n");
    return;
  }

  incl_arr[index] = true;
  comb_intern(arr, n-1, incl_arr, index+1);
  incl_arr[index] = false;

  comb_intern(arr, n, incl_arr, index+1);
}

fn main() {
  let arr1 = ~[1, 2, 3, 4, 5];
  comb(arr1, 3);

  let arr2 = ~["A", "B", "C", "D", "E"];
  comb(arr2, 3);
}


Combinations with repetitions

#include <stdio.h>

const char *donuts[] = {"iced", "jam", "plain",
                        "something completely different"};
int pos[] = {0, 0, 0, 0};

void printDonuts(int k) {
  for (size_t i = 1; i < k + 1; i += 1)
    printf("%s\t", donuts[pos[i]]);
  printf("\n");
}

void combination_with_repetiton(int n, int k) {
  while (1) {
    for (int i = k; i > 0; i -= 1) {
      if (pos[i] > n - 1)
      {
        pos[i - 1] += 1;
        for (int j = i; j <= k; j += 1)
          pos[j] = pos[j - 1];
      }
    }
    if (pos[0] > 0)
      break;
    printDonuts(k);
    pos[k] += 1;
  }
}

int main() {
  combination_with_repetiton(3, 2);
  return 0;
}

struct CombinationsWithRepetitions<'a, T: 'a> {

    arr: &'a [T],

    k: u32,

    counts: Vec<u32>,

    remaining: bool,
}

impl<'a, T> CombinationsWithRepetitions<'a, T> {
    fn new(arr: &[T], k: u32) -> CombinationsWithRepetitions<T> {
        let mut counts = vec![0; arr.len()];
        counts[arr.len() - 1] = k;
        CombinationsWithRepetitions {
            arr,
            k,
            counts,
            remaining: true,
        }
    }
}

impl<'a, T> Iterator for CombinationsWithRepetitions<'a, T> {
    type Item = Vec<&'a T>;

    fn next(&mut self) -> Option<Vec<&'a T>> {
        if !self.remaining {
            return None;
        }
        let mut comb = Vec::new();
        for (count, item) in self.counts.iter().zip(self.arr.iter()) {
            for _ in 0..*count {
                comb.push(item);
            }
        }

        if self.counts[0] == self.k {
            self.remaining = false;
        } else {
            let n = self.counts.len();
            for i in (1..n).rev() {
                if self.counts[i] > 0 {
                    let original_value = self.counts[i];
                    self.counts[i - 1] += 1;
                    for j in i..(n - 1) {
                        self.counts[j] = 0;
                    }
                    self.counts[n - 1] = original_value - 1;
                    break;
                }
            }
        }
        Some(comb)
    }
}

fn main() {
    let collection = vec!["iced", "jam", "plain"];
    for comb in CombinationsWithRepetitions::new(&collection, 2) {
        for item in &comb {
            print!("{} ", item)
        }
        println!()
    }
}


Comma quibbling

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

char *quib(const char **strs, size_t size)
{

    size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0);
    size_t i;

    for (i = 0; i < size; i++)
        len += strlen(strs[i]);

    char *s = malloc(len * sizeof(*s));
    if (!s)
    {
        perror("Can't allocate memory!\n");
        exit(EXIT_FAILURE);
    }

    strcpy(s, "{");
    switch (size) {
        case 0:  break;
        case 1:  strcat(s, strs[0]);
                 break;
        default: for (i = 0; i < size - 1; i++)
                 {
                     strcat(s, strs[i]);
                     if (i < size - 2)
                         strcat(s, ", ");
                     else
                         strcat(s, " and ");
                 }
                 strcat(s, strs[i]);
                 break;
    }
    strcat(s, "}");
    return s;
}

int main(void)
{
    const char *test[] = {"ABC", "DEF", "G", "H"};
    char *s;

    for (size_t i = 0; i < 5; i++)
    {
        s = quib(test, i);
        printf("%s\n", s);
        free(s);
    }
    return EXIT_SUCCESS;
}


Command-line arguments

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

int main(int argc, char* argv[])
{
  int i;
  (void) printf("This program is named %s.\n", argv[0]);
  for (i = 1; i < argc; ++i)
    (void) printf("the argument #%d is %s\n", i, argv[i]);
  return EXIT_SUCCESS;
}

use std::env;

fn main(){
    let args: Vec<_> = env::args().collect();
    println!("{:?}", args);
}


Compare a list of strings

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

static bool
strings_are_equal(const char **strings, size_t nstrings)
{
    for (size_t i = 1; i < nstrings; i++)
        if (strcmp(strings[0], strings[i]) != 0)
            return false;
    return true;
}

static bool
strings_are_in_ascending_order(const char **strings, size_t nstrings)
{
    for (size_t i = 1; i < nstrings; i++)
        if (strcmp(strings[i - 1], strings[i]) >= 0)
            return false;
    return true;
}

fn strings_are_equal(seq: &[&str]) -> bool {
    match seq {
        &[] | &[_] => true,
        &[x, y, ref tail @ ..] if x == y => strings_are_equal(&[&[y], tail].concat()),
        _ => false
    }
}

fn asc_strings(seq: &[&str]) -> bool {
    match seq {
        &[] | &[_] => true,
        &[x, y, ref tail @ ..] if x < y => asc_strings(&[&[y], tail].concat()),
        _ => false
    }
}


Compare length of two strings

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

int cmp(const int* a, const int* b)
{
    return *b - *a;
}

void compareAndReportStringsLength(const char* strings[], const int n)
{
    if (n > 0)
    {
        char* has_length = "has length";
        char* predicate_max = "and is the longest string";
        char* predicate_min = "and is the shortest string";
        char* predicate_ave = "and is neither the longest nor the shortest string";

        int* si = malloc(2 * n * sizeof(int));
        if (si != NULL)
        {
            for (int i = 0; i < n; i++)
            {
                si[2 * i] = strlen(strings[i]);
                si[2 * i + 1] = i;
            }
            qsort(si, n, 2 * sizeof(int), cmp);

            int max = si[0];
            int min = si[2 * (n - 1)];

            for (int i = 0; i < n; i++)
            {
                int length = si[2 * i];
                char* string = strings[si[2 * i + 1]];
                char* predicate;
                if (length == max)
                    predicate = predicate_max;
                else if (length == min)
                    predicate = predicate_min;
                else
                    predicate = predicate_ave;
                printf("\"%s\" %s %d %s\n",
                    string, has_length, length, predicate);
            }

            free(si);
        }
        else
        {
            fputs("unable allocate memory buffer", stderr);
        }
    }
}

int main(int argc, char* argv[])
{
    char* list[] = { "abcd", "123456789", "abcdef", "1234567" };

    compareAndReportStringsLength(list, 4);

    return EXIT_SUCCESS;
}

fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {
    let strings = [string1.to_string(), string2.to_string()];
    let difference = strings[0].len() as i32 - strings[1].len() as i32;
    if difference == 0 {
        format!("\"{}\" and \"{}\" are of equal length, {}", strings[0], strings[1], strings[0].len())
    } else if difference > 1 {
        format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[0], strings[0].len(), strings[1], strings[1].len())
    } else {
        format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[1], strings[1].len(), strings[0], strings[0].len())
    }
}

fn main() {
    println!("{}", compare_and_report("a", "b"));
    println!("\n{}", compare_and_report("cd", "e"));
    println!("\n{}", compare_and_report("f", "gh"));
}


Compile-time calculation

#include <stdio.h>
#include <order/interpreter.h>

#define ORDER_PP_DEF_8fac ORDER_PP_FN( \
8fn(8X, 8seq_fold(8times, 1, 8seq_iota(1, 8inc(8X)))) )

int main(void) {
	printf("10! = %d\n", ORDER_PP( 8to_lit( 8fac(10) ) ) );
	return 0;
}

fn factorial(n: i64) -> i64 {
    let mut total = 1;
    for i in 1..n+1 {
        total *= i;
    }
    return total;
}

fn main() {
    println!("Factorial of 10 is {}.", factorial(10));
}


Compound data type

typedef struct Point
{
  int x;
  int y;
} Point;

struct Point<T> {
    x: T,
    y: T,
}
fn main() {
    let p = Point { x: 1.0, y: 2.5 };
    println!("{}, {}", p.x, p.y);
}


Concurrent computing

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t condm = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int bang = 0;

#define WAITBANG() do { \
   pthread_mutex_lock(&condm); \
   while( bang == 0 ) \
   { \
      pthread_cond_wait(&cond, &condm); \
   } \
   pthread_mutex_unlock(&condm); } while(0);\

void *t_enjoy(void *p)
{
  WAITBANG();
  printf("Enjoy\n");
  pthread_exit(0);
}

void *t_rosetta(void *p)
{
  WAITBANG();
  printf("Rosetta\n");
  pthread_exit(0);
}

void *t_code(void *p)
{
  WAITBANG();
  printf("Code\n");
  pthread_exit(0);
}

typedef void *(*threadfunc)(void *);
int main()
{
   int i;
   pthread_t a[3];
   threadfunc p[3] = {t_enjoy, t_rosetta, t_code};

   for(i=0;i<3;i++)
   {
     pthread_create(&a[i], NULL, p[i], NULL);
   }
   sleep(1);
   bang = 1;
   pthread_cond_broadcast(&cond);
   for(i=0;i<3;i++)
   {
     pthread_join(a[i], NULL);
   }
}

extern crate rand;
use std::thread;
use rand::thread_rng;
use rand::distributions::{Range, IndependentSample};

fn main() {
    let mut rng = thread_rng();
    let rng_range = Range::new(0u32, 100);
    for word in "Enjoy Rosetta Code".split_whitespace() {
        let snooze_time = rng_range.ind_sample(&mut rng);
        let local_word = word.to_owned();
        std::thread::spawn(move || {
            thread::sleep_ms(snooze_time);
            println!("{}", local_word);
        });
    }
    thread::sleep_ms(1000);
}


Conditional structures

int a = 3;

if (a == 2) {
    puts ("a is 2");
} else if (a == 3) {
    puts ("a is 3");
} else {
    puts("a is 4");
}

unless (a == 2) {
    puts ("a is 2");
} else if (a == 3) {
    puts ("a is 3");
} else {
    puts("a is 4");
}

switch (a) {
    case 2:
        puts ("a is 2");
        break;
    case 3:
        puts ("a is 3");
        break;
    case 4:
        puts ("a is 4");
        break;
    default:
        puts("is neither");
}

#[cfg(target_os = "linux")]
fn running_linux() {
    println!("This is linux");
}
#[cfg(not(target_os = "linux"))]
fn running_linux() {
    println!("This is not linux");
}

#[cfg_attr(target_os = "linux", target_env = "gnu")]

#[cfg(all(
        any(target_arch = "arm", target_endian = "little"),
        not(target_pointer_width = "32"),
        unix,
        test
        ))]
fn highly_specific_function() {}


Constrained random points on a circle

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

inline
int randn(int m)
{
	int rand_max = RAND_MAX - (RAND_MAX % m);
	int r;
	while ((r = rand()) > rand_max);
	return r / (rand_max / m);
}

int main()
{
	int i, x, y, r2;
	unsigned long buf[31] = {0};

	for (i = 0; i < 100; ) {
		x = randn(31) - 15;
		y = randn(31) - 15;
		r2 = x * x + y * y;
		if (r2 >= 100 && r2 <= 225) {
			buf[15 + y] |= 1 << (x + 15);
			i++;
		}
	}

	for (y = 0; y < 31; y++) {
		for (x = 0; x < 31; x++)
			printf((buf[y] & 1 << x) ? ". " : "  ");
		printf("\n");
	}

	return 0;
}

extern crate rand;

use rand::Rng;

const POINTS_N: usize = 100;

fn generate_point<R: Rng>(rng: &mut R) -> (i32, i32) {
    loop {
        let x = rng.gen_range(-15, 16);
        let y = rng.gen_range(-15, 16);

        let r2 = x * x + y * y;
        if r2 >= 100 && r2 <= 225 {
            return (x, y);
        }
    }
}

fn filtering_method<R: Rng>(rng: &mut R) {
    let mut rows = [[" "; 62]; 31];

    for _ in 0..POINTS_N {
        let (x, y) = generate_point(rng);
        rows[(y + 15) as usize][(x + 15) as usize * 2] = "*";
    }

    for row in &rows {
        println!("{}", row.concat());
    }
}

fn precalculating_method<R: Rng>(rng: &mut R) {

    let mut possible_points = Vec::with_capacity(404);
    for y in -15..=15 {
        for x in -15..=15 {
            let r2 = x * x + y * y;
            if r2 >= 100 && r2 <= 225 {
                possible_points.push((x, y));
            }
        }
    }

    let len = possible_points.len();
    for i in (len - POINTS_N..len).rev() {
        let j = rng.gen_range(0, i + 1);
        possible_points.swap(i, j);
    }

    let mut rows = [[" "; 62]; 31];
    for &(x, y) in &possible_points[len - POINTS_N..] {
        rows[(y + 15) as usize][(x + 15) as usize * 2] = "*";
    }

    for row in &rows {
        println!("{}", row.concat());
    }
}

fn main() {
    let mut rng = rand::weak_rng();

    filtering_method(&mut rng);

    precalculating_method(&mut rng);
}


Continued fraction

#include <stdio.h>

typedef double (*coeff_func)(unsigned n);

double calc(coeff_func f_a, coeff_func f_b, unsigned expansions)
{
	double a, b, r;
	a = b = r = 0.0;

	unsigned i;
	for (i = expansions; i > 0; i--) {
		a = f_a(i);
		b = f_b(i);
		r = b / (a + r);
	}
	a = f_a(0);

	return a + r;
}

double sqrt2_a(unsigned n)
{
	return n ? 2.0 : 1.0;
}

double sqrt2_b(unsigned n)
{
	return 1.0;
}

double napier_a(unsigned n)
{
	return n ? n : 2.0;
}

double napier_b(unsigned n)
{
	return n > 1.0 ? n - 1.0 : 1.0;
}

double pi_a(unsigned n)
{
	return n ? 6.0 : 3.0;
}

double pi_b(unsigned n)
{
	double c = 2.0 * n - 1.0;

	return c * c;
}

int main(void)
{
	double sqrt2, napier, pi;

	sqrt2  = calc(sqrt2_a,  sqrt2_b,  1000);
	napier = calc(napier_a, napier_b, 1000);
	pi     = calc(pi_a,     pi_b,     1000);

	printf("%12.10g\n%12.10g\n%12.10g\n", sqrt2, napier, pi);

	return 0;
}

use std::iter;

macro_rules! continued_fraction {
    ($a:expr, $b:expr ; $iterations:expr) => (
        ($a).zip($b)
            .take($iterations)
            .collect::<Vec<_>>().iter()
            .rev()
            .fold(0 as f64, |acc: f64, &(x, y)| {
                x as f64 + (y as f64 / acc)
            })
    );

    ($a:expr, $b:expr) => (continued_fraction!($a, $b ; 1000));
}

fn main() {

    let sqrt2a = (1..2).chain(iter::repeat(2));
    let sqrt2b = iter::repeat(1);
    println!("{}", continued_fraction!(sqrt2a, sqrt2b));

    let napiera = (2..3).chain(1..);
    let napierb = (1..2).chain(1..);
    println!("{}", continued_fraction!(napiera, napierb));

    let pia = (3..4).chain(iter::repeat(6));
    let pib = (1i64..).map(|x| (2 * x - 1).pow(2));
    println!("{}", continued_fraction!(pia, pib));
}


Continued fraction_Arithmetic_Construct from rational number

#include<stdio.h>

typedef struct{
	int num,den;
	}fraction;

fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}};
fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}};
fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};

int r2cf(int *numerator,int *denominator)
{
	int quotient=0,temp;

	if(denominator != 0)
	{
		quotient = *numerator / *denominator;

		temp = *numerator;

		*numerator = *denominator;

		*denominator = temp % *denominator;
	}

	return quotient;
}

int main()
{
	int i;

	printf("Running the examples :");

	for(i=0;i<sizeof(examples)/sizeof(fraction);i++)
	{
		printf("\nFor N = %d, D = %d :",examples[i].num,examples[i].den);

		while(examples[i].den != 0){
			printf(" %d ",r2cf(&examples[i].num,&examples[i].den));
			}
	}

	printf("\n\nRunning for %c2 :",251);

	for(i=0;i<sizeof(sqrt2)/sizeof(fraction);i++)
	{
		printf("\nFor N = %d, D = %d :",sqrt2[i].num,sqrt2[i].den);

		while(sqrt2[i].den != 0){
			printf(" %d ",r2cf(&sqrt2[i].num,&sqrt2[i].den));
			}
	}

	printf("\n\nRunning for %c :",227);

	for(i=0;i<sizeof(pi)/sizeof(fraction);i++)
	{
		printf("\nFor N = %d, D = %d :",pi[i].num,pi[i].den);

		while(pi[i].den != 0){
			printf(" %d ",r2cf(&pi[i].num,&pi[i].den));
			}
	}

	return 0;
}


Convert seconds to compound duration

#define _CRT_SECURE_NO_WARNINGS

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

char* seconds2string(unsigned long seconds)
{
    int i;

    const unsigned long s =  1;
    const unsigned long m = 60 * s;
    const unsigned long h = 60 * m;
    const unsigned long d = 24 * h;
    const unsigned long w =  7 * d;

    const unsigned long coeff[5] = { w, d, h, m, s };
    const char units[5][4] = { "wk", "d", "hr", "min", "sec" };

    static char buffer[256];
    char* ptr = buffer;

    for ( i = 0; i < 5; i++ )
    {
        unsigned long value;
        value   = seconds / coeff[i];
        seconds = seconds % coeff[i];
        if ( value )
        {
            if ( ptr != buffer )
                ptr += sprintf(ptr, ", ");
            ptr += sprintf(ptr,"%lu %s",value,units[i]);
        }
    }

    return buffer;
}

int main(int argc, char argv[])
{
    unsigned long seconds;

    if ( (argc <  2) && scanf( "%lu", &seconds )
    ||   (argc >= 2) && sscanf( argv[1], "%lu", & seconds ) )
    {
        printf( "%s\n", seconds2string(seconds) );
        return EXIT_SUCCESS;
    }

    return EXIT_FAILURE;
}

use std::fmt;

struct CompoundTime {
    w: usize,
    d: usize,
    h: usize,
    m: usize,
    s: usize,
}

macro_rules! reduce {
    ($s: ident, $(($from: ident, $to: ident, $factor: expr)),+) => {{
        $(
            $s.$to += $s.$from / $factor;
            $s.$from %= $factor;
        )+
    }}
}

impl CompoundTime {
    #[inline]
    fn new(w: usize, d: usize, h: usize, m: usize, s: usize) -> Self{
        CompoundTime { w: w, d: d, h: h, m: m, s: s, }
    }

    #[inline]
    fn balance(&mut self) {
        reduce!(self, (s, m, 60), (m, h, 60),
                      (h, d, 24), (d, w, 7));
    }
}

impl fmt::Display for CompoundTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}w {}d {}h {}m {}s",
               self.w, self.d, self.h, self.m, self.s)
    }
}

fn main() {
    let mut ct = CompoundTime::new(0,3,182,345,2412);
    println!("Before: {}", ct);
    ct.balance();
    println!("After: {}", ct);
}


Convex hull

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

typedef struct tPoint {
    int x, y;
} Point;

bool ccw(const Point *a, const Point *b, const Point *c) {
    return (b->x - a->x) * (c->y - a->y)
         > (b->y - a->y) * (c->x - a->x);
}

int comparePoints(const void *lhs, const void *rhs) {
    const Point* lp = lhs;
    const Point* rp = rhs;
    if (lp->x < rp->x)
        return -1;
    if (rp->x < lp->x)
        return 1;
    if (lp->y < rp->y)
        return -1;
    if (rp->y < lp->y)
        return 1;
    return 0;
}

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

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

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

void printPoints(const Point* points, int len) {
    printf("[");
    if (len > 0) {
        const Point* ptr = points;
        const Point* end = points + len;
        printf("(%d, %d)", ptr->x, ptr->y);
        ++ptr;
        for (; ptr < end; ++ptr)
            printf(", (%d, %d)", ptr->x, ptr->y);
    }
    printf("]");
}

Point* convexHull(Point p[], int len, int* hsize) {
    if (len == 0) {
        *hsize = 0;
        return NULL;
    }

    int i, size = 0, capacity = 4;
    Point* hull = xmalloc(capacity * sizeof(Point));

    qsort(p, len, sizeof(Point), comparePoints);

    for (i = 0; i < len; ++i) {
        while (size >= 2 && !ccw(&hull[size - 2], &hull[size - 1], &p[i]))
            --size;
        if (size == capacity) {
            capacity *= 2;
            hull = xrealloc(hull, capacity * sizeof(Point));
        }
        assert(size >= 0 && size < capacity);
        hull[size++] = p[i];
    }

    int t = size + 1;
    for (i = len - 1; i >= 0; i--) {
        while (size >= t && !ccw(&hull[size - 2], &hull[size - 1], &p[i]))
            --size;
        if (size == capacity) {
            capacity *= 2;
            hull = xrealloc(hull, capacity * sizeof(Point));
        }
        assert(size >= 0 && size < capacity);
        hull[size++] = p[i];
    }
    --size;
    assert(size >= 0);
    hull = xrealloc(hull, size * sizeof(Point));
    *hsize = size;
    return hull;
}

int main() {
    Point points[] = {
        {16,  3}, {12, 17}, { 0,  6}, {-4, -6}, {16,  6},
        {16, -7}, {16, -3}, {17, -4}, { 5, 19}, {19, -8},
        { 3, 16}, {12, 13}, { 3, -4}, {17,  5}, {-3, 15},
        {-3, -9}, { 0, 11}, {-9, -3}, {-4, -2}, {12, 10}
    };
    int hsize;
    Point* hull = convexHull(points, sizeof(points)/sizeof(Point), &hsize);
    printf("Convex Hull: ");
    printPoints(hull, hsize);
    printf("\n");
    free(hull);

    return 0;
}

#[derive(Debug, Clone)]
struct Point {
    x: f32,
    y: f32
}

fn calculate_convex_hull(points: &Vec<Point>) -> Vec<Point> {

    if points.len() < 3 { return points.clone(); }

    let mut hull = vec![];

    let (left_most_idx, _) = points.iter()
        .enumerate()
        .min_by(|lhs, rhs| lhs.1.x.partial_cmp(&rhs.1.x).unwrap())
        .expect("No left most point");

    let mut p = left_most_idx;
    let mut q = 0_usize;

    loop {

        hull.push(points[p].clone());

        q = (p + 1) % points.len();

        for i in 0..points.len() {
            if orientation(&points[p], &points[i], &points[q]) == 2 {
                q = i;
            }
        }

        p = q;

        if p == left_most_idx { break; }
    }

    return hull;
}

fn orientation(p: &Point, q: &Point, r: &Point) -> usize {
    let val = (q.y - p.y) * (r.x - q.x) -
        (q.x - p.x) * (r.y - q.y);

    if val == 0. { return 0 };
    if val > 0. { return 1; } else { return 2; }
}

fn main(){
    let points = vec![pt(16,3), pt(12,17), pt(0,6), pt(-4,-6), pt(16,6), pt(16,-7), pt(16,-3), pt(17,-4), pt(5,19), pt(19,-8), pt(3,16), pt(12,13), pt(3,-4), pt(17,5), pt(-3,15), pt(-3,-9), pt(0,11), pt(-9,-3), pt(-4,-2), pt(12,10)];
    let hull = calculate_convex_hull(&points);

    hull.iter()
        .for_each(|pt| println!("{:?}", pt));
}

fn pt(x: i32, y: i32) -> Point {
    return Point {x:x as f32, y:y as f32};
}


Conway's Game of Life

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

#define for_x for (int x = 0; x < w; x++)
#define for_y for (int y = 0; y < h; y++)
#define for_xy for_x for_y
void show(void *u, int w, int h)
{
	int (*univ)[w] = u;
	printf("\033[H");
	for_y {
		for_x printf(univ[y][x] ? "\033[07m  \033[m" : "  ");
		printf("\033[E");
	}
	fflush(stdout);
}

void evolve(void *u, int w, int h)
{
	unsigned (*univ)[w] = u;
	unsigned new[h][w];

	for_y for_x {
		int n = 0;
		for (int y1 = y - 1; y1 <= y + 1; y1++)
			for (int x1 = x - 1; x1 <= x + 1; x1++)
				if (univ[(y1 + h) % h][(x1 + w) % w])
					n++;

		if (univ[y][x]) n--;
		new[y][x] = (n == 3 || (n == 2 && univ[y][x]));
	}
	for_y for_x univ[y][x] = new[y][x];
}

void game(int w, int h)
{
	unsigned univ[h][w];
	for_xy univ[y][x] = rand() < RAND_MAX / 10 ? 1 : 0;
	while (1) {
		show(univ, w, h);
		evolve(univ, w, h);
		usleep(200000);
	}
}

int main(int c, char **v)
{
	int w = 0, h = 0;
	if (c > 1) w = atoi(v[1]);
	if (c > 2) h = atoi(v[2]);
	if (w <= 0) w = 30;
	if (h <= 0) h = 30;
	game(w, h);
}

use std::collections::HashMap;
use std::collections::HashSet;

type Cell = (i32, i32);
type Colony = HashSet<Cell>;

fn print_colony(col: &Colony, width: i32, height: i32) {
    for y in 0..height {
        for x in 0..width {
            print!("{} ",
                if col.contains(&(x, y)) {"O"}
                else {"."}
            );
        }
        println!();
    }
}

fn neighbours(&(x,y): &Cell) -> Vec<Cell> {
    vec![
        (x-1,y-1), (x,y-1), (x+1,y-1),
        (x-1,y),            (x+1,y),
        (x-1,y+1), (x,y+1), (x+1,y+1),
    ]
}

fn neighbour_counts(col: &Colony) -> HashMap<Cell, i32> {
    let mut ncnts = HashMap::new();
    for cell in col.iter().flat_map(neighbours) {
        *ncnts.entry(cell).or_insert(0) += 1;
    }
    ncnts
}

fn generation(col: Colony) -> Colony {
    neighbour_counts(&col)
        .into_iter()
        .filter_map(|(cell, cnt)|
            match (cnt, col.contains(&cell)) {
                (2, true) |
                (3, ..) => Some(cell),
                _ => None
        })
        .collect()
}

fn life(init: Vec<Cell>, iters: i32, width: i32, height: i32) {
    let mut col: Colony = init.into_iter().collect();
    for i in 0..iters+1
    {
        println!("({})", &i);
        if i != 0 {
            col = generation(col);
        }
        print_colony(&col, width, height);
    }
}

fn main() {
    let blinker = vec![
        (1,0),
        (1,1),
        (1,2)];

    life(blinker, 3, 3, 3);

    let glider = vec![
                (1,0),
                        (2,1),
        (0,2),  (1,2),  (2,2)];

    life(glider, 20, 8, 8);
}


Copy stdin to stdout

#include <stdio.h>

int main(){
  char c;
  while ( (c=getchar()) != EOF ){
    putchar(c);
  }
  return 0;
}

use std::io;

fn main() {
    io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());
}


Count in factors

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

typedef unsigned long long ULONG;

ULONG get_prime(int idx)
{
        static long n_primes = 0, alloc = 0;
        static ULONG *primes = 0;
        ULONG last, p;
        int i;

        if (idx >= n_primes) {
                if (n_primes >= alloc) {
                        alloc += 16;
                        primes = realloc(primes, sizeof(ULONG) * alloc);
                }
                if (!n_primes) {
                        primes[0] = 2;
                        primes[1] = 3;
                        n_primes = 2;
                }

                last = primes[n_primes-1];
                while (idx >= n_primes) {
                        last += 2;
                        for (i = 0; i < n_primes; i++) {
                                p = primes[i];
                                if (p * p > last) {
                                        primes[n_primes++] = last;
                                        break;
                                }
                                if (last % p == 0) break;
                        }
                }
        }
        return primes[idx];
}

int main()
{
        ULONG n, x, p;
        int i, first;

        for (x = 1; ; x++) {
                printf("%lld = ", n = x);

                for (i = 0, first = 1; ; i++) {
                        p = get_prime(i);
                        while (n % p == 0) {
                                n /= p;
                                if (!first) printf(" x ");
                                first = 0;
                                printf("%lld", p);
                        }
                        if (n <= p * p) break;
                }

                if (first)      printf("%lld\n", n);
                else if (n > 1) printf(" x %lld\n", n);
                else            printf("\n");
        }
        return 0;
}

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let n = if args.len() > 1 {
        args[1].parse().expect("Not a valid number to count to")
    }
    else {
        20
    };
    count_in_factors_to(n);
}

fn count_in_factors_to(n: u64) {
    println!("1");
    let mut primes = vec![];
    for i in 2..=n {
        let fs = factors(&primes, i);
        if fs.len() <= 1 {
            primes.push(i);
            println!("{}", i);
        }
        else {
            println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x "));
        }
    }
}

fn factors(primes: &[u64], mut n: u64) -> Vec<u64> {
    let mut result = Vec::new();
    for p in primes {
        while n % p == 0 {
            result.push(*p);
            n /= p;
        }
        if n == 1 {
            return result;
        }
    }
    vec![n]
}


Count in octal

#include <stdio.h>

int main()
{
        unsigned int i = 0;
        do { printf("%o\n", i++); } while(i);
        return 0;
}

fn main() {
    for i in 0..std::usize::MAX {
        println!("{:o}", i);
    }
}


Count the coins

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

typedef struct { uint64_t x[2]; } i128;

void show(i128 v) {
	uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32};
	int i, j = 0, len = 4;
	char buf[100];
	do {
		uint64_t c = 0;
		for (i = len; i--; ) {
			c = (c << 32) + x[i];
			x[i] = c / 10, c %= 10;
		}

		buf[j++] = c + '0';
		for (len = 4; !x[len - 1]; len--);
	} while (len);

	while (j--) putchar(buf[j]);
	putchar('\n');
}

i128 count(int sum, int *coins)
{
	int n, i, k;
	for (n = 0; coins[n]; n++);

	i128 **v = malloc(sizeof(int*) * n);
	int *idx = malloc(sizeof(int) * n);

	for (i = 0; i < n; i++) {
		idx[i] = coins[i];

		v[i] = calloc(sizeof(i128), coins[i]);
	}

	v[0][coins[0] - 1] = (i128) {{1, 0}};

	for (k = 0; k <= sum; k++) {
		for (i = 0; i < n; i++)
			if (!idx[i]--) idx[i] = coins[i] - 1;

		i128 c = v[0][ idx[0] ];

		for (i = 1; i < n; i++) {
			i128 *p = v[i] + idx[i];

			p->x[0] += c.x[0];
			p->x[1] += c.x[1];
			if (p->x[0] < c.x[0])
				p->x[1] ++;
			c = *p;
		}
	}

	i128 r = v[n - 1][idx[n-1]];

	for (i = 0; i < n; i++) free(v[i]);
	free(v);
	free(idx);

	return r;
}

int count2(int sum, int *coins)
{
	if (!*coins || sum < 0) return 0;
	if (!sum) return 1;
	return count2(sum - *coins, coins) + count2(sum, coins + 1);
}

int main(void)
{
	int us_coins[] = { 100, 50, 25, 10, 5, 1, 0 };
	int eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 };

	show(count(   100, us_coins + 2));
	show(count(  1000, us_coins));

	show(count(  1000 * 100, us_coins));
	show(count( 10000 * 100, us_coins));
	show(count(100000 * 100, us_coins));

	putchar('\n');

	show(count(     1 * 100, eu_coins));
	show(count(  1000 * 100, eu_coins));
	show(count( 10000 * 100, eu_coins));
	show(count(100000 * 100, eu_coins));

	return 0;
}

fn make_change(coins: &[usize], cents: usize) -> usize {
    let size = cents + 1;
    let mut ways = vec![0; size];
    ways[0] = 1;
    for &coin in coins {
        for amount in coin..size {
            ways[amount] += ways[amount - coin];
        }
    }
    ways[cents]
}

fn main() {
    println!("{}", make_change(&[1,5,10,25], 100));
    println!("{}", make_change(&[1,5,10,25,50,100], 100_000));
}


Cramer's rule

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

typedef struct {
    int n;
    double **elems;
} SquareMatrix;

SquareMatrix init_square_matrix(int n, double elems[n][n]) {
    SquareMatrix A = {
        .n = n,
        .elems = malloc(n * sizeof(double *))
    };
    for(int i = 0; i < n; ++i) {
        A.elems[i] = malloc(n * sizeof(double));
        for(int j = 0; j < n; ++j)
            A.elems[i][j] = elems[i][j];
    }

    return A;
}

SquareMatrix copy_square_matrix(SquareMatrix src) {
    SquareMatrix dest;
    dest.n = src.n;
    dest.elems = malloc(dest.n * sizeof(double *));
    for(int i = 0; i < dest.n; ++i) {
        dest.elems[i] = malloc(dest.n * sizeof(double));
        for(int j = 0; j < dest.n; ++j)
            dest.elems[i][j] = src.elems[i][j];
    }

    return dest;
}

double det(SquareMatrix A) {
    double det = 1;

    for(int j = 0; j < A.n; ++j) {
        int i_max = j;
        for(int i = j; i < A.n; ++i)
            if(A.elems[i][j] > A.elems[i_max][j])
                i_max = i;

        if(i_max != j) {
            for(int k = 0; k < A.n; ++k) {
                double tmp = A.elems[i_max][k];
                A.elems[i_max][k] = A.elems[j][k];
                A.elems[j][k]     = tmp;
            }

            det *= -1;
        }

        if(abs(A.elems[j][j]) < 1e-12) {
            puts("Singular matrix!");
            return NAN;
        }

        for(int i = j + 1; i < A.n; ++i) {
            double mult = -A.elems[i][j] / A.elems[j][j];
            for(int k = 0; k < A.n; ++k)
                A.elems[i][k] += mult * A.elems[j][k];
        }
    }

    for(int i = 0; i < A.n; ++i)
        det *= A.elems[i][i];

    return det;
}

void deinit_square_matrix(SquareMatrix A) {
    for(int i = 0; i < A.n; ++i)
        free(A.elems[i]);
    free(A.elems);
}

double cramer_solve(SquareMatrix A, double det_A, double *b, int var) {
    SquareMatrix tmp = copy_square_matrix(A);
    for(int i = 0; i < tmp.n; ++i)
        tmp.elems[i][var] = b[i];

    double det_tmp = det(tmp);
    deinit_square_matrix(tmp);

    return det_tmp / det_A;
}

int main(int argc, char **argv) {
#define N 4
    double elems[N][N] = {
        { 2, -1,  5,  1},
        { 3,  2,  2, -6},
        { 1,  3,  3, -1},
        { 5, -2, -3,  3}
    };
    SquareMatrix A = init_square_matrix(N, elems);

    SquareMatrix tmp = copy_square_matrix(A);
    int det_A = det(tmp);
    deinit_square_matrix(tmp);

    double b[] = {-3, -32, -47, 49};

    for(int i = 0; i < N; ++i)
        printf("%7.3lf\n", cramer_solve(A, det_A, b, i));

    deinit_square_matrix(A);
    return EXIT_SUCCESS;
}

use std::ops::{Index, IndexMut};

fn main() {
    let m = matrix(
        vec![
            2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3.,
        ],
        4,
    );
    let mm = m.solve(&vec![-3., -32., -47., 49.]);
    println!("{:?}", mm);
}

#[derive(Clone)]
struct Matrix {
    elts: Vec<f64>,
    dim: usize,
}

impl Matrix {

    fn det(&self) -> f64 {
        match self.dim {
            0 => 0.,
            1 => self[0][0],
            2 => self[0][0] * self[1][1] - self[0][1] * self[1][0],
            d => {
                let mut acc = 0.;
                let mut signature = 1.;
                for k in 0..d {
                    acc += signature * self[0][k] * self.comatrix(0, k).det();
                    signature *= -1.
                }
                acc
            }
        }
    }

    fn solve(&self, target: &Vec<f64>) -> Vec<f64> {
        let mut solution: Vec<f64> = vec![0.; self.dim];
        let denominator = self.det();
        for j in 0..self.dim {
            let mut mm = self.clone();
            for i in 0..self.dim {
                mm[i][j] = target[i]
            }
            solution[j] = mm.det() / denominator
        }
        solution
    }

    fn comatrix(&self, k: usize, l: usize) -> Matrix {
        let mut v: Vec<f64> = vec![];
        for i in 0..self.dim {
            for j in 0..self.dim {
                if i != k && j != l {
                    v.push(self[i][j])
                }
            }
        }
        matrix(v, self.dim - 1)
    }
}

fn matrix(elts: Vec<f64>, dim: usize) -> Matrix {
    assert_eq!(elts.len(), dim * dim);
    Matrix { elts, dim }
}

impl Index<usize> for Matrix {
    type Output = [f64];

    fn index(&self, i: usize) -> &Self::Output {
        let m = self.dim;
        &self.elts[m * i..m * (i + 1)]
    }
}

impl IndexMut<usize> for Matrix {
    fn index_mut(&mut self, i: usize) -> &mut Self::Output {
        let m = self.dim;
        &mut self.elts[m * i..m * (i + 1)]
    }
}


Create a file

#include <stdio.h>

int main() {
  FILE *fh = fopen("output.txt", "w");
  fclose(fh);

  return 0;
}

use std::io::{self, Write};
use std::fs::{DirBuilder, File};
use std::path::Path;
use std::{process,fmt};

const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";

fn main() {
    create(".").and(create("/"))
               .unwrap_or_else(|e| error_handler(e,1));
}

fn create<P>(root: P) -> io::Result<File>
    where P: AsRef<Path>
{
    let f_path = root.as_ref().join(FILE_NAME);
    let d_path = root.as_ref().join(DIR_NAME);
    DirBuilder::new().create(d_path).and(File::create(f_path))
}

fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "Error: {}", error);
    process::exit(code)
}


Create a two-dimensional array at runtime

#include <stdio.h>

int main(int argc, char **argv) {

   int user1 = 0, user2 = 0;
   printf("Enter two integers.  Space delimited, please:  ");
   scanf("%d %d",&user1, &user2);
   int array[user1][user2];
   array[user1/2][user2/2] = user1 + user2;
   printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);

   return 0;
}

use std::env;

fn main() {
    let mut args = env::args().skip(1).flat_map(|num| num.parse());
    let rows = args.next().expect("Expected number of rows as first argument");
    let cols = args.next().expect("Expected number of columns as second argument");

    assert_ne!(rows, 0, "rows were zero");
    assert_ne!(cols, 0, "cols were zero");

    let mut v = vec![vec![0; cols]; rows];
    v[0][0] = 1;
    println!("{}", v[0][0]);
}


Create an HTML table

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

int main()
{
	int i;
	printf("
	"
		"X	Y	Z	");
	for (i = 0; i < 4; i++) {
		printf("
%d	%d	%d	%d
", i,
			rand() % 10000, rand() % 10000, rand() % 10000);
	}
	printf("
");

	return 0;
}

extern crate rand;

use rand::Rng;

fn random_cell<R: Rng>(rng: &mut R) -> u32 {

    rng.gen_range(0, 10_000)
}

fn main() {
    let mut rng = rand::thread_rng();

    println!("

	X	Y	Z

");

    for row in 0..3 {
        let x = random_cell(&mut rng);
        let y = random_cell(&mut rng);
        let z = random_cell(&mut rng);
        println!("
{}	{}	{}	{}
", row, x, y, z);
    }

    println!("
");
}


Cumulative standard deviation

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

typedef enum Action { STDDEV, MEAN, VAR, COUNT } Action;

typedef struct stat_obj_struct {
   double sum, sum2;
   size_t num;
   Action action;
} sStatObject, *StatObject;

StatObject NewStatObject( Action action )
{
  StatObject so;

  so = malloc(sizeof(sStatObject));
  so->sum = 0.0;
  so->sum2 = 0.0;
  so->num = 0;
  so->action = action;
  return so;
}
#define FREE_STAT_OBJECT(so) \
   free(so); so = NULL
double stat_obj_value(StatObject so, Action action)
{
  double num, mean, var, stddev;

  if (so->num == 0.0) return 0.0;
  num = so->num;
  if (action==COUNT) return num;
  mean = so->sum/num;
  if (action==MEAN) return mean;
  var = so->sum2/num - mean*mean;
  if (action==VAR) return var;
  stddev = sqrt(var);
  if (action==STDDEV) return stddev;
  return 0;
}

double stat_object_add(StatObject so, double v)
{
  so->num++;
  so->sum += v;
  so->sum2 += v*v;
  return stat_obj_value(so, so->action);
}

pub struct CumulativeStandardDeviation {
    n: f64,
    sum: f64,
    sum_sq: f64
}

impl CumulativeStandardDeviation {
    pub fn new() -> Self {
        CumulativeStandardDeviation {
            n: 0.,
            sum: 0.,
            sum_sq: 0.
        }
    }

    fn push(&mut self, x: f64) -> f64 {
        self.n += 1.;
        self.sum += x;
        self.sum_sq += x * x;

        (self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt()
    }
}

fn main() {
    let nums = [2, 4, 4, 4, 5, 5, 7, 9];

    let mut cum_stdev = CumulativeStandardDeviation::new();
    for num in nums.iter() {
        println!("{}", cum_stdev.push(*num as f64));
    }
}


Currency

	mpf_set_d(burgerUnitPrice,5.50);
	mpf_set_d(milkshakePrice,2 * 2.86);
	mpf_set_d(burgerNum,4000000000000000);
	mpf_set_d(milkshakeNum,2);

extern crate num_bigint;
extern crate num_rational;

use num_bigint::BigInt;
use num_rational::BigRational;

use std::ops::{Add, Mul};
use std::fmt;

fn main() {
    let hamburger = Currency::new(5.50);
    let milkshake = Currency::new(2.86);
    let pre_tax = hamburger * 4_000_000_000_000_000 + milkshake * 2;
    println!("Price before tax: {}", pre_tax);
    let tax = pre_tax.calculate_tax();
    println!("Tax: {}", tax);
    let post_tax = pre_tax + tax;
    println!("Price after tax: {}", post_tax);
}

#[derive(Debug)]
struct Currency {
    amount: BigRational,
}

impl Add for Currency {

    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            amount: self.amount + other.amount,
        }
    }
}

impl Mul<u64> for Currency {

    type Output = Self;

    fn mul(self, other: u64) -> Self {
        Self {
            amount: self.amount * BigInt::from(other),
        }
    }
}

impl fmt::Display for Currency {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cents = (&self.amount * BigInt::from(100)).to_integer();
        write!(f, "${}.{}", &cents / 100, &cents % 100)
    }
}

impl Currency {

    fn new(num: f64) -> Self {
        Self {
            amount: BigRational::new(((num * 100.0) as i64).into(), 100.into())
        }
    }

    fn calculate_tax(&self) -> Self {
        let tax_val = BigRational::new(765.into(), 100.into());
        let amount = (&self.amount * tax_val).ceil() / BigInt::from(100);
        Self {
            amount
        }
    }
}


Currying

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

long int factorial(int n){
	if(n>1)
		return n*factorial(n-1);
	return 1;
}

long int sumOfFactorials(int num,...){
	va_list vaList;
	long int sum = 0;

	va_start(vaList,num);

	while(num--)
		sum += factorial(va_arg(vaList,int));

	va_end(vaList);

	return sum;
}

int main()
{
	printf("\nSum of factorials of [1,5] : %ld",sumOfFactorials(5,1,2,3,4,5));
	printf("\nSum of factorials of [3,5] : %ld",sumOfFactorials(3,3,4,5));
	printf("\nSum of factorials of [1,3] : %ld",sumOfFactorials(3,1,2,3));

	return 0;
}

fn add_n(n : i32) -> impl Fn(i32) -> i32 {
    move |x| n + x
}

fn main() {
    let adder = add_n(40);
    println!("The answer to life is {}.", adder(2));
}


DNS query

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main()
{
	struct addrinfo hints, *res, *res0;
	int error;
	char host[NI_MAXHOST];

	memset(&hints, 0, sizeof hints);
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;

	error = getaddrinfo("www.kame.net", NULL, &hints, &res0);
	if (error) {
		fprintf(stderr, "%s\n", gai_strerror(error));
		exit(1);
	}

	for (res = res0; res; res = res->ai_next) {

		error = getnameinfo(res->ai_addr, res->ai_addrlen,
		    host, sizeof host, NULL, 0, NI_NUMERICHOST);

		if (error) {
			fprintf(stderr, "%s\n", gai_strerror(error));
		} else {

			printf("%s\n", host);
		}
	}

	freeaddrinfo(res0);

	return 0;
}

use std::net::ToSocketAddrs;

fn main() {
    let host = "www.kame.net";

    let host_port = (host, 0);
    let ip_iter = host_port.to_socket_addrs().unwrap();

    for ip_port in ip_iter {
        println!("{}", ip_port.ip());
    }
}


Date format

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_BUF 50

int main(void)
{
  char buf[MAX_BUF];
  time_t seconds = time(NULL);
  struct tm *now = localtime(&seconds);
  const char *months[] = {"January", "February", "March", "April", "May", "June",
                          "July", "August", "September", "October", "November", "December"};

  const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday"};

  (void) printf("%d-%d-%d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
  (void) printf("%s, %s %d, %d\n",days[now->tm_wday], months[now->tm_mon],
               now->tm_mday, now->tm_year + 1900);

  (void) strftime(buf, MAX_BUF, "%A, %B %e, %Y", now);
  (void) printf("%s\n", buf);
  return EXIT_SUCCESS;
}

fn main() {
    let now = chrono::Utc::now();
    println!("{}", now.format("%Y-%m-%d"));
    println!("{}", now.format("%A, %B %d, %Y"));
}


Date manipulation

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

int main()
{
  struct tm ts;
  time_t t;
  const char *d = "March 7 2009 7:30pm EST";

  strptime(d, "%B %d %Y %I:%M%p %Z", &ts);

  t = mktime(&ts);
  t += 12*60*60;
  printf("%s", ctime(&t));

  return EXIT_SUCCESS;
}

use chrono::prelude::*;
use chrono::Duration;

fn main() {

    let ndt =
        NaiveDateTime::parse_from_str("March 7 2009 7:30pm EST", "%B %e %Y %l:%M%P %Z").unwrap();

    let dt = chrono_tz::EST.from_local_datetime(&ndt).unwrap();
    println!("Date parsed: {:?}", dt);

    let new_date = dt + Duration::hours(12);
    println!("+12 hrs in EST: {:?}", new_date);
    println!(
        "+12 hrs in CET: {:?}",
        new_date.with_timezone(&chrono_tz::CET)
    );
}


Day of the week

#include <stdio.h>

int wday(int year, int month, int day)
{
	int adjustment, mm, yy;

	adjustment = (14 - month) / 12;
	mm = month + 12 * adjustment - 2;
	yy = year - adjustment;
	return (day + (13 * mm - 1) / 5 +
		yy + yy / 4 - yy / 100 + yy / 400) % 7;
}

int main()
{
	int y;

	for (y = 2008; y <= 2121; y++) {
		if (wday(y, 12, 25) == 0) printf("%04d-12-25\n", y);
	}

	return 0;
}

extern crate chrono;

use chrono::prelude::*;

fn main() {
    let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::<Vec<i32>>();
    println!("Years = {:?}", years);
}


Days between dates

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

typedef struct{
    int year, month, day;
}date;

date extractDate(char* str){
    return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}

bool isValidDate(char* str){
    date newDate;

    if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
        return false;
    }

    newDate = extractDate(str);

    if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
      ((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
      newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
          return false;
      }

    return true;
}

int diffDays(date date1,date date2){
    int days1, days2;

    date1.month = (date1.month + 9)%12;
    date1.year = date1.year - date1.month/10;

    date2.month = (date2.month + 9)%12;
    date2.year = date2.year - date2.month/10;

    days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
    days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );

    return days2 - days1;
}

int main(int argc,char** argv)
{
    if(argc!=3){
        return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
    }

    if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
        return printf("Dates are invalid.\n");
    }

    printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));

    return 0;
}

use chrono::NaiveDate;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 3 {
        eprintln!("usage: {} start-date end-date", args[0]);
        std::process::exit(1);
    }
    if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
        if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
            let d = end_date.signed_duration_since(start_date);
            println!("{}", d.num_days());
        } else {
            eprintln!("Can't parse end date");
            std::process::exit(1);
        }
    } else {
        eprintln!("Can't parse start date");
        std::process::exit(1);
    }
}


Deal cards for FreeCell

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

wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK";

#define RMAX32 ((1U << 31) - 1)
static int seed = 1;
int  rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; }
void srnd(int x) { seed = x; }

void show(const int *c)
{
	int i;
	for (i = 0; i < 52; c++) {
		printf("  \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2,
			s_suits[*c % 4], s_nums[*c / 4]);
		if (!(++i % 8) || i == 52) putchar('\n');
	}
}

void deal(int s, int *t)
{
	int i, j;
	srnd(s);

	for (i = 0; i < 52; i++) t[i] = 51 - i;
	for (i = 0; i < 51; i++) {
		j = 51 - rnd() % (52 - i);
		s = t[i], t[i] = t[j], t[j] = s;
	}
}

int main(int c, char **v)
{
	int s, card[52];
	if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982;

	setlocale(LC_ALL, "");

	deal(s, card);
	printf("Hand %d\n", s);
	show(card);

	return 0;
}

extern crate linear_congruential_generator;

use linear_congruential_generator::{MsLcg, Rng, SeedableRng};

fn shuffle<T>(rng: &mut MsLcg, deck: &mut [T]) {
    let len = deck.len() as u32;
    for i in (1..len).rev() {
        let j = rng.next_u32() % (i + 1);
        deck.swap(i as usize, j as usize);
    }
}

fn gen_deck() -> Vec<String> {
    const RANKS: [char; 13] = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'];
    const SUITS: [char; 4] = ['C', 'D', 'H', 'S'];

    let render_card = |card: usize| {
        let (suit, rank) = (card % 4, card / 4);
        format!("{}{}", RANKS[rank], SUITS[suit])
    };

    (0..52).map(render_card).collect()
}

fn deal_ms_fc_board(seed: u32) -> Vec<String> {
    let mut rng = MsLcg::from_seed(seed);
    let mut deck = gen_deck();

    shuffle(&mut rng, &mut deck);
    deck.reverse();

    deck.chunks(8).map(|row| row.join(" ")).collect::<Vec<_>>()
}

fn main() {
    let seed = std::env::args()
        .nth(1)
        .and_then(|n| n.parse().ok())
        .expect("A 32-bit seed is required");

    for row in deal_ms_fc_board(seed) {
        println!(": {}", row);
    }
}


Delegates

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

typedef const char * (*Responder)( int p1);

typedef struct sDelegate {
    Responder operation;
} *Delegate;

Delegate NewDelegate( Responder rspndr )
{
    Delegate dl = malloc(sizeof(struct sDelegate));
    dl->operation = rspndr;
    return dl;
}

const char *DelegateThing(Delegate dl, int p1)
{
    return  (dl->operation)? (*dl->operation)(p1) : NULL;
}

typedef struct sDelegator {
    int     param;
    char    *phrase;
    Delegate delegate;
} *Delegator;

const char * defaultResponse( int p1)
{
    return "default implementation";
}

static struct sDelegate defaultDel = { &defaultResponse };

Delegator NewDelegator( int p, char *phrase)
{
    Delegator d  = malloc(sizeof(struct sDelegator));
    d->param = p;
    d->phrase = phrase;
    d->delegate = &defaultDel;
    return d;
}

const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
    const char *rtn;
    if (delroy) {
        rtn = DelegateThing(delroy, p1);
        if (!rtn) {
            rtn = DelegateThing(theDelegator->delegate, p1);
        }
    }
    else
        rtn = DelegateThing(theDelegator->delegate, p1);

    printf("%s\n", theDelegator->phrase );
    return rtn;
}

const char *thing1( int p1)
{
    printf("We're in thing1 with value %d\n" , p1);
    return "delegate implementation";
}

int main()
{
    Delegate del1 = NewDelegate(&thing1);
    Delegate del2 = NewDelegate(NULL);
    Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");

    printf("Delegator returns %s\n\n",
            Delegator_Operation( theDelegator, 3, NULL));
    printf("Delegator returns %s\n\n",
            Delegator_Operation( theDelegator, 3, del1));
    printf("Delegator returns %s\n\n",
            Delegator_Operation( theDelegator, 3, del2));
    return 0;
}

trait Thingable {
    fn thing(&self) -> &str;
}

struct Delegator<T>(Option<T>);

struct Delegate {}

impl Thingable for Delegate {
    fn thing(&self) -> &'static str {
        "Delegate implementation"
    }
}

impl<T: Thingable> Thingable for Delegator<T> {
    fn thing(&self) -> &str {
        self.0.as_ref().map(|d| d.thing()).unwrap_or("Default implmementation")
    }
}

fn main() {
    let d: Delegator<Delegate> = Delegator(None);
    println!("{}", d.thing());

    let d: Delegator<Delegate> = Delegator(Some(Delegate {}));
    println!("{}", d.thing());
}


Delete a file

#include <stdio.h>

int main() {
  remove("input.txt");
  remove("/input.txt");
  remove("docs");
  remove("/docs");
  return 0;
}

use std::io::{self, Write};
use std::fs::{remove_file,remove_dir};
use std::path::Path;
use std::{process,display};

const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";

fn main() {
    delete(".").and(delete("/"))
               .unwrap_or_else(|e| error_handler(e,1));
}

fn delete<P>(root: P) -> io::Result<()>
    where P: AsRef<Path>
{
    remove_file(root.as_ref().join(FILE_NAME))
        .and(remove_dir(root.as_ref().join(DIR_NAME)))
}

fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "{:?}", error);
    process::exit(code)
}


Department numbers

#include<stdio.h>

int main()
{
	int police,sanitation,fire;

	printf("Police     Sanitation         Fire\n");
	printf("----------------------------------");

	for(police=2;police<=6;police+=2){
		for(sanitation=1;sanitation<=7;sanitation++){
			for(fire=1;fire<=7;fire++){
				if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){
					printf("\n%d\t\t%d\t\t%d",police,sanitation,fire);
				}
			}
		}
	}

	return 0;
}

extern crate num_iter;
fn main() {
    println!("Police Sanitation Fire");
    println!("----------------------");

    for police in num_iter::range_step(2, 7, 2) {
        for sanitation in 1..8 {
            for fire in 1..8 {
                if police != sanitation
                    && sanitation != fire
                    && fire != police
                    && police + fire + sanitation == 12
                {
                    println!("{:6}{:11}{:4}", police, sanitation, fire);
                }
            }
        }
    }
}


Detect division by zero

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

static sigjmp_buf fpe_env;

static void
fpe_handler(int signal, siginfo_t *w, void *a)
{
	siglongjmp(fpe_env, w->si_code);

}

void
try_division(int x, int y)
{
	struct sigaction act, old;
	int code;

	volatile int result;

	code = sigsetjmp(fpe_env, 1);
	if (code == 0) {

		act.sa_sigaction = fpe_handler;
		sigemptyset(&act.sa_mask);
		act.sa_flags = SA_SIGINFO;
		if (sigaction(SIGFPE, &act, &old) < 0) {
			perror("sigaction");
			exit(1);
		}

		result = x / y;

		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}

		printf("%d / %d is %d\n", x, y, result);
	} else {

		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}

		switch (code) {
		case FPE_INTDIV:
		case FPE_FLTDIV:
			printf("%d / %d: caught division by zero!\n", x, y);
			break;
		default:
			printf("%d / %d: caught mysterious error!\n", x, y);
			break;
		}
	}
}

int
main()
{
	try_division(-44, 0);
	try_division(-44, 5);
	try_division(0, 5);
	try_division(0, 0);
	try_division(INT_MIN, -1);
	return 0;
}

fn test_division(numerator: u32, denominator: u32) {
    match numerator.checked_div(denominator) {
        Some(result) => println!("{} / {} = {}", numerator, denominator, result),
        None => println!("{} / {} results in a division by zero", numerator, denominator)
    }
}

fn main() {
    test_division(5, 4);
    test_division(4, 0);
}


Determine if a string has all the same characters

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

int main(int argc,char** argv)
{
    int i,len;
    char reference;

    if(argc>2){
        printf("Usage : %s <Test String>\n",argv[0]);
        return 0;
    }

    if(argc==1||strlen(argv[1])==1){
        printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argc==1?"":argv[1],argc==1?0:(int)strlen(argv[1]));
        return 0;
    }

    reference = argv[1][0];
    len = strlen(argv[1]);

    for(i=1;i<len;i++){
        if(argv[1][i]!=reference){
            printf("Input string : \"%s\"\nLength : %d\nFirst different character : \"%c\"(0x%x) at position : %d\n",argv[1],len,argv[1][i],argv[1][i],i+1);
            return 0;
        }
    }

    printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argv[1],len);

    return 0;

}

fn test_string(input: &str) {
    println!("Checking string {:?} of length {}:", input, input.chars().count());

    let mut chars = input.chars();

    match chars.next() {
        Some(first) => {
            if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c != first).next() {
                println!("\tNot all characters are the same.");
                println!("\t{:?} (0x{:X}) at position {} differs.", character, character as u32, pos);

                return;
            }
        },
        None => {}
    }

    println!("\tAll characters in the string are the same");
}

fn main() {
    let tests = ["", "   ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"];

    for string in &tests {
        test_string(string);
    }
}