S-expressions

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

enum { S_NONE, S_LIST, S_STRING, S_SYMBOL };

typedef struct {
	int type;
	size_t len;
	void *buf;
} s_expr, *expr;

void whine(const char *s)
{
	fprintf(stderr, "parse error before ==>%.10s\n", s);
}

expr parse_string(const char *s, char **e)
{
	expr ex = calloc(sizeof(s_expr), 1);
	char buf[256] = {0};
	int i = 0;

	while (*s) {
		if (i >= 256) {
			fprintf(stderr, "string too long:\n");
			whine(s);
			goto fail;
		}
		switch (*s) {
		case '\\':
			switch (*++s) {
			case '\\':
			case '"':	buf[i++] = *s++;
					continue;

			default:	whine(s);
					goto fail;
			}
		case '"':	goto success;
		default:	buf[i++] = *s++;
		}
	}
fail:
	free(ex);
	return 0;

success:
	*(const char **)e = s + 1;
	ex->type = S_STRING;
	ex->buf = strdup(buf);
	ex->len = strlen(buf);
	return ex;
}

expr parse_symbol(const char *s, char **e)
{
	expr ex = calloc(sizeof(s_expr), 1);
	char buf[256] = {0};
	int i = 0;

	while (*s) {
		if (i >= 256) {
			fprintf(stderr, "symbol too long:\n");
			whine(s);
			goto fail;
		}
		if (isspace(*s)) goto success;
		if (*s == ')' || *s == '(') {
			s--;
			goto success;
		}

		switch (*s) {
		case '\\':
			switch (*++s) {
			case '\\': case '"': case '(': case ')':
					buf[i++] = *s++;
					continue;
			default:	whine(s);
					goto fail;
			}
		case '"':	whine(s);
				goto success;
		default:	buf[i++] = *s++;
		}
	}
fail:
	free(ex);
	return 0;

success:
	*(const char **)e = s + 1;
	ex->type = S_SYMBOL;
	ex->buf = strdup(buf);
	ex->len = strlen(buf);
	return ex;
}

void append(expr list, expr ele)
{
	list->buf = realloc(list->buf, sizeof(expr) * ++list->len);
	((expr*)(list->buf))[list->len - 1] = ele;
}

expr parse_list(const char *s, char **e)
{
	expr ex = calloc(sizeof(s_expr), 1), chld;
	char *next;

	ex->len = 0;

	while (*s) {
		if (isspace(*s)) {
			s++;
			continue;
		}

		switch (*s) {
		case '"':
			chld = parse_string(s+1, &next);
			if (!chld) goto fail;
			append(ex, chld);
			s = next;
			continue;
		case '(':
			chld = parse_list(s+1, &next);
			if (!chld) goto fail;
			append(ex, chld);
			s = next;
			continue;
		case ')':
			goto success;

		default:
			chld = parse_symbol(s, &next);
			if (!chld) goto fail;
			append(ex, chld);
			s = next;
			continue;
		}
	}

fail:
	whine(s);
	free(ex);
	return 0;

success:
	*(const char **)e = s+1;
	ex->type = S_LIST;
	return ex;
}

expr parse_term(const char *s, char **e)
{
	while (*s) {
		if (isspace(*s)) {
			s++;
			continue;
		}
		switch(*s) {
		case '(':
			return parse_list(s+1, e);
		case '"':
			return parse_string(s+1, e);
		default:
			return parse_symbol(s+1, e);
		}
	}
	return 0;
}

void print_expr(expr e, int depth)
{
#define sep() for(i = 0; i < depth; i++) printf("    ")
	int i;
	if (!e) return;

	switch(e->type) {
	case S_LIST:
		sep();
		puts("(");
		for (i = 0; i < e->len; i++)
			print_expr(((expr*)e->buf)[i], depth + 1);
		sep();
		puts(")");
		return;
	case S_SYMBOL:
	case S_STRING:
		sep();
		if (e->type == S_STRING) putchar('"');
		for (i = 0; i < e->len; i++) {
			switch(((char*)e->buf)[i]) {
			case '"':
			case '\\':
				putchar('\\');
				break;
			case ')': case '(':
				if (e->type == S_SYMBOL)
					putchar('\\');
			}

			putchar(((char*)e->buf)[i]);
		}
		if (e->type == S_STRING) putchar('"');
		putchar('\n');
		return;
	}
}

int main()
{
	char *next;
	const char *in = "((data da\\(\\)ta \"quot\\\\ed data\" 123 4.5)\n"
			" (\"data\" (!@# (4.5) \"(mo\\\"re\" \"data)\")))";

	expr x = parse_term(in, &next);

	printf("input is:\n%s\n", in);
	printf("parsed as:\n");
	print_expr(x, 0);
	return 0;
}

extern crate typed_arena;

use typed_arena::Arena;

use self::Error::*;
use self::SExp::*;
use self::Token::*;
use std::io;
use std::num::FpCategory;
use std::str::FromStr;

#[derive(PartialEq, Debug)]
pub enum SExp<'a> {

    F64(f64),

    List(&'a [SExp<'a>]),

    Str(&'a str),
}

#[derive(PartialEq, Debug)]
pub enum Error {

    NoReprForFloat,

    UnterminatedStringLiteral,

    Io,

    IncorrectCloseDelimiter,

    UnexpectedEOF,

    ExpectedEOF,
}

impl From<io::Error> for Error {
    fn from(_err: io::Error) -> Error {
        Error::Io
    }
}

#[derive(PartialEq, Debug)]
enum Token<'a> {

    ListStart,

    ListEnd,

    Literal(SExp<'a>),

    Eof,
}

#[derive(Copy, Clone, Debug)]
struct Tokens<'a> {

    string: &'a str,

    first: Option<char>,

    rest: &'a str,
}

impl<'a> Tokens<'a> {

    fn new(string: &str) -> Tokens {
        let mut chars = string.chars();

        match chars.next() {
            Some(ch) => Tokens {
                string,
                first: Some(ch),
                rest: chars.as_str(),
            },
            None => Tokens {
                string,
                first: None,
                rest: string,
            },
        }
    }

    fn update(&mut self, string: &'a str) {
        self.string = string;
        let mut chars = self.string.chars();

        if let Some(ch) = chars.next() {
            self.first = Some(ch);
            self.rest = chars.as_str();
        } else {
            self.first = None;
        };
    }

    fn next_token(&mut self) -> Result<Token<'a>, Error> {
        loop {
            match self.first {

                Some('(') => {
                    self.update(self.rest);
                    return Ok(ListStart);
                }

                Some(')') => {
                    self.update(self.rest);
                    return Ok(ListEnd);
                }

                Some('"') => {

                    let mut iter = self.rest.splitn(2, '"');

                    let str = iter.next().unwrap();
                    match iter.next() {

                        Some(s) => {
                            self.update(s);
                            return Ok(Literal(Str(str)));
                        }
                        None => return Err(UnterminatedStringLiteral),
                    }
                }

                Some(c) => {

                    if c.is_whitespace() {
                        self.update(self.rest);
                        continue;
                    }

                    let mut end_ch = None;
                    let str = {
                        let mut iter = self.string.splitn(2, |ch: char| {
                            let term = ch == ')' || ch == '(';
                            if term {
                                end_ch = Some(ch)
                            }
                            term || ch.is_whitespace()
                        });

                        let str = iter.next().unwrap();
                        self.rest = iter.next().unwrap_or("");
                        str
                    };
                    match end_ch {

                        Some(_) => self.first = end_ch,
                        None => self.update(self.rest),
                    }
                    return Ok(Literal(parse_literal(str)));
                }
                None => return Ok(Eof),
            }
        }
    }
}

fn parse_literal(literal: &str) -> SExp {
    match literal.bytes().next() {
        Some(b'0'..=b'9') | Some(b'-') => match f64::from_str(literal) {
            Ok(f) => F64(f),
            Err(_) => Str(literal),
        },
        _ => Str(literal),
    }
}

pub struct ParseContext<'a> {

    string: &'a str,

    arena: Option<Arena<Vec<SExp<'a>>>>,

    stack: Vec<Vec<SExp<'a>>>,
}

impl<'a> ParseContext<'a> {

    pub fn new(string: &'a str) -> ParseContext<'a> {
        ParseContext {
            string,
            arena: None,
            stack: Vec::new(),
        }
    }
}

impl<'a> SExp<'a> {

    fn encode<T: io::Write>(&self, writer: &mut T) -> Result<(), Error> {
        match *self {
            F64(f) => {
                match f.classify() {

                    FpCategory::Normal | FpCategory::Zero => {
                        write!(writer, "{}", f)?;
                        Ok(())
                    }
                    _ => Err(Error::NoReprForFloat),
                }
            }
            List(l) => {

                write!(writer, "(")?;
                let mut iter = l.iter();
                if let Some(sexp) = iter.next() {
                    sexp.encode(writer)?;
                    for sexp in iter {
                        write!(writer, " ")?;
                        sexp.encode(writer)?;
                    }
                }
                write!(writer, ")")?;
                Ok(())
            }
            Str(s) => {
                write!(writer, "\"{}\"", s)?;
                Ok(())
            }
        }
    }

    pub fn parse(ctx: &'a mut ParseContext<'a>) -> Result<SExp<'a>, Error> {
        ctx.arena = Some(Arena::new());

        let arena = match ctx.arena {
            Some(ref mut arena) => arena,
            None => unreachable!(),
        };
        let ParseContext {
            string,
            ref mut stack,
            ..
        } = *ctx;

        stack.clear();
        let mut tokens = Tokens::new(string);

        let next = tokens.next_token();
        let mut list = match next? {
            ListStart => Vec::new(),
            Literal(s) => {
                return if tokens.next_token()? == Eof {
                    Ok(s)
                } else {
                    Err(ExpectedEOF)
                };
            }
            ListEnd => return Err(IncorrectCloseDelimiter),
            Eof => return Err(UnexpectedEOF),
        };

        loop {
            let tok = tokens.next_token();
            match tok? {
                ListStart => {

                    stack.push(list);
                    list = Vec::new()
                }
                Literal(s) => list.push(s),
                ListEnd => {
                    match stack.pop() {

                        Some(mut l) => {

                            l.push(List(&*arena.alloc(list)));

                            list = l;
                        }

                        None => {
                            return match tokens.next_token()? {
                                Eof => Ok(List(&*arena.alloc(list))),
                                _ => Err(ExpectedEOF),
                            };
                        }
                    }
                }

                Eof => return Err(UnexpectedEOF),
            }
        }
    }

    pub fn buffer_encode(&self) -> Result<String, Error> {
        let mut m = Vec::new();
        self.encode(&mut m)?;

        unsafe { Ok(String::from_utf8_unchecked(m)) }
    }
}

pub const SEXP_STRUCT: SExp<'static> = List(&[
    List(&[Str("data"), Str("quoted data"), F64(123.), F64(4.5)]),
    List(&[
        Str("data"),
        List(&[Str("!@#"), List(&[F64(4.5)]), Str("(more"), Str("data)")]),
    ]),
]);

pub const SEXP_STRING_IN: &str = r#"((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))"#;

and main.rs:

use s_expressions::{ParseContext, SExp, SEXP_STRING_IN, SEXP_STRUCT};

fn main() {
    println!("{:?}", SEXP_STRUCT.buffer_encode());
    let ctx = &mut ParseContext::new(SEXP_STRING_IN);
    println!("{:?}", SExp::parse(ctx));
}


SEDOLs

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

int sedol_weights[] = {1, 3, 1, 7, 3, 9};
const char *reject = "AEIOUaeiou";

int sedol_checksum(const char *sedol6)
{
  int len = strlen(sedol6);
  int sum = 0, i;

  if ( len == 7 ) {
    fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6);
    return sedol6[6] & 0x7f;
  }
  if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) {
    fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6);
    return -1;
  }
  for(i=0; i < 6; i++) {
    if ( isdigit(sedol6[i]) ) {
      sum += (sedol6[i]-'0')*sedol_weights[i];
    } else if ( isalpha(sedol6[i]) ) {
      sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i];
    } else {
      fprintf(stderr, "SEDOL with not alphanumeric digit\n");
      return -1;
    }
  }
  return (10 - (sum%10))%10 + '0';
}

#define MAXLINELEN 10
int main()
{
  char line[MAXLINELEN];
  int sr, len;
  while( fgets(line, MAXLINELEN, stdin) != NULL ) {
    len = strlen(line);
    if ( line[len-1] == '\n' ) line[len-1]='\0';
    sr = sedol_checksum(line);
    if ( sr > 0 )
      printf("%s%c\n", line, sr);
  }
  return 0;
}

fn sedol(input: &str) -> Option<String> {
    let weights = vec![1, 3, 1, 7, 3, 9, 1];
    let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ";

    if input.len() != 6 {
        return None;
    }

    for c in input.chars() {
        if !valid_chars.contains(c) {
            return None;
        }
    }

    let mut result: u32 = input
        .chars()
        .map(|c| {
            if c.is_digit(10) {
                c as u32 - 48
            } else {
                c as u32 - 55
            }
        })
        .zip(weights)
        .map(|(cnum, w)| w * cnum)
        .collect::<Vec<u32>>()
        .iter()
        .sum();

    result = (10 - result % 10) % 10;

    Some(input.to_owned() + &result.to_string())
}

