Determine if a string has all unique characters

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

typedef struct positionList{
    int position;
    struct positionList *next;
}positionList;

typedef struct letterList{
    char letter;
    int repititions;
    positionList* positions;
    struct letterList *next;
}letterList;

letterList* letterSet;
bool duplicatesFound = false;

void checkAndUpdateLetterList(char c,int pos){
    bool letterOccurs = false;
    letterList *letterIterator,*newLetter;
    positionList *positionIterator,*newPosition;

    if(letterSet==NULL){
        letterSet = (letterList*)malloc(sizeof(letterList));
        letterSet->letter = c;
        letterSet->repititions = 0;

        letterSet->positions = (positionList*)malloc(sizeof(positionList));
        letterSet->positions->position = pos;
        letterSet->positions->next = NULL;

        letterSet->next = NULL;
    }

    else{
        letterIterator = letterSet;

        while(letterIterator!=NULL){
            if(letterIterator->letter==c){
                letterOccurs = true;
                duplicatesFound = true;

                letterIterator->repititions++;
                positionIterator = letterIterator->positions;

                while(positionIterator->next!=NULL)
                    positionIterator = positionIterator->next;

                newPosition = (positionList*)malloc(sizeof(positionList));
                newPosition->position = pos;
                newPosition->next = NULL;

                positionIterator->next = newPosition;
            }
            if(letterOccurs==false && letterIterator->next==NULL)
                break;
            else
                letterIterator = letterIterator->next;
        }

        if(letterOccurs==false){
            newLetter = (letterList*)malloc(sizeof(letterList));
            newLetter->letter = c;

            newLetter->repititions = 0;

            newLetter->positions = (positionList*)malloc(sizeof(positionList));
            newLetter->positions->position = pos;
            newLetter->positions->next = NULL;

            newLetter->next = NULL;

            letterIterator->next = newLetter;
        }
    }
}

void printLetterList(){
    positionList* positionIterator;
    letterList* letterIterator = letterSet;

    while(letterIterator!=NULL){
        if(letterIterator->repititions>0){
            printf("\n'%c' (0x%x) at positions :",letterIterator->letter,letterIterator->letter);

            positionIterator = letterIterator->positions;

            while(positionIterator!=NULL){
                printf("%3d",positionIterator->position + 1);
                positionIterator = positionIterator->next;
            }
        }

        letterIterator = letterIterator->next;
    }
    printf("\n");
}

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

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

    if(argc==1||strlen(argv[1])==1){
        printf("\"%s\" - Length %d - Contains only unique characters.\n",argc==1?"":argv[1],argc==1?0:1);
        return 0;
    }

    len = strlen(argv[1]);

    for(i=0;i<len;i++){
        checkAndUpdateLetterList(argv[1][i],i);
    }

    printf("\"%s\" - Length %d - %s",argv[1],len,duplicatesFound==false?"Contains only unique characters.\n":"Contains the following duplicate characters :");

    if(duplicatesFound==true)
        printLetterList();

    return 0;
}

fn unique(s: &str) -> Option<(usize, usize, char)> {
    s.chars().enumerate().find_map(|(i, c)| {
        s.chars()
            .enumerate()
            .skip(i + 1)
            .find(|(_, other)| c == *other)
            .map(|(j, _)| (i, j, c))
    })
}

fn main() {
    let strings = [
        "",
        ".",
        "abcABC",
        "XYZ ZYX",
        "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
        "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
        "hétérogénéité",
        "🎆🎃🎇🎈",
        "😍😀🙌💃😍🙌",
        "🐠🐟🐡🦈🐬🐳🐋🐡",
    ];

    for string in &strings {
        print!("\"{}\" (length {})", string, string.chars().count());
        match unique(string) {
            None => println!(" is unique"),
            Some((i, j, c)) => println!(
                " is not unique\n\tfirst duplicate: \"{}\" (U+{:0>4X}) at indices {} and {}",
                c, c as usize, i, j
            ),
        }
    }
}


Determine if a string is collapsible

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

#define COLLAPSE 0
#define SQUEEZE 1

typedef struct charList{
    char c;
    struct charList *next;
} charList;

int strcmpi(char* str1,char* str2){
    int len1 = strlen(str1), len2 = strlen(str2), i;

    if(len1!=len2){
        return 1;
    }

    else{
        for(i=0;i<len1;i++){
            if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
                return 1;
            else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
                return 1;
            else if(str1[i]!=str2[i])
                return 1;
        }
    }

    return 0;
}

charList *strToCharList(char* str){
    int len = strlen(str),i;

    charList *list, *iterator, *nextChar;

    list = (charList*)malloc(sizeof(charList));
    list->c = str[0];
    list->next = NULL;

    iterator = list;

    for(i=1;i<len;i++){
        nextChar = (charList*)malloc(sizeof(charList));
        nextChar->c = str[i];
        nextChar->next = NULL;

        iterator->next = nextChar;
        iterator = nextChar;
    }

    return list;
}

char* charListToString(charList* list){
    charList* iterator = list;
    int count = 0,i;
    char* str;

    while(iterator!=NULL){
        count++;
        iterator = iterator->next;
    }

    str = (char*)malloc((count+1)*sizeof(char));
    iterator = list;

    for(i=0;i<count;i++){
        str[i] = iterator->c;
        iterator = iterator->next;
    }

    free(list);
    str[i] = '\0';

    return str;
}

char* processString(char str[100],int operation, char squeezeChar){
    charList *strList = strToCharList(str),*iterator = strList, *scout;

    if(operation==SQUEEZE){
        while(iterator!=NULL){
            if(iterator->c==squeezeChar){
                scout = iterator->next;

                while(scout!=NULL && scout->c==squeezeChar){
                        iterator->next = scout->next;
                        scout->next = NULL;
                        free(scout);
                        scout = iterator->next;
                }
            }
            iterator = iterator->next;
        }
    }

    else{
        while(iterator!=NULL && iterator->next!=NULL){
            if(iterator->c == (iterator->next)->c){
                scout = iterator->next;
                squeezeChar = iterator->c;

                while(scout!=NULL && scout->c==squeezeChar){
                        iterator->next = scout->next;
                        scout->next = NULL;
                        free(scout);
                        scout = iterator->next;
                }
            }
            iterator = iterator->next;
        }
    }

    return charListToString(strList);
}

void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
    if(operation==SQUEEZE){
        printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
    }

    else
        printf("Specified Operation : COLLAPSE");

    printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
    printf("\nFinal    %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}

int main(int argc, char** argv){
    int operation;
    char squeezeChar;

    if(argc<3||argc>4){
        printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
        return 0;
    }

    if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
        scanf("Please enter characted to be squeezed : %c",&squeezeChar);
        operation = SQUEEZE;
    }

    else if(argc==4){
        operation = SQUEEZE;
        squeezeChar = argv[3][0];
    }

    else if(strcmpi(argv[1],"COLLAPSE")==0){
        operation = COLLAPSE;
    }

    if(strlen(argv[2])<2){
        printResults(argv[2],argv[2],operation,squeezeChar);
    }

    else{
        printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
    }

    return 0;
}

fn collapse_string(val: &str) -> String {
    let mut output = String::new();
    let mut chars = val.chars().peekable();

    while let Some(c) = chars.next() {
        while let Some(&b) = chars.peek() {
            if b == c {
                chars.next();
            } else {
                break;
            }
        }

        output.push(c);
    }

    output
}

fn main() {
    let tests = [
        "122333444455555666666777777788888888999999999",
        "",
        "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                    --- Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
    ];

    for s in &tests {
        println!("Old: {:>3} <<<{}>>>", s.len(), s);
        let collapsed = collapse_string(s);
        println!("New: {:>3} <<<{}>>>", collapsed.len(), collapsed);

        println!();
    }
}


Determine if a string is numeric

#include <ctype.h>
#include <stdlib.h>
int isNumeric (const char * s)
{
    if (s == NULL || *s == '\0' || isspace(*s))
      return 0;
    char * p;
    strtod (s, &p);
    return *p == '\0';
}

fn parsable<T: FromStr>(s: &str) -> bool {
    s.parse::<T>().is_ok()
}


Determine if a string is squeezable

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

#define COLLAPSE 0
#define SQUEEZE 1

typedef struct charList{
    char c;
    struct charList *next;
} charList;

int strcmpi(char str1[100],char str2[100]){
    int len1 = strlen(str1), len2 = strlen(str2), i;

    if(len1!=len2){
        return 1;
    }

    else{
        for(i=0;i<len1;i++){
            if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
                return 1;
            else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
                return 1;
            else if(str1[i]!=str2[i])
                return 1;
        }
    }

    return 0;
}

charList *strToCharList(char* str){
    int len = strlen(str),i;

    charList *list, *iterator, *nextChar;

    list = (charList*)malloc(sizeof(charList));
    list->c = str[0];
    list->next = NULL;

    iterator = list;

    for(i=1;i<len;i++){
        nextChar = (charList*)malloc(sizeof(charList));
        nextChar->c = str[i];
        nextChar->next = NULL;

        iterator->next = nextChar;
        iterator = nextChar;
    }

    return list;
}

char* charListToString(charList* list){
    charList* iterator = list;
    int count = 0,i;
    char* str;

    while(iterator!=NULL){
        count++;
        iterator = iterator->next;
    }

    str = (char*)malloc((count+1)*sizeof(char));
    iterator = list;

    for(i=0;i<count;i++){
        str[i] = iterator->c;
        iterator = iterator->next;
    }

    free(list);
    str[i] = '\0';

    return str;
}

char* processString(char str[100],int operation, char squeezeChar){
    charList *strList = strToCharList(str),*iterator = strList, *scout;

    if(operation==SQUEEZE){
        while(iterator!=NULL){
            if(iterator->c==squeezeChar){
                scout = iterator->next;

                while(scout!=NULL && scout->c==squeezeChar){
                        iterator->next = scout->next;
                        scout->next = NULL;
                        free(scout);
                        scout = iterator->next;
                }
            }
            iterator = iterator->next;
        }
    }

    else{
        while(iterator!=NULL && iterator->next!=NULL){
            if(iterator->c == (iterator->next)->c){
                scout = iterator->next;
                squeezeChar = iterator->c;

                while(scout!=NULL && scout->c==squeezeChar){
                        iterator->next = scout->next;
                        scout->next = NULL;
                        free(scout);
                        scout = iterator->next;
                }
            }
            iterator = iterator->next;
        }
    }

    return charListToString(strList);
}

void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
    if(operation==SQUEEZE){
        printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
    }

    else
        printf("Specified Operation : COLLAPSE");

    printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
    printf("\nFinal    %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}

int main(int argc, char** argv){
    int operation;
    char squeezeChar;

    if(argc<3||argc>4){
        printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
        return 0;
    }

    if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
        scanf("Please enter characted to be squeezed : %c",&squeezeChar);
        operation = SQUEEZE;
    }

    else if(argc==4){
        operation = SQUEEZE;
        squeezeChar = argv[3][0];
    }

    else if(strcmpi(argv[1],"COLLAPSE")==0){
        operation = COLLAPSE;
    }

    if(strlen(argv[2])<2){
        printResults(argv[2],argv[2],operation,squeezeChar);
    }

    else{
        printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
    }

    return 0;
}

fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a {
    let mut previous = None;

    s.chars().filter(move |c| match previous {
        Some(p) if p == squeezable && p == *c => false,
        _ => {
            previous = Some(*c);
            true
        }
    })
}

fn main() {
    fn show(input: &str, c: char) {
        println!("Squeeze: '{}'", c);
        println!("Input ({} chars): \t{}", input.chars().count(), input);
        let output: String = squeezable_string(input, c).collect();
        println!("Output ({} chars): \t{}", output.chars().count(), output);
        println!();
    }

    let harry = r#"I never give 'em hell, I just tell the truth, and they think it's hell.
    ---  Harry S Truman"#;

    #[rustfmt::skip]
    let inputs = [
        ("", ' '),
        (r#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#, '-'),
        ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'),
        (harry, ' '),
        (harry, '-'),
        (harry, 'r'),
        ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e'),
        ("headmistressship", 's'),
    ];

    inputs.iter().for_each(|(input, c)| show(input, *c));
}


Determine if only one instance is running

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

#define INSTANCE_LOCK "rosetta-code-lock"

void
fail(const char *message)
{
	perror(message);
	exit(1);
}

static char *ooi_path;

void
ooi_unlink(void)
{
	unlink(ooi_path);
}

void
only_one_instance(void)
{
	struct flock fl;
	size_t dirlen;
	int fd;
	char *dir;

	dir = getenv("HOME");
	if (dir == NULL || dir[0] != '/') {
		fputs("Bad home directory.\n", stderr);
		exit(1);
	}
	dirlen = strlen(dir);

	ooi_path = malloc(dirlen + sizeof("/" INSTANCE_LOCK));
	if (ooi_path == NULL)
		fail("malloc");
	memcpy(ooi_path, dir, dirlen);
	memcpy(ooi_path + dirlen, "/" INSTANCE_LOCK,
	    sizeof("/" INSTANCE_LOCK));

	fd = open(ooi_path, O_RDWR | O_CREAT, 0600);
	if (fd < 0)
		fail(ooi_path);

	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	if (fcntl(fd, F_SETLK, &fl) < 0) {
		fputs("Another instance of this program is running.\n",
		    stderr);
		exit(1);
	}

	atexit(ooi_unlink);
}

int
main()
{
	int i;

	only_one_instance();

	for(i = 10; i > 0; i--) {
		printf("%d...%s", i, i % 5 == 1 ? "\n" : " ");
		fflush(stdout);
		sleep(1);
	}
	puts("Fin!");
	return 0;
}

use std::net::TcpListener;

fn create_app_lock(port: u16) -> TcpListener {
    match TcpListener::bind(("0.0.0.0", port)) {
        Ok(socket) => {
            socket
        },
        Err(_) => {
            panic!("Couldn't lock port {}: another instance already running?", port);
        }
    }
}

fn remove_app_lock(socket: TcpListener) {
    drop(socket);
}

fn main() {
    let lock_socket = create_app_lock(12345);

    remove_app_lock(lock_socket);
}


Digital root

#include <stdio.h>

int droot(long long int x, int base, int *pers)
{
	int d = 0;
	if (pers)
		for (*pers = 0; x >= base; x = d, (*pers)++)
			for (d = 0; x; d += x % base, x /= base);
	else if (x && !(d = x % (base - 1)))
			d = base - 1;

	return d;
}

int main(void)
{
	int i, d, pers;
	long long x[] = {627615, 39390, 588225, 393900588225LL};

	for (i = 0; i < 4; i++) {
		d = droot(x[i], 10, &pers);
		printf("%lld: pers %d, root %d\n", x[i], pers, d);
	}

	return 0;
}

fn sum_digits(mut n: u64, base: u64) -> u64 {
    let mut sum = 0u64;
    while n > 0 {
        sum = sum + (n % base);
        n = n / base;
    }
    sum
}

fn digital_root(mut num: u64, base: u64) -> (u64, u64) {
    let mut pers = 0;
    while num >= base {
        pers = pers + 1;
        num = sum_digits(num, base);
    }
    (pers, num)
}

fn main() {

    let values = [627615u64, 39390u64, 588225u64, 393900588225u64];
    for &value in values.iter() {
        let (pers, root) = digital_root(value, 10);
        println!("{} has digital root {} and additive persistance {}",
                 value,
                 root,
                 pers);
    }

    println!("");

    let values_base16 = [0x7e0, 0x14e344, 0xd60141, 0x12343210];
    for &value in values_base16.iter() {
        let (pers, root) = digital_root(value, 16);
        println!("0x{:x} has digital root 0x{:x} and additive persistance 0x{:x}",
                 value,
                 root,
                 pers);
    }
}


Discordian date

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

#define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\
                          (x) == 2 ? "Boomtime" :\
                          (x) == 3 ? "Pungenday" :\
                          (x) == 4 ? "Prickle-Prickle" :\
                          "Setting Orange")

#define season( x ) ((x) == 0 ? "Chaos" :\
                    (x) == 1 ? "Discord" :\
                    (x) == 2 ? "Confusion" :\
                    (x) == 3 ? "Bureaucracy" :\
                    "The Aftermath")

#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)

#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))

char * ddate( int y, int d ){
  int dyear = 1166 + y;
  char * result = malloc( 100 * sizeof( char ) );

  if( leap_year( y ) ){
    if( d == 60 ){
      sprintf( result, "St. Tib's Day, YOLD %d", dyear );
      return result;
    } else if( d >= 60 ){
      -- d;
    }
  }

  sprintf( result, "%s, %s %d, YOLD %d",
           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );

  return result;
}

int day_of_year( int y, int m, int d ){
  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

  for( ; m > 1; m -- ){
    d += month_lengths[ m - 2 ];
    if( m == 3 && leap_year( y ) ){
      ++ d;
    }
  }
  return d;
}

int main( int argc, char * argv[] ){
  time_t now;
  struct tm * now_time;
  int year, doy;

  if( argc == 1 ){
    now = time( NULL );
    now_time = localtime( &now );
    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;
  } else if( argc == 4 ){
    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );
  }

  char * result = ddate( year, doy );
  puts( result );
  free( result );

  return 0;
}

extern crate chrono;

use chrono::NaiveDate;
use std::str::FromStr;

fn main() {
    let date = std::env::args().nth(1).expect("Please provide a YYYY-MM-DD date.");
    println!("{} is {}", date, NaiveDate::from_str(&date).unwrap().to_poee());
}

const APOSTLES: [&str; 5] = ["Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"];
const HOLYDAYS: [&str; 5] = ["Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"];
const SEASONS: [&str; 5] = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"];
const WEEKDAYS: [&str; 5] = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"];

const APOSTLE_HOLYDAY: usize = 5;
const CURSE_OF_GREYFACE: i32 = 1166;
const SEASON_DAYS: usize = 73;
const SEASON_HOLYDAY: usize = 50;
const ST_TIBS_DAY: usize = 59;
const WEEK_DAYS: usize = 5;

impl<T: Datelike> DiscordianDate for T {}
pub trait DiscordianDate: Datelike {
    fn to_poee(&self) -> String {
        let day = self.ordinal0() as usize;
        let leap = self.year() % 4 == 0 && self.year() % 100 != 0 || self.year() % 400 == 0;
        let year = self.year() + CURSE_OF_GREYFACE;

        if leap && day == ST_TIBS_DAY { return format!("St. Tib's Day, in the YOLD {}", year); }

        let day_offset = if leap && day > ST_TIBS_DAY { day - 1 } else { day };

        let day_of_season = day_offset % SEASON_DAYS + 1;

        let season = SEASONS[day_offset / SEASON_DAYS];
        let weekday = WEEKDAYS[day_offset % WEEK_DAYS];

        let holiday = if day_of_season == APOSTLE_HOLYDAY {
            format!("\nCelebrate {}", APOSTLES[day_offset / SEASON_DAYS])
        } else if day_of_season == SEASON_HOLYDAY {
            format!("\nCelebrate {}", HOLYDAYS[day_offset / SEASON_DAYS])
        } else {
            String::with_capacity(0)
        };

        format!("{}, the {} day of {} in the YOLD {}{}",
            weekday, ordinalize(day_of_season), season, year, holiday)
    }
}

fn ordinalize(num: usize) -> String {
    let s = format!("{}", num);

    let suffix = if s.ends_with('1') && !s.ends_with("11") {
        "st"
    } else if s.ends_with('2') && !s.ends_with("12") {
        "nd"
    } else if s.ends_with('3') && !s.ends_with("13") {
        "rd"
    } else {
        "th"
    };

    format!("{}{}", s, suffix)
}


Display a linear combination

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

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

	int i,zeroCount= 0,firstNonZero = -1;
	double* vector;

	if(argC == 1){
		printf("Usage : %s <Vector component coefficients seperated by single space>",argV[0]);
	}

	else{

		printf("Vector for [");
		for(i=1;i<argC;i++){
			printf("%s,",argV[i]);
		}
		printf("\b] -> ");

		vector = (double*)malloc((argC-1)*sizeof(double));

		for(i=1;i<=argC;i++){
			vector[i-1] = atof(argV[i]);
			if(vector[i-1]==0.0)
				zeroCount++;
			if(vector[i-1]!=0.0 && firstNonZero==-1)
				firstNonZero = i-1;
		}

		if(zeroCount == argC){
			printf("0");
		}

		else{
			for(i=0;i<argC;i++){
				if(i==firstNonZero && vector[i]==1)
					printf("e%d ",i+1);
				else if(i==firstNonZero && vector[i]==-1)
					printf("- e%d ",i+1);
				else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])>0.0)
					printf("- %lf e%d ",fabs(vector[i]),i+1);
				else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])==0.0)
					printf("- %ld e%d ",labs(vector[i]),i+1);
				else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])>0.0)
					printf("%lf e%d ",vector[i],i+1);
				else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])==0.0)
					printf("%ld e%d ",vector[i],i+1);
				else if(fabs(vector[i])==1.0 && i!=0)
					printf("%c e%d ",(vector[i]==-1)?'-':'+',i+1);
				else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])>0.0)
					printf("%c %lf e%d ",(vector[i]<0)?'-':'+',fabs(vector[i]),i+1);
				else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])==0.0)
					printf("%c %ld e%d ",(vector[i]<0)?'-':'+',labs(vector[i]),i+1);
			}
		}
	}

	free(vector);

	return 0;
}

use std::fmt::{Display, Formatter, Result};
use std::process::exit;

struct Coefficient(usize, f64);

impl Display for Coefficient {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        let i = self.0;
        let c = self.1;

        if c == 0. {
            return Ok(());
        }

        write!(
            f,
            " {} {}e({})",
            if c < 0. {
                "-"
            } else if f.alternate() {
                " "
            } else {
                "+"
            },
            if (c.abs() - 1.).abs() < f64::EPSILON {
                "".to_string()
            } else {
                c.abs().to_string() + "*"
            },
            i + 1
        )
    }
}

fn usage() {
    println!("Usage: display-linear-combination a1 [a2 a3 ...]");
}

fn linear_combination(coefficients: &[f64]) -> String {
    let mut string = String::new();

    let mut iter = coefficients.iter().enumerate();

    loop {
        match iter.next() {
            Some((_, &c)) if c == 0. => {
                continue;
            }
            Some((i, &c)) => {
                string.push_str(format!("{:#}", Coefficient(i, c)).as_str());
                break;
            }
            None => {
                string.push('0');
                return string;
            }
        }
    }

    for (i, &c) in iter {
        string.push_str(format!("{}", Coefficient(i, c)).as_str());
    }

    string
}

fn main() {
    let mut coefficients = Vec::new();
    let mut args = std::env::args();

    args.next();

    for arg in args {
        let c = arg.parse::<f64>().unwrap_or_else(|e| {
            eprintln!("Failed to parse argument \"{}\": {}", arg, e);
            exit(-1);
        });
        coefficients.push(c);
    }

    if coefficients.is_empty() {
        usage();
        return;
    }

    println!("{}", linear_combination(&coefficients));
}


Documentation

int add(int a, int b) {
    return a + b;
}

#![doc(html_favicon_url = "https:
#![doc(html_logo_url = "https:

pub const THINGY: u32 = 42;

pub enum Whatsit {

    Yo(Whatchamabob),

    HoHo,
}

pub struct Whatchamabob {

    pub doodad: f64,

    pub thingamabob: bool
}

pub trait Frobnify {

    fn frob(&self);
}

impl Frobnify for Whatchamabob {

    fn frob(&self) {
        println!("Frobbed: {}", self.doodad);
    }
}

pub fn main() {
    let foo = Whatchamabob{ doodad: 1.2, thingamabob: false };
    foo.frob();
}


Dot product

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

int dot_product(int *, int *, size_t);

int
main(void)
{
        int a[3] = {1, 3, -5};
        int b[3] = {4, -2, -1};

        printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0])));

        return EXIT_SUCCESS;
}

int
dot_product(int *a, int *b, size_t n)
{
        int sum = 0;
        size_t i;

        for (i = 0; i < n; i++) {
                sum += a[i] * b[i];
        }

        return sum;
}

fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> {
    if a.len() != b.len() { return None }
    Some(
        a.iter()
            .zip( b.iter() )
            .fold(0, |sum, (el_a, el_b)| sum + el_a*el_b)
    )
}

fn main() {
    let v1 = vec![1, 3, -5];
    let v2 = vec![4, -2, -1];

    println!("{}", dot_product(&v1, &v2).unwrap());
}


Doubly-linked list_Element definition

struct Node
{
  struct Node *next;
  struct Node *prev;
  void  *data;
};

use std::collections::LinkedList;
fn main() {

     let list = LinkedList::<i32>::new();
}


Doubly-linked list_Element insertion

void insert(link* anchor, link* newlink) {
  newlink->next = anchor->next;
  newlink->prev = anchor;
  (newlink->next)->prev = newlink;
  anchor->next = newlink;
}

use std::collections::LinkedList;
fn main() {
    let mut list = LinkedList::new();
    list.push_front(8);
}


Dragon curve

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

long long x, y, dx, dy, scale, clen;
typedef struct { double r, g, b; } rgb;
rgb ** pix;

void sc_up()
{
	long long tmp = dx - dy; dy = dx + dy; dx = tmp;
	scale *= 2; x *= 2; y *= 2;
}