fn main() {
    let inputs = vec![
        "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284",
        "B0YBKT", "B00030",
    ];

    for input in inputs {
        println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap());
    }
}


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

int main()
{
  int i;
  unsigned char result[SHA_DIGEST_LENGTH];
  const char *string = "Rosetta Code";

  SHA1(string, strlen(string), result);

  for(i = 0; i < SHA_DIGEST_LENGTH; i++)
    printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n');

  return EXIT_SUCCESS;
}

use sha1::Sha1;

fn main() {
    let mut hash_msg = Sha1::new();
    hash_msg.update(b"Rosetta Code");
    println!("{}", hash_msg.digest().to_string());
}


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

int main (void) {
	const char *s = "Rosetta code";
	unsigned char *d = SHA256(s, strlen(s), 0);

	int i;
	for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
		printf("%02x", d[i]);
	putchar('\n');

	return 0;
}

use sha2::{Digest, Sha256};

fn hex_string(input: &[u8]) -> String {
    input.as_ref().iter().map(|b| format!("{:x}", b)).collect()
}

fn main() {

    let mut hasher = Sha256::new();

    hasher.update(b"Rosetta code");

    let result = hasher.finalize();

    let hex = hex_string(&result);

    assert_eq!(
        hex,
        "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
    );

    println!("{}", hex);
}


Search a list

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

const char *haystack[] = {
  "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
  "Bush", "Boz", "Zag", NULL
};

int search_needle(const char *needle, const char **hs)
{
  int i = 0;
  while( hs[i] != NULL ) {
    if ( strcmp(hs[i], needle) == 0 ) return i;
    i++;
  }
  return -1;
}

int search_last_needle(const char *needle, const char **hs)
{
  int i, last=0;
  i = last = search_needle(needle, hs);
  if ( last < 0 ) return -1;
  while( hs[++i] != NULL ) {
    if ( strcmp(needle, hs[i]) == 0 ) {
      last = i;
    }
  }
  return last;
}

int main()
{
  printf("Bush is at %d\n", search_needle("Bush", haystack));
  if ( search_needle("Washington", haystack) == -1 )
    printf("Washington is not in the haystack\n");
  printf("First index for Zag: %d\n", search_needle("Zag", haystack));
  printf("Last index for Zag: %d\n", search_last_needle("Zag", haystack));
  return 0;
}

fn main() {
    let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
                        "Bush", "Boz", "Zag"];

    println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush"));
    println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s=="Bush"));
    println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob"));
}


Secure temporary file

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

int main(void)
{
  FILE *fh = tmpfile();

  fclose(fh);

  return 0;
}

use tempfile::tempfile;

fn main() {

    let fh = tempfile();

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


Semiprime

#include <stdio.h>

int semiprime(int n)
{
	int p, f = 0;
	for (p = 2; f < 2 && p*p <= n; p++)
		while (0 == n % p)
			n /= p, f++;

	return f + (n > 1) == 2;
}

int main(void)
{
	int i;
	for (i = 2; i < 100; i++)
		if (semiprime(i)) printf(" %d", i);
	putchar('\n');

	return 0;
}

extern crate primal;

fn isqrt(n: usize) -> usize {
    (n as f64).sqrt() as usize
}

fn is_semiprime(mut n: usize) -> bool {
    let root = isqrt(n) + 1;
    let primes1 = primal::Sieve::new(root);
    let mut count = 0;

    for i in primes1.primes_from(2).take_while(|&x| x < root) {
        while n % i == 0 {
            n /= i;
            count += 1;
        }
        if n == 1 {
            break;
        }
    }

    if n != 1 {
        count += 1;
    }
    count == 2
}

#[test]
fn test1() {
    assert_eq!((2..10).filter(|&n| is_semiprime(n)).count(), 3);
}

#[test]
fn test2() {
    assert_eq!((2..100).filter(|&n| is_semiprime(n)).count(), 34);
}

#[test]
fn test3() {
    assert_eq!((2..1_000).filter(|&n| is_semiprime(n)).count(), 299);
}

#[test]
fn test4() {
    assert_eq!((2..10_000).filter(|&n| is_semiprime(n)).count(), 2_625);
}

#[test]
fn test5() {
    assert_eq!((2..100_000).filter(|&n| is_semiprime(n)).count(), 23_378);
}

#[test]
fn test6() {
    assert_eq!((2..1_000_000).filter(|&n| is_semiprime(n)).count(), 210_035);
}


Semordnilap

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

static void reverse(char *s, int len)
{
    int i, j;
    char tmp;

    for (i = 0, j = len - 1; i < len / 2; ++i, --j)
        tmp = s[i], s[i] = s[j], s[j] = tmp;
}

static int strsort(const void *s1, const void *s2)
{
    return strcmp(*(char *const *) s1, *(char *const *) s2);
}

int main(void)
{
    int i, c, ct = 0, len, sem = 0;
    char **words, **drows, tmp[24];
    FILE *dict = fopen("unixdict.txt", "r");

    while ((c = fgetc(dict)) != EOF)
        ct += c == '\n';
    rewind(dict);

    words = alloca(ct * sizeof words);
    drows = alloca(ct * sizeof drows);

    for (i = 0; fscanf(dict, "%s%n", tmp, &len) != EOF; ++i) {

        strcpy(words[i] = alloca(len), tmp);

        strcpy(drows[i] = alloca(len), tmp);
        reverse(drows[i], len - 1);
    }

    fclose(dict);
    qsort(drows, ct, sizeof drows, strsort);

    for (c = i = 0; i < ct; ++i) {
        while (strcmp(drows[i], words[c]) > 0 && c < ct - 1)
            c++;

        if (!strcmp(drows[i], words[c])) {
            strcpy(tmp, drows[i]);
            reverse(tmp, strlen(tmp));

            if (strcmp(drows[i], tmp) > 0 && sem++ < 5)
                printf("%s\t%s\n", drows[i], tmp);
        }
    }

    printf("Semordnilap pairs: %d\n", sem);
    return 0;
}

use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;

fn semordnilap(filename: &str) -> std::io::Result<()> {
    let file = File::open(filename)?;
    let mut seen = HashSet::new();
    let mut count = 0;
    for line in io::BufReader::new(file).lines() {
        let mut word = line?;
        word.make_ascii_lowercase();
        let rev = String::from_iter(word.chars().rev());
        if seen.contains(&rev) {
            if count < 5 {
                println!("{}\t{}", word, rev);
            }
            count += 1;
        } else {
            seen.insert(word);
        }
    }
    println!("\nSemordnilap pairs found: {}", count);
    Ok(())
}

fn main() {
    match semordnilap("unixdict.txt") {
        Ok(()) => {}
        Err(error) => eprintln!("{}", error),
    }
}


Sequence of non-squares

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

int nonsqr(int n) {
    return n + (int)(0.5 + sqrt(n));

}

int main() {
    int i;

    for (i = 1; i < 23; i++)
        printf("%d ", nonsqr(i));
    printf("\n");

    for (i = 1; i < 1000000; i++) {
        double j = sqrt(nonsqr(i));
        assert(j != floor(j));
    }
    return 0;
}


Sequence of primes by trial division

#include<stdio.h>

int isPrime(unsigned int n)
{
	unsigned int num;

	if ( n < 2||!(n & 1))
		return n == 2;

	for (num = 3; num <= n/num; num += 2)
		if (!(n % num))
			return 0;
	return 1;
}

int main()
{
	unsigned int l,u,i,sum=0;

	printf("Enter lower and upper bounds: ");
	scanf("%ld%ld",&l,&u);

	for(i=l;i<=u;i++){
		if(isPrime(i)==1)
			{
				printf("\n%ld",i);
				sum++;
			}
	}

	printf("\n\nPrime numbers found in [%ld,%ld] : %ld",l,u,sum);

	return 0;
}

fn is_prime(number: u32) -> bool {
    #[allow(clippy::cast_precision_loss)]
    let limit = (number as f32).sqrt() as u32 + 1;

    !(number < 2 || (2..limit).any(|x| number % x == 0))
}

fn main() {
    println!(
        "Primes below 100:\n{:?}",
        (0_u32..100).fold(vec![], |mut acc, number| {
            if is_prime(number) {
                acc.push(number)
            };
            acc
        })
    );
}


Set

#include <stdio.h>

typedef unsigned int set_t;

void show_set(set_t x, const char *name)
{
	int i;
	printf("%s is:", name);
	for (i = 0; (1U << i) <= x; i++)
		if (x & (1U << i))
			printf(" %d", i);
	putchar('\n');
}

int main(void)
{
	int i;
	set_t a, b, c;

	a = 0;
	for (i = 0; i < 10; i += 3)
		a |= (1U << i);
	show_set(a, "a");

	for (i = 0; i < 5; i++)
		printf("\t%d%s in set a\n", i, (a & (1U << i)) ? "":" not");

	b = a;
	b |= (1U << 5); b |= (1U << 10);
	b &= ~(1U << 0);
	show_set(b, "b");

	show_set(a | b, "union(a, b)");
	show_set(c = a & b, "c = common(a, b)");
	show_set(a & ~b, "a - b");
	show_set(b & ~a, "b - a");
	printf("b is%s a subset of a\n", !(b & ~a) ? "" : " not");
	printf("c is%s a subset of a\n", !(c & ~a) ? "" : " not");

	printf("union(a, b) - common(a, b) %s union(a - b, b - a)\n",
		((a | b) & ~(a & b)) == ((a & ~b) | (b & ~a))
			? "equals" : "does not equal");

	return 0;
}

use std::collections::HashSet;

fn main() {
  let a = vec![1, 3, 4].into_iter().collect::<HashSet<i32>>();
  let b = vec![3, 5, 6].into_iter().collect::<HashSet<i32>>();

  println!("Set A: {:?}", a.iter().collect::<Vec<_>>());
  println!("Set B: {:?}", b.iter().collect::<Vec<_>>());
  println!("Does A contain 4? {}", a.contains(&4));
  println!("Union: {:?}", a.union(&b).collect::<Vec<_>>());
  println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<_>>());
  println!("Difference: {:?}", a.difference(&b).collect::<Vec<_>>());
  println!("Is A a subset of B? {}", a.is_subset(&b));
  println!("Is A equal to B? {}", a == b);
}


Set puzzle

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

char *names[4][3] = {
	{ "red", "green", "purple" },
	{ "oval", "squiggle", "diamond" },
	{ "one", "two", "three" },
	{ "solid", "open", "striped" }
};

int set[81][81];

void init_sets(void)
{
	int i, j, t, a, b;
	for (i = 0; i < 81; i++) {
		for (j = 0; j < 81; j++) {
			for (t = 27; t; t /= 3) {
				a = (i / t) % 3;
				b = (j / t) % 3;
				set[i][j] += t * (a == b ? a : 3 - a - b);
			}
		}
	}
}

void deal(int *out, int n)
{
	int i, j, t, c[81];
	for (i = 0; i < 81; i++) c[i] = i;
	for (i = 0; i < n; i++) {
		j = i + (rand() % (81 - i));
		t = c[i], c[i] = out[i] = c[j], c[j] = t;
	}
}

int get_sets(int *cards, int n, int sets[][3])
{
	int i, j, k, s = 0;
	for (i = 0; i < n; i++) {
		for (j = i + 1; j < n; j++) {
			for (k = j + 1; k < n; k++) {
				if (set[cards[i]][cards[j]] == cards[k])
					sets[s][0] = i,
					sets[s][1] = j,
					sets[s][2] = k,
					s++;
			}
		}
	}

	return s;
}

void show_card(int c)
{
	int i, t;
	for (i = 0, t = 27; t; i++, t /= 3)
		printf("%9s", names[i][(c/t)%3]);
	putchar('\n');
}

void deal_sets(int ncard, int nset)
{
	int c[81];
	int csets[81][3];
	int i, j, s;

	do deal(c, ncard); while ((s = get_sets(c, ncard, csets)) != nset);

	printf("dealt %d cards\n", ncard);
	for (i = 0; i < ncard; i++) {
		printf("%2d:", i);
		show_card(c[i]);
	}
	printf("\nsets:\n");

	for (i = 0; i < s; i++) {
		for (j = 0; j < 3; j++) {
			printf("%2d:", csets[i][j]);
			show_card(c[csets[i][j]]);
		}
		putchar('\n');
	}
}

int main(void)
{
	init_sets();
	deal_sets(9, 4);

	while (1) deal_sets(12, 6);

	return 0;
}

use itertools::Itertools;
use rand::Rng;

const DECK_SIZE: usize = 81;
const NUM_ATTRIBUTES: usize = 4;
const ATTRIBUTES: [&[&str]; NUM_ATTRIBUTES] = [
    &["red", "green", "purple"],
    &["one", "two", "three"],
    &["oval", "squiggle", "diamond"],
    &["solid", "open", "striped"],
];

fn get_random_card_indexes(num_of_cards: usize) -> Vec<usize> {
    let mut selected_cards: Vec<usize> = Vec::with_capacity(num_of_cards);
    let mut rng = rand::thread_rng();
    loop {
        let idx = rng.gen_range(0..DECK_SIZE);
        if !selected_cards.contains(&idx) {
            selected_cards.push(idx);
        }
        if selected_cards.len() == num_of_cards {
            break;
        }
    }

    selected_cards
}

fn run_game(num_of_cards: usize, minimum_number_of_sets: usize) {
    println!(
        "\nGAME: # of cards: {} # of sets: {}",
        num_of_cards, minimum_number_of_sets
    );

    let deck = (0..NUM_ATTRIBUTES)
        .map(|_| (0..=2_usize))
        .multi_cartesian_product()
        .collect::<Vec<_>>();

    let valid_attribute =
        |a: usize, b: usize, c: usize| -> bool { a == b && b == c || (a != b && b != c && a != c) };

    let valid_set = |t: &Vec<&Vec<usize>>| -> bool {
        for attr in 0..NUM_ATTRIBUTES {
            if !valid_attribute(t[0][attr], t[1][attr], t[2][attr]) {
                return false;
            }
        }
        true
    };

    loop {

        let selected_cards = get_random_card_indexes(num_of_cards)
            .iter()
            .map(|idx| deck[*idx].clone())
            .collect::<Vec<_>>();

        let valid_sets = selected_cards
            .iter()
            .combinations(3)
            .filter(|triplet| valid_set(triplet))
            .collect::<Vec<_>>();

        if valid_sets.len() == minimum_number_of_sets {
            print!("SELECTED CARDS:");
            for card in &selected_cards {
                print!("\ncard: ");
                for attr in 0..NUM_ATTRIBUTES {
                    print!("{}, ", ATTRIBUTES[attr][card[attr]]);
                }
            }

            print!("\nSets:");
            for triplet in &valid_sets {
                print!("\nSet: ");
                for card in triplet {
                    for attr in 0..NUM_ATTRIBUTES {
                        print!("{}, ", ATTRIBUTES[attr][card[attr]]);
                    }
                    print!(" | ");
                }
            }

            break;
        }

    }
}
fn main() {
    run_game(9, 4);
    run_game(12, 6);
}


Short-circuit evaluation

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

bool a(bool in)
{
  printf("I am a\n");
  return in;
}

bool b(bool in)
{
  printf("I am b\n");
  return in;
}

#define TEST(X,Y,O)						\
  do {								\
    x = a(X) O b(Y);						\
    printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false");	\
  } while(false);

int main()
{
  bool x;

  TEST(false, true, &&);
  TEST(true, false, ||);
  TEST(true, false, &&);
  TEST(false, false, ||);

  return 0;
}

fn a(foo: bool) -> bool {
    println!("a");
    foo
}

fn b(foo: bool) -> bool {
    println!("b");
    foo
}

fn main() {
    for i in vec![true, false] {
        for j in vec![true, false] {
            println!("{} and {} == {}", i, j, a(i) && b(j));
            println!("{} or {} == {}", i, j, a(i) || b(j));
            println!();
        }
    }
}


Show ASCII table

#include <stdio.h>

int main() {
    int i, j;
    char k[4];
    for (i = 0; i < 16; ++i) {
        for (j = 32 + i; j < 128; j += 16) {
            switch (j) {
                default:  sprintf(k, "%c", j); break;
                case 32:  sprintf(k, "Spc"); break;
                case 127: sprintf(k, "Del"); break;
            }
            printf("%3d : %-3s   ", j, k);
        }
        printf("\n");
    }
    return 0;
}


Show the (decimal) value of a number of 1s appended with a 3, then squared

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

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

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

fn main() {
   let mut big_squares : Vec<u64> = Vec::new( ) ;
   let mut numberstrings : Vec<String> = Vec::new( ) ;
   for n in 0..8 {
      let mut numberstring : String = String::new( ) ;
      for i in 0..=n {
         if  i != 0  {
            numberstring.push( '1' ) ;
         }
      }
      numberstring.push('3') ;
      let number : u64 = numberstring.parse::<u64>().unwrap( ) ;
      numberstrings.push( numberstring ) ;
      big_squares.push( number.pow( 2 )) ;
   }
   for i in 0..numberstrings.len( ) {
      print!("{} ^ 2 =" , numberstrings[ i ] ) ;
      let width = 30 - (7 + i )  ;
      println!("{:>width$}" , big_squares[ i ] ) ;
   }
}


Show the epoch

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

int main() {
    time_t t = 0;
    printf("%s", asctime(gmtime(&t)));
    return 0;
}

extern crate time;

use time::{at_utc, Timespec};

fn main() {
    let epoch = at_utc(Timespec::new(0, 0));
    println!("{}", epoch.asctime());
}


Sierpinski carpet

#include <stdio.h>

int main()
{
	int i, j, dim, d;
	int depth = 3;

	for (i = 0, dim = 1; i < depth; i++, dim *= 3);

	for (i = 0; i < dim; i++) {
		for (j = 0; j < dim; j++) {
			for (d = dim / 3; d; d /= 3)
				if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
					break;
			printf(d ? "  " : "##");
		}
		printf("\n");
	}

	return 0;
}

fn main() {
    for i in 0..4 {
        println!("\nN={}", i);
        println!("{}", sierpinski_carpet(i));
    }
}

fn sierpinski_carpet(n: u32) -> String {
    let mut carpet = vec!["#".to_string()];
    for _ in 0..n {
        let mut top: Vec<_> = carpet.iter().map(|x| x.repeat(3)).collect();
        let middle: Vec<_> = carpet
            .iter()
            .map(|x| x.to_string() + &x.replace("#", " ") + x)
            .collect();
        let bottom = top.clone();

        top.extend(middle);
        top.extend(bottom);
        carpet = top;
    }
    carpet.join("\n")
}


Sierpinski triangle

#include <stdio.h>

#define SIZE (1 << 4)
int main()
{
	int x, y, i;
	for (y = SIZE - 1; y >= 0; y--, putchar('\n')) {
		for (i = 0; i < y; i++) putchar(' ');
		for (x = 0; x + y < SIZE; x++)
			printf((x & y) ? "  " : "* ");
	}
	return 0;
}

use std::iter::repeat;

fn sierpinski(order: usize) {
    let mut triangle = vec!["*".to_string()];
    for i in 0..order {
        let space = repeat(' ').take(2_usize.pow(i as u32)).collect::<String>();

        let mut d = triangle.clone();

        d.iter_mut().for_each(|r| {
            let new_row = format!("{}{}{}", space, r, space);
            *r = new_row;
        });

        triangle.iter().for_each(|r| {
            let new_row = format!("{}{}{}", r, " ", r);
            d.push(new_row);
        });

        triangle = d;
    }

    triangle.iter().for_each(|r| println!("{}", r));
}
fn main() {
    let order = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "4".to_string())
        .parse::<usize>()
        .unwrap();

    sierpinski(order);
}


Sieve of Eratosthenes

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

char*
eratosthenes(int n, int *c)
{
	char* sieve;
	int i, j, m;

	if(n < 2)
		return NULL;

	*c = n-1;
	m = (int) sqrt((double) n);

	sieve = calloc(n+1,sizeof(char));
	sieve[0] = 1;
	sieve[1] = 1;
	for(i = 2; i <= m; i++)
		if(!sieve[i])
			for (j = i*i; j <= n; j += i)
				if(!sieve[j]){
					sieve[j] = 1;
					--(*c);
				}
  	return sieve;
}

fn primes(n: usize) -> impl Iterator<Item = usize> {
    const START: usize = 2;
    if n < START {
        Vec::new()
    } else {
        let mut is_prime = vec![true; n + 1 - START];
        let limit = (n as f64).sqrt() as usize;
        for i in START..limit + 1 {
            let mut it = is_prime[i - START..].iter_mut().step_by(i);
            if let Some(true) = it.next() {
                it.for_each(|x| *x = false);
            }
        }
        is_prime
    }
    .into_iter()
    .enumerate()
    .filter_map(|(e, b)| if b { Some(e + START) } else { None })
}


Simple windowed application

#include <stdio.h>
#include <gtk/gtk.h>

const gchar *clickme = "Click Me";
guint counter = 0;

#define MAXLEN 64
void clickedme(GtkButton *o, gpointer d)
{
    GtkLabel *l = GTK_LABEL(d);
    char nt[MAXLEN];

    counter++;
    snprintf(nt, MAXLEN, "You clicked me %d times", counter);
    gtk_label_set_text(l, nt);
}

int main(int argc, char **argv)
{
    GtkWindow *win;
    GtkButton *button;
    GtkLabel *label;
    GtkVBox *vbox;

    gtk_init(&argc, &argv);
    win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(win, clickme);
    button = (GtkButton*)gtk_button_new_with_label(clickme);
    label = (GtkLabel*)gtk_label_new("There have been no clicks yet");
    gtk_label_set_single_line_mode(label, TRUE);
    vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1);
    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label));
    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button));
    gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));
    g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
    g_signal_connect(G_OBJECT(button), "clicked", (GCallback)clickedme, label);
    gtk_widget_show_all(GTK_WIDGET(win));
    gtk_main();
    return 0;
}

use iced::{
    button, Button, Column, Element, Length,
    Text, Sandbox, Settings, Space,
};

#[derive(Debug, Copy, Clone)]
struct Pressed;
struct Simple {
    value: i32,
    button: button::State,
}

impl Sandbox for Simple {
    type Message = Pressed;

    fn new() -> Simple {
        Simple {
            value: 0,
            button: button::State::new(),
        }
    }

    fn title(&self) -> String {
        "Simple Windowed Application".into()
    }

    fn view(&mut self) -> Element<Self::Message> {
        Column::new()
            .padding(20)
            .push({
                let text = match self.value {
                    0 => "there have been no clicks yet".into(),
                    1 => "there has been 1 click".into(),
                    n => format!("there have been {} clicks", n),
                };
                Text::new(text).size(24)
            }).push(
                Space::with_height(Length::Fill)
            ).push(
                Button::new(&mut self.button, Text::new("Click Me!"))
                    .on_press(Pressed)
            ).into()
    }

    fn update(&mut self, _: Self::Message) {
        self.value += 1;
    }
}

fn main() {
    let mut settings = Settings::default();
    settings.window.size = (600, 400);
    Simple::run(settings).unwrap();
}


Singly-linked list_Element definition

struct link {
  struct link *next;
  int data;
};

 struct Node<T> {
    elem: T,
    next: Option<Box<Node<T>>>,
}


Singly-linked list_Element insertion

void insert_append (struct link *anchor, struct link *newlink) {
  newlink->next = anchor->next;
  anchor->next = newlink;
}

impl<T> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push(&mut self, elem: T) {
    let new_node = Box::new(Node {
        elem: elem,
        next: self.head.take(),
    });
    self.head = Some(new_node);
}


Singly-linked list_Traversal

struct link *first;

struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {

}

pub struct IntoIter<T>(List<T>);

impl<T> Iterator for IntoIter<T> {
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.head.take().map(|node| {
            let node = *node;
            self.0.head = node.next;
            node.elem
        })
    }
}

pub struct Iter<'a, T: 'a> {
    next: Option<&'a Node<T>>,
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        self.next.take().map(|node| {
            self.next = node.next.as_ref().map(|node| &**node);
            &node.elem
        })
    }
}

pub struct IterMut<'a, T: 'a> {
    next: Option<&'a mut Node<T>>,
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;
    fn next(&mut self) -> Option<Self::Item> {
        self.next.take().map(|node| {
            self.next = node.next.as_mut().map(|node| &mut **node);
            &mut node.elem
        })
    }
}

impl<T> List<T> {
    pub fn into_iter(self) -> IntoIter<T> {
        IntoIter(self)
    }

    pub fn iter<'a>(&'a self) -> Iter<'a,T> {
        Iter { next: self.head.as_ref().map(|node| &**node) }
    }

    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut { next: self.head.as_mut().map(|node| &mut **node) }
    }

}


Sleep

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

int main()
{
  unsigned int seconds;
  scanf("%u", &seconds);
  printf("Sleeping...\n");
  sleep(seconds);
  printf("Awake!\n");
  return 0;
}

use std::{io, time, thread};

fn main() {
    println!("How long should we sleep in milliseconds?");

    let mut sleep_string = String::new();

    io::stdin().read_line(&mut sleep_string)
               .expect("Failed to read line");

    let sleep_timer: u64 = sleep_string.trim()
                                       .parse()
                                       .expect("Not an integer");
    let sleep_duration = time::Duration::from_millis(sleep_timer);

    println!("Sleeping...");
    thread::sleep(sleep_duration);
    println!("Awake!");
}


Smith numbers

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

int numPrimeFactors(unsigned x) {
    unsigned p = 2;
    int pf = 0;
    if (x == 1)
        return 1;
    else {
        while (true) {
            if (!(x % p)) {
                pf++;
                x /= p;
                if (x == 1)
                    return pf;
            }
            else
                ++p;
        }
    }
}