void h_rgb(long long x, long long y)
{
	rgb *p = &pix[y][x];

#	define SAT 1
	double h = 6.0 * clen / scale;
	double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;
	double c = SAT * VAL;
	double X = c * (1 - fabs(fmod(h, 2) - 1));

	switch((int)h) {
	case 0: p->r += c; p->g += X; return;
	case 1:	p->r += X; p->g += c; return;
	case 2: p->g += c; p->b += X; return;
	case 3: p->g += X; p->b += c; return;
	case 4: p->r += X; p->b += c; return;
	default:
		p->r += c; p->b += X;
	}
}

void iter_string(const char * str, int d)
{
	long tmp;
#	define LEFT  tmp = -dy; dy = dx; dx = tmp
#	define RIGHT tmp = dy; dy = -dx; dx = tmp
	while (*str != '\0') {
		switch(*(str++)) {
		case 'X':	if (d) iter_string("X+YF+", d - 1); continue;
		case 'Y':	if (d) iter_string("-FX-Y", d - 1); continue;
		case '+':	RIGHT; continue;
		case '-':	LEFT;  continue;
		case 'F':

				clen ++;
				h_rgb(x/scale, y/scale);
				x += dx; y += dy;
				continue;
		}
	}
}

void dragon(long leng, int depth)
{
	long i, d = leng / 3 + 1;
	long h = leng + 3, w = leng + d * 3 / 2 + 2;

	rgb *buf = malloc(sizeof(rgb) * w * h);
	pix = malloc(sizeof(rgb *) * h);
	for (i = 0; i < h; i++)
		pix[i] = buf + w * i;
	memset(buf, 0, sizeof(rgb) * w * h);

	x = y = d; dx = leng; dy = 0; scale = 1; clen = 0;
	for (i = 0; i < depth; i++) sc_up();
	iter_string("FX", depth);

	unsigned char *fpix = malloc(w * h * 3);
	double maxv = 0, *dbuf = (double*)buf;

	for (i = 3 * w * h - 1; i >= 0; i--)
		if (dbuf[i] > maxv) maxv = dbuf[i];
	for (i = 3 * h * w - 1; i >= 0; i--)
		fpix[i] = 255 * dbuf[i] / maxv;

	printf("P6\n%ld %ld\n255\n", w, h);
	fflush(stdout);
	fwrite(fpix, h * w * 3, 1, stdout);
}

int main(int c, char ** v)
{
	int size, depth;

	depth  = (c > 1) ? atoi(v[1]) : 10;
	size = 1 << depth;

	fprintf(stderr, "size: %d depth: %d\n", size, depth);
	dragon(size, depth * 2);

	return 0;
}

use ggez::{
    conf::{WindowMode, WindowSetup},
    error::GameResult,
    event,
    graphics::{clear, draw, present, Color, MeshBuilder},
    nalgebra::Point2,
    Context,
};
use std::time::Duration;

fn l_system_next_generation(current_generation: &str) -> String {
    let f_rule = "f-h";
    let h_rule = "f+h";
    let mut next_gen = String::new();
    for char in current_generation.chars() {
        match char {
            'f' => next_gen.push_str(f_rule),
            'h' => next_gen.push_str(h_rule),
            '-' | '+' => next_gen.push(char),
            _ => panic!("Unknown char {}", char),
        }
    }
    next_gen
}

const WINDOW_WIDTH: f32 = 700.0;
const WINDOW_HEIGHT: f32 = 700.0;
const START_X: f32 = WINDOW_WIDTH / 6.0;
const START_Y: f32 = WINDOW_HEIGHT / 6.0;
const MAX_DEPTH: i32 = 15;
const LINE_LENGTH: f32 = 20.0;

struct MainState {
    start_gen: String,
    next_gen: String,
    line_length: f32,
    max_depth: i32,
    current_depth: i32,
}

impl MainState {
    fn new() -> GameResult<MainState> {
        let start_gen = "f";
        let next_gen = String::new();
        let line_length = LINE_LENGTH;
        let max_depth = MAX_DEPTH;
        let current_depth = 0;
        Ok(MainState {
            start_gen: start_gen.to_string(),
            next_gen,
            line_length,
            max_depth,
            current_depth,
        })
    }
}

impl event::EventHandler for MainState {

    fn update(&mut self, _ctx: &mut Context) -> GameResult {
        if self.current_depth < self.max_depth {
            self.next_gen = l_system_next_generation(&self.start_gen);
            self.start_gen = self.next_gen.clone();
            self.line_length -= (self.line_length / self.max_depth as f32) * 1.9;
            self.current_depth += 1;
        }
        ggez::timer::sleep(Duration::from_millis(500));
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        let grey = Color::from_rgb(77, 77, 77);
        let blue = Color::from_rgb(51, 153, 255);
        let initial_point_blue = Point2::new(START_X, START_Y);
        clear(ctx, grey);
        draw_lines(
            &self.next_gen,
            ctx,
            self.line_length,
            blue,
            initial_point_blue,
        )?;
        present(ctx)?;
        Ok(())
    }
}

fn next_point(current_point: Point2<f32>, heading: f32, line_length: f32) -> Point2<f32> {
    let next_point = (
        (current_point.x + (line_length * heading.to_radians().cos().trunc() as f32)),
        (current_point.y + (line_length * heading.to_radians().sin().trunc() as f32)),
    );
    Point2::new(next_point.0, next_point.1)
}

fn draw_lines(
    instructions: &str,
    ctx: &mut Context,
    line_length: f32,
    colour: Color,
    initial_point: Point2<f32>,
) -> GameResult {
    let line_width = 2.0;
    let mut heading = 0.0;
    let turn_angle = 90.0;
    let mut start_point = initial_point;
    let mut line_builder = MeshBuilder::new();
    for char in instructions.chars() {
        let end_point = next_point(start_point, heading, line_length);
        match char {
            'f' | 'h' => {
                line_builder.line(&[start_point, end_point], line_width, colour)?;
                start_point = end_point;
            }
            '+' => heading += turn_angle,
            '-' => heading -= turn_angle,
            _ => panic!("Unknown char {}", char),
        }
    }
    let lines = line_builder.build(ctx)?;
    draw(ctx, &lines, (initial_point,))?;
    Ok(())
}

fn main() -> GameResult {
    let cb = ggez::ContextBuilder::new("dragon curve", "huw")
        .window_setup(WindowSetup::default().title("Dragon curve"))
        .window_mode(WindowMode::default().dimensions(WINDOW_WIDTH, WINDOW_HEIGHT));
    let (ctx, event_loop) = &mut cb.build()?;
    let state = &mut MainState::new()?;
    event::run(ctx, event_loop, state)
}


Draw a clock

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>

#define PI 3.14159265
const char * shades = " .:-*ca&#%@";

double dist(double x, double y, double x0, double y0) {
	double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0);

	if (l > 1) {
		x -= x0;
		y -= y0;
	} else if (l >= 0) {
		x -= l * x0;
		y -= l * y0;
	}
	return sqrt(x * x + y * y);
}

enum { sec = 0, min, hur };

void draw(int size)
{
#	define for_i for(int i = 0; i < size; i++)
#	define for_j for(int j = 0; j < size * 2; j++)

	double angle, cx = size / 2.;
	double sx[3], sy[3], sw[3];
	double fade[] = { 1, .35, .35 };
	struct timeval tv;
	struct tm *t;

	sw[sec] = size * .02;
	sw[min] = size * .03;
	sw[hur] = size * .05;

every_second:
	gettimeofday(&tv, 0);
	t = localtime(&tv.tv_sec);

	angle = t->tm_sec * PI / 30;
	sy[sec] = -cx * cos(angle);
	sx[sec] =  cx * sin(angle);

	angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI;
	sy[min] = -cx * cos(angle) * .8;
	sx[min] =  cx * sin(angle) * .8;

	angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI;
	sy[hur] = -cx * cos(angle) * .6;
	sx[hur] =  cx * sin(angle) * .6;

	printf("\033[s");
	for_i {
		printf("\033[%d;0H", i);
		double y = i - cx;
		for_j {
			double x = (j - 2 * cx) / 2;

			int pix = 0;

			for (int k = hur; k >= sec; k--) {
				double d = dist(x, y, sx[k], sy[k]);
				if (d < sw[k] - .5)
					pix = 10 * fade[k];
				else if (d < sw[k] + .5)
					pix = (5 + (sw[k] - d) * 10) * fade[k];
			}
			putchar(shades[pix]);
		}
	}
	printf("\033[u");

	fflush(stdout);
	sleep(1);
	goto every_second;
}

int main(int argc, char *argv[])
{
	int s;
	if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20;
	draw(s);
	return 0;
}

extern crate time;

use std::thread;
use std::time::Duration;

const TOP: &str = " ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀";
const BOT: &str = " ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀";

fn main() {
    let top: Vec<&str> = TOP.split_whitespace().collect();
    let bot: Vec<&str> = BOT.split_whitespace().collect();

    loop {
        let tm = &time::now().rfc822().to_string()[17..25];
        let top_str: String = tm.chars().map(|x| top[x as usize - '0' as usize]).collect();
        let bot_str: String = tm.chars().map(|x| bot[x as usize - '0' as usize]).collect();

        clear_screen();
        println!("{}", top_str);
        println!("{}", bot_str);

        thread::sleep(Duration::from_secs(1));
    }
}

fn clear_screen() {
    println!("{}[H{}[J", 27 as char, 27 as char);
}


Dutch national flag problem

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

#define NUMBALLS 5

int compar(const void *a, const void *b){
	char c1=*(const char*)a, c2=*(const char*)b;
	return c1-c2;
}

_Bool issorted(char *balls){
	int i,state;
	state=0;
	for(i=0;i<NUMBALLS;i++){
		if(balls[i]<state)return false;
		if(balls[i]>state)state=balls[i];
	}
	return true;
}

void printout(char *balls){
	int i;
	char str[NUMBALLS+1];
	for(i=0;i<NUMBALLS;i++)str[i]=balls[i]==0?'r':balls[i]==1?'w':'b';
	printf("%s\n",str);
}

int main(void) {
	char balls[NUMBALLS];
	int i;
	srand(time(NULL));
	rand();

	for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3;
	while(issorted(balls)){
		printf("Accidentally still sorted: ");
		printout(balls);
		for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3;
	}
	printf("Non-sorted: ");
	printout(balls);
	qsort(balls,NUMBALLS,sizeof(char),compar);
	if(issorted(balls)){
		printf("Sorted: ");
		printout(balls);
	} else {
		printf("Sort failed: ");
		printout(balls);
	}
	return 0;
}

extern crate rand;

use rand::Rng;

#[derive(Eq,Ord,PartialOrd,PartialEq,Debug)]
enum Color {
    Red,
    White,
    Blue
}

fn is_sorted(list: &Vec<Color>) -> bool {
    let mut state = &Color::Red;
    for current in list.iter() {
        if current < state { return false; }
        if current > state { state = current; }
    }
    true
}

fn main() {
    let mut rng = rand::thread_rng();
    let mut colors: Vec<Color> = Vec::new();

    for _ in 1..10 {
        let r = rng.gen_range(0, 3);
        if      r == 0 { colors.push(Color::Red); }
        else if r == 1 { colors.push(Color::White); }
        else if r == 2 { colors.push(Color::Blue); }
    }

    while is_sorted(&colors) {
        rng.shuffle(&mut colors);
    }

    println!("Before: {:?}", colors);
    colors.sort();
    println!("After:  {:?}", colors);
    if !is_sorted(&colors) {
        println!("Oops, did not sort colors correctly!");
    }
}


Echo server

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#define MAX_ENQUEUED 20
#define BUF_LEN 256
#define PORT_STR "12321"

void wait_for_zombie(int s)
{
    while(waitpid(-1, NULL, WNOHANG) > 0) ;
}

void echo_lines(int csock)
{
    char buf[BUF_LEN];
    int r;

    while( (r = read(csock, buf, BUF_LEN)) > 0 ) {
        (void)write(csock, buf, r);
    }
    exit(EXIT_SUCCESS);
}

void take_connections_forever(int ssock)
{
    for(;;) {
        struct sockaddr addr;
        socklen_t addr_size = sizeof(addr);
        int csock;

        csock = accept(ssock, &addr, &addr_size);

        if ( csock == -1 ) {
            perror("accept");
        } else if ( fork() == 0 ) {
            close(ssock);
            echo_lines(csock);
        } else {
            close(csock);
        }
    }
}

int main()
{
    struct addrinfo hints, *res;
    struct sigaction sa;
    int sock;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) {
        perror("getaddrinfo");
        exit(EXIT_FAILURE);
    }

    if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    sa.sa_handler = wait_for_zombie;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(res);

    if ( listen(sock, MAX_ENQUEUED) != 0 ) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    take_connections_forever(sock);
    return EXIT_SUCCESS;
}