void primeFactors(unsigned x, unsigned* arr) {
    unsigned p = 2;
    int pf = 0;
    if (x == 1)
        arr[pf] = 1;
    else {
        while (true) {
            if (!(x % p)) {
                arr[pf++] = p;
                x /= p;
                if (x == 1)
                    return;
            }
            else
                p++;
        }
    }
}

unsigned sumDigits(unsigned x) {
    unsigned sum = 0, y;
    while (x) {
        y = x % 10;
        sum += y;
        x /= 10;
    }
    return sum;
}

unsigned sumFactors(unsigned* arr, int size) {
    unsigned sum = 0;
    for (int a = 0; a < size; a++)
        sum += sumDigits(arr[a]);
    return sum;
}

void listAllSmithNumbers(unsigned x) {
    unsigned *arr;
    for (unsigned a = 4; a < x; a++) {
        int numfactors = numPrimeFactors(a);
        arr = (unsigned*)malloc(numfactors * sizeof(unsigned));
        if (numfactors < 2)
            continue;
        primeFactors(a, arr);
        if (sumDigits(a) == sumFactors(arr,numfactors))
            printf("%4u ",a);
        free(arr);
    }
}

int main(int argc, char* argv[]) {
    printf("All the Smith Numbers < 10000 are:\n");
    listAllSmithNumbers(10000);
    return 0;
}

fn main () {

    let primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
    let mut solution = Vec::new();
    let mut number;
    for i in 4..10000 {

        let mut prime_factors = Vec::new();
        number = i;
        for j in &primes {
            while number % j == 0 {
                number = number / j;
                prime_factors.push(j);
            }
            if number == 1 { break; }
        }

        if number != 1 { prime_factors.push(&number); }

        if prime_factors.len() < 2 { continue; }

        if prime_factors.iter().fold(0, |n,x| n + x.to_string().chars().map(|d| d.to_digit(10).unwrap()).fold(0, |n,x| n + x))
            == i.to_string().chars().map(|d| d.to_digit(10).unwrap()).fold(0, |n,x| n + x) {
            solution.push(i);
        }
    }
    println!("Smith numbers below 10000 ({}) : {:?}",solution.len(), solution);
}


Sockets

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

const char *msg = "hello socket world";

int main()
{
   int i, sock, len, slen;

   struct addrinfo hints, *addrs;
   memset(&hints, 0, sizeof(struct addrinfo));
   hints.ai_family = AF_UNSPEC;
   hints.ai_socktype = SOCK_STREAM;

   if (0 == getaddrinfo("localhost", "256", &hints, &addrs))
   {
       sock = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);
       if ( sock >= 0 )
       {
           if ( connect(sock, addrs->ai_addr, addrs->ai_addrlen) >= 0 )
           {
               const char *pm = msg;
               do
               {
                  len = strlen(pm);
                  slen = send(sock, pm, len, 0);
                  pm += slen;
               } while ((0 <= slen) && (slen < len));
           }
           close(sock);
       }
       freeaddrinfo(addrs);
   }
}

use std::io::prelude::*;
use std::net::TcpStream;

fn main() {

    let mut my_stream = TcpStream::connect("127.0.0.1:256").unwrap();

    let _ = my_stream.write(b"hello socket world");

}


Soloway's recurring rainfall

#include <stdio.h>

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

	(void)argc;
	(void)argv;

	float currentAverage = 0;
	unsigned int currentEntryNumber = 0;

	for (;;)
	{
		int ret, entry;

		printf("Enter rainfall int, 99999 to quit: ");
		ret = scanf("%d", &entry);

		if (ret)
		{
			if (entry == 99999)
			{
				printf("User requested quit.\n");
				break;
			}
			else
			{
				currentEntryNumber++;
				currentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage;

				printf("New Average: %f\n", currentAverage);
			}
		}
		else
		{
			printf("Invalid input\n");
			while (getchar() != '\n');
		}
	}

	return 0;
}

fn main() {

	let mut current_average:f32 = 0.0;
	let mut current_entry_number:u32 = 0;

	loop
	{
		let current_entry;

		println!("Enter rainfall int, 99999 to quit: ");
		let mut input_text = String::new();
		std::io::stdin().read_line(&mut input_text).expect("Failed to read from stdin");
		let trimmed = input_text.trim();
		match trimmed.parse::<u32>() {
			Ok(new_entry) => current_entry = new_entry,
			Err(..) => { println!("Invalid input"); continue; }
		};

		if current_entry == 99999
		{
			println!("User requested quit.");
			break;
		}
		else
		{
			current_entry_number = current_entry_number + 1;
			current_average = current_average + (1.0 / current_entry_number as f32)*(current_entry as f32) - (1.0 / current_entry_number as f32)*current_average;

			println!("New Average: {}", current_average);
		}
	}
}


Sort a list of object identifiers

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

typedef struct oid_tag {
    char* str_;
    int* numbers_;
    int length_;
} oid;

void oid_destroy(oid* p) {
    if (p != 0) {
        free(p->str_);
        free(p->numbers_);
        free(p);
    }
}

int char_count(const char* str, char ch) {
    int count = 0;
    for (const char* p = str; *p; ++p) {
        if (*p == ch)
            ++count;
    }
    return count;
}

oid* oid_create(const char* str) {
    oid* ptr = calloc(1, sizeof(oid));
    if (ptr == 0)
        return 0;
    ptr->str_ = strdup(str);
    if (ptr->str_ == 0) {
        oid_destroy(ptr);
        return 0;
    }
    int dots = char_count(str, '.');
    ptr->numbers_ = malloc(sizeof(int) * (dots + 1));
    if (ptr->numbers_ == 0) {
        oid_destroy(ptr);
        return 0;
    }
    ptr->length_ = dots + 1;
    const char* p = str;
    for (int i = 0; i <= dots && *p;) {
        char* eptr = 0;
        int num = strtol(p, &eptr, 10);
        if (*eptr != 0 && *eptr != '.') {

            oid_destroy(ptr);
            return 0;
        }
        ptr->numbers_[i++] = num;
        p = eptr;
        if (*p)
            ++p;
    }
    return ptr;
}

int oid_compare(const void* p1, const void* p2) {
    const oid* o1 = *(oid* const*)p1;
    const oid* o2 = *(oid* const*)p2;
    int i1 = 0, i2 = 0;
    for (; i1 < o1->length_ && i2 < o2->length_; ++i1, ++i2) {
        if (o1->numbers_[i1] < o2->numbers_[i2])
            return -1;
        if (o1->numbers_[i1] > o2->numbers_[i2])
            return 1;
    }
    if (o1->length_ < o2->length_)
        return -1;
    if (o1->length_ > o2->length_)
        return 1;
    return 0;
}

int main() {
    const char* input[] = {
        "1.3.6.1.4.1.11.2.17.19.3.4.0.10",
        "1.3.6.1.4.1.11.2.17.5.2.0.79",
        "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
        "1.3.6.1.4.1.11150.3.4.0.1",
        "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
        "1.3.6.1.4.1.11150.3.4.0"
    };
    const int len = sizeof(input)/sizeof(input[0]);
    oid* oids[len];
    memset(oids, 0, sizeof(oids));
    int i;
    for (i = 0; i < len; ++i) {
        oids[i] = oid_create(input[i]);
        if (oids[i] == 0)
        {
            fprintf(stderr, "Out of memory\n");
            goto cleanup;
        }
    }
    qsort(oids, len, sizeof(oid*), oid_compare);
    for (i = 0; i < len; ++i)
        puts(oids[i]->str_);
cleanup:
    for (i = 0; i < len; ++i)
        oid_destroy(oids[i]);
    return 0;
}


Sort an array of composite structures

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

typedef struct twoStringsStruct {
    char * key, *value;
} sTwoStrings;

int ord( char v )
{
    static char *dgts = "012345679";
    char *cp;
    for (cp=dgts; v != *cp; cp++);
    return (cp-dgts);
}

int cmprStrgs(const sTwoStrings *s1,const sTwoStrings *s2)
{
    char *p1 = s1->key;
    char *p2 = s2->key;
    char *mrk1, *mrk2;
    while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++;}
    if (isdigit(*p1) && isdigit(*p2)) {
        long v1, v2;
        if ((*p1 == '0') ||(*p2 == '0')) {
            while (p1 > s1->key) {
                p1--; p2--;
                if (*p1 != '0') break;
            }
            if (!isdigit(*p1)) {
                p1++; p2++;
            }
        }
        mrk1 = p1; mrk2 = p2;
        v1 = 0;
        while(isdigit(*p1)) {
            v1 = 10*v1+ord(*p1);
            p1++;
        }
        v2 = 0;
        while(isdigit(*p2)) {
            v2 = 10*v2+ord(*p2);
            p2++;
        }
        if (v1 == v2)
           return(p2-mrk2)-(p1-mrk1);
        return v1 - v2;
    }
    if (tolower(*p1) != tolower(*p2))
       return (tolower(*p1) - tolower(*p2));
    for(p1=s1->key, p2=s2->key; (*p1 == *p2) && *p1; p1++, p2++);
    return (*p1 -*p2);
}

int maxstrlen( char *a, char *b)
{
	int la = strlen(a);
	int lb = strlen(b);
	return (la>lb)? la : lb;
}

int main()
{
    sTwoStrings toBsorted[] = {
        { "Beta11a", "many" },
        { "alpha1", "This" },
        { "Betamax", "sorted." },
        { "beta3", "order" },
        { "beta11a", "strings" },
        { "beta001", "is" },
        { "beta11", "which" },
        { "beta041", "be" },
        { "beta05", "in" },
        { "beta1", "the" },
        { "beta40", "should" },
    };
#define ASIZE (sizeof(toBsorted)/sizeof(sTwoStrings))
    int k, maxlens[ASIZE];
    char format[12];
    sTwoStrings *cp;

    qsort( (void*)toBsorted, ASIZE, sizeof(sTwoStrings),cmprStrgs);

    for (k=0,cp=toBsorted; k < ASIZE; k++,cp++) {
        maxlens[k] = maxstrlen(cp->key, cp->value);
        sprintf(format," %%-%ds", maxlens[k]);
        printf(format, toBsorted[k].value);
	}
    printf("\n");
    for (k=0; k < ASIZE; k++) {
        sprintf(format," %%-%ds", maxlens[k]);
        printf(format, toBsorted[k].key);
	}
    printf("\n");

  return 0;
}

use std::cmp::Ordering;

#[derive(Debug)]
struct Employee {
    name: String,
    category: String,
}

impl Employee {
    fn new(name: &str, category: &str) -> Self {
        Employee {
            name: name.into(),
            category: category.into(),
        }
    }
}

impl PartialEq for Employee {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl Eq for Employee {}

impl PartialOrd for Employee {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Employee {
    fn cmp(&self, other: &Self) -> Ordering {
        self.name.cmp(&other.name)
    }
}

fn main() {
    let mut employees = vec![
        Employee::new("David", "Manager"),
        Employee::new("Alice", "Sales"),
        Employee::new("Joanna", "Director"),
        Employee::new("Henry", "Admin"),
        Employee::new("Tim", "Sales"),
        Employee::new("Juan", "Admin"),
    ];
    employees.sort();
    for e in employees {
        println!("{:<6} : {}", e.name, e.category);
    }
}


Sort an integer array

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

int intcmp(const void *aa, const void *bb)
{
    const int *a = aa, *b = bb;
    return (*a < *b) ? -1 : (*a > *b);
}

int main()
{
    int nums[5] = {2,4,3,1,2};
    qsort(nums, 5, sizeof(int), intcmp);
    printf("result: %d %d %d %d %d\n",
      nums[0], nums[1], nums[2], nums[3], nums[4]);
    return 0;
}


Sort disjoint sublist

#include <stdio.h>

void bubble_sort(int *idx, int n_idx, int *buf)
{
        int i, j, tmp;
#define for_ij for (i = 0; i < n_idx; i++) for (j = i + 1; j < n_idx; j++)
#define sort(a, b) if (a < b) { tmp = a; a = b; b = tmp;}
        for_ij { sort(idx[j], idx[i]);          }
        for_ij { sort(buf[idx[j]], buf[idx[i]]);}
#undef for_ij
#undef sort
}

int main()
{
        int values[] = {7, 6, 5, 4, 3, 2, 1, 0};
        int idx[] = {6, 1, 7};
        int i;

        printf("before sort:\n");
        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);

        printf("\n\nafter sort:\n");
        bubble_sort(idx, 3, values);

        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);
        printf("\n");

        return 0;
}

use std::collections::BTreeSet;

fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) {
    let mut sorted = indices.to_owned();
    sorted.sort_unstable_by_key(|k| &array[*k]);
    indices
        .iter()
        .zip(sorted.iter())
        .map(|(&a, &b)| if a > b { (b, a) } else { (a, b) })
        .collect::<BTreeSet<_>>()
        .iter()
        .for_each(|(a, b)| array.swap(*a, *b))
}

fn main() {
    let mut array = [7, 6, 5, 4, 3, 2, 1, 0];
    let indices = [6, 1, 7];
    disjoint_sort(&mut array, &indices);
    println!("{:?}", array);
}