use std::net::{TcpListener, TcpStream};
use std::io::{BufReader, BufRead, Write};
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:12321").unwrap();
    println!("server is running on 127.0.0.1:12321 ...");

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        thread::spawn(move || handle_client(stream));
    }
}

fn handle_client(stream: TcpStream) {
    let mut stream = BufReader::new(stream);
    loop {
        let mut buf = String::new();
        if stream.read_line(&mut buf).is_err() {
            break;
        }
        stream
            .get_ref()
            .write(buf.as_bytes())
            .unwrap();
    }
}


Egyptian division

'---Ported from the c code example to BaCon by bigbass

'==================================================================================
FUNCTION EGYPTIAN_DIVISION(long dividend, long divisor, long remainder) TYPE long
'==================================================================================
'--- remainder is the third  parameter, pass 0 if you do not need the remainder

DECLARE powers[64] TYPE long
DECLARE doublings[64] TYPE long

	LOCAL i TYPE long

	FOR i = 0 TO  63 STEP 1
		powers[i] = 1 << i
		doublings[i] = divisor << i
		IF (doublings[i] > dividend) THEN
			BREAK
		ENDIF
	NEXT

	LOCAL answer TYPE long
	LOCAL accumulator TYPE long
	answer = 0
	accumulator = 0

	WHILE i >= 0
		'--- If the current value of the accumulator added to the
		'--- doublings cell would be less than or equal to the
		'--- dividend then add it to the accumulator
		IF (accumulator + doublings[i] <= dividend) THEN
			accumulator = accumulator + doublings[i]
			answer = answer + powers[i]
		ENDIF
		DECR i
	WEND

	IF remainder THEN
		remainder = dividend - accumulator
		PRINT dividend ," / ", divisor, " = " , answer ," remainder " , remainder

        PRINT "Decoded the answer to a standard fraction"
        PRINT  (remainder + 0.0 )/ (divisor + 0.0) + answer
        PRINT

	ELSE
		PRINT dividend ," / ", divisor , " = " , answer
	ENDIF

	RETURN answer

ENDFUNCTION

	'--- the large number divided by the smaller number
	'--- the third argument is 1 if you want to have a remainder
	'--- and 0 if you dont want to have a remainder

	EGYPTIAN_DIVISION(580,34,1)
	EGYPTIAN_DIVISION(580,34,0)

EGYPTIAN_DIVISION(580,34,1)

fn egyptian_divide(dividend: u32, divisor: u32) -> (u32, u32) {
    let dividend = dividend as u64;
    let divisor = divisor as u64;

    let pows = (0..32).map(|p| 1 << p);
    let doublings = (0..32).map(|p| divisor << p);

    let (answer, sum) = doublings
        .zip(pows)
        .rev()
        .skip_while(|(i, _)| i > &dividend )
        .fold((0, 0), |(answer, sum), (double, power)| {
            if sum + double < dividend {
                (answer + power, sum + double)
            } else {
                (answer, sum)
            }
        });

    (answer as u32, (dividend - sum) as u32)
}

fn main() {
    let (div, rem) = egyptian_divide(580, 34);
    println!("580 divided by 34 is {} remainder {}", div, rem);
}


Element-wise operations

#include <math.h>

#define for_i for(i = 0; i < h; i++)
#define for_j for(j = 0; j < w; j++)
#define _M double**
#define OPM(name, _op_) \
	void eop_##name(_M a, _M b, _M c, int w, int h){int i,j;\
		for_i for_j c[i][j] = a[i][j] _op_ b[i][j];}
OPM(add, +);OPM(sub, -);OPM(mul, *);OPM(div, /);

#define OPS(name, res) \
	void eop_s_##name(_M a, double s, _M b, int w, int h) {double x;int i,j;\
		for_i for_j {x = a[i][j]; b[i][j] = res;}}
OPS(mul, x*s);OPS(div, x/s);OPS(add, x+s);OPS(sub, x-s);OPS(pow, pow(x, s));

struct Matrix {
    elements: Vec<f32>,
    pub height: u32,
    pub width: u32,
}

impl Matrix {
    fn new(elements: Vec<f32>, height: u32, width: u32) -> Matrix {

        Matrix {
            elements: elements,
            height: height,
            width: width,
        }
    }

    fn get(&self, row: u32, col: u32) -> f32 {
        let row = row as usize;
        let col = col as usize;
        self.elements[col + row * (self.width as usize)]
    }

    fn set(&mut self, row: u32, col: u32, value: f32) {
        let row = row as usize;
        let col = col as usize;
        self.elements[col + row * (self.width as usize)] = value;
    }

    fn print(&self) {
        for row in 0..self.height {
            for col in 0..self.width {
                print!("{:3.0}", self.get(row, col));
            }
            println!("");
        }
        println!("");
    }
}

fn matrix_addition(first: &Matrix, second: &Matrix) -> Result<Matrix, String> {
    if first.width == second.width && first.height == second.height {
        let mut result = Matrix::new(vec![0.0f32; (first.height * first.width) as usize],
                                     first.height,
                                     first.width);
        for row in 0..first.height {
            for col in 0..first.width {
                let first_value = first.get(row, col);
                let second_value = second.get(row, col);
                result.set(row, col, first_value + second_value);
            }
        }
        Ok(result)
    } else {
        Err("Dimensions don't match".to_owned())
    }
}

fn scalar_multiplication(scalar: f32, matrix: &Matrix) -> Matrix {
    let mut result = Matrix::new(vec![0.0f32; (matrix.height * matrix.width) as usize],
                                 matrix.height,
                                 matrix.width);
    for row in 0..matrix.height {
        for col in 0..matrix.width {
            let value = matrix.get(row, col);
            result.set(row, col, scalar * value);
        }
    }
    result
}

fn matrix_subtraction(first: &Matrix, second: &Matrix) -> Result<Matrix, String> {
    if first.width == second.width && first.height == second.height {
        let negative_matrix = scalar_multiplication(-1.0, second);
        let result = matrix_addition(first, &negative_matrix).unwrap();
        Ok(result)
    } else {
        Err("Dimensions don't match".to_owned())
    }
}

fn matrix_multiplication(first: &Matrix, second: &Matrix) -> Result<Matrix, String> {
    if first.width == second.height {
        let mut result = Matrix::new(vec![0.0f32; (first.height * second.width) as usize],
                                     first.height,
                                     second.width);
        for row in 0..result.height {
            for col in 0..result.width {
                let mut value = 0.0;
                for it in 0..first.width {
                    value += first.get(row, it) * second.get(it, col);
                }
                result.set(row, col, value);
            }
        }
        Ok(result)
    } else {
        Err("Dimensions don't match. Width of first must equal height of second".to_owned())
    }
}

fn main() {
    let height = 2;
    let width = 3;

    let matrix1 = Matrix::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], height, width);

    let matrix2 = Matrix::new(vec![6.0, 5.0, 4.0, 3.0, 2.0, 1.0], height, width);

    matrix_addition(&matrix1, &matrix2).unwrap().print();

    scalar_multiplication(2.0, &matrix1).print();

    matrix_subtraction(&matrix1, &matrix2).unwrap().print();

    let matrix3 = Matrix::new(vec![1.0, 1.0, 1.0], width, 1);

    matrix_multiplication(&matrix1, &matrix3).unwrap().print();
}


Elementary cellular automaton

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

typedef unsigned long long ull;
#define N  (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))

void evolve(ull state, int rule)
{
	int i;
	ull st;

	printf("Rule %d:\n", rule);
	do {
		st = state;
		for (i = N; i--; ) putchar(st & B(i) ? '#' : '.');
		putchar('\n');

		for (state = i = 0; i < N; i++)
			if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
				state |= B(i);
	} while (st != state);
}

int main(int argc, char **argv)
{
	evolve(B(N/2), 90);
	evolve(B(N/4)|B(N - N/4), 30);

	return 0;
}

fn main() {
    struct ElementaryCA {
        rule: u8,
        state: u64,
    }
    impl ElementaryCA {
        fn new(rule: u8) -> (u64, ElementaryCA) {
            let out = ElementaryCA {
                rule,
                state: 1,
            };
            (out.state, out)
        }
        fn next(&mut self) -> u64 {
            let mut next_state = 0u64;
            let state = self.state;
            for i in 0..64 {
                next_state |= (((self.rule as u64)>>(7 & (state.rotate_left(1).rotate_right(i as u32)))) & 1)<<i;
            }
            self.state = next_state;
            self.state
        }
    }
    fn rep_u64(val: u64) -> String {
        let mut out = String::new();
        for i in (0..64).rev() {
            if 1<<i & val != 0 {
                out = out + "\u{2588}";
            } else {
                out = out + "-";
            }
        }
        out
    }

    let (i, mut thirty) = ElementaryCA::new(154);
    println!("{}",rep_u64(i));
    for _ in 0..32 {
        let s = thirty.next();
        println!("{}", rep_u64(s));
    }
}


Empty directory

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

int dir_empty(const char *path)
{
	struct dirent *ent;
	int ret = 1;

	DIR *d = opendir(path);
	if (!d) {
		fprintf(stderr, "%s: ", path);
		perror("");
		return -1;
	}

	while ((ent = readdir(d))) {
		if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, "..")))
			continue;
		ret = 0;
		break;
	}

	closedir(d);
	return ret;
}

int main(int c, char **v)
{
	int ret = 0, i;
	if (c < 2) return -1;

	for (i = 1; i < c; i++) {
		ret = dir_empty(v[i]);
		if (ret >= 0)
			printf("%s: %sempty\n", v[i], ret ? "" : "not ");
	}

	return 0;
}

use std::fs::read_dir;
use std::error::Error;

fn main() {
    for path in std::env::args().skip(1) {
        match read_dir(path.as_str()) {
            Ok(contents) => {
                let len = contents.collect::<Vec<_>>().len();
                if len == 0 {
                    println!("{} is empty", path);
                } else {
                    println!("{} is not empty", path);
                }
            },
            Err(e) => {
                println!("Failed to read directory \"{}\": {}", path, e.description());
            }
        }
    }
}


Empty string

let s = "";
println!("is empty: {}", s.is_empty());
let t = "x";
println!("is empty: {}", t.is_empty());
let a = String::new();
println!("is empty: {}", a.is_empty());
let b = "x".to_string();
println!("is empty: {}", b.is_empty());
println!("is not empty: {}", !b.is_empty());


Entropy

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

#define MAXLEN 100

int makehist(unsigned char *S,int *hist,int len){
	int wherechar[256];
	int i,histlen;
	histlen=0;
	for(i=0;i<256;i++)wherechar[i]=-1;
	for(i=0;i<len;i++){
		if(wherechar[(int)S[i]]==-1){
			wherechar[(int)S[i]]=histlen;
			histlen++;
		}
		hist[wherechar[(int)S[i]]]++;
	}
	return histlen;
}

double entropy(int *hist,int histlen,int len){
	int i;
	double H;
	H=0;
	for(i=0;i<histlen;i++){
		H-=(double)hist[i]/len*log2((double)hist[i]/len);
	}
	return H;
}

int main(void){
	unsigned char S[MAXLEN];
	int len,*hist,histlen;
	double H;
	scanf("%[^\n]",S);
	len=strlen(S);
	hist=(int*)calloc(len,sizeof(int));
	histlen=makehist(S,hist,len);

	H=entropy(hist,histlen,len);
	printf("%lf\n",H);
	return 0;
}

fn entropy(s: &[u8]) -> f32 {
    let mut histogram = [0u64; 256];

    for &b in s {
        histogram[b as usize] += 1;
    }

    histogram
        .iter()
        .cloned()
        .filter(|&h| h != 0)
        .map(|h| h as f32 / s.len() as f32)
        .map(|ratio| -ratio * ratio.log2())
        .sum()
}

fn main() {
    let arg = std::env::args().nth(1).expect("Need a string.");
    println!("Entropy of {} is {}.", arg, entropy(arg.as_bytes()));
}


Enumerations

enum fruits { apple, banana, cherry };

enum fruits { apple = 0, banana = 1, cherry = 2 };

enum Fruits {
    Apple,
    Banana,
    Cherry
}

enum FruitsWithNumbers {
    Strawberry = 0,
    Pear = 27,
}

fn main() {

    println!("{}", FruitsWithNumbers::Pear as u8);
}


Environment variables

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

int main() {
  puts(getenv("HOME"));
  puts(getenv("PATH"));
  puts(getenv("USER"));
  return 0;
}

use std::env;

fn main() {
    println!("{:?}", env::var("HOME"));
    println!();
    for (k, v) in env::vars().filter(|(k, _)| k.starts_with('P')) {
        println!("{}: {}", k, v);
    }
}