Sort numbers lexicographically

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

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

void lexOrder(int n, int *ints) {
    char **strs;
    int i, first = 1, last = n, k = n, len;
    if (n < 1) {
        first = n; last = 1; k = 2 - n;
    }
    strs = malloc(k * sizeof(char *));
    for (i = first; i <= last; ++i) {
        if (i >= 1) len = (int)log10(i) + 2;
        else if (i == 0) len = 2;
        else len = (int)log10(-i) + 3;
        strs[i-first] = malloc(len);
        sprintf(strs[i-first], "%d", i);
    }
    qsort(strs, k, sizeof(char *), compareStrings);
    for (i = 0; i < k; ++i) {
        ints[i] = atoi(strs[i]);
        free(strs[i]);
    }
    free(strs);
}

int main() {
    int i, j, k, n,  *ints;
    int numbers[5] = {0, 5, 13, 21, -22};
    printf("In lexicographical order:\n\n");
    for (i = 0; i < 5; ++i) {
        k = n = numbers[i];
        if (k < 1) k = 2 - k;
        ints = malloc(k * sizeof(int));
        lexOrder(n, ints);
        printf("%3d: [", n);
        for (j = 0; j < k; ++j) {
            printf("%d ", ints[j]);
        }
        printf("\b]\n");
        free(ints);
    }
    return 0;
}

fn lex_sorted_vector(num: i32) -> Vec<i32> {
    let (min, max) = if num >= 1 { (1, num) } else { (num, 1) };
    let mut str: Vec<String> = (min..=max).map(|i| i.to_string()).collect();
    str.sort();
    str.iter().map(|s| s.parse::<i32>().unwrap()).collect()
}

fn main() {
    for n in &[0, 5, 13, 21, -22] {
        println!("{}: {:?}", n, lex_sorted_vector(*n));
    }
}


Sort three variables

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

#define MAX 3

int main()
{
  char values[MAX][100],tempStr[100];
  int i,j,isString=0;
  double val[MAX],temp;

  for(i=0;i<MAX;i++){
    printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd"));
    fgets(values[i],100,stdin);

    for(j=0;values[i][j]!=00;j++){
      if(((values[i][j]<'0' || values[i][j]>'9') && (values[i][j]!='.' ||values[i][j]!='-'||values[i][j]!='+'))
      ||((values[i][j]=='.' ||values[i][j]=='-'||values[i][j]=='+')&&(values[i][j+1]<'0' || values[i][j+1]>'9')))
        isString = 1;
    }
  }

  if(isString==0){
    for(i=0;i<MAX;i++)
      val[i] = atof(values[i]);
  }

  for(i=0;i<MAX-1;i++){
    for(j=i+1;j<MAX;j++){
      if(isString==0 && val[i]>val[j]){
        temp = val[j];
        val[j] = val[i];
        val[i] = temp;
      }

      else if(values[i][0]>values[j][0]){
        strcpy(tempStr,values[j]);
        strcpy(values[j],values[i]);
        strcpy(values[i],tempStr);
      }
    }
  }

  for(i=0;i<MAX;i++)
    isString==1?printf("%c = %s",'X'+i,values[i]):printf("%c = %lf",'X'+i,val[i]);

  return 0;
}

fn main() {
    let mut array = [5, 1, 3];
    array.sort();
    println!("Sorted: {:?}", array);
    array.sort_by(|a, b| b.cmp(a));
    println!("Reverse sorted: {:?}", array);
}


Sort using a custom comparator

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

int mycmp(const void *s1, const void *s2)
{
    const char *l = *(const char **)s1, *r = *(const char **)s2;
    size_t ll = strlen(l), lr = strlen(r);

    if (ll > lr) return -1;
    if (ll < lr) return 1;
    return strcasecmp(l, r);
}

int main()
{
    const char *strings[] = {
      "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };

    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
    return 0;
}

fn main() {
    let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
    words.sort_by(|l, r| Ord::cmp(&r.len(), &l.len()).then(Ord::cmp(l, r)));
    println!("{:?}", words);
}


Sorting algorithms_Bogosort

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

bool is_sorted(int *a, int n)
{
  while ( --n >= 1 ) {
    if ( a[n] < a[n-1] ) return false;
  }
  return true;
}

void shuffle(int *a, int n)
{
  int i, t, r;
  for(i=0; i < n; i++) {
    t = a[i];
    r = rand() % n;
    a[i] = a[r];
    a[r] = t;
  }
}

void bogosort(int *a, int n)
{
  while ( !is_sorted(a, n) ) shuffle(a, n);
}

int main()
{
  int numbers[] = { 1, 10, 9,  7, 3, 0 };
  int i;

  bogosort(numbers, 6);
  for (i=0; i < 6; i++) printf("%d ", numbers[i]);
  printf("\n");
}

extern crate rand;
use rand::Rng;

fn bogosort_by<T,F>(order: F, coll: &mut [T])
    where F: Fn(&T, &T) -> bool
{
    let mut rng = rand::thread_rng();
    while !is_sorted_by(&order, coll) {
        rng.shuffle(coll);
    }
}

#[inline]
fn is_sorted_by<T,F>(order: F, coll: &[T]) -> bool
    where F: Fn(&T,&T) -> bool,
{
    coll[..].iter().zip(&coll[1..]).all(|(x,y)| order(x,y))
}

fn main() {
    let mut testlist = [1,55,88,24,990876,312,67,0,854,13,4,7];
    bogosort_by(|x,y| x < y, &mut testlist);
    println!("{:?}", testlist);
    bogosort_by(|x,y| x > y, &mut testlist);
    println!("{:?}", testlist);
}


Sorting algorithms_Bubble sort

fn bubble_sort<T: Ord>(values: &mut[T]) {
    let mut n = values.len();
    let mut swapped = true;

    while swapped {
        swapped = false;

        for i in 1..n {
            if values[i - 1] > values[i] {
                values.swap(i - 1, i);
                swapped = true;
            }
        }

        n = n - 1;
    }
}

fn main() {

    let mut numbers = [8, 7, 1, 2, 9, 3, 4, 5, 0, 6];
    println!("Before: {:?}", numbers);

    bubble_sort(&mut numbers);
    println!("After: {:?}", numbers);

    let mut strings = ["empty", "beach", "art", "car", "deal"];
    println!("Before: {:?}", strings);

    bubble_sort(&mut strings);
    println!("After: {:?}", strings);
}


Sorting algorithms_Cocktail sort

#include <stdio.h>

void swap(int *x, int *y) {
	if(x == y)
		return;
	*x ^= *y;
	*y ^= *x;
	*x ^= *y;
}
void cocktailsort(int *a, size_t n) {
	while(1) {

		char flag;
		size_t start[2] = {1, n - 1},
			   end[2] = {n, 0},
			   inc[2] = {1, -1};
		for(int it = 0; it < 2; ++it) {
			flag = 1;
			for(int i = start[it]; i != end[it]; i += inc[it])
				if(a[i - 1] > a[i]) {
					swap(a + i - 1, a + i);
					flag = 0;
				}
			if(flag)
				return;
		}
	}
}

int main(void) {
	int a[] = { 5, -1, 101, -4, 0, 1, 8, 6, 2, 3 };
	size_t n = sizeof(a)/sizeof(a[0]);

	cocktailsort(a, n);
	for (size_t i = 0; i < n; ++i)
		printf("%d ", a[i]);
	return 0;
}

fn cocktail_sort<T: PartialOrd>(a: &mut [T]) {
    let len = a.len();
    loop {
        let mut swapped = false;
        let mut i = 0;
        while i + 1 < len {
            if a[i] > a[i + 1] {
                a.swap(i, i + 1);
                swapped = true;
            }
            i += 1;
        }
        if swapped {
            swapped = false;
            i = len - 1;
            while i > 0 {
                if a[i - 1] > a[i] {
                    a.swap(i - 1, i);
                    swapped = true;
                }
                i -= 1;
            }
        }
        if !swapped {
            break;
        }
    }
}

fn main() {
    let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
    println!("before: {:?}", v);
    cocktail_sort(&mut v);
    println!("after:  {:?}", v);
}


Sorting algorithms_Comb sort

void Combsort11(double a[], int nElements)
{
  int i, j, gap, swapped = 1;
  double temp;

  gap = nElements;
  while (gap > 1 || swapped == 1)
  {
    gap = gap * 10 / 13;
    if (gap == 9 || gap == 10) gap = 11;
    if (gap < 1) gap = 1;
    swapped = 0;
    for (i = 0, j = gap; j < nElements; i++, j++)
    {
      if (a[i] > a[j])
      {
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        swapped = 1;
      }
    }
  }
}

fn comb_sort<T: PartialOrd>(a: &mut [T]) {
    let len = a.len();
    let mut gap = len;
    let mut swapped = true;
    while gap > 1 || swapped {
        gap = (4 * gap) / 5;
        if gap < 1 {
            gap = 1;
        }
        let mut i = 0;
        swapped = false;
        while i + gap < len {
            if a[i] > a[i + gap] {
                a.swap(i, i + gap);
                swapped = true;
            }
            i += 1;
        }
    }
}

fn main() {
    let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
    println!("before: {:?}", v);
    comb_sort(&mut v);
    println!("after:  {:?}", v);
}


Sorting algorithms_Counting sort

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

void counting_sort_mm(int *array, int n, int min, int max)
{
  int i, j, z;

  int range = max - min + 1;
  int *count = malloc(range * sizeof(*array));

  for(i = 0; i < range; i++) count[i] = 0;
  for(i = 0; i < n; i++) count[ array[i] - min ]++;

  for(i = min, z = 0; i <= max; i++) {
    for(j = 0; j < count[i - min]; j++) {
      array[z++] = i;
    }
  }

  free(count);
}

void min_max(int *array, int n, int *min, int *max)
{
  int i;

  *min = *max = array[0];
  for(i=1; i < n; i++) {
    if ( array[i] < *min ) {
      *min = array[i];
    } else if ( array[i] > *max ) {
      *max = array[i];
    }
  }
}

fn counting_sort(
    mut data: Vec<usize>,
    min: usize,
    max: usize,
) -> Vec<usize> {

    let mut count: Vec<usize> = Vec::with_capacity(data.len());
    count.resize(data.len(), 0);

    for num in &data {
        count[num - min] = count[num - min] + 1;
    }
    let mut z: usize = 0;
    for i in min..max+1 {
        while count[i - min] > 0 {
            data[z] = i;
            z += 1;
            count[i - min] = count[i - min] - 1;
        }
    }

    data
}

fn main() {
    let arr1 = vec![1, 0, 2, 9, 3, 8, 4, 7, 5, 6];
    println!("{:?}", counting_sort(arr1, 0, 9));

    let arr2 = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    println!("{:?}", counting_sort(arr2, 0, 9));

    let arr3 = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
    println!("{:?}", counting_sort(arr3, 0, 10));
}


Sorting algorithms_Gnome sort

void gnome_sort(int *a, int n)
{
  int i=1, j=2, t;
# define swap(i, j) { t = a[i]; a[i] = a[j]; a[j] = t; }
  while(i < n) {
    if (a[i - 1] > a[i]) {
      swap(i - 1, i);
      if (--i) continue;
    }
    i = j++;
  }
# undef swap
}

fn gnome_sort<T: PartialOrd>(a: &mut [T]) {
    let len = a.len();
    let mut i: usize = 1;
    let mut j: usize = 2;
    while i < len {
        if a[i - 1] <= a[i] {

            i = j;
            j += 1;
        } else {
            a.swap(i - 1, i);
            i -= 1;
            if i == 0 {
                i = j;
                j += 1;
            }
        }
    }
}

fn main() {
    let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
    println!("before: {:?}", v);
    gnome_sort(&mut v);
    println!("after:  {:?}", v);
}


Sorting algorithms_Heapsort

#include <stdio.h>

int max (int *a, int n, int i, int j, int k) {
    int m = i;
    if (j < n && a[j] > a[m]) {
        m = j;
    }
    if (k < n && a[k] > a[m]) {
        m = k;
    }
    return m;
}

void downheap (int *a, int n, int i) {
    while (1) {
        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
        if (j == i) {
            break;
        }
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
        i = j;
    }
}

void heapsort (int *a, int n) {
    int i;
    for (i = (n - 2) / 2; i >= 0; i--) {
        downheap(a, n, i);
    }
    for (i = 0; i < n; i++) {
        int t = a[n - i - 1];
        a[n - i - 1] = a[0];
        a[0] = t;
        downheap(a, n - i - 1, 0);
    }
}

int main () {
    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
    int n = sizeof a / sizeof a[0];
    int i;
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    heapsort(a, n);
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    return 0;
}

fn main() {
    let mut v = [4, 6, 8, 1, 0, 3, 2, 2, 9, 5];
    heap_sort(&mut v, |x, y| x < y);
    println!("{:?}", v);
}

fn heap_sort<T, F>(array: &mut [T], order: F)
where
    F: Fn(&T, &T) -> bool,
{
    let len = array.len();

    for start in (0..len / 2).rev() {
        shift_down(array, &order, start, len - 1)
    }

    for end in (1..len).rev() {
        array.swap(0, end);
        shift_down(array, &order, 0, end - 1)
    }
}

fn shift_down<T, F>(array: &mut [T], order: &F, start: usize, end: usize)
where
    F: Fn(&T, &T) -> bool,
{
    let mut root = start;
    loop {
        let mut child = root * 2 + 1;
        if child > end {
            break;
        }
        if child + 1 <= end && order(&array[child], &array[child + 1]) {
            child += 1;
        }
        if order(&array[root], &array[child]) {
            array.swap(root, child);
            root = child
        } else {
            break;
        }
    }
}


Sorting algorithms_Insertion sort

#include <stdio.h>

void insertion_sort(int*, const size_t);

void insertion_sort(int *a, const size_t n) {
	for(size_t i = 1; i < n; ++i) {
		int key = a[i];
		size_t j = i;
		while( (j > 0) && (key < a[j - 1]) ) {
			a[j] = a[j - 1];
			--j;
		}
		a[j] = key;
	}
}

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

    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};

    const size_t n = sizeof(a) / sizeof(a[0]) ;

    for (size_t i = 0; i < n; i++)
        printf("%d%s", a[i], (i == (n - 1))? "\n" : " ");

    insertion_sort(a, n);

    for (size_t i = 0; i < n; i++)
        printf("%d%s", a[i], (i == (n - 1))? "\n" : " ");

    return 0;
}

fn insertion_sort<T: std::cmp::Ord>(arr: &mut [T]) {
    for i in 1..arr.len() {
        let mut j = i;
        while j > 0 && arr[j] < arr[j-1] {
            arr.swap(j, j-1);
            j = j-1;
        }
    }
}


Sorting algorithms_Merge sort

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

void merge (int *a, int n, int m) {
    int i, j, k;
    int *x = malloc(n * sizeof (int));
    for (i = 0, j = m, k = 0; k < n; k++) {
        x[k] = j == n      ? a[i++]
             : i == m      ? a[j++]
             : a[j] < a[i] ? a[j++]
             :               a[i++];
    }
    for (i = 0; i < n; i++) {
        a[i] = x[i];
    }
    free(x);
}

void merge_sort (int *a, int n) {
    if (n < 2)
        return;
    int m = n / 2;
    merge_sort(a, m);
    merge_sort(a + m, n - m);
    merge(a, n, m);
}

int main () {
    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
    int n = sizeof a / sizeof a[0];
    int i;
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    merge_sort(a, n);
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    return 0;
}

pub fn merge_sort1<T: Copy + Ord>(v: &mut [T]) {
    sort(v, &mut Vec::new());

    fn sort<T: Copy + Ord>(v: &mut [T], t: &mut Vec<T>) {
        match v.len() {
            0 | 1 => (),

            n => {
                if t.is_empty() {
                    t.reserve_exact(n);
                    t.resize(n, v[0]);
                }
                let m = n / 2;
                sort(&mut v[..m], t);
                sort(&mut v[m..], t);
                if v[m - 1] <= v[m] {
                    return;
                }
                copy(v, t);
                merge(&t[..m], &t[m..n], v);
            }
        }
    }

    #[inline(always)]
    fn merge<T: Copy + Ord>(a: &[T], b: &[T], c: &mut [T]) {
        let (mut i, mut j) = (0, 0);
        for k in 0..c.len() {
            if i < a.len() && (j >= b.len() || a[i] <= b[j]) {
                c[k] = a[i];
                i += 1;
            } else {
                c[k] = b[j];
                j += 1;
            }
        }
    }

    #[inline(always)]
    fn copy<T: Copy>(src: &[T], dst: &mut [T]) {
        for i in 0..src.len() {
            dst[i] = src[i];
        }
    }

    #[inline(always)]
    fn insertion_sort<T: Ord>(v: &mut [T]) {
        for i in 1..v.len() {
            let mut j = i;
            while j > 0 && v[j] < v[j - 1] {
                v.swap(j, j - 1);
                j -= 1;
            }
        }
    }
}


Sorting algorithms_Quicksort

#include <stdio.h>

void quicksort(int *A, int len);

int main (void) {
  int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
  int n = sizeof a / sizeof a[0];

  int i;
  for (i = 0; i < n; i++) {
    printf("%d ", a[i]);
  }
  printf("\n");

  quicksort(a, n);

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

  return 0;
}

void quicksort(int *A, int len) {
  if (len < 2) return;

  int pivot = A[len / 2];

  int i, j;
  for (i = 0, j = len - 1; ; i++, j--) {
    while (A[i] < pivot) i++;
    while (A[j] > pivot) j--;

    if (i >= j) break;

    int temp = A[i];
    A[i]     = A[j];
    A[j]     = temp;
  }

  quicksort(A, i);
  quicksort(A + i, len - i);
}

fn main() {
    println!("Sort numbers in descending order");
    let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
    println!("Before: {:?}", numbers);

    quick_sort(&mut numbers, &|x,y| x > y);
    println!("After:  {:?}\n", numbers);

    println!("Sort strings alphabetically");
    let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"];
    println!("Before: {:?}", strings);

    quick_sort(&mut strings, &|x,y| x < y);
    println!("After:  {:?}\n", strings);

    println!("Sort strings by length");
    println!("Before: {:?}", strings);

    quick_sort(&mut strings, &|x,y| x.len() < y.len());
    println!("After:  {:?}", strings);
}

fn quick_sort<T,F>(v: &mut [T], f: &F)
    where F: Fn(&T,&T) -> bool
{
    let len = v.len();
    if len >= 2 {
        let pivot_index = partition(v, f);
        quick_sort(&mut v[0..pivot_index], f);
        quick_sort(&mut v[pivot_index + 1..len], f);
    }
}

fn partition<T,F>(v: &mut [T], f: &F) -> usize
    where F: Fn(&T,&T) -> bool
{
    let len = v.len();
    let pivot_index = len / 2;
    let last_index = len - 1;

    v.swap(pivot_index, last_index);

    let mut store_index = 0;
    for i in 0..last_index {
        if f(&v[i], &v[last_index]) {
            v.swap(i, store_index);
            store_index += 1;
        }
    }

    v.swap(store_index, len - 1);
    store_index
}


Sorting algorithms_Radix sort

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

#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)

#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));

static void swap(unsigned *a, unsigned *b) {
    unsigned tmp = *a;
    *a = *b;
    *b = tmp;
}

static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
	if (!bit || to < from + 1) return;

	unsigned *ll = from, *rr = to - 1;
	for (;;) {

		while (ll < rr && !(*ll & bit)) ll++;
		while (ll < rr &&  (*rr & bit)) rr--;
		if (ll >= rr) break;
		swap(ll, rr);
	}

	if (!(bit & *ll) && ll < to) ll++;
	bit >>= 1;

	rad_sort_u(from, ll, bit);
	rad_sort_u(ll, to, bit);
}

static void radix_sort(int *a, const size_t len)
{
	size_t i;
	unsigned *x = (unsigned*) a;

	for (i = 0; i < len; i++)
            x[i] ^= INT_MIN;

        rad_sort_u(x, x + len, INT_MIN);

        for (i = 0; i < len; i++)
            x[i] ^= INT_MIN;
}

int main(void)
{

    srand(time(NULL));
    int x[16];

     for (size_t i = 0; i < ARR_LEN(x); i++)
        x[i] = RAND_RNG(-128,127)

    radix_sort(x, ARR_LEN(x));

    for (size_t i = 0; i < ARR_LEN(x); i++)
        printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}

fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) {
    let (left, right) = out.split_at_mut(in1.len());
    left.clone_from_slice(in1);
    right.clone_from_slice(in2);
}

fn radix_sort(data: &mut [i32]) {
    for bit in 0..31 {

        let (small, big): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| (x >> bit) & 1 == 0);
        merge(&small, &big, data);
    }

    let (negative, positive): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| x < 0);
    merge(&negative, &positive, data);
}

fn main() {
    let mut data = [170, 45, 75, -90, -802, 24, 2, 66, -17, 2];
    println!("Before: {:?}", data);
    radix_sort(&mut data);
    println!("After: {:?}", data);
}


Sorting algorithms_Selection sort

fn selection_sort(array: &mut [i32]) {

    let mut min;

    for i in 0..array.len() {

        min = i;

        for j in (i+1)..array.len() {

            if array[j] < array[min] {
                min = j;
            }
        }

        let tmp = array[i];
        array[i] = array[min];
        array[min] = tmp;
    }
}

fn main() {

    let mut array = [ 9, 4, 8, 3, -5, 2, 1, 6 ];
    println!("The initial array is {:?}", array);

    selection_sort(&mut array);
    println!(" The sorted array is {:?}", array);
}


Sorting algorithms_Sleep sort

use std::thread;

fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
    let threads: Vec<_> = nums.map(|n|
        thread::spawn(move || {
            thread::sleep_ms(n);
            println!("{}", n); })).collect();
    for t in threads { t.join(); }
}

fn main() {
    sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap()));
}


Spiral matrix

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

#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
	int i, j, m = 0, n = 0;

	if (c >= 2) m = atoi(v[1]);
	if (c >= 3) n = atoi(v[2]);
	if (m <= 0) m = 5;
	if (n <= 0) n = m;

	int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
	s[0] = (int*)(s + m);
	for (i = 1; i < m; i++) s[i] = s[i - 1] + n;

	int dx = 1, dy = 0, val = 0, t;
	for (i = j = 0; valid(i, j); i += dy, j += dx ) {
		for (; valid(i, j); j += dx, i += dy)
			s[i][j] = ++val;

		j -= dx; i -= dy;
		t = dy; dy = dx; dx = -t;
	}

	for (t = 2; val /= 10; t++);

	for(i = 0; i < m; i++)
		for(j = 0; j < n || !putchar('\n'); j++)
			printf("%*d", t, s[i][j]);

	return 0;
}

const VECTORS: [(isize, isize); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)];

pub fn spiral_matrix(size: usize) -> Vec<Vec<u32>> {
    let mut matrix = vec![vec![0; size]; size];
    let mut movement = VECTORS.iter().cycle();
    let (mut x, mut y, mut n) = (-1, 0, 1..);

    for (move_x, move_y) in std::iter::once(size)
        .chain((1..size).rev().flat_map(|n| std::iter::repeat(n).take(2)))
        .flat_map(|steps| std::iter::repeat(movement.next().unwrap()).take(steps))
    {
        x += move_x;
        y += move_y;
        matrix[y as usize][x as usize] = n.next().unwrap();
    }

    matrix
}

fn main() {
    for i in spiral_matrix(4).iter() {
        for j in i.iter() {
            print!("{:>2} ", j);
        }
        println!();
    }
}


Split a character string based on change of character

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *split(char *str);
int main(int argc,char **argv)
{
	char input[13]="gHHH5YY++
	printf("%s\n",split(input));
}
char *split(char *str)
{
	char last=*str,*result=malloc(3*strlen(str)),*counter=result;
	for (char *c=str;*c;c++) {
		if (*c!=last) {
			strcpy(counter,", ");
			counter+=2;
			last=*c;
		}
		*counter=*c;
		counter++;
	}
	*(counter--)='\0';
	return realloc(result,strlen(result));
}

fn splitter(string: &str) -> String {
    let chars: Vec<_> = string.chars().collect();
    let mut result = Vec::new();
    let mut last_mismatch = 0;
    for i in 0..chars.len() {
        if chars.len() == 1 {
            return chars[0..1].iter().collect();
        }
        if i > 0 && chars[i-1] != chars[i] {
            let temp_result: String = chars[last_mismatch..i].iter().collect();
            result.push(temp_result);
            last_mismatch = i;
        }
        if i == chars.len() - 1 {
            let temp_result: String = chars[last_mismatch..chars.len()].iter().collect();
            result.push(temp_result);
        }
    }
    result.join(", ")
}

fn main() {
    let test_string = "g";
    println!("input string: {}", test_string);
    println!("output string: {}", splitter(test_string));

    let test_string = "";
    println!("input string: {}", test_string);
    println!("output string: {}", splitter(test_string));

    let test_string = "gHHH5YY++
    println!("input string: {}", test_string);
    println!("output string: {}", splitter(test_string));
}


Square but not cube

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

int main() {
    int n = 1, count = 0, sq, cr;
    for ( ; count < 30; ++n) {
        sq = n * n;
        cr = (int)cbrt((double)sq);
        if (cr * cr * cr != sq) {
            count++;
            printf("%d\n", sq);
        }
        else {
            printf("%d is square and cube\n", sq);
        }
    }
    return 0;
}

fn main() {
    let mut s = 1;
    let mut c = 1;
    let mut cube = 1;
    let mut n = 0;
    while n < 30 {
        let square = s * s;
        while cube < square {
            c += 1;
            cube = c * c * c;
        }
        if cube == square {
            println!("{} is a square and a cube.", square);
        } else {
            println!("{}", square);
            n += 1;
        }
        s += 1;
    }
}


Stack

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