Equilibrium index

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

int list[] = {-7, 1, 5, 2, -4, 3, 0};

int eq_idx(int *a, int len, int **ret)
{
	int i, sum, s, cnt;

        cnt = s = sum = 0;
	*ret = malloc(sizeof(int) * len);

	for (i = 0; i < len; i++)
                sum += a[i];

	for (i = 0; i < len; i++) {
		if (s * 2 + a[i] == sum) {
			(*ret)[cnt] = i;
                        cnt++;
                }
		s += a[i];
	}

	*ret = realloc(*ret, cnt * sizeof(int));

	return cnt;
}

int main()
{
	int i, cnt, *idx;
	cnt = eq_idx(list, sizeof(list) / sizeof(int), &idx);

	printf("Found:");
	for (i = 0; i < cnt; i++)
                printf(" %d", idx[i]);
	printf("\n");

	return 0;
}

extern crate num;

use num::traits::Zero;

fn equilibrium_indices(v: &[i32]) -> Vec<usize> {
    let mut right = v.iter().sum();
    let mut left = i32::zero();

    v.iter().enumerate().fold(vec![], |mut out, (i, &el)| {
        right -= el;
        if left == right {
            out.push(i);
        }
        left += el;

        out
    })
}

fn main() {
    let v = [-7i32, 1, 5, 2, -4, 3, 0];
    let indices = equilibrium_indices(&v);
    println!("Equilibrium indices for {:?} are: {:?}", v, indices);
}


Ethiopian multiplication

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

void halve(int *x) { *x >>= 1; }
void doublit(int *x)  { *x <<= 1; }
bool iseven(const int x) { return (x & 1) ==  0; }

int ethiopian(int plier,
	      int plicand, const bool tutor)
{
  int result=0;

  if (tutor)
    printf("ethiopian multiplication of %d by %d\n", plier, plicand);

  while(plier >= 1) {
    if ( iseven(plier) ) {
      if (tutor) printf("%4d %6d struck\n", plier, plicand);
    } else {
      if (tutor) printf("%4d %6d kept\n", plier, plicand);
      result += plicand;
    }
    halve(&plier); doublit(&plicand);
  }
  return result;
}

int main()
{
  printf("%d\n", ethiopian(17, 34, true));
  return 0;
}

fn double(a: i32) -> i32 {
    2*a
}

fn halve(a: i32) -> i32 {
    a/2
}

fn is_even(a: i32) -> bool {
    a % 2 == 0
}

fn ethiopian_multiplication(mut x: i32, mut y: i32) -> i32 {
    let mut sum = 0;

    while x >= 1 {
        print!("{} \t {}", x, y);
        match is_even(x) {
            true  => println!("\t Not Kept"),
            false => {
                println!("\t Kept");
                sum += y;
            }
        }
        x = halve(x);
        y = double(y);
    }
    sum
}

fn main() {
    let output = ethiopian_multiplication(17, 34);
    println!("---------------------------------");
    println!("\t {}", output);
}


Euler method

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

typedef double (*deriv_f)(double, double);
#define FMT " %7.3f"

void ivp_euler(deriv_f f, double y, int step, int end_t)
{
	int t = 0;

	printf(" Step %2d: ", (int)step);
	do {
		if (t % 10 == 0) printf(FMT, y);
		y += step * f(t, y);
	} while ((t += step) <= end_t);
	printf("\n");
}

void analytic()
{
	double t;
	printf("    Time: ");
	for (t = 0; t <= 100; t += 10) printf(" %7g", t);
	printf("\nAnalytic: ");

	for (t = 0; t <= 100; t += 10)
		printf(FMT, 20 + 80 * exp(-0.07 * t));
	printf("\n");
}

double cooling(double t, double temp)
{
	return -0.07 * (temp - 20);
}

int main()
{
	analytic();
	ivp_euler(cooling, 100, 2, 100);
	ivp_euler(cooling, 100, 5, 100);
	ivp_euler(cooling, 100, 10, 100);

	return 0;
}


Euler's identity

#include <stdio.h>
#include <math.h>
#include <complex.h>
#include <wchar.h>
#include <locale.h>

int main() {
    wchar_t pi = L'\u03c0';
    wchar_t ae = L'\u2245';
    double complex e = cexp(M_PI * I) + 1.0;
    setlocale(LC_CTYPE, "");
    printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae);
    return 0;
}

use std::f64::consts::PI;

extern crate num_complex;
use num_complex::Complex;

fn main() {
    println!("{:e}", Complex::new(0.0, PI).exp() + 1.0);
}


Euler's sum of powers conjecture

#include <stdio.h>
#include <time.h>
typedef long long mylong;

void compute(int N, char find_only_one_solution)
{	const int M = 30;
	int a, b, c, d, e;
	mylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M));

	for(s=0; s < N; ++s)
		p5[s] = s * s, p5[s] *= p5[s] * s;
	for(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1);

	for(a = 1; a < N; ++a)
	for(b = a + 1; b < N; ++b)
	for(c = b + 1; c < N; ++c)
	for(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e)
	{	for(e -= M; p5[e + M] <= s; e += M);
		if(p5[e] == s)
		{	printf("%d %d %d %d %d\r\n", a, b, c, d, e);
			if(find_only_one_solution) goto onexit;
		}
	}
onexit:
	free(p5);
}

int main(void)
{
	int tm = clock();
	compute(250, 0);
	printf("time=%d milliseconds\r\n", (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC));
	return 0;
}

const MAX_N : u64 = 250;

fn eulers_sum_of_powers() -> (usize, usize, usize, usize, usize) {
    let pow5: Vec<u64> = (0..MAX_N).map(|i| i.pow(5)).collect();
    let pow5_to_n = |pow| pow5.binary_search(&pow);

    for x0 in 1..MAX_N as usize {
        for x1 in 1..x0 {
            for x2 in 1..x1 {
                for x3 in 1..x2 {
                    let pow_sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3];
                    if let Ok(n) = pow5_to_n(pow_sum) {
                        return (x0, x1, x2, x3, n)
                    }
                }
            }
        }
    }

    panic!();
}

fn main() {
	let (x0, x1, x2, x3, y) = eulers_sum_of_powers();
	println!("{}^5 + {}^5 + {}^5 + {}^5 == {}^5", x0, x1, x2, x3, y)
}


Evaluate binomial coefficients

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

static unsigned long gcd_ui(unsigned long x, unsigned long y) {
  unsigned long t;
  if (y < x) { t = x; x = y; y = t; }
  while (y > 0) {
    t = y;  y = x % y;  x = t;
  }
  return x;
}

unsigned long binomial(unsigned long n, unsigned long k) {
  unsigned long d, g, r = 1;
  if (k == 0) return 1;
  if (k == 1) return n;
  if (k >= n) return (k == n);
  if (k > n/2) k = n-k;
  for (d = 1; d <= k; d++) {
    if (r >= ULONG_MAX/n) {
      unsigned long nr, dr;
      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;
      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;
      if (r >= ULONG_MAX/nr) return 0;
      r *= nr;
      r /= dr;
      n--;
    } else {
      r *= n--;
      r /= d;
    }
  }
  return r;
}

int main() {
    printf("%lu\n", binomial(5, 3));
    printf("%lu\n", binomial(40, 19));
    printf("%lu\n", binomial(67, 31));
    return 0;
}

fn fact(n:u32) -> u64 {
  let mut f:u64 = n as u64;
  for i in 2..n {
    f *= i as u64;
  }
  return f;
}

fn choose(n: u32, k: u32)  -> u64 {
   let mut num:u64 = n as u64;
   for i in 1..k {
     num *= (n-i) as u64;
   }
   return num / fact(k);
}

fn main() {
  println!("{}", choose(5,3));
}


Events

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

int main()
{
	int p[2];
	pipe(p);
	if (fork()) {
		close(p[0]);
		sleep(1);
		write(p[1], p, 1);
		wait(0);
	} else {
		close(p[1]);
		read(p[0], p + 1, 1);
		puts("received signal from pipe");
	}
	return 0;
}

use std::{sync::mpsc, thread, time::Duration};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("[1] Starting");
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        println!("[2] Waiting for event");
        rx.recv();
        println!("[2] Received event");
    });
    thread::sleep(Duration::from_secs(1));
    println!("[1] Sending event");
    tx.send(())?;
    thread::sleep(Duration::from_secs(1));

    Ok(())
}


Evolutionary algorithm

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

const char target[] = "METHINKS IT IS LIKE A WEASEL";
const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";

#define CHOICE (sizeof(tbl) - 1)
#define MUTATE 15
#define COPIES 30

int irand(int n)
{
	int r, rand_max = RAND_MAX - (RAND_MAX % n);
	while((r = rand()) >= rand_max);
	return r / (rand_max / n);
}

int unfitness(const char *a, const char *b)
{
	int i, sum = 0;
	for (i = 0; a[i]; i++)
		sum += (a[i] != b[i]);
	return sum;
}

void mutate(const char *a, char *b)
{
	int i;
	for (i = 0; a[i]; i++)
		b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)];

	b[i] = '\0';
}

int main()
{
	int i, best_i, unfit, best, iters = 0;
	char specimen[COPIES][sizeof(target) / sizeof(char)];

	for (i = 0; target[i]; i++)
		specimen[0][i] = tbl[irand(CHOICE)];
	specimen[0][i] = 0;

	do {
		for (i = 1; i < COPIES; i++)
			mutate(specimen[0], specimen[i]);

		for (best_i = i = 0; i < COPIES; i++) {
			unfit = unfitness(target, specimen[i]);
			if(unfit < best || !i) {
				best = unfit;
				best_i = i;
			}
		}

		if (best_i) strcpy(specimen[0], specimen[best_i]);
		printf("iter %d, score %d: %s\n", iters++, best, specimen[0]);
	} while (best);

	return 0;
}

extern crate rand;

use rand::Rng;

fn main() {
    let target = "METHINKS IT IS LIKE A WEASEL";
    let copies = 100;
    let mutation_rate = 20;

    let mut rng = rand::weak_rng();

    let start = mutate(&mut rng, target, 1);

    println!("{}", target);
    println!("{}", start);

    evolve(&mut rng, target, start, copies, mutation_rate);
}

fn evolve<R: Rng>(
    rng: &mut R,
    target: &str,
    mut parent: String,
    copies: usize,
    mutation_rate: u32,
) -> usize {
    let mut counter = 0;
    let mut parent_fitness = target.len() + 1;

    loop {
        counter += 1;

        let (best_fitness, best_sentence) = (0..copies)
            .map(|_| {

                let sentence = mutate(rng, &parent, mutation_rate);

                (fitness(target, &sentence), sentence)
            })
            .min_by_key(|&(f, _)| f)
            .unwrap();

        if best_fitness < parent_fitness {
            parent = best_sentence;
            parent_fitness = best_fitness;
            println!(
                "{} : generation {} with fitness {}",
                parent, counter, best_fitness
            );

            if best_fitness == 0 {
                return counter;
            }
        }
    }
}

fn fitness(target: &str, sentence: &str) -> usize {
    sentence
        .chars()
        .zip(target.chars())
        .filter(|&(c1, c2)| c1 != c2)
        .count()
}

fn mutate<R: Rng>(rng: &mut R, sentence: &str, mutation_rate: u32) -> String {
    let maybe_mutate = |c| {
        if rng.gen_weighted_bool(mutation_rate) {
            random_char(rng)
        } else {
            c
        }
    };
    sentence.chars().map(maybe_mutate).collect()
}

fn random_char<R: Rng>(rng: &mut R) -> char {

    match rng.gen_range(b'A', b'Z' + 2) {
        c if c == b'Z' + 1 => ' ',
        c => c as char,
    }
}


Exceptions_Catch an exception thrown in a nested call

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

typedef struct exception {
        int extype;
        char what[128];
} exception;

typedef struct exception_ctx {
        exception * exs;
        int size;
        int pos;
} exception_ctx;

exception_ctx * Create_Ex_Ctx(int length) {
        const int safety = 8;
        char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length);
        if (! tmp) return NULL;
        exception_ctx * ctx = (exception_ctx*)tmp;
        ctx->size = length;
        ctx->pos = -1;
        ctx->exs = (exception*) (tmp + sizeof(exception_ctx));
        return ctx;
}

void Free_Ex_Ctx(exception_ctx * ctx) {
        free(ctx);
}

int Has_Ex(exception_ctx * ctx) {
        return (ctx->pos >= 0) ? 1 : 0;
}

int Is_Ex_Type(exception_ctx * exctx, int extype) {
        return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0;
}

void Pop_Ex(exception_ctx * ctx) {
        if (ctx->pos >= 0) --ctx->pos;
}