#define DECL_STACK_TYPE(type, name)					\
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;	\
stk_##name stk_##name##_create(size_t init_size) {			\
	stk_##name s; if (!init_size) init_size = 4;			\
	s = malloc(sizeof(struct stk_##name##_t));			\
	if (!s) return 0;						\
	s->buf = malloc(sizeof(type) * init_size);			\
	if (!s->buf) { free(s); return 0; }				\
	s->len = 0, s->alloc = init_size;				\
	return s; }							\
int stk_##name##_push(stk_##name s, type item) {			\
	type *tmp;							\
	if (s->len >= s->alloc) {					\
		tmp = realloc(s->buf, s->alloc*2*sizeof(type));		\
		if (!tmp) return -1; s->buf = tmp;			\
		s->alloc *= 2; }					\
	s->buf[s->len++] = item;					\
	return s->len; }						\
type stk_##name##_pop(stk_##name s) {					\
	type tmp;							\
	if (!s->len) abort();						\
	tmp = s->buf[--s->len];						\
	if (s->len * 2 <= s->alloc && s->alloc >= 8) {			\
		s->alloc /= 2;						\
		s->buf = realloc(s->buf, s->alloc * sizeof(type));}	\
	return tmp; }							\
void stk_##name##_delete(stk_##name s) {				\
	free(s->buf); free(s); }

#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)

DECL_STACK_TYPE(int, int)

int main(void)
{
	int i;
	stk_int stk = stk_int_create(0);

	printf("pushing: ");
	for (i = 'a'; i <= 'z'; i++) {
		printf(" %c", i);
		stk_int_push(stk, i);
	}

	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	printf("\npoppoing:");
	while (stk_size(stk))
		printf(" %c", stk_int_pop(stk));
	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	stk_int_delete(stk);
	return 0;
}

fn main() {
    let mut stack = Vec::new();
    stack.push("Element1");
    stack.push("Element2");
    stack.push("Element3");

    assert_eq!(Some(&"Element3"), stack.last());
    assert_eq!(Some("Element3"), stack.pop());
    assert_eq!(Some("Element2"), stack.pop());
    assert_eq!(Some("Element1"), stack.pop());
    assert_eq!(None, stack.pop());
}


Stair-climbing puzzle

void step_up(void)
{
    while (!step()) {
        step_up();
    }
}

fn step_up() {
	while !step() {
		step_up();
	}
}


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

#define n_bins 10

double rand01() { return rand() / (RAND_MAX + 1.0); }

double avg(int count, double *stddev, int *hist)
{
	double x[count];
	double m = 0, s = 0;

	for (int i = 0; i < n_bins; i++) hist[i] = 0;
	for (int i = 0; i < count; i++) {
		m += (x[i] = rand01());
		hist[(int)(x[i] * n_bins)] ++;
	}

	m /= count;
	for (int i = 0; i < count; i++)
		s += x[i] * x[i];
	*stddev = sqrt(s / count - m * m);
	return m;
}

void hist_plot(int *hist)
{
	int max = 0, step = 1;
	double inc = 1.0 / n_bins;

	for (int i = 0; i < n_bins; i++)
		if (hist[i] > max) max = hist[i];

	if (max >= 60) step = (max + 59) / 60;

	for (int i = 0; i < n_bins; i++) {
		printf("[%5.2g,%5.2g]%5d ", i * inc, (i + 1) * inc, hist[i]);
		for (int j = 0; j < hist[i]; j += step)
			printf("#");
		printf("\n");
	}
}

typedef struct {
	uint64_t size;
	double sum, x2;
	uint64_t hist[n_bins];
} moving_rec;

void moving_avg(moving_rec *rec, double *data, int count)
{
	double sum = 0, x2 = 0;

	for (int i = 0; i < count; i++) {
		sum += data[i];
		x2 += data[i] * data[i];
		rec->hist[(int)(data[i] * n_bins)]++;
	}

	rec->sum += sum;
	rec->x2 += x2;
	rec->size += count;
}

int main()
{
	double m, stddev;
	int hist[n_bins], samples = 10;

	while (samples <= 10000) {
		m = avg(samples, &stddev, hist);
		printf("size %5d: %g %g\n", samples, m, stddev);
		samples *= 10;
	}

	printf("\nHistograph:\n");
	hist_plot(hist);

	printf("\nMoving average:\n  N     Mean    Sigma\n");
	moving_rec rec = { 0, 0, 0, {0} };
	double data[100];
	for (int i = 0; i < 10000; i++) {
		for (int j = 0; j < 100; j++) data[j] = rand01();

		moving_avg(&rec, data, 100);

		if ((i % 1000) == 999) {
			printf("%4lluk %f %f\n",
				rec.size/1000,
				rec.sum / rec.size,
				sqrt(rec.x2 * rec.size - rec.sum * rec.sum)/rec.size
			);
		}
	}
}

#![feature(iter_arith)]
extern crate rand;

use rand::distributions::{IndependentSample, Range};

pub fn mean(data: &[f32]) -> Option<f32> {
    if data.is_empty() {
        None
    } else {
        let sum: f32 = data.iter().sum();
        Some(sum / data.len() as f32)
    }
}

pub fn variance(data: &[f32]) -> Option<f32> {
    if data.is_empty() {
        None
    } else {
        let mean = mean(data).unwrap();
        let mut sum = 0f32;
        for &x in data {
            sum += (x - mean).powi(2);
        }
        Some(sum / data.len() as f32)
    }
}

pub fn standard_deviation(data: &[f32]) -> Option<f32> {
    if data.is_empty() {
        None
    } else {
        let variance = variance(data).unwrap();
        Some(variance.sqrt())
    }
}

fn print_histogram(width: u32, data: &[f32]) {
    let mut histogram = [0; 10];
    let len = histogram.len() as f32;
    for &x in data {
        histogram[(x * len) as usize] += 1;
    }
    let max_frequency = *histogram.iter().max().unwrap() as f32;
    for (i, &frequency) in histogram.iter().enumerate() {
        let bar_width = frequency as f32 * width as f32 / max_frequency;
        print!("{:3.1}: ", i as f32 / len);
        for _ in 0..bar_width as usize {
            print!("*");
        }
        println!("");
    }
}

fn main() {
    let range = Range::new(0f32, 1f32);
    let mut rng = rand::thread_rng();

    for &number_of_samples in [1000, 10_000, 1_000_000].iter() {
        let mut data = vec![];
        for _ in 0..number_of_samples {
            let x = range.ind_sample(&mut rng);
            data.push(x);
        }
        println!("  Statistics for sample size {}", number_of_samples);
        println!("Mean:               {:?}", mean(&data));
        println!("Variance:           {:?}", variance(&data));
        println!("Standard deviation: {:?}", standard_deviation(&data));
        print_histogram(40, &data);
    }
}


String append

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

int main()
{
    char str[24]="Good Morning";
    char *cstr=" to all";
    char *cstr2=" !!!";
    int x=0;

    if(sizeof(str)>strlen(str)+strlen(cstr)+strlen(cstr2))
            {

                strcat(str,cstr);

                x=strlen(str);
                sprintf(&str[x],"%s",cstr2);

                printf("%s\n",str);

            }
    return 0;
}

use std::ops::Add;

fn main(){
    let hello = String::from("Hello world");
    println!("{}", hello.add("!!!!"));
}


String case

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

void str_toupper(char *s)
{
    while(*s)
    {
        *s=toupper(*s);
        s++;
    }
}

void str_tolower(char *s)
{
    while(*s)
    {
        *s=tolower(*s);
        s++;
    }
}

int main(int argc, char *argv[])
{
    char t[255]="alphaBETA";
    str_toupper(t);
    printf("uppercase: %s\n", t);
    str_tolower(t);
    printf("lowercase: %s\n", t);
    return 0;
}

fn main() {
    println!("{}", "jalapeño".to_uppercase());
    println!("{}", "JALAPEÑO".to_lowercase());
}


String concatenation

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

char *sconcat(const char *s1, const char *s2)
{
  char *s0 = malloc(strlen(s1)+strlen(s2)+1);
  strcpy(s0, s1);
  strcat(s0, s2);
  return s0;
}

int main()
{
   const char *s = "hello";
   char *s2;

   printf("%s literal\n", s);

   printf("%s%s\n", s, " literal");

   s2 = sconcat(s, " literal");
   puts(s2);
   free(s2);
}

fn main() {
    let s = "hello".to_owned();
    println!("{}", s);

    let s1 = s + " world";
    println!("{}", s1);
}


String interpolation (included)

#include <stdio.h>

int main() {
  const char *extra = "little";
  printf("Mary had a %s lamb.\n", extra);
  return 0;
}

fn main() {
    println!("Mary had a {} lamb", "little");

    println!("{1} had a {0} lamb", "little", "Mary");

    println!("{name} had a {adj} lamb", adj="little", name="Mary");
}


String length

#include <string.h>

int main(void)
{
  const char *string = "Hello, world!";
  size_t length = strlen(string);

  return 0;
}

fn main() {
    let s = "文字化け";
    println!("Character length: {}", s.chars().count());
}


String matching

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

int startsWith(const char* container, const char* target)
{
  size_t clen = strlen(container), tlen = strlen(target);
  if (clen < tlen)
    return 0;
  return strncmp(container, target, tlen) == 0;
}

int endsWith(const char* container, const char* target)
{
  size_t clen = strlen(container), tlen = strlen(target);
  if (clen < tlen)
    return 0;
  return strncmp(container + clen - tlen, target, tlen) == 0;
}

int doesContain(const char* container, const char* target)
{
  return strstr(container, target) != 0;
}

int main(void)
{
  printf("Starts with Test ( Hello,Hell ) : %d\n", startsWith("Hello","Hell"));
  printf("Ends with Test ( Code,ode ) : %d\n", endsWith("Code","ode"));
  printf("Contains Test ( Google,msn ) : %d\n", doesContain("Google","msn"));

  return 0;
}

fn print_match(possible_match: Option<usize>) {
    match possible_match {
        Some(match_pos) => println!("Found match at pos {}", match_pos),
        None => println!("Did not find any matches")
    }
}

fn main() {
    let s1 = "abcd";
    let s2 = "abab";
    let s3 = "ab";

    assert!(s1.starts_with(s3));

    assert!(s1.contains(s3));

    print_match(s1.find(s3));
    print_match(s1.find(s2));

    assert!(s2.ends_with(s3));
}


String prepend

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

int main()
{
    char str[100]="my String";
    char *cstr="Changed ";
    char *dup;
    sprintf(str,"%s%s",cstr,(dup=strdup(str)));
    free(dup);
    printf("%s\n",str);
    return 0;
}

let mut s = "World".to_string();
s.insert_str(0, "Hello ");
println!("{}", s);


Strip a set of characters from a string

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

char *strip_chars(const char *string, const char *chars)
{
  char * newstr = malloc(strlen(string) + 1);
  int counter = 0;

  for ( ; *string; string++) {
    if (!strchr(chars, *string)) {
      newstr[ counter ] = *string;
      ++ counter;
    }
  }

  newstr[counter] = 0;
  return newstr;
}

int main(void)
{
  char *new = strip_chars("She was a soul stripper. She took my heart!", "aei");
  printf("%s\n", new);

  free(new);
  return 0;
}

fn strip_characters(original : &str, to_strip : &str) -> String {
    let mut result = String::new();
    for c in original.chars() {
        if !to_strip.contains(c) {
           result.push(c);
       }
    }
    result
}


Strip comments from a string

#include<stdio.h>

int main()
{
	char ch, str[100];
	int i;

	do{
		printf("\nEnter the string :");
		fgets(str,100,stdin);
		for(i=0;str[i]!=00;i++)
		{
			if(str[i]=='#'||str[i]==';')
			{
				str[i]=00;
				break;
			}
		}
		printf("\nThe modified string is : %s",str);
		printf("\nDo you want to repeat (y/n): ");
		scanf("%c",&ch);
		fflush(stdin);
	}while(ch=='y'||ch=='Y');

	return 0;
}

fn strip_comment<'a>(input: &'a str, markers: &[char]) -> &'a str {
    input
        .find(markers)
        .map(|idx| &input[..idx])
        .unwrap_or(input)
        .trim()
}

fn main() {
    println!("{:?}", strip_comment("apples, pears # and bananas", &['#', ';']));
    println!("{:?}", strip_comment("apples, pears ; and bananas", &['#', ';']));
    println!("{:?}", strip_comment("apples, pears and bananas ", &['#', ';']));
}


Strip whitespace from a string_Top and tail

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

char *rtrim(const char *s)
{
  while( isspace(*s) || !isprint(*s) ) ++s;
  return strdup(s);
}

char *ltrim(const char *s)
{
  char *r = strdup(s);
  if (r != NULL)
  {
    char *fr = r + strlen(s) - 1;
    while( (isspace(*fr) || !isprint(*fr) || *fr == 0) && fr >= r) --fr;
    *++fr = 0;
  }
  return r;
}

char *trim(const char *s)
{
  char *r = rtrim(s);
  char *f = ltrim(r);
  free(r);
  return f;
}

const char *a = "     this is a string      ";

int main()
{
  char *b = rtrim(a);
  char *c = ltrim(a);
  char *d = trim(a);

  printf("'%s'\n'%s'\n'%s'\n", b, c, d);

  free(b);
  free(c);
  free(d);
  return 0;
}

fn main() {
    let spaces = " \t\n\x0B\x0C\r \u{A0} \u{2000}\u{3000}";
    let string_with_spaces = spaces.to_owned() + "String without spaces" + spaces;

    assert_eq!(string_with_spaces.trim(), "String without spaces");
    assert_eq!(string_with_spaces.trim_left(), "String without spaces".to_owned() + spaces);
    assert_eq!(string_with_spaces.trim_right(), spaces.to_owned() + "String without spaces");
}


Substring

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

void putm(char* string, size_t m)
{
    while(*string && m--)
        putchar(*string++);
}

int main(void)
{

    char string[] =
        "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)."

    int n = 3;
    int m = 4;
    char knownCharacter = '(';
    char knownSubstring[] = "encodings";

    putm(string+n-1, m );                       putchar('\n');
    puts(string+n+1);                           putchar('\n');
    putm(string, strlen(string)-1);             putchar('\n');
    putm(strchr(string, knownCharacter), m );   putchar('\n');
    putm(strstr(string, knownSubstring), m );   putchar('\n');

    return EXIT_SUCCESS;
}

let s = "abc文字化けdef";
let n = 2;
let m = 3;

println!("{}", s.chars().skip(n).take(m).collect::<String>());

println!("{}", s.chars().skip(n).collect::<String>());

println!("{}", s.chars().rev().skip(1).collect::<String>());

let cpos = s.find('b').unwrap();
println!("{}", s[cpos..].chars().take(m).collect::<String>());

let spos = s.find("けd").unwrap();
println!("{}", s[spos..].chars().take(m).collect::<String>());


Subtractive generator

#include<stdio.h>

#define MOD 1000000000
int state[55], si = 0, sj = 0;

int subrand();

void subrand_seed(int p1)
{
	int i, j, p2 = 1;

	state[0] = p1 % MOD;
	for (i = 1, j = 21; i < 55; i++, j += 21) {
		if (j >= 55) j -= 55;
		state[j] = p2;
		if ((p2 = p1 - p2) < 0) p2 += MOD;
		p1 = state[j];
	}
	si = 0;
	sj = 24;
	for (i = 0; i < 165; i++) subrand();
}

int subrand()
{
	int x;
	if (si == sj) subrand_seed(0);

	if (!si--) si = 54;
	if (!sj--) sj = 54;
	if ((x = state[si] - state[sj]) < 0) x += MOD;

	return state[si] = x;
}

int main()
{
	subrand_seed(292929);
	int i;
	for (i = 0; i < 10; i++) printf("%d\n", subrand());

	return 0;
}

struct SubtractiveGenerator {

    modulo: i32,

    offsets: (u32, u32),

    state: Vec<i32>,

    position: usize,
}

impl SubtractiveGenerator {
    fn new(modulo: i32, first_offset: u32, second_offset: u32) -> Self {

        let state_size: usize = first_offset.try_into().unwrap();

        assert!(first_offset <= i32::MAX as u32);
        assert!(first_offset > second_offset);
        SubtractiveGenerator {
            modulo,
            offsets: (first_offset, second_offset),
            state: Vec::with_capacity(state_size),
            position: 0,
        }
    }
}

impl Iterator for SubtractiveGenerator {
    type Item = i32;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        let state_size = self.offsets.0 as usize;

        assert_eq!(self.state.len(), state_size);

        self.position = (self.position + 1) % self.offsets.0 as usize;

        let i1 = (self.position as i32 - self.offsets.0 as i32).rem_euclid(state_size as i32);
        let i2 = (self.position as i32 - self.offsets.1 as i32).rem_euclid(state_size as i32);

        let p1 = self.state[i1 as usize];
        let p2 = self.state[i2 as usize];

        self.state[self.position] = (p1 - p2).rem_euclid(self.modulo);

        Some(self.state[self.position])
    }
}

fn get_seeded_xpat2_gen(seed: i32) -> SubtractiveGenerator {
    let mut gen = SubtractiveGenerator::new(1_000_000_000, 55, 24);

    let state_size = gen.offsets.0 as usize;

    let mut pre_state = Vec::with_capacity(state_size);
    pre_state.push(seed);
    pre_state.push(1);
    for i in 2..state_size {
        pre_state.push((pre_state[i - 2] - pre_state[i - 1]).rem_euclid(gen.modulo));
    }

    for i in 0..state_size {
        gen.state.push(pre_state[(34 * (i + 1)) % 55]);
    }

    gen.position = 54;
    for _ in 0..165 {
        gen.next();
    }

    gen
}

fn main() {
    let gen = get_seeded_xpat2_gen(292929);

    for n in gen.take(5) {
        println!("{}", n);
    }
}


Sudoku

type Sudoku = [u8; 81];

fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool {
    (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && {
        let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3);
        (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val))
    }
}

fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool {
    (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| {
        let (x, y) = (pos % 9, pos / 9);
        for n in 1..10 {
            if is_valid(n, x, y, sudoku_ar) {
                sudoku_ar[pos] = n;
                if place_number(pos + 1, sudoku_ar) {
                    return true;
                }
                sudoku_ar[pos] = 0;
            }
        }
        false
    })
}

fn pretty_print(sudoku_ar: Sudoku) {
    let line_sep = "------+-------+------";
    println!("{}", line_sep);
    for (i, e) in sudoku_ar.iter().enumerate() {
        print!("{} ", e);
        if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 {
            print!("| ");
        }
        if (i + 1) % 9 == 0 {
            println!(" ");
        }
        if (i + 1) % 27 == 0 {
            println!("{}", line_sep);
        }
    }
}

fn solve(sudoku_ar: &mut Sudoku) -> bool {
    place_number(0, sudoku_ar)
}

fn main() {
    let mut sudoku_ar: Sudoku = [
        8, 5, 0, 0, 0, 2, 4, 0, 0,
        7, 2, 0, 0, 0, 0, 0, 0, 9,
        0, 0, 4, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 1, 0, 7, 0, 0, 2,
        3, 0, 5, 0, 0, 0, 9, 0, 0,
        0, 4, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 8, 0, 0, 7, 0,
        0, 1, 7, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 3, 6, 0, 4, 0
    ];
    if solve(&mut sudoku_ar) {
        pretty_print(sudoku_ar);
    } else {
        println!("Unsolvable");
    }
}


Sum and product of an array

int arg[] = { 1,2,3,4,5 };
int arg_length = sizeof(arg)/sizeof(arg[0]);
int *end = arg+arg_length;
int sum = 0, prod = 1;
int *p;

for (p = arg; p!=end; ++p) {
   sum += *p;
   prod *= *p;
}

fn main() {
    let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];

    let sum = arr.iter().fold(0i32, |a, &b| a + b);
    let product = arr.iter().fold(1i32, |a, &b| a * b);
    println!("the sum is {} and the product is {}", sum, product);

    let sum = arr.iter().sum::<i32>();
    let product = arr.iter().product::<i32>();
    println!("the sum is {} and the product is {}", sum, product);
}


Sum digits of an integer

#include <stdio.h>

int SumDigits(unsigned long long n, const int base) {
    int sum = 0;
    for (; n; n /= base)
    	sum += n % base;
    return sum;
}

int main() {
    printf("%d %d %d %d %d\n",
        SumDigits(1, 10),
        SumDigits(12345, 10),
        SumDigits(123045, 10),
        SumDigits(0xfe, 16),
        SumDigits(0xf0e, 16) );
    return 0;
}

struct DigitIter(usize, usize);

impl Iterator for DigitIter {
    type Item = usize;
    fn next(&mut self) -> Option<Self::Item> {
        if self.0 == 0 {
            None
        } else {
            let ret = self.0 % self.1;
            self.0 /= self.1;
            Some(ret)
        }
    }
}

fn main() {
    println!("{}", DigitIter(1234,10).sum::<usize>());
}


Sum multiples of 3 and 5

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

unsigned long long sum35(unsigned long long limit)
{
    unsigned long long sum = 0;
    for (unsigned long long i = 0; i < limit; i++)
        if (!(i % 3) || !(i % 5))
            sum += i;
    return sum;
}

int main(int argc, char **argv)
{
    unsigned long long limit;

    if (argc == 2)
        limit = strtoull(argv[1], NULL, 10);
    else
        limit = 1000;

    printf("%lld\n", sum35(limit));
    return 0;
}

extern crate rug;

use rug::Integer;
use rug::ops::Pow;

fn main() {
    for i in [3, 20, 100, 1_000].iter() {
        let ten = Integer::from(10);
        let mut limit = Integer::from(Integer::from(&ten.pow(*i as u32)) - 1);
        let mut aux_3_1 = &limit.mod_u(3u32);
        let mut aux_3_2 = Integer::from(&limit - aux_3_1);
        let mut aux_3_3 = Integer::from(&aux_3_2/3);
        let mut aux_3_4 = Integer::from(3 + aux_3_2);
        let mut aux_3_5 = Integer::from(&aux_3_3*&aux_3_4);
        let mut aux_3_6 = Integer::from(&aux_3_5/2);

        let mut aux_5_1 = &limit.mod_u(5u32);
        let mut aux_5_2 = Integer::from(&limit - aux_5_1);
        let mut aux_5_3 = Integer::from(&aux_5_2/5);
        let mut aux_5_4 = Integer::from(5 + aux_5_2);
        let mut aux_5_5 = Integer::from(&aux_5_3*&aux_5_4);
        let mut aux_5_6 = Integer::from(&aux_5_5/2);

        let mut aux_15_1 = &limit.mod_u(15u32);
        let mut aux_15_2 = Integer::from(&limit - aux_15_1);
        let mut aux_15_3 = Integer::from(&aux_15_2/15);
        let mut aux_15_4 = Integer::from(15 + aux_15_2);
        let mut aux_15_5 = Integer::from(&aux_15_3*&aux_15_4);
        let mut aux_15_6 = Integer::from(&aux_15_5/2);

        let mut result_aux_1 = Integer::from(&aux_3_6 + &aux_5_6);
        let mut result = Integer::from(&result_aux_1 - &aux_15_6);

        println!("Sum for 10^{} : {}",i,result);
    }
}


Sum of a series

#include <stdio.h>

double Invsqr(double n)
{
	return 1 / (n*n);
}

int main (int argc, char *argv[])
{
	int i, start = 1, end = 1000;
	double sum = 0.0;

	for( i = start; i <= end; i++)
		sum += Invsqr((double)i);

	printf("%16.14f\n", sum);

	return 0;
}

const LOWER: i32 = 1;
const UPPER: i32 = 1000;

const NUMBER_OF_TERMS: i32 = (UPPER + 1) - LOWER;
fn main() {

    println!("{}", (NUMBER_OF_TERMS * (LOWER + UPPER)) / 2);

    println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x));
}


Sum of squares

#include <stdio.h>

double squaredsum(double *l, int e)
{
   int i; double sum = 0.0;
   for(i = 0 ; i < e ; i++) sum += l[i]*l[i];
   return sum;
}

int main()
{
   double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0};

   printf("%lf\n", squaredsum(list, 6));
   printf("%lf\n", squaredsum(list, 0));

   printf("%lf\n", squaredsum(NULL, 0));
   return 0;
}


Symmetric difference

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

const char *A[] = { "John", "Serena", "Bob", "Mary", "Serena" };
const char *B[] = { "Jim", "Mary", "John", "Jim", "Bob" };

#define LEN(x) sizeof(x)/sizeof(x[0])

void uniq(const char *x[], int len)
{
	int i, j;
	for (i = 0; i < len; i++)
		for (j = i + 1; j < len; j++)
			if (x[j] && x[i] && !strcmp(x[i], x[j])) x[j] = 0;
}

int in_set(const char *const x[], int len, const char *match)
{
	int i;
	for (i = 0; i < len; i++)
		if (x[i] && !strcmp(x[i], match))
			return 1;
	return 0;
}

void show_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
	int i;
	for (i = 0; i < lenx; i++)
		if (x[i] && !in_set(y, leny, x[i]))
			printf("  %s\n", x[i]);
}

void show_sym_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
	show_diff(x, lenx, y, leny);
	show_diff(y, leny, x, lenx);
}

int main()
{
	uniq(A, LEN(A));
	uniq(B, LEN(B));
	printf("A \\ B:\n"); show_diff(A, LEN(A), B, LEN(B));
	printf("\nB \\ A:\n"); show_diff(B, LEN(B), A, LEN(A));
	printf("\nA ^ B:\n");  show_sym_diff(A, LEN(A), B, LEN(B));

	return 0;
}

use std::collections::HashSet;

fn main() {
    let a: HashSet<_> = ["John", "Bob", "Mary", "Serena"]
        .iter()
        .collect();
    let b = ["Jim", "Mary", "John", "Bob"]
        .iter()
        .collect();

    let diff = a.symmetric_difference(&b);
    println!("{:?}", diff);
}