const char * Get_What(exception_ctx * ctx) {
        if (ctx->pos >= 0) return ctx->exs[ctx->pos].what;
        return NULL;
}

int Push_Ex(exception_ctx * exctx, int extype, const char * msg) {
        if (++exctx->pos == exctx->size) {

                --exctx->pos;
                fprintf(stderr, "*** Error: Overflow in exception context.\n");
        }
        snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), "%s", msg);
        exctx->exs[exctx->pos].extype = extype;
        return -1;
}

exception_ctx * GLOBALEX = NULL;
enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR };

void baz(int n) {
        if (! n) {
                Push_Ex(GLOBALEX, U0_DRINK_ERROR , "U0 Drink Error. Insufficient drinks in bar Baz.");
                return;
        }
        else {
                Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , "U1 Bartender Error. Bartender kicked customer out of bar Baz.");
                return;
        }
}

void bar(int n) {
        fprintf(stdout, "Bar door is open.\n");
        baz(n);
        if (Has_Ex(GLOBALEX)) goto bar_cleanup;
        fprintf(stdout, "Baz has been called without errors.\n");
bar_cleanup:
        fprintf(stdout, "Bar door is closed.\n");
}

void foo() {
        fprintf(stdout, "Foo entering bar.\n");
        bar(0);
        while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) {
                fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX));
                Pop_Ex(GLOBALEX);
        }
        if (Has_Ex(GLOBALEX)) return;
        fprintf(stdout, "Foo left the bar.\n");
        fprintf(stdout, "Foo entering bar again.\n");
        bar(1);
        while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) {
                fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX));
                Pop_Ex(GLOBALEX);
        }
        if (Has_Ex(GLOBALEX)) return;
        fprintf(stdout, "Foo left the bar.\n");
}

int main(int argc, char ** argv) {
        exception_ctx * ctx = Create_Ex_Ctx(5);
        GLOBALEX = ctx;

        foo();
        if (Has_Ex(ctx)) goto main_ex;

        fprintf(stdout, "No errors encountered.\n");

main_ex:
        while (Has_Ex(ctx)) {
                fprintf(stderr, "*** Error: %s\n", Get_What(ctx));
                Pop_Ex(ctx);
        }
        Free_Ex_Ctx(ctx);
        return 0;
}

#[derive(Debug)]
enum U {
    U0(i32),
    U1(String),
}

fn baz(i: u8) -> Result<(), U> {
    match i {
        0 => Err(U::U0(42)),
        1 => Err(U::U1("This will be returned from main".into())),
        _ => Ok(()),
    }
}

fn bar(i: u8) -> Result<(), U> {
    baz(i)
}

fn foo() -> Result<(), U> {
    for i in 0..2 {
        match bar(i) {
            Ok(()) => {},
            Err(U::U0(n)) => eprintln!("Caught U0 in foo: {}", n),
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

fn main() -> Result<(), U> {
    foo()
}


Execute a system command

#include <stdlib.h>

int main()
{
    system("ls");
    return 0;
}

use std::process::Command;
fn main() {
    let output = Command::new("ls").output().unwrap_or_else(|e| {
        panic!("failed to execute process: {}", e)
    });
    println!("{}", String::from_utf8_lossy(&output.stdout));
}


Exponentiation operator

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

int ipow(int base, int exp)
{
   int pow = base;
   int v = 1;
   if (exp < 0) {
      assert (base != 0);
      return (base*base != 1)? 0: (exp&1)? base : 1;
   }

   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
    }
   return v;
}

double dpow(double base, int exp)
{
   double v=1.0;
   double pow = (exp <0)? 1.0/base : base;
   if (exp < 0) exp = - exp;

   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
   }
   return v;
}

int main()
{
    printf("2^6 = %d\n", ipow(2,6));
    printf("2^-6 = %d\n", ipow(2,-6));
    printf("2.71^6 = %lf\n", dpow(2.71,6));
    printf("2.71^-6 = %lf\n", dpow(2.71,-6));
}

extern crate num;
use num::traits::One;
use std::ops::Mul;

fn pow<T>(mut base: T, mut exp: usize) -> T
    where T: Clone + One + Mul<T, Output=T>
{
    if exp == 0 { return T::one() }
    while exp & 1 == 0 {
        base = base.clone() * base;
        exp >>= 1;
    }
    if exp == 1 { return base }
    let mut acc = base.clone();

    while exp > 1 {
        exp >>= 1;
        base = base.clone() * base;
        if exp & 1 == 1 {
            acc = acc * base.clone();
        }
    }
    acc
}


Exponentiation order

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

int main()
{
    printf("(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2));
    printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2)));

    return 0;
}


Extend your language

#define if2(firsttest,secondtest,bothtrue,firsttrue,secondtrue,bothfalse)\
	switch(((firsttest)?0:2)+((secondtest)?0:1)) {\
		case 0: bothtrue; break;\
		case 1: firsttrue; break;\
		case 2: secondtrue; break;\
		case 3: bothfalse; break;\
	}

#![allow(unused_variables)]
macro_rules! if2 {
    ($cond1: expr, $cond2: expr
        => $both:expr
        => $first: expr
        => $second:expr
        => $none:expr)
    => {
        match ($cond1, $cond2) {
            (true, true) => $both,
            (true, _   ) => $first,
            (_   , true) => $second,
            _            => $none
        }
    }
}

fn main() {
    let i = 1;
    let j = 2;
    if2!(i > j, i + j >= 3
        => {

            let k = i + j;
            println!("both were true")
        }
        => println!("the first was true")
        => println!("the second was true")
        => println!("neither were true")
    )
}


Factorial

int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; ++i)
        result *= i;
    return result;
}

fn factorial_recursive (n: u64) -> u64 {
    match n {
        0 => 1,
        _ => n * factorial_recursive(n-1)
    }
}

fn factorial_iterative(n: u64) -> u64 {
    (1..=n).product()
}

fn main () {
    for i in 1..10 {
        println!("{}", factorial_recursive(i))
    }
    for i in 1..10 {
        println!("{}", factorial_iterative(i))
    }
}


Factors of a Mersenne number

int isPrime(int n){
	if (n%2==0) return n==2;
	if (n%3==0) return n==3;
	int d=5;
	while(d*d<=n){
		if(n%d==0) return 0;
		d+=2;
		if(n%d==0) return 0;
		d+=4;}
	return 1;}

main() {int i,d,p,r,q=929;
	if (!isPrime(q)) return 1;
	r=q;
	while(r>0) r<<=1;
	d=2*q+1;
	do { 	for(p=r, i= 1; p; p<<= 1){
			i=((long long)i * i) % d;
			if (p < 0) i *= 2;
			if (i > d) i -= d;}
		if (i != 1) d += 2*q;
		else break;
	} while(1);
	printf("2^%d - 1 = 0 (mod %d)\n", q, d);}

fn bit_count(mut n: usize) -> usize {
    let mut count = 0;
    while n > 0 {
        n >>= 1;
        count += 1;
    }
    count
}

fn mod_pow(p: usize, n: usize) -> usize {
    let mut square = 1;
    let mut bits = bit_count(p);
    while bits > 0 {
        square = square * square;
        bits -= 1;
        if (p & (1 << bits)) != 0 {
            square <<= 1;
        }
        square %= n;
    }
    return square;
}

fn is_prime(n: usize) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }
    if n % 3 == 0 {
        return n == 3;
    }
    let mut p = 5;
    while p * p <= n {
        if n % p == 0 {
            return false;
        }
        p += 2;
        if n % p == 0 {
            return false;
        }
        p += 4;
    }
    true
}

fn find_mersenne_factor(p: usize) -> usize {
    let mut k = 0;
    loop {
        k += 1;
        let q = 2 * k * p + 1;
        if q % 8 == 1 || q % 8 == 7 {
            if mod_pow(p, q) == 1 && is_prime(p) {
                return q;
            }
        }
    }
}

fn main() {
    println!("{}", find_mersenne_factor(929));
}


Factors of an integer

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

typedef struct {
    int *list;
    short count;
} Factors;

void xferFactors( Factors *fctrs, int *flist, int flix )
{
    int ix, ij;
    int newSize = fctrs->count + flix;
    if (newSize > flix)  {
        fctrs->list = realloc( fctrs->list, newSize * sizeof(int));
    }
    else {
        fctrs->list = malloc(  newSize * sizeof(int));
    }
    for (ij=0,ix=fctrs->count; ix<newSize; ij++,ix++) {
        fctrs->list[ix] = flist[ij];
    }
    fctrs->count = newSize;
}

Factors *factor( int num, Factors *fctrs)
{
    int flist[301], flix;
    int dvsr;
    flix = 0;
    fctrs->count = 0;
    free(fctrs->list);
    fctrs->list = NULL;
    for (dvsr=1; dvsr*dvsr < num; dvsr++) {
        if (num % dvsr != 0) continue;
        if ( flix == 300) {
            xferFactors( fctrs, flist, flix );
            flix = 0;
        }
        flist[flix++] = dvsr;
        flist[flix++] = num/dvsr;
    }
    if (dvsr*dvsr == num)
        flist[flix++] = dvsr;
    if (flix > 0)
        xferFactors( fctrs, flist, flix );

    return fctrs;
}

int main(int argc, char*argv[])
{
    int nums2factor[] = { 2059, 223092870, 3135, 45 };
    Factors ftors = { NULL, 0};
    char sep;
    int i,j;

    for (i=0; i<4; i++) {
        factor( nums2factor[i], &ftors );
        printf("\nfactors of %d are:\n  ", nums2factor[i]);
        sep = ' ';
        for (j=0; j<ftors.count; j++) {
            printf("%c %d", sep, ftors.list[j]);
            sep = ',';
        }
        printf("\n");
    }
    return 0;
}

fn main() {
    assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100));
    assert_eq!(vec![1, 101], factor(101));

}

fn factor(num: i32) -> Vec<i32> {
    let mut factors: Vec<i32> = Vec::new();

    for i in 1..((num as f32).sqrt() as i32 + 1) {
        if num % i == 0 {
            factors.push(i);
            factors.push(num/i);
        }
    }
    factors.sort();
    factors
}


Fast Fourier transform

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

double PI;
typedef double complex cplx;

void _fft(cplx buf[], cplx out[], int n, int step)
{
	if (step < n) {
		_fft(out, buf, n, step * 2);
		_fft(out + step, buf + step, n, step * 2);

		for (int i = 0; i < n; i += 2 * step) {
			cplx t = cexp(-I * PI * i / n) * out[i + step];
			buf[i / 2]     = out[i] + t;
			buf[(i + n)/2] = out[i] - t;
		}
	}
}

void fft(cplx buf[], int n)
{
	cplx out[n];
	for (int i = 0; i < n; i++) out[i] = buf[i];

	_fft(buf, out, n, 1);
}

void show(const char * s, cplx buf[]) {
	printf("%s", s);
	for (int i = 0; i < 8; i++)
		if (!cimag(buf[i]))
			printf("%g ", creal(buf[i]));
		else
			printf("(%g, %g) ", creal(buf[i]), cimag(buf[i]));
}

int main()
{
	PI = atan2(1, 1) * 4;
	cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0};

	show("Data: ", buf);
	fft(buf, 8);
	show("\nFFT : ", buf);

	return 0;
}

extern crate num;
use num::complex::Complex;
use std::f64::consts::PI;

const I: Complex<f64> = Complex { re: 0.0, im: 1.0 };

pub fn fft(input: &[Complex<f64>]) -> Vec<Complex<f64>> {
    fn fft_inner(
        buf_a: &mut [Complex<f64>],
        buf_b: &mut [Complex<f64>],
        n: usize,
        step: usize,
    ) {
        if step >= n {
            return;
        }

        fft_inner(buf_b, buf_a, n, step * 2);
        fft_inner(&mut buf_b[step..], &mut buf_a[step..], n, step * 2);

        let (left, right) = buf_a.split_at_mut(n / 2);

        for i in (0..n).step_by(step * 2) {
            let t = (-I * PI * (i as f64) / (n as f64)).exp() * buf_b[i + step];
            left[i / 2] = buf_b[i] + t;
            right[i / 2] = buf_b[i] - t;
        }
    }

    let n_orig = input.len();
    let n = n_orig.next_power_of_two();

    let mut buf_a = input.to_vec();

    buf_a.append(&mut vec![Complex { re: 0.0, im: 0.0 }; n - n_orig]);

    let mut buf_b = buf_a.clone();
    fft_inner(&mut buf_a, &mut buf_b, n, 1);
    buf_a
}

fn show(label: &str, buf: &[Complex<f64>]) {
    println!("{}", label);
    let string = buf
        .into_iter()
        .map(|x| format!("{:.4}{:+.4}i", x.re, x.im))
        .collect::<Vec<_>>()
        .join(", ");
    println!("{}", string);
}

fn main() {
    let input: Vec<_> = [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
        .into_iter()
        .map(|x| Complex::from(x))
        .collect();
    show("input:", &input);
    let output = fft(&input);
    show("output:", &output);
}


Fibonacci n-step number sequences

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

int *
anynacci (int *seedArray, int howMany)
{
  int *result = malloc (howMany * sizeof (int));
  int i, j, initialCardinality;

  for (i = 0; seedArray[i] != 0; i++);
  initialCardinality = i;

  for (i = 0; i < initialCardinality; i++)
    result[i] = seedArray[i];

  for (i = initialCardinality; i < howMany; i++)
    {
      result[i] = 0;
      for (j = i - initialCardinality; j < i; j++)
        result[i] += result[j];
    }
  return result;
}

int
main ()
{
  int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 };
  int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10),
      *lucas = anynacci(luca, 10);
  int i;

  printf ("\nFibonacci\tTribonacci\tTetranacci\tLucas\n");

  for (i = 0; i < 10; i++)
    printf ("\n%d\t\t%d\t\t%d\t\t%d", fibonacci[i], tribonacci[i],
            tetranacci[i], lucas[i]);

  return 0;
}

struct GenFibonacci {
    buf:    Vec<u64>,
    sum:    u64,
    idx:    usize,
}

impl Iterator for GenFibonacci {
    type Item = u64;
    fn next(&mut self) -> Option<u64> {
        let result = Some(self.sum);
        self.sum -= self.buf[self.idx];
        self.buf[self.idx] += self.sum;
        self.sum += self.buf[self.idx];
        self.idx = (self.idx + 1) % self.buf.len();
        result
    }
}

fn print(buf: Vec<u64>, len: usize) {
    let mut sum = 0;
    for &elt in buf.iter() { sum += elt; print!("\t{}", elt); }
    let iter = GenFibonacci { buf: buf, sum: sum, idx: 0 };
    for x in iter.take(len) {
        print!("\t{}", x);
    }
}

fn main() {
    print!("Fib2:");
    print(vec![1,1], 10 - 2);

    print!("\nFib3:");
    print(vec![1,1,2], 10 - 3);

    print!("\nFib4:");
    print(vec![1,1,2,4], 10 - 4);

    print!("\nLucas:");
    print(vec![2,1], 10 - 2);
}


Fibonacci sequence

fun fibb
    loop
        a = funparam[0]
        break (a < 2)

        a--

        a -> stack

        funparam[0] = a
        call fibb

        b = funparam[0]
        stack -> a

        b -> stack

        a--

        funparam[0] = a
        call fibb

        c = funparam[0]
        stack -> b

        b += c
        a = b

        funparam[0] = a

        break
    end
end

fn main() {
    let mut prev = 0;

    let mut curr = 1usize;

    while let Some(n) = curr.checked_add(prev) {
        prev = curr;
        curr = n;
        println!("{}", n);
    }
}


File input_output

#include <stdio.h>

int main(int argc, char **argv) {
  FILE *in, *out;
  int c;

  in = fopen("input.txt", "r");
  if (!in) {
    fprintf(stderr, "Error opening input.txt for reading.\n");
    return 1;
  }

  out = fopen("output.txt", "w");
  if (!out) {
    fprintf(stderr, "Error opening output.txt for writing.\n");
    fclose(in);
    return 1;
  }

  while ((c = fgetc(in)) != EOF) {
    fputc(c, out);
  }

  fclose(out);
  fclose(in);
  return 0;
}

use std::fs::File;
use std::io::{Read, Write};

fn main() {
    let mut file = File::open("input.txt").unwrap();
    let mut data = Vec::new();
    file.read_to_end(&mut data).unwrap();
    let mut file = File::create("output.txt").unwrap();
    file.write_all(&data).unwrap();
}


File modification time

#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#include <utime.h>

const char *filename = "input.txt";

int main() {
  struct stat foo;
  time_t mtime;
  struct utimbuf new_times;

  if (stat(filename, &foo) < 0) {
    perror(filename);
    return 1;
  }
  mtime = foo.st_mtime;

  new_times.actime = foo.st_atime;
  new_times.modtime = time(NULL);
  if (utime(filename, &new_times) < 0) {
    perror(filename);
    return 1;
  }

  return 0;
}

use std::fs;

fn main() -> std::io::Result<()> {
    let metadata = fs::metadata("foo.txt")?;

    if let Ok(time) = metadata.accessed() {
        println!("{:?}", time);
    } else {
        println!("Not supported on this platform");
    }
    Ok(())
}


File size

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

long getFileSize(const char *filename)
{
  long result;
  FILE *fh = fopen(filename, "rb");
  fseek(fh, 0, SEEK_END);
  result = ftell(fh);
  fclose(fh);
  return result;
}

int main(void)
{
  printf("%ld\n", getFileSize("input.txt"));
  printf("%ld\n", getFileSize("/input.txt"));
  return 0;
}

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

fn main() {
    let file_name = env::args().nth(1).unwrap_or_else(|| exit_err("No file name supplied", 1));
    let metadata = fs::metadata(file_name).unwrap_or_else(|e| exit_err(e, 2));

    println!("Size of file.txt is {} bytes", metadata.len());
}

#[inline]
fn exit_err<T: Display>(msg: T, code: i32) -> ! {
    writeln!(&mut io::stderr(), "Error: {}", msg).expect("Could not write to stdout");
    process::exit(code)
}

}


Filter

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

int even_sel(int x) { return !(x & 1); }
int tri_sel(int x) { return x % 3; }

int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace)
{
	int i, j, *out;

	if (inplace)	out = in;
	else		out = malloc(sizeof(int) * len);

	for (i = j = 0; i < len; i++)
		if (sel(in[i]))
			out[j++] = in[i];

	if (!inplace && j < len)
		out = realloc(out, sizeof(int) * j);

	*outlen = j;
	return out;
}

int main()
{
	int in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int i, len;

	int *even = grep(in, 10, &len, even_sel, 0);
	printf("Filtered even:");
	for (i = 0; i < len; i++) printf(" %d", even[i]);
	printf("\n");

	grep(in, 8, &len, tri_sel, 1);
	printf("In-place filtered not multiple of 3:");
	for (i = 0; i < len; i++) printf(" %d", in[i]);

	printf("\n");

	return 0;
}

fn main() {
    println!("new vec filtered: ");
    let nums: Vec<i32> = (1..20).collect();
    let evens: Vec<i32> = nums.iter().cloned().filter(|x| x % 2 == 0).collect();
    println!("{:?}", evens);

    println!("original vec filtered: ");
    let mut nums: Vec<i32> = (1..20).collect();
    nums.retain(|x| x % 2 == 0);
    println!("{:?}", nums);
}


Find common directory path

#include <stdio.h>

int common_len(const char *const *names, int n, char sep)
{
	int i, pos;
	for (pos = 0; ; pos++) {
		for (i = 0; i < n; i++) {
			if (names[i][pos] != '\0' &&
					names[i][pos] == names[0][pos])
				continue;

			while (pos > 0 && names[0][--pos] != sep);
			return pos;
		}
	}

	return 0;
}

int main()
{
	const char *names[] = {
		"/home/user1/tmp/coverage/test",
		"/home/user1/tmp/covert/operator",
		"/home/user1/tmp/coven/members",
	};
	int len = common_len(names, sizeof(names) / sizeof(const char*), '/');

	if (!len) printf("No common path\n");
	else      printf("Common path: %.*s\n", len, names[0]);

	return 0;
}

use std::path::{Path, PathBuf};

fn main() {
    let paths = [
        Path::new("/home/user1/tmp/coverage/test"),
        Path::new("/home/user1/tmp/covert/operator"),
        Path::new("/home/user1/tmp/coven/members"),
    ];
    match common_path(&paths) {
        Some(p) => println!("The common path is: {:#?}", p),
        None => println!("No common paths found"),
    }
}

fn common_path<I, P>(paths: I) -> Option<PathBuf>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    let mut iter = paths.into_iter();
    let mut ret = iter.next()?.as_ref().to_path_buf();
    for path in iter {
        if let Some(r) = common(ret, path.as_ref()) {
            ret = r;
        } else {
            return None;
        }
    }
    Some(ret)
}

fn common<A: AsRef<Path>, B: AsRef<Path>>(a: A, b: B) -> Option<PathBuf> {
    let a = a.as_ref().components();
    let b = b.as_ref().components();
    let mut ret = PathBuf::new();
    let mut found = false;
    for (one, two) in a.zip(b) {
        if one == two {
            ret.push(one);
            found = true;
        } else {
            break;
        }
    }
    if found {
        Some(ret)
    } else {
        None
    }
}


Find limit of recursion

#include <stdio.h>

void recurse(unsigned int i)
{
  printf("%d\n", i);
  recurse(i+1);
}

int main()
{
  recurse(0);
  return 0;
}

fn recurse(n: i32) {
    println!("depth: {}", n);
    recurse(n + 1)
}

fn main() {
    recurse(0);
}


Find the intersection of a line with a plane

#include<stdio.h>

typedef struct{
	double x,y,z;
}vector;

vector addVectors(vector a,vector b){
	return (vector){a.x+b.x,a.y+b.y,a.z+b.z};
}

vector subVectors(vector a,vector b){
	return (vector){a.x-b.x,a.y-b.y,a.z-b.z};
}

double dotProduct(vector a,vector b){
	return a.x*b.x + a.y*b.y + a.z*b.z;
}

vector scaleVector(double l,vector a){
	return (vector){l*a.x,l*a.y,l*a.z};
}

vector intersectionPoint(vector lineVector, vector linePoint, vector planeNormal, vector planePoint){
	vector diff = subVectors(linePoint,planePoint);

	return addVectors(addVectors(diff,planePoint),scaleVector(-dotProduct(diff,planeNormal)/dotProduct(lineVector,planeNormal),lineVector));
}

int main(int argC,char* argV[])
{
	vector lV,lP,pN,pP,iP;

	if(argC!=5)
		printf("Usage : %s <line direction, point on line, normal to plane and point on plane given as (x,y,z) tuples separated by space>");
	else{
		sscanf(argV[1],"(%lf,%lf,%lf)",&lV.x,&lV.y,&lV.z);
		sscanf(argV[3],"(%lf,%lf,%lf)",&pN.x,&pN.y,&pN.z);

		if(dotProduct(lV,pN)==0)
			printf("Line and Plane do not intersect, either parallel or line is on the plane");
		else{
			sscanf(argV[2],"(%lf,%lf,%lf)",&lP.x,&lP.y,&lP.z);
			sscanf(argV[4],"(%lf,%lf,%lf)",&pP.x,&pP.y,&pP.z);

			iP = intersectionPoint(lV,lP,pN,pP);

			printf("Intersection point is (%lf,%lf,%lf)",iP.x,iP.y,iP.z);
		}
	}

	return 0;
}

use std::ops::{Add, Div, Mul, Sub};

#[derive(Copy, Clone, Debug, PartialEq)]
struct V3<T> {
    x: T,
    y: T,
    z: T,
}

impl<T> V3<T> {
    fn new(x: T, y: T, z: T) -> Self {
        V3 { x, y, z }
    }
}

fn zip_with<F, T, U>(f: F, a: V3<T>, b: V3<T>) -> V3<U>
where
    F: Fn(T, T) -> U,
{
    V3 {
        x: f(a.x, b.x),
        y: f(a.y, b.y),
        z: f(a.z, b.z),
    }
}

impl<T> Add for V3<T>
where
    T: Add<Output = T>,
{
    type Output = Self;

    fn add(self, other: Self) -> Self {
        zip_with(<T>::add, self, other)
    }
}

impl<T> Sub for V3<T>
where
    T: Sub<Output = T>,
{
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        zip_with(<T>::sub, self, other)
    }
}

impl<T> Mul for V3<T>
where
    T: Mul<Output = T>,
{
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        zip_with(<T>::mul, self, other)
    }
}

impl<T> V3<T>
where
    T: Mul<Output = T> + Add<Output = T>,
{
    fn dot(self, other: Self) -> T {
        let V3 { x, y, z } = self * other;
        x + y + z
    }
}

impl<T> V3<T>
where
    T: Mul<Output = T> + Copy,
{
    fn scale(self, scalar: T) -> Self {
        self * V3 {
            x: scalar,
            y: scalar,
            z: scalar,
        }
    }
}

fn intersect<T>(
    ray_vector: V3<T>,
    ray_point: V3<T>,
    plane_normal: V3<T>,
    plane_point: V3<T>,
) -> V3<T>
where
    T: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Copy,
{
    let diff = ray_point - plane_point;
    let prod1 = diff.dot(plane_normal);
    let prod2 = ray_vector.dot(plane_normal);
    let prod3 = prod1 / prod2;
    ray_point - ray_vector.scale(prod3)
}

fn main() {
    let rv = V3::new(0.0, -1.0, -1.0);
    let rp = V3::new(0.0, 0.0, 10.0);
    let pn = V3::new(0.0, 0.0, 1.0);
    let pp = V3::new(0.0, 0.0, 5.0);
    println!("{:?}", intersect(rv, rp, pn, pp));
}


Find the intersection of two lines

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

typedef struct{
	double x,y;
}point;

double lineSlope(point a,point b){

	if(a.x-b.x == 0.0)
		return NAN;
	else
		return (a.y-b.y)/(a.x-b.x);
}

point extractPoint(char* str){
	int i,j,start,end,length;
	char* holder;
	point c;

	for(i=0;str[i]!=00;i++){
		if(str[i]=='(')
			start = i;
		if(str[i]==','||str[i]==')')
		{
			end = i;

			length = end - start;

			holder = (char*)malloc(length*sizeof(char));

			for(j=0;j<length-1;j++)
				holder[j] = str[start + j + 1];
			holder[j] = 00;

			if(str[i]==','){
				start = i;
				c.x = atof(holder);
			}
			else
				c.y = atof(holder);
		}
	}

	return c;
}

point intersectionPoint(point a1,point a2,point b1,point b2){
	point c;

	double slopeA = lineSlope(a1,a2), slopeB = lineSlope(b1,b2);

	if(slopeA==slopeB){
		c.x = NAN;
		c.y = NAN;
	}
	else if(isnan(slopeA) && !isnan(slopeB)){
		c.x = a1.x;
		c.y = (a1.x-b1.x)*slopeB + b1.y;
	}
	else if(isnan(slopeB) && !isnan(slopeA)){
		c.x = b1.x;
		c.y = (b1.x-a1.x)*slopeA + a1.y;
	}
	else{
		c.x = (slopeA*a1.x - slopeB*b1.x + b1.y - a1.y)/(slopeA - slopeB);
		c.y = slopeB*(c.x - b1.x) + b1.y;
	}

	return c;
}

int main(int argC,char* argV[])
{
	point c;

	if(argC < 5)
		printf("Usage : %s <four points specified as (x,y) separated by a space>",argV[0]);
	else{
		c = intersectionPoint(extractPoint(argV[1]),extractPoint(argV[2]),extractPoint(argV[3]),extractPoint(argV[4]));

		if(isnan(c.x))
			printf("The lines do not intersect, they are either parallel or co-incident.");
		else
			printf("Point of intersection : (%lf,%lf)",c.x,c.y);
	}

	return 0;
}

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

impl Point {
    pub fn new(x: f64, y: f64) -> Self {
        Point { x, y }
    }
}

#[derive(Copy, Clone, Debug)]
struct Line(Point, Point);

impl Line {
    pub fn intersect(self, other: Self) -> Option<Point> {
        let a1 = self.1.y - self.0.y;
        let b1 = self.0.x - self.1.x;
        let c1 = a1 * self.0.x + b1 * self.0.y;

        let a2 = other.1.y - other.0.y;
        let b2 = other.0.x - other.1.x;
        let c2 = a2 * other.0.x + b2 * other.0.y;

        let delta = a1 * b2 - a2 * b1;

        if delta == 0.0 {
            return None;
        }

        Some(Point {
            x: (b2 * c1 - b1 * c2) / delta,
            y: (a1 * c2 - a2 * c1) / delta,
        })
    }
}

fn main() {
    let l1 = Line(Point::new(4.0, 0.0), Point::new(6.0, 10.0));
    let l2 = Line(Point::new(0.0, 3.0), Point::new(10.0, 7.0));
    println!("{:?}", l1.intersect(l2));

    let l1 = Line(Point::new(0.0, 0.0), Point::new(1.0, 1.0));
    let l2 = Line(Point::new(1.0, 2.0), Point::new(4.0, 5.0));
    println!("{:?}", l1.intersect(l2));
}


Find the missing permutation

#include <stdio.h>

#define N 4
const char *perms[] = {
	"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
	"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
	"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB",
};

int main()
{
	int i, j, n, cnt[N];
	char miss[N];

	for (n = i = 1; i < N; i++) n *= i;

	for (i = 0; i < N; i++) {
		for (j = 0; j < N; j++) cnt[j] = 0;

		for (j = 0; j < sizeof(perms)/sizeof(const char*); j++)
			cnt[perms[j][i] - 'A']++;

		for (j = 0; j < N && cnt[j] == n; j++);

		miss[i] = j + 'A';
	}
	printf("Missing: %.*s\n", N, miss);

	return 0;

}

const GIVEN_PERMUTATIONS: [&str; 23] = [
    "ABCD",
    "CABD",
    "ACDB",
    "DACB",
    "BCDA",
    "ACBD",
    "ADCB",
    "CDAB",
    "DABC",
    "BCAD",
    "CADB",
    "CDBA",
    "CBAD",
    "ABDC",
    "ADBC",
    "BDCA",
    "DCBA",
    "BACD",
    "BADC",
    "BDAC",
    "CBDA",
    "DBCA",
    "DCAB"
];

fn main() {

    const PERMUTATION_LEN: usize = GIVEN_PERMUTATIONS[0].len();
    let mut bytes_result: [u8; PERMUTATION_LEN] = [0; PERMUTATION_LEN];

    for permutation in &GIVEN_PERMUTATIONS {
        for (i, val) in permutation.bytes().enumerate() {
            bytes_result[i] ^= val;
        }
    }
    println!("{}", std::str::from_utf8(&bytes_result).unwrap());
}


First-class functions

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

typedef double (*Class2Func)(double);

double functionA( double v)
{
   return v*v*v;
}
double functionB(double v)
{
   return exp(log(v)/3);
}

double Function1( Class2Func f2, double val )
{
    return f2(val);
}

Class2Func WhichFunc( int idx)
{
   return (idx < 4) ? &functionA : &functionB;
}

Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };

double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
   return f1(f2(val));
}

typedef struct sComposition {
   Class2Func f1;
   Class2Func f2;
} *Composition;

Composition Compose( Class2Func f1, Class2Func f2)
{
   Composition comp = malloc(sizeof(struct sComposition));
   comp->f1 = f1;
   comp->f2 = f2;
   return comp;
}

double CallComposed( Composition comp, double val )
{
    return comp->f1( comp->f2(val) );
}

int main(int argc, char *argv[])
{
   int ix;
   Composition c;

   printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));

   for (ix=0; ix<4; ix++) {
       c = Compose(funcListA[ix], funcListB[ix]);
       printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
   }

   return 0;
}

#![feature(conservative_impl_trait)]
fn main() {
    let cube      = |x: f64| x.powi(3);
    let cube_root = |x: f64| x.powf(1.0 / 3.0);

    let flist  : [&Fn(f64) -> f64; 3] = [&cube     , &f64::sin , &f64::cos ];
    let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos];

    let result = flist.iter()
                      .zip(&invlist)
                      .map(|(f,i)| compose(f,i)(0.5))
                      .collect::<Vec<_>>();

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

}

fn compose<'a, F, G, T, U, V>(f: F, g: G) -> impl 'a + Fn(T) -> V
    where F: 'a + Fn(T) -> U,
          G: 'a + Fn(U) -> V,
{
    move |x| g(f(x))

}


Five weekends

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

static const char *months[] = {"January", "February", "March", "April", "May",
    "June", "July", "August", "September", "October", "November", "December"};
static int long_months[] = {0, 2, 4, 6, 7, 9, 11};

int main() {
    int n = 0, y, i, m;
    struct tm t = {0};
    printf("Months with five weekends:\n");
    for (y = 1900; y <= 2100; y++) {
        for (i = 0; i < 7; i++) {
            m = long_months[i];
            t.tm_year = y-1900;
	    t.tm_mon = m;
	    t.tm_mday = 1;
            if (mktime(&t) == -1) {
                printf("Error: %d %s\n", y, months[m]);
                continue;
            }
            if (t.tm_wday == 5) {
                printf("  %d %s\n", y, months[m]);
                n++;
            }
        }
    }
    printf("%d total\n", n);
    return 0;
}

extern crate chrono;
use chrono::prelude::*;

const LONGMONTHS: [u32; 7] = [1, 3, 5, 7, 8, 10, 12];

fn five_weekends(start: i32, end: i32) -> Vec<(i32, u32)> {
    let mut out = vec![];

    for year in start..=end {
        for month in LONGMONTHS.iter() {

            if Local.ymd(year, *month, 1).weekday() == Weekday::Fri {
                out.push((year, *month));
            }
        }
    }

    out
}

fn main() {
    let out = five_weekends(1900, 2100);

    let len = out.len();
    println!(
        "There are {} months of which the first and last five are:",
        len
    );
    for (y, m) in &out[..5] {
        println!("\t{} / {}", y, m);
    }
    println!("...");
    for (y, m) in &out[(len - 5..)] {
        println!("\t{} / {}", y, m);
    }
}

#[test]
fn test() {
    let out = five_weekends(1900, 2100);
    assert_eq!(out.len(), 201);
}


Fivenum

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

double median(double *x, int start, int end_inclusive) {
    int size = end_inclusive - start + 1;
    if (size <= 0) {
        printf("Array slice cannot be empty\n");
        exit(1);
    }
    int m = start + size / 2;
    if (size % 2) return x[m];
    return (x[m - 1] + x[m]) / 2.0;
}

int compare (const void *a, const void *b) {
    double aa = *(double*)a;
    double bb = *(double*)b;
    if (aa > bb) return 1;
    if (aa < bb) return -1;
    return 0;
}

int fivenum(double *x, double *result, int x_len) {
    int i, m, lower_end;
    for (i = 0; i < x_len; i++) {
        if (x[i] != x[i]) {
           printf("Unable to deal with arrays containing NaN\n\n");
           return 1;
        }
    }
    qsort(x, x_len, sizeof(double), compare);
    result[0] = x[0];
    result[2] = median(x, 0, x_len - 1);
    result[4] = x[x_len - 1];
    m = x_len / 2;
    lower_end = (x_len % 2) ? m : m - 1;
    result[1] = median(x, 0, lower_end);
    result[3] = median(x, m, x_len - 1);
    return 0;
}

int show(double *result, int places) {
    int i;
    char f[7];
    sprintf(f, "%%.%dlf", places);
    printf("[");
    for (i = 0; i < 5; i++) {
        printf(f, result[i]);
        if (i < 4) printf(", ");
    }
    printf("]\n\n");
}

int main() {
    double result[5];

    double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0};
    if (!fivenum(x1, result, 11)) show(result, 1);

    double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0};
    if (!fivenum(x2, result, 6)) show(result, 1);

    double x3[20] = {
         0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
        -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
        -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
         0.75775634,  0.32566578
    };
    if (!fivenum(x3, result, 20)) show(result, 9);

    return 0;
}

#[derive(Debug)]
struct FiveNum {
    minimum: f64,
    lower_quartile: f64,
    median: f64,
    upper_quartile: f64,
    maximum: f64,
}

fn median(samples: &[f64]) -> f64 {

    let n = samples.len();
    let m = n / 2;
    if n % 2 == 0 {
        (samples[m] + samples[m - 1]) / 2.0
    } else {
        samples[m]
    }
}

fn fivenum(samples: &[f64]) -> FiveNum {
    let mut xs = samples.to_vec();
    xs.sort_by(|x, y| x.partial_cmp(y).unwrap());

    let m = xs.len() / 2;

    FiveNum {
        minimum: xs[0],
        lower_quartile: median(&xs[0..(m + (xs.len() % 2))]),
        median: median(&xs),
        upper_quartile: median(&xs[m..]),
        maximum: xs[xs.len() - 1],
    }
}
fn main() {
    let inputs = vec![
        vec![15., 6., 42., 41., 7., 36., 49., 40., 39., 47., 43.],
        vec![36., 40., 7., 39., 41., 15.],
        vec![
            0.14082834,
            0.09748790,
            1.73131507,
            0.87636009,
            -1.95059594,
            0.73438555,
            -0.03035726,
            1.46675970,
            -0.74621349,
            -0.72588772,
            0.63905160,
            0.61501527,
            -0.98983780,
            -1.00447874,
            -0.62759469,
            0.66206163,
            1.04312009,
            -0.10305385,
            0.75775634,
            0.32566578,
        ],
    ];

    for input in inputs {
        let result = fivenum(&input);
        println!("Fivenum",);
        println!("  Minumum: {}", result.minimum);
        println!("  Lower quartile: {}", result.lower_quartile);
        println!("  Median: {}", result.median);
        println!("  Upper quartile: {}", result.upper_quartile);
        println!("  Maximum: {}", result.maximum);
    }
}