File extension is in extensions list

#define _CRT_SECURE_NO_WARNINGS

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

#ifdef _Bool
#include <stdbool.h>
#else
#define bool int
#define true  1
#define false 0
#endif

int checkFileExtension(char* fileName, char* fileExtensions)
{
    char* fileExtension = fileExtensions;

    if ( *fileName )
    {
        while ( *fileExtension )
        {
            int fileNameLength = strlen(fileName);
            int extensionLength = strlen(fileExtension);
            if ( fileNameLength >= extensionLength )
            {
                char* a = fileName + fileNameLength - extensionLength;
                char* b = fileExtension;
                while ( *a && toupper(*a++) == toupper(*b++) )
                    ;
                if ( !*a )
                    return true;
            }
            fileExtension += extensionLength + 1;
        }
    }
    return false;
}

void printExtensions(char* extensions)
{
    while( *extensions )
    {
        printf("%s\n", extensions);
        extensions += strlen(extensions) + 1;
    }
}

bool test(char* fileName, char* extension, bool expectedResult)
{
    bool result = checkFileExtension(fileName,extension);
    bool returnValue = result == expectedResult;
    printf("%20s  result: %-5s  expected: %-5s  test %s\n",
        fileName,
        result         ? "true"   : "false",
        expectedResult ? "true"   : "false",
        returnValue    ? "passed" : "failed" );
    return returnValue;
}

int main(void)
{
    static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0";

    setlocale(LC_ALL,"");

    printExtensions(extensions);
    printf("\n");

    if ( test("MyData.a##",         extensions,true )
    &&   test("MyData.tar.Gz",      extensions,true )
    &&   test("MyData.gzip",        extensions,false)
    &&   test("MyData.7z.backup",   extensions,false)
    &&   test("MyData...",          extensions,false)
    &&   test("MyData",             extensions,false)
    &&   test("MyData_v1.0.tar.bz2",extensions,true )
    &&   test("MyData_v1.0.bz2",    extensions,false)
    &&   test("filename",           extensions,false)
    )
        printf("\n%s\n", "All tests passed.");
    else
        printf("\n%s\n", "Last test failed.");

    printf("\n%s\n", "press enter");
    getchar();
    return 0;
}

fn main() {
    let exts = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"];
    let filenames = [
        "MyData.a##",
        "MyData.tar.Gz",
        "MyData.gzip",
        "MyData.7z.backup",
        "MyData...",
        "MyData",
        "MyData_v1.0.tar.bz2",
        "MyData_v1.0.bz2",
    ];

    println!("extenstions: {:?}\n", exts);

    for filename in filenames.iter() {
        let check = exts.iter().any(|ext| {
            filename
                .to_lowercase()
                .ends_with(&format!(".{}", ext.to_lowercase()))
        });
        println!("{:20} {}", filename, check);
    }
}


Find prime n such that reversed n is also prime

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

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

unsigned int reverse(unsigned int n) {
    unsigned int rev = 0;
    for (; n > 0; n /= 10)
        rev = rev * 10 + n % 10;
    return rev;
}

int main() {
    unsigned int count = 0;
    for (unsigned int n = 1; n < 500; ++n) {
        if (is_prime(n) && is_prime(reverse(n)))
            printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
    }
    printf("\nCount = %u\n", count);
    return 0;
}

use prime_tools ;

fn myreverse( n : u32 ) -> u32 {
   let forward : String = n.to_string( ) ;
   let numberstring = &forward[..] ;
   let mut reversed : String = String::new( ) ;
   for c in numberstring.chars( ).rev( ) {
      reversed.push( c ) ;
   }
   *&reversed[..].parse::<u32>( ).unwrap( )
}

fn main() {
   let mut reversible_primes : Vec<u32> = Vec::new( ) ;
   for num in 2..=500 {
      if prime_tools::is_u32_prime( num ) && prime_tools::is_u32_prime(
               myreverse( num ))  {
            reversible_primes.push( num ) ;
      }
   }
   println!("{:?}" , reversible_primes ) ;
}


Find prime numbers of the form n_n_n+2

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

bool isPrime(int n) {
    int d;
    if (n < 2)  return false;
    if (!(n%2)) return n == 2;
    if (!(n%3)) return n == 3;
    d = 5;
    while (d*d <= n) {
        if (!(n%d)) return false;
        d += 2;
        if (!(n%d)) return false;
        d += 4;
    }
    return true;
}

int main() {
    int n, p;
    const int limit = 200;
    setlocale(LC_ALL, "");
    for (n = 1; n < limit; ++n) {
        p = n*n*n + 2;
        if (isPrime(p)) {
            printf("n = %3d => n³ + 2 = %'9d\n", n, p);
        }
    }
    return 0;
}

use primes::is_prime;

fn main() {

   let mut count = 0;
   let begin     = 0;
   let end       = 200;

   println!("Find prime numbers of the form");
   println!("   n => n³ + 2 ");

   for n in begin+1..end-1 {
      let m = n*n*n+2;
      if is_prime(m) {
        println!("{:4} => {}", n, m);
        count += 1;
      }
   }

   println!("Found {} such prime numbers where {} < n < {}.", count,begin,end);
}


First 9 prime Fibonacci number

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

bool isPrime(uint64_t n) {
    if (n < 2) return false;
    if (!(n%2)) return n == 2;
    if (!(n%3)) return n == 3;
    uint64_t d = 5;
    while (d*d <= n) {
        if (!(n%d)) return false;
        d += 2;
        if (!(n%d)) return false;
        d += 4;
    }
    return true;
}

int main() {
    uint64_t f1 = 1, f2 = 1, f3;
    int count = 0, limit = 12;
    printf("The first %d prime Fibonacci numbers are:\n", limit);
    while (count < limit) {
        f3 = f1 + f2;
        if (isPrime(f3)) {
            printf("%ld ", f3);
            count++;
        }
        f1 = f2;
        f2 = f3;
    }
    printf("\n");
    return 0;
}

use rug::{Assign, Integer};

fn fibonacci() -> impl std::iter::Iterator<Item = Integer> {
    let mut f0 = Integer::from(0);
    let mut f1 = Integer::from(1);
    std::iter::from_fn(move || {
        let result = Integer::from(&f0);
        let f = Integer::from(&f0 + &f1);
        f0.assign(&f1);
        f1.assign(&f);
        Some(result)
    })
}

fn prime_fibonacci() -> impl std::iter::Iterator<Item = (usize, Integer)> {
    use rug::integer::IsPrime;
    let mut primes = primal::Primes::all().skip(2);
    let mut fib = fibonacci();
    let mut n = 0;
    std::iter::from_fn(move || loop {
        if n > 4 {
            let p = primes.next().unwrap();
            while p > n {
                fib.next();
                n += 1;
            }
        }
        n += 1;
        if let Some(f) = fib.next() {
            if f.is_probably_prime(30) != IsPrime::No {
                return Some((n - 1, f));
            }
        }
    })
}

fn to_string(num: &Integer) -> String {
    let str = num.to_string();
    let len = str.len();
    if len > 40 {
        let mut result = String::from(&str[..20]);
        result.push_str("...");
        result.push_str(&str[len - 20..]);
        result.push_str(" (");
        result.push_str(&len.to_string());
        result.push_str(" digits)");
        return result;
    }
    str
}

fn main() {
    use std::time::Instant;
    let now = Instant::now();
    for (i, (n, f)) in prime_fibonacci().take(26).enumerate() {
        println!("{}: F({}) = {}", i + 1, n, to_string(&f));
    }
    let time = now.elapsed();
    println!("elapsed time: {} milliseconds", time.as_millis());
}


Flipping bits game

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

int i, j;

void fliprow(int **b, int sz, int n)
{
	for(i = 0; i < sz; i++)
		b[n+1][i] = !b[n+1][i];
}

void flipcol(int **b, int sz, int n)
{
	for(i = 1; i <= sz; i++)
		b[i][n] = !b[i][n];
}

void initt(int **t, int sz)
{
	for(i = 1; i <= sz; i++)
		for(j = 0; j < sz; j++)
			t[i][j] = rand()%2;
}

void initb(int **t, int **b, int sz)
{
	for(i = 1; i <= sz; i++)
		for(j = 0; j < sz; j++)
			b[i][j] = t[i][j];

	for(i = 1; i <= sz; i++)
		fliprow(b, sz, rand()%sz+1);
	for(i = 0; i < sz; i++)
		flipcol(b, sz, rand()%sz);
}

void printb(int **b, int sz)
{
	printf(" ");
	for(i = 0; i < sz; i++)
		printf(" %d", i);
	printf("\n");

	for(i = 1; i <= sz; i++)
	{
		printf("%d", i-1);
		for(j = 0; j < sz; j++)
			printf(" %d", b[i][j]);
		printf("\n");
	}

	printf("\n");
}

int eq(int **t, int **b, int sz)
{
	for(i = 1; i <= sz; i++)
		for(j = 0; j < sz; j++)
			if(b[i][j] != t[i][j])
				return 0;
	return 1;
}

void main()
{
	int sz = 3;
	int eql = 0;
	int mov = 0;
	int **t = malloc(sz*(sizeof(int)+1));
	for(i = 1; i <= sz; i++)
		t[i] = malloc(sz*sizeof(int));

	int **b = malloc(sz*(sizeof(int)+1));
	for(i = 1; i <= sz; i++)
		b[i] = malloc(sz*sizeof(int));
	char roc;
	int n;
	initt(t, sz);
	initb(t, b, sz);

	while(eq(t, b, sz))
		initb(t, b, sz);

	while(!eql)
	{
		printf("Target: \n");
		printb(t, sz);
		printf("Board: \n");
		printb(b, sz);
		printf("What to flip: ");
		scanf(" %c", &roc);
		scanf(" %d", &n);

		switch(roc)
		{
			case 'r':
				fliprow(b, sz, n);
				break;
			case 'c':
				flipcol(b, sz, n);
				break;
			default:
				perror("Please specify r or c and an number");
				break;
		}

		printf("Moves Taken: %d\n", ++mov);

		if(eq(t, b, sz))
		{
			printf("You win!\n");
			eql = 1;
		}
	}
}

extern crate rand;

use std::fmt;

use std::io::prelude::*;

use rand::Rng;

struct Board {

    cells: Vec<bool>,

    size: usize,
}

impl Board {

    fn new(size: usize) -> Board {

        if size > 0 {
            Board {
                cells: vec![false; size * size],
                size,
            }
        } else {
            Board::new(1)
        }
    }

    fn fliprow(&mut self, row: usize) -> bool {

        if row > self.size {
            return false;
        }

        let start = row * self.size;

        for i in start..start + self.size {
            self.cells[i] = !self.cells[i];
        }
        true
    }

    fn flipcol(&mut self, col: usize) -> bool {

        if col > self.size {
            return false;
        }

        for i in 0..self.size {
            self.cells[col + i * self.size] = !self.cells[col + i * self.size];
        }
        true
    }

    fn random<R: Rng>(rng: &mut R, size: usize) -> Board {

        if size == 0 {
            return Board::random(rng, 1);
        }

        let cells = (0..size * size)
            .map(|_| rng.gen::<bool>())
            .collect::<Vec<_>>();

        Board { cells, size }
    }
}

impl PartialEq for Board {
    fn eq(&self, rhs: &Board) -> bool {
        self.cells == rhs.cells
    }
}

impl fmt::Display for Board {

    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

        let width = (self.size - 1).to_string().len();

        write!(f, "{space: >0$}", width, space = " ")?;

        for i in 0..self.size {
            write!(f, " {offset:>0$}", width, offset = i)?;
        }

        writeln!(f)?;

        for row in 0..self.size {

            write!(f, "{row:>0$}", width, row = row)?;

            for col in 0..self.size {

                let p = self.cells[row * self.size + col] as usize;

                write!(f, " {col:>0$}", width, col = p)?;
            }

            writeln!(f)?;
        }

        Ok(())
    }
}

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

    let size: usize = 3;

    let target: Board = Board::random(&mut rng, size);

    let mut board: Board = Board::new(size);

    let mut moves: u32 = 0;

    'mainloop: loop {

        let mut input: String;

        println!("Target:\n{}\nBoard:\n{}", &target, &board);

        'userinput: loop {

            print!("\nFlip? [q|[r|c]#] ");

            match std::io::stdout().flush() {
                Ok(_) => {}
                Err(e) => {
                    println!("Error: cannot flush stdout: {}", e);
                    break 'mainloop;
                }
            };

            input = String::new();

            match std::io::stdin().read_line(&mut input) {
                Ok(_) => {
                    input = input.trim().to_string();

                    let rc: char = match input.chars().next() {
                        Some(c) => c,
                        None => {
                            println!("Error: No input");
                            continue 'userinput;
                        }
                    };

                    if rc != 'r' && rc != 'c' && rc != 'q' {
                        println!("Error: '{}': Must use 'r'ow or 'c'olumn or 'q'uit", rc);
                        continue 'userinput;
                    }

                    if rc == 'q' {
                        println!("Thanks for playing!");
                        break 'mainloop;
                    }

                    let n: usize = match input[1..].to_string().parse() {
                        Ok(x) => {

                            if x < size {
                                x
                            } else {
                                println!(
                                    "Error: Must specify a row or column within size({})",
                                    size
                                );
                                continue 'userinput;
                            }
                        }
                        Err(_) => {
                            println!(
                                "Error: '{}': Unable to parse row or column number",
                                input[1..].to_string()
                            );
                            continue 'userinput;
                        }
                    };

                    match rc {
                        'r' => board.fliprow(n),
                        'c' => board.flipcol(n),
                        _ => {

                            panic!("How did you end up here?");
                        }
                    };

                    moves += 1;
                    println!("Moves taken: {}", moves);
                    break 'userinput;
                }
                Err(e) => {
                    println!("Error reading input: {}", e);
                    break 'mainloop;
                }
            }
        }
        if board == target {
            println!("You win!");
            break;
        }
    }
}


Fractal tree

#include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif

#define SIZE           800
#define SCALE          5
#define BRANCHES       14
#define ROTATION_SCALE 0.75
#define INITIAL_LENGTH 50

double rand_fl(){
  return (double)rand() / (double)RAND_MAX;
}

void draw_tree(SDL_Surface * surface, double offsetx, double offsety,
               double directionx, double directiony, double size,
               double rotation, int depth) {
#ifdef WITH_CAIRO
  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,
                                                               CAIRO_FORMAT_RGB24,
							       surface->w, surface->h,
							       surface->pitch );
  cairo_t *ct = cairo_create(surf);

  cairo_set_line_width(ct, 1);
  cairo_set_source_rgba(ct, 0,0,0,1);
  cairo_move_to(ct, (int)offsetx, (int)offsety);
  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));
  cairo_stroke(ct);
#else
  sge_AALine(surface,
      (int)offsetx, (int)offsety,
      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),
      SDL_MapRGB(surface->format, 0, 0, 0));
#endif
  if (depth > 0){

    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(rotation) + directiony * sin(rotation),
        directionx * -sin(rotation) + directiony * cos(rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);

    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(-rotation) + directiony * sin(-rotation),
        directionx * -sin(-rotation) + directiony * cos(-rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);
  }
}

void render(SDL_Surface * surface){
  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
  draw_tree(surface,
      surface->w / 2.0,
      surface->h - 10.0,
      0.0, -1.0,
      INITIAL_LENGTH,
      PI / 8,
      BRANCHES);
  SDL_UpdateRect(surface, 0, 0, 0, 0);
}

int main(){
  SDL_Surface * screen;
  SDL_Event evt;

  SDL_Init(SDL_INIT_VIDEO);

  srand((unsigned)time(NULL));

  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);

  render(screen);
  while(1){
    if (SDL_PollEvent(&evt)){
      if(evt.type == SDL_QUIT) break;
    }
    SDL_Delay(1);
  }
  SDL_Quit();
  return 0;
}

extern crate piston;
extern crate graphics;
extern crate opengl_graphics;
extern crate glutin_window;

use piston::window::WindowSettings;
use piston::event_loop::{Events, EventSettings};
use piston::input::RenderEvent;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use graphics::{clear, line, Context};

const ANG: f64 = 20.0;
const COLOR: [f32; 4] = [1.0, 0.0, 0.5, 1.0];
const LINE_THICKNESS: f64 = 5.0;
const DEPTH: u32 = 11;

fn main() {
    let mut window: Window = WindowSettings::new("Fractal Tree", [1024, 768])
        .opengl(OpenGL::V3_2)
        .exit_on_esc(true)
        .build()
        .unwrap();
    let mut gl = GlGraphics::new(OpenGL::V3_2);

    let mut events = Events::new(EventSettings::new());
    while let Some(e) = events.next(&mut window) {
        if let Some(args) = e.render_args() {
            gl.draw(args.viewport(), |c, g| {
                clear([1.0, 1.0, 1.0, 1.0], g);
                draw_fractal_tree(512.0, 700.0, 0.0, DEPTH, c, g);
            });
        }
    }
}

fn draw_fractal_tree(x1: f64, y1: f64, angle: f64, depth: u32, c: Context, g: &mut GlGraphics) {
    let x2 = x1 + angle.to_radians().sin() * depth as f64 * 10.0;
    let y2 = y1 - angle.to_radians().cos() * depth as f64 * 10.0;
    line(
        COLOR,
        LINE_THICKNESS * depth as f64 * 0.2,
        [x1, y1, x2, y2],
        c.transform,
        g,
    );
    if depth > 0 {
        draw_fractal_tree(x2, y2, angle - ANG, depth - 1, c, g);
        draw_fractal_tree(x2, y2, angle + ANG, depth - 1, c, g);
    }
}


Gray code

int gray_encode(int n) {
    return n ^ (n >> 1);
}

int gray_decode(int n) {
    int p = n;
    while (n >>= 1) p ^= n;
    return p;
}

fn gray_encode(integer: u64) -> u64 {
    (integer >> 1) ^ integer
}

fn gray_decode(integer: u64) -> u64 {
    match integer {
        0 => 0,
        _ => integer ^ gray_decode(integer >> 1)
    }
}

fn main() {
    for i in 0..32 {
        println!("{:2} {:0>5b} {:0>5b} {:2}", i, i, gray_encode(i),
            gray_decode(i));
    }

}


Hello world_Line printer

#include <stdio.h>

int main()
{
   FILE *lp;
   lp = fopen("/dev/lp0","w");
   fprintf(lp,"Hello world!\n");
   fclose(lp);
   return 0;
}

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    let file = OpenOptions::new().write(true).open("/dev/lp0").unwrap();
    file.write(b"Hello, World!").unwrap();
}


Hickerson series of almost integers

#include <stdio.h>
#include <mpfr.h>

void h(int n)
{
	MPFR_DECL_INIT(a, 200);
	MPFR_DECL_INIT(b, 200);

	mpfr_fac_ui(a, n, MPFR_RNDD);

	mpfr_set_ui(b, 2, MPFR_RNDD);
	mpfr_log(b, b, MPFR_RNDD);
	mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);

	mpfr_div(a, a, b, MPFR_RNDD);
	mpfr_div_ui(a, a, 2, MPFR_RNDD);

	mpfr_frac(b, a, MPFR_RNDD);
	mpfr_printf("%2d: %23.4Rf  %c\n", n, a,
		mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}

int main(void)
{
	int n;
	for (n = 1; n <= 17; n++) h(n);

	return 0;
}

use decimal::d128;
use factorial::Factorial;

fn hickerson(n: u64) -> d128 {
    d128::from(n.factorial()) / (d128!(2) * (d128!(2).ln().pow(d128::from(n + 1))))
}

fn main() {
    for i in 1..18 {
        let h = hickerson(i);
        let string = h.to_string();
        let dec_part = string.split('.').nth(1).unwrap();
        if dec_part.starts_with('0') || dec_part.starts_with('9') {
            println!("{} is an almost integer.", h);
        } else {
            println!("{} is not an almost integer.", h);
        }
    }
}


Hofstadter Q sequence

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

#define N 100000
int main()
{
	int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;

	q[1] = q[2] = 1;

	for (i = 3; i <= N; i++)
		q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];

	for (i = 1; i <= 10; i++)
		printf("%d%c", q[i], i == 10 ? '\n' : ' ');

	printf("%d\n", q[1000]);

	for (flip = 0, i = 1; i < N; i++)
		flip += q[i] > q[i + 1];

	printf("flips: %d\n", flip);
	return 0;
}

fn hofq(q: &mut Vec<u32>, x : u32) -> u32 {
    let cur_len=q.len()-1;
    let i=x as usize;
    if i>cur_len {

        q.reserve(i+1);
        for j in (cur_len+1)..(i+1) {
            let qj=(q[j-q[j-1] as usize]+q[j-q[j-2] as usize]) as u32;
            q.push(qj);
        }
    }
    q[i]
}

fn main() {
    let mut q_memo: Vec<u32>=vec![0,1,1];
    let mut q=|i| {hofq(&mut q_memo, i)};
    for i in 1..11 {
        println!("Q({})={}", i, q(i));
    }
    println!("Q(1000)={}", q(1000));
    let q100001=q(100_000);
    println!("Q(100000)={}", q100000);
    let nless=(1..100_000).fold(0,|s,i|{if q(i+1)<q(i) {s+1} else {s}});
    println!("Term is less than preceding term {} times", nless);
}


Include a file

#include <stdlib.h>

#include "myutil.h"

mod test;

fn main() {
    test::some_function();
}


Kahan summation

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

float epsilon() {
    float eps = 1.0f;
    while (1.0f + eps != 1.0f) eps /= 2.0f;
    return eps;
}

float kahanSum(float *nums, int count) {
    float sum = 0.0f;
    float c = 0.0f;
    float t, y;
    int i;
    for (i = 0; i < count; ++i) {
        y = nums[i] - c;
        t = sum + y;
        c = (t - sum) - y;
        sum = t;
    }
    return sum;
}

int main() {
    float a = 1.0f;
    float b = epsilon();
    float c = -b;
    float fa[3];

    fa[0] = a;
    fa[1] = b;
    fa[2] = c;

    printf("Epsilon     = %0.12f\n", b);
    printf("(a + b) + c = %0.12f\n", (a + b) + c);
    printf("Kahan sum   = %0.12f\n", kahanSum(fa, 3));

    return 0;
}

extern crate num;
extern crate permutohedron;

use num::Float;
use permutohedron::Heap;
use std::f32;

fn find_max(lst: &[f32]) -> Option<f32> {
    if lst.is_empty() {
        return None;
    }
    let max = lst.iter().fold(f32::NEG_INFINITY, |a, &b| Float::max(a, b));
    Some(max)
}

fn with_bits(val: f32, digits: usize) -> f32 {
    let num = format!("{:.*}", digits, val);
    num.parse::<f32>().unwrap()
}

fn kahan_sum(lst: &[f32]) -> Option<f32> {
    let mut sum = 0.0f32;
    let mut c = 0.0f32;
    for i in lst {
        let y = *i - c;
        let t = sum + y;
        c = (t - sum) - y;
        sum = t;
    }
    Some(with_bits(sum, 1))
}

fn all_sums(vec: &mut [f32]) -> Vec<f32> {
    let mut res = Vec::new();
    let mut perms = Heap::new(vec);
    loop {
        let v = perms.next();
        match v {
            Some(v) => {
                let mut sum = 0.0f32;
                for e in &v {
                    sum += with_bits(*e, 1);
                }
                res.push(with_bits(sum, 1));
            }
            None => break,
        }
    }
    res
}

#[allow(clippy::approx_constant)]
fn main() {
    let v = vec![10_000f32, 3.14159, 2.71828];
    let sums = all_sums(&mut v.clone());
    let res = kahan_sum(&v).unwrap();
    let max = find_max(&sums[..]).unwrap();
    println!("max: {} res: {}", max, res);
}


Keyboard input_Obtain a Y or N response

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>

void set_mode(int want_key)
{
	static struct termios old, new;
	if (!want_key) {
		tcsetattr(STDIN_FILENO, TCSANOW, &old);
		return;
	}

	tcgetattr(STDIN_FILENO, &old);
	new = old;
	new.c_lflag &= ~(ICANON);
	tcsetattr(STDIN_FILENO, TCSANOW, &new);
}

int get_key(int no_timeout)
{
	int c = 0;
	struct timeval tv;
	fd_set fs;
	tv.tv_usec = tv.tv_sec = 0;

	FD_ZERO(&fs);
	FD_SET(STDIN_FILENO, &fs);

	select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
	if (FD_ISSET(STDIN_FILENO, &fs)) {
		c = getchar();
		set_mode(0);
	}
	return c;
}

int main()
{
	int c;
	while(1) {
		set_mode(1);
		while (get_key(0));
		printf("Prompt again [Y/N]? ");
		fflush(stdout);

		c = get_key(1);
		if (c == 'Y' || c == 'y') {
			printf("\n");
			continue;
		}

		if (c == 'N' || c == 'n') {
			printf("\nDone\n");
			break;
		}

		printf("\nYes or no?\n");
	}

	return 0;
}

extern crate ncurses;
use ncurses::*;

fn main() {
    initscr();
    loop {
        printw("Yes or no? ");
        refresh();

        match getch() as u8 as char {
            'Y'|'y' => {printw("You said yes!");},
            'N'|'n' => {printw("You said no!");},
            _ => {printw("Try again!\n"); continue;},
        }
        break
    }
    refresh();
    endwin();
}


Knuth's algorithm S

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

struct s_env {
    unsigned int n, i;
    size_t size;
    void *sample;
};

void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
    s_env->i = 0;
    s_env->n = n;
    s_env->size = size;
    s_env->sample = malloc(n * size);
}

void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
    memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}

void *s_of_n(struct s_env *s_env, void *item)
{
    s_env->i++;
    if (s_env->i <= s_env->n)
        sample_set_i(s_env, s_env->i - 1, item);
    else if ((rand() % s_env->i) < s_env->n)
        sample_set_i(s_env, rand() % s_env->n, item);
    return s_env->sample;
}

int *test(unsigned int n, int *items_set, unsigned int num_items)
{
    int i;
    struct s_env s_env;
    s_of_n_init(&s_env, sizeof(items_set[0]), n);
    for (i = 0; i < num_items; i++) {
        s_of_n(&s_env, (void *) &items_set[i]);
    }
    return (int *)s_env.sample;
}

int main()
{
    unsigned int i, j;
    unsigned int n = 3;
    unsigned int num_items = 10;
    unsigned int *frequencies;
    int *items_set;
    srand(time(NULL));
    items_set = malloc(num_items * sizeof(int));
    frequencies = malloc(num_items * sizeof(int));
    for (i = 0; i < num_items; i++) {
        items_set[i] = i;
        frequencies[i] = 0;
    }
    for (i = 0; i < 100000; i++) {
        int *res = test(n, items_set, num_items);
        for (j = 0; j < n; j++) {
            frequencies[res[j]]++;
        }
	free(res);
    }
    for (i = 0; i < num_items; i++) {
        printf(" %d", frequencies[i]);
    }
    puts("");
    return 0;
}

use rand::{Rng,weak_rng};

struct SofN<R: Rng+Sized, T> {
    rng: R,
    sample: Vec<T>,
    i: usize,
    n: usize,
}

impl<R: Rng, T> SofN<R, T> {
    fn new(rng: R, n: usize) -> Self {
        SofN{rng, sample: Vec::new(), i: 0, n}
    }

    fn add(&mut self, item: T) {
        self.i += 1;
        if self.i <= self.n {
            self.sample.push(item);
        } else if self.rng.gen_range(0, self.i) < self.n {
            self.sample[self.rng.gen_range(0, self.n)] = item;
        }
    }

    fn sample(&self) -> &Vec<T> {
        &self.sample
    }
}

pub fn main() {
    const MAX: usize = 10;
    let mut bin: [i32; MAX] = Default::default();
    for _ in 0..100000 {
        let mut s_of_n = SofN::new(weak_rng(), 3);

        for i in 0..MAX { s_of_n.add(i); }

        for s in s_of_n.sample() {
            bin[*s] += 1;
        }
    }

    for (i, x) in bin.iter().enumerate() {
        println!("frequency of {}: {}", i, x);
    }
}


Kronecker product based fractals

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

typedef struct{
    int row, col;
}cell;

int ROW,COL,SUM=0;

unsigned long raiseTo(int base,int power){
    if(power==0)
        return 1;
    else
        return base*raiseTo(base,power-1);
}

cell* kroneckerProduct(char* inputFile,int power){
    FILE* fp = fopen(inputFile,"r");

    int i,j,k,l;
    unsigned long prod;
    int** matrix;
    cell *coreList,*tempList,*resultList;

    fscanf(fp,"%d%d",&ROW,&COL);

    matrix = (int**)malloc(ROW*sizeof(int*));

    for(i=0;i<ROW;i++){
        matrix[i] = (int*)malloc(COL*sizeof(int));
        for(j=0;j<COL;j++){
            fscanf(fp,"%d",&matrix[i][j]);
            if(matrix[i][j]==1)
                SUM++;
        }
    }

    coreList = (cell*)malloc(SUM*sizeof(cell));
    resultList = (cell*)malloc(SUM*sizeof(cell));

    k = 0;

    for(i=0;i<ROW;i++){
        for(j=0;j<COL;j++){
            if(matrix[i][j]==1){
                coreList[k].row = i+1;
                coreList[k].col = j+1;
                resultList[k].row = i+1;
                resultList[k].col = j+1;
                k++;
            }
        }
    }

    prod = k;

    for(i=2;i<=power;i++){
        tempList = (cell*)malloc(prod*k*sizeof(cell));

        l = 0;

        for(j=0;j<prod;j++){
            for(k=0;k<SUM;k++){
                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;
                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;
                l++;
            }
        }

        free(resultList);

        prod *= k;

        resultList = (cell*)malloc(prod*sizeof(cell));

        for(j=0;j<prod;j++){
            resultList[j].row = tempList[j].row;
            resultList[j].col = tempList[j].col;
        }
        free(tempList);
    }

    return resultList;
}

int main(){
    char fileName[100];
    int power,i,length;

    cell* resultList;

    printf("Enter input file name : ");
    scanf("%s",fileName);

    printf("Enter power : ");
    scanf("%d",&power);

    resultList = kroneckerProduct(fileName,power);

    initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal");

    length = raiseTo(SUM,power);

    for(i=0;i<length;i++){
        putpixel(resultList[i].row,resultList[i].col,15);
    }

    getch();

    closegraph();

    return 0;
}

use std::{
    fmt::{Debug, Display, Write},
    ops::Mul,
};

#[derive(Clone, Debug)]
pub struct Mat<T> {
    col_count: usize,
    row_count: usize,
    items: Vec<T>,
}

impl<T> Mat<T> {
    pub fn from_vec(items: Vec<T>, col_count: usize, row_count: usize) -> Self {
        assert_eq!(items.len(), col_count * row_count, "mismatching dimensions");

        Self {
            col_count,
            row_count,
            items,
        }
    }

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

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

    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.items.iter()
    }

    pub fn row_iter(&self, row: usize) -> impl Iterator<Item = &T> {
        assert!(row < self.row_count, "index out of bounds");
        let start = row * self.col_count;
        self.items[start..start + self.col_count].iter()
    }

    pub fn col_iter(&self, col: usize) -> impl Iterator<Item = &T> {
        assert!(col < self.col_count, "index out of bounds");
        self.items.iter().skip(col).step_by(self.col_count)
    }
}

impl<T: Display> Display for Mat<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {

        let mut len = 0usize;
        let mut buf = String::new();
        for item in (0..self.row_count).flat_map(|row| self.row_iter(row)) {
            buf.clear();
            write!(buf, "{}", item)?;
            len = std::cmp::max(len, buf.chars().count());
        }

        len += 1;
        let width = len * self.col_count + 1;
        writeln!(f, "┌{:width$}┐", "", width = width)?;

        for row in (0..self.row_count).map(|row| self.row_iter(row)) {
            write!(f, "│")?;

            for item in row {
                write!(f, "{:>width$}", item, width = len)?;
            }

            writeln!(f, " │")?;
        }

        write!(f, "└{:width$}┘", "", width = width)
    }
}

impl<T> Mat<T> {
    pub fn write_ppm(
        &self,
        f: &mut dyn std::io::Write,
        rgb: impl Fn(&T) -> (u8, u8, u8),
    ) -> std::io::Result<()> {
        let bytes = self
            .iter()
            .map(rgb)
            .flat_map(|(r, g, b)| {
                use std::iter::once;
                once(r).chain(once(g)).chain(once(b))
            })
            .collect::<Vec<u8>>();

        write!(f, "P6\n{} {}\n255\n", self.col_count, self.row_count)?;
        f.write_all(&bytes)
    }
}

mod kronecker {

    use super::Mat;
    use std::ops::Mul;

    pub fn product<T, U>(a: &Mat<T>, b: &Mat<U>) -> Mat<<T as Mul<U>>::Output>
    where
        T: Clone + Mul<U>,
        U: Clone,
    {
        let row_count = a.row_count() * b.row_count();
        let col_count = a.col_count() * b.col_count();
        let mut items = Vec::with_capacity(row_count * col_count);

        for i in 0..a.row_count() {
            for k in 0..b.row_count() {
                for a_x in a.row_iter(i) {
                    for b_x in b.row_iter(k) {
                        items.push(a_x.clone() * b_x.clone());
                    }
                }
            }
        }

        Mat::from_vec(items, col_count, row_count)
    }

    pub fn power<T>(m: &Mat<T>, n: u32) -> Mat<T>
    where
        T: Clone + Mul<T, Output = T>,
    {
        match n {
            0 => m.clone(),
            _ => (1..n).fold(product(&m, &m), |result, _| product(&result, &m)),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Char(char);

impl Char {
    fn space() -> Self {
        Char(' ')
    }

    fn is_space(&self) -> bool {
        self.0 == ' '
    }
}

impl Display for Char {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl Mul for Char {
    type Output = Self;

    #[allow(clippy::suspicious_arithmetic_impl)]
    fn mul(self, rhs: Self) -> Self {
        if self.is_space() || rhs.is_space() {
            Char(' ')
        } else {
            self
        }
    }
}

fn main() -> std::io::Result<()> {

    #[rustfmt::skip]
    let vicsek = Mat::<u8>::from_vec(vec![
        0, 1, 0,
        1, 1, 1,
        0, 1, 0,
    ], 3, 3);

    println!("{}", vicsek);
    println!("{}", kronecker::power(&vicsek, 3));

    let s = Char::space();
    let b = Char('\u{2588}');

    #[rustfmt::skip]
    let sierpienski = Mat::from_vec(vec![
        b, b, b,
        b, s, b,
        b, b, b,
    ], 3, 3);

    println!("{}", sierpienski);
    println!("{}", kronecker::power(&sierpienski, 3));

    #[rustfmt::skip]
    let matrix = Mat::from_vec(vec![
        s, s, b, s, s,
        s, b, b, b, s,
        b, s, b, s, b,
        s, s, b, s, s,
        s, b, s, b, s,
    ], 5, 5,);

    println!("{}", kronecker::power(&matrix, 1));

    kronecker::power(&matrix, 4).write_ppm(
        &mut std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open("kronecker_power.ppm")?,
        |&item| {
            if item.is_space() {
                (0, 0, 32)
            } else {
                (192, 192, 0)
            }
        },
    )
}


LU decomposition

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

#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }

typedef double **mat;

#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }

#define _new(a) a = mat_new(n)
mat mat_new(_dim)
{
	mat x = malloc(sizeof(double*) * n);
	x[0]  = malloc(sizeof(double) * n * n);

	for_i x[i] = x[0] + n * i;
	_zero(x);

	return x;
}

#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim)
{
	mat x = mat_new(n);
	for_ij x[i][j] = ((double (*)[n])s)[i][j];
	return x;
}

#define _del(x) mat_del(x)
void mat_del(mat x) { free(x[0]); free(x); }

#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim)
{
	if (!fmt) fmt = "%8.4g";
	for_i {
		printf(i ? "      " : " [ ");
		for_j {
			printf(fmt, x[i][j]);
			printf(j < n - 1 ? "  " : i == n - 1 ? " ]\n" : "\n");
		}
	}
}

#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim)
{
	mat c = _new(c);
	for_ijk c[i][j] += a[i][k] * b[k][j];
	return c;
}

#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim)
{
	for_ij { p[i][j] = (i == j); }
	for_i  {
		int max_j = i;
		foreach(j, i, n)
			if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;

		if (max_j != i)
			for_k { _swap(p[i][k], p[max_j][k]); }
	}
}

#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
	_zero(L); _zero(U);
	_pivot(A, P);

	mat Aprime = _mul(P, A);

	for_i  { L[i][i] = 1; }
	for_ij {
		double s;
		if (j <= i) {
			_sum_k(0, j, L[j][k] * U[k][i], s)
			U[j][i] = Aprime[j][i] - s;
		}
		if (j >= i) {
			_sum_k(0, i, L[j][k] * U[k][i], s);
			L[j][i] = (Aprime[j][i] - s) / U[i][i];
		}
	}

	_del(Aprime);
}

double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};

int main()
{
	int n = 3;
	mat A, L, P, U;

	_new(L); _new(P); _new(U);
	A = _copy(A3);
	_LU(A, L, U, P);
	_show(A); _show(L); _show(U); _show(P);
	_del(A);  _del(L);  _del(U);  _del(P);

	printf("\n");

	n = 4;

	_new(L); _new(P); _new(U);
	A = _copy(A4);
	_LU(A, L, U, P);
	_show(A); _show(L); _show(U); _show(P);
	_del(A);  _del(L);  _del(U);  _del(P);

	return 0;
}

#![allow(non_snake_case)]
use ndarray::{Array, Axis, Array2, arr2, Zip, NdFloat, s};

fn main() {
    println!("Example 1:");
    let A: Array2<f64> = arr2(&[
        [1.0, 3.0, 5.0],
        [2.0, 4.0, 7.0],
        [1.0, 1.0, 0.0],
    ]);
    println!("A \n {}", A);
    let (L, U, P) = lu_decomp(A);
    println!("L \n {}", L);
    println!("U \n {}", U);
    println!("P \n {}", P);

    println!("\nExample 2:");
    let A: Array2<f64> = arr2(&[
        [11.0, 9.0, 24.0, 2.0],
        [1.0, 5.0, 2.0, 6.0],
        [3.0, 17.0, 18.0, 1.0],
        [2.0, 5.0, 7.0, 1.0],
    ]);
    println!("A \n {}", A);
    let (L, U, P) = lu_decomp(A);
    println!("L \n {}", L);
    println!("U \n {}", U);
    println!("P \n {}", P);
}

fn pivot<T>(A: &Array2<T>) -> Array2<T>
where T: NdFloat {
    let matrix_dimension = A.rows();
    let mut P: Array2<T> = Array::eye(matrix_dimension);
    for (i, column) in A.axis_iter(Axis(1)).enumerate() {

        let mut max_pos = i;
        for j in i..matrix_dimension {
            if column[max_pos].abs() < column[j].abs() {
                max_pos = j;
            }
        }

        if max_pos != i {
            swap_rows(&mut P, i, max_pos);
        }
    }
    P
}

fn swap_rows<T>(A: &mut Array2<T>, idx_row1: usize, idx_row2: usize)
where T: NdFloat {

    let (.., mut matrix_rest) = A.view_mut().split_at(Axis(0), idx_row1);
    let (row0, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), 1);
    let (_matrix_helper, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), idx_row2 - idx_row1 - 1);
    let (row1, ..) = matrix_rest.view_mut().split_at(Axis(0), 1);
    Zip::from(row0).and(row1).apply(std::mem::swap);
}

fn lu_decomp<T>(A: Array2<T>) -> (Array2<T>, Array2<T>, Array2<T>)
where T: NdFloat {

    let matrix_dimension = A.rows();
    assert_eq!(matrix_dimension, A.cols(), "Tried LU decomposition with a non-square matrix.");
    let P = pivot(&A);
    let pivotized_A = P.dot(&A);

    let mut L: Array2<T> = Array::eye(matrix_dimension);
    let mut U: Array2<T> = Array::zeros((matrix_dimension, matrix_dimension));
    for idx_col in 0..matrix_dimension {

        for idx_row in 0..idx_col+1 {
            U[[idx_row, idx_col]] = pivotized_A[[idx_row, idx_col]] -
                U.slice(s![0..idx_row,idx_col]).dot(&L.slice(s![idx_row,0..idx_row]));
        }

        for idx_row in idx_col+1..matrix_dimension {
            L[[idx_row, idx_col]] = (pivotized_A[[idx_row, idx_col]] -
                U.slice(s![0..idx_col,idx_col]).dot(&L.slice(s![idx_row,0..idx_col]))) /
                U[[idx_col, idx_col]];
        }
    }
    (L, U, P)
}


LZW compression

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

void* mem_alloc(size_t item_size, size_t n_item)
{
  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);
  x[0] = item_size;
  x[1] = n_item;
  return x + 2;
}

void* mem_extend(void *m, size_t new_n)
{
  size_t *x = (size_t*)m - 2;
  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);
  if (new_n > x[1])
    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));
  x[1] = new_n;
  return x + 2;
}

inline void _clear(void *m)
{
  size_t *x = (size_t*)m - 2;
  memset(m, 0, x[0] * x[1]);
}

#define _new(type, n) mem_alloc(sizeof(type), n)
#define _del(m)   { free((size_t*)(m) - 2); m = 0; }
#define _len(m)   *((size_t*)m - 1)
#define _setsize(m, n)  m = mem_extend(m, n)
#define _extend(m)  m = mem_extend(m, _len(m) * 2)

typedef uint8_t byte;
typedef uint16_t ushort;

#define M_CLR 256
#define M_EOD 257
#define M_NEW 258

typedef struct {
  ushort next[256];
} lzw_enc_t;

typedef struct {
  ushort prev, back;
  byte c;
} lzw_dec_t;

byte* lzw_encode(byte *in, int max_bits)
{
  int len = _len(in), bits = 9, next_shift = 512;
  ushort code, c, nc, next_code = M_NEW;
  lzw_enc_t *d = _new(lzw_enc_t, 512);

  if (max_bits > 15) max_bits = 15;
  if (max_bits < 9 ) max_bits = 12;

  byte *out = _new(ushort, 4);
  int out_len = 0, o_bits = 0;
  uint32_t tmp = 0;

  inline void write_bits(ushort x) {
    tmp = (tmp << bits) | x;
    o_bits += bits;
    if (_len(out) <= out_len) _extend(out);
    while (o_bits >= 8) {
      o_bits -= 8;
      out[out_len++] = tmp >> o_bits;
      tmp &= (1 << o_bits) - 1;
    }
  }

  for (code = *(in++); --len; ) {
    c = *(in++);
    if ((nc = d[code].next[c]))
      code = nc;
    else {
      write_bits(code);
      nc = d[code].next[c] = next_code++;
      code = c;
    }

    if (next_code == next_shift) {

      if (++bits > max_bits) {

        write_bits(M_CLR);

        bits = 9;
        next_shift = 512;
        next_code = M_NEW;
        _clear(d);
      } else
        _setsize(d, next_shift *= 2);
    }
  }

  write_bits(code);
  write_bits(M_EOD);
  if (tmp) write_bits(tmp);

  _del(d);

  _setsize(out, out_len);
  return out;
}

byte* lzw_decode(byte *in)
{
  byte *out = _new(byte, 4);
  int out_len = 0;

  inline void write_out(byte c)
  {
    while (out_len >= _len(out)) _extend(out);
    out[out_len++] = c;
  }

  lzw_dec_t *d = _new(lzw_dec_t, 512);
  int len, j, next_shift = 512, bits = 9, n_bits = 0;
  ushort code, c, t, next_code = M_NEW;

  uint32_t tmp = 0;
  inline void get_code() {
    while(n_bits < bits) {
      if (len > 0) {
        len --;
        tmp = (tmp << 8) | *(in++);
        n_bits += 8;
      } else {
        tmp = tmp << (bits - n_bits);
        n_bits = bits;
      }
    }
    n_bits -= bits;
    code = tmp >> n_bits;
    tmp &= (1 << n_bits) - 1;
  }

  inline void clear_table() {
    _clear(d);
    for (j = 0; j < 256; j++) d[j].c = j;
    next_code = M_NEW;
    next_shift = 512;
    bits = 9;
  };

  clear_table();
  for (len = _len(in); len;) {
    get_code();
    if (code == M_EOD) break;
    if (code == M_CLR) {
      clear_table();
      continue;
    }

    if (code >= next_code) {
      fprintf(stderr, "Bad sequence\n");
      _del(out);
      goto bail;
    }

    d[next_code].prev = c = code;
    while (c > 255) {
      t = d[c].prev; d[t].back = c; c = t;
    }

    d[next_code - 1].c = c;

    while (d[c].back) {
      write_out(d[c].c);
      t = d[c].back; d[c].back = 0; c = t;
    }
    write_out(d[c].c);

    if (++next_code >= next_shift) {
      if (++bits > 16) {

        fprintf(stderr, "Too many bits\n");
        _del(out);
        goto bail;
      }
      _setsize(d, next_shift *= 2);
    }
  }

  if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr);

  _setsize(out, out_len);
bail: _del(d);
  return out;
}

int main()
{
  int i, fd = open("unixdict.txt", O_RDONLY);

  if (fd == -1) {
    fprintf(stderr, "Can't read file\n");
    return 1;
  };

  struct stat st;
  fstat(fd, &st);

  byte *in = _new(char, st.st_size);
  read(fd, in, st.st_size);
  _setsize(in, st.st_size);
  close(fd);

  printf("input size:   %d\n", _len(in));

  byte *enc = lzw_encode(in, 9);
  printf("encoded size: %d\n", _len(enc));

  byte *dec = lzw_decode(enc);
  printf("decoded size: %d\n", _len(dec));

  for (i = 0; i < _len(dec); i++)
    if (dec[i] != in[i]) {
      printf("bad decode at %d\n", i);
      break;
    }

  if (i == _len(dec)) printf("Decoded ok\n");

  _del(in);
  _del(enc);
  _del(dec);

  return 0;
}

use std::collections::HashMap;

fn compress(data: &[u8]) -> Vec<u32> {

    let mut dictionary: HashMap<Vec<u8>, u32> = (0u32..=255)
        .map(|i| (vec![i as u8], i))
        .collect();

    let mut w = Vec::new();
    let mut compressed = Vec::new();

    for &b in data {
        let mut wc = w.clone();
        wc.push(b);

        if dictionary.contains_key(&wc) {
            w = wc;
        } else {

            compressed.push(dictionary[&w]);

            dictionary.insert(wc, dictionary.len() as u32);
            w.clear();
            w.push(b);
        }
    }

    if !w.is_empty() {
        compressed.push(dictionary[&w]);
    }

    compressed
}

fn decompress(mut data: &[u32]) -> Vec<u8> {

    let mut dictionary: HashMap::<u32, Vec<u8>> = (0u32..=255)
        .map(|i| (i, vec![i as u8]))
        .collect();

    let mut w = dictionary[&data[0]].clone();
    data = &data[1..];
    let mut decompressed = w.clone();

    for &k in data {
        let entry = if dictionary.contains_key(&k) {
            dictionary[&k].clone()
        } else if k == dictionary.len() as u32 {
            let mut entry = w.clone();
            entry.push(w[0]);
            entry
        } else {
            panic!("Invalid dictionary!");
        };

        decompressed.extend_from_slice(&entry);

        w.push(entry[0]);
        dictionary.insert(dictionary.len() as u32, w);

        w = entry;
    }

    decompressed
}

fn main() {
    let compressed = compress("TOBEORNOTTOBEORTOBEORNOT".as_bytes());
    println!("{:?}", compressed);

    let decompressed = decompress(&compressed);
    let decompressed = String::from_utf8(decompressed).unwrap();
    println!("{}", decompressed);
}


Longest string challenge

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

int cmp(const char *p, const char *q)
{
	while (*p && *q) p = &p[1], q = &q[1];
	return *p;
}

int main()
{
	char line[65536];
	char buf[1000000] = {0};
	char *last = buf;
	char *next = buf;

	while (gets(line)) {
		strcat(line, "\n");
		if (cmp(last, line)) continue;
		if (cmp(line, last)) next = buf;
		last = next;
		strcpy(next, line);
		while (*next) next = &next[1];
	}

	printf("%s", buf);
	return 0;
}

use std::cmp::Ordering;
use std::io::BufRead;

fn compare(a: &str, b: &str) -> Ordering {
    let mut a = a.chars();
    let mut b = b.chars();
    loop {
        match (a.next(), b.next()) {
            (None, None) => return Ordering::Equal,
            (Some(_), None) => return Ordering::Greater,
            (None, Some(_)) => return Ordering::Less,
            (Some(_), Some(_)) => {}
        }
    }
}

fn longest<I: IntoIterator<Item = String>>(input: I) -> String {
    let mut longest = String::new();
    let mut output = String::new();

    for line in input {
        match compare(&line, &longest) {

            Ordering::Greater => {
                output.clear();
                output.push_str(&line);
                longest = line;
            }

            Ordering::Equal => {
                output.push('\n');
                output.push_str(&line);
            }

            Ordering::Less => {}
        }
    }

    output
}

fn main() {
    let stdin = std::io::stdin();
    let lines = stdin.lock().lines().map(|l| l.expect("Failed to read."));

    println!("{}", longest(lines))
}


MAC vendor lookup

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

/* Length of http:
#define FIXED_LENGTH 16

struct MemoryStruct {
  char *memory;
  size_t size;
};

static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)userp;

  mem->memory = realloc(mem->memory, mem->size + realsize + 1);

  memcpy(&(mem->memory[mem->size]), contents, realsize);
  mem->size += realsize;
  mem->memory[mem->size] = 0;

  return realsize;
}

void checkResponse(char* str){
	char ref[] = "Vendor not found";
	int len = strlen(str),flag = 1,i;

	if(len<16)
		fputs(str,stdout);
	else{
		for(i=0;i<len && i<16;i++)
			flag = flag && (ref[i]==str[i]);

		flag==1?fputs("N/A",stdout):fputs(str,stdout);
	}
}

int main(int argC,char* argV[])
{
		if(argC!=2)
			printf("Usage : %s <MAC address>",argV[0]);
		else{
			CURL *curl;
			int len = strlen(argV[1]);
			char* str = (char*)malloc((FIXED_LENGTH + len)*sizeof(char));
			struct MemoryStruct chunk;
			CURLcode res;

			chunk.memory = malloc(1);
			chunk.size = 0;

        if ((curl = curl_easy_init()) != NULL) {
				sprintf(str,"http:

                                curl_easy_setopt(curl, CURLOPT_URL, str);
				curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
				curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

				free(str);

				res = curl_easy_perform(curl);

                if (res == CURLE_OK) {
				checkResponse(chunk.memory);
                                return EXIT_SUCCESS;
                }

                curl_easy_cleanup(curl);
			}
		}

        return EXIT_FAILURE;
}

extern crate reqwest;

use std::{thread, time};

fn get_vendor(mac: &str) -> Option<String> {
    let mut url = String::from("http:
    url.push_str(mac);
    let url_ref = &url;
    match reqwest::get(url_ref) {
        Ok(mut res) => match res.text() {
            Ok(text) => {
                if text.contains("Not Found") {
                    Some("N/A".to_string())
                } else {
                    Some(text)
                }
            }
            Err(e) => {
                println!("{:?}", e);
                None
            }
        },
        Err(e) => {
            println!("{:?}", e);
            None
        }
    }
}

fn main() {
    let duration = time::Duration::from_millis(1000);
    match get_vendor("88:53:2E:67:07:BE") {
        None => println!("Error!"),
        Some(text) => println!("{}", text),
    }
    thread::sleep(duration);
    match get_vendor("FC:FB:FB:01:FA:21") {
        None => println!("Error!"),
        Some(text) => println!("{}", text),
    }
    thread::sleep(duration);
    match get_vendor("FC-A1-3E") {
        None => println!("Error!"),
        Some(text) => println!("{}", text),
    }
    thread::sleep(duration);
    match get_vendor("abcdefg") {
        None => println!("Error!"),
        Some(text) => println!("{}", text),
    }
}


Mad Libs

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

#define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)

typedef struct {
    char *data;
    size_t alloc;
    size_t length;
} dstr;

inline int dstr_space(dstr *s, size_t grow_amount)
{
    return s->length + grow_amount < s->alloc;
}

int dstr_grow(dstr *s)
{
    s->alloc *= 2;
    char *attempt = realloc(s->data, s->alloc);

    if (!attempt) return 0;
    else s->data = attempt;

    return 1;
}

dstr* dstr_init(const size_t to_allocate)
{
    dstr *s = malloc(sizeof(dstr));
    if (!s) goto failure;

    s->length = 0;
    s->alloc  = to_allocate;
    s->data   = malloc(s->alloc);

    if (!s->data) goto failure;

    return s;

failure:
    if (s->data) free(s->data);
    if (s) free(s);
    return NULL;
}

void dstr_delete(dstr *s)
{
    if (s->data) free(s->data);
    if (s) free(s);
}

dstr* readinput(FILE *fd)
{
    static const size_t buffer_size = 4096;
    char buffer[buffer_size];

    dstr *s = dstr_init(buffer_size);
    if (!s) goto failure;

    while (fgets(buffer, buffer_size, fd)) {
        while (!dstr_space(s, buffer_size))
            if (!dstr_grow(s)) goto failure;

        strncpy(s->data + s->length, buffer, buffer_size);
        s->length += strlen(buffer);
    }

    return s;

failure:
    dstr_delete(s);
    return NULL;
}

void dstr_replace_all(dstr *story, const char *replace, const char *insert)
{
    const size_t replace_l = strlen(replace);
    const size_t insert_l  = strlen(insert);
    char *start = story->data;

    while ((start = strstr(start, replace))) {
        if (!dstr_space(story, insert_l - replace_l))
            if (!dstr_grow(story)) err("Failed to allocate memory");

        if (insert_l != replace_l) {
            memmove(start + insert_l, start + replace_l, story->length -
                    (start + replace_l - story->data));

            story->length += insert_l - replace_l;
            story->data[story->length] = 0;
        }

        memmove(start, insert, insert_l);
    }
}

void madlibs(dstr *story)
{
    static const size_t buffer_size = 128;
    char insert[buffer_size];
    char replace[buffer_size];

    char *start,
         *end = story->data;

    while (start = strchr(end, '<')) {
        if (!(end = strchr(start, '>'))) err("Malformed brackets in input");

        strncpy(replace, start, end - start + 1);
        replace[end - start + 1] = '\0';

        printf("Enter value for field %s: ", replace);

        fgets(insert, buffer_size, stdin);
        const size_t il = strlen(insert) - 1;
        if (insert[il] == '\n')
            insert[il] = '\0';

        dstr_replace_all(story, replace, insert);
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
    if (argc < 2) return 0;

    FILE *fd = fopen(argv[1], "r");
    if (!fd) err("Could not open file: '%s\n", argv[1]);

    dstr *story = readinput(fd); fclose(fd);
    if (!story) err("Failed to allocate memory");

    madlibs(story);
    printf("%s\n", story->data);
    dstr_delete(story);
    return 0;
}

extern crate regex;

use regex::Regex;
use std::collections::HashMap;
use std::io;

fn main() {
    let mut input_line = String::new();
    let mut template = String::new();

    println!("Please enter a multi-line story template with <parts> to replace, terminated by a blank line.\n");
    loop {
        io::stdin()
            .read_line(&mut input_line)
            .expect("The read line failed.");
        if input_line.trim().is_empty() {
            break;
        }
        template.push_str(&input_line);
        input_line.clear();
    }

    let re = Regex::new(r"<[^>]+>").unwrap();
    let mut parts: HashMap<_, _> = re
        .captures_iter(&template)
        .map(|x| (x.get(0).unwrap().as_str().to_string(), "".to_string()))
        .collect();
    if parts.is_empty() {
        println!("No <parts> to replace.\n");
    } else {
        for (k, v) in parts.iter_mut() {
            println!("Please provide a replacement for {}: ", k);
            io::stdin()
                .read_line(&mut input_line)
                .expect("The read line failed.");
            *v = input_line.trim().to_string();
            println!();
            template = template.replace(k, v);
            input_line.clear();
        }
    }
    println!("Resulting story:\n\n{}", template);
}


Magic 8-ball

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

int main() {
    char *question = NULL;
    size_t len = 0;
    ssize_t read;
    const char* answers[20] = {
        "It is certain", "It is decidedly so", "Without a doubt",
        "Yes, definitely", "You may rely on it", "As I see it, yes",
        "Most likely", "Outlook good", "Signs point to yes", "Yes",
        "Reply hazy, try again", "Ask again later",
        "Better not tell you now", "Cannot predict now",
        "Concentrate and ask again", "Don't bet on it",
        "My reply is no", "My sources say no", "Outlook not so good",
        "Very doubtful"
    };
    srand(time(NULL));
    printf("Please enter your question or a blank line to quit.\n");
    while (1) {
        printf("\n? : ");
        read = getline(&question, &len, stdin);
        if (read < 2) break;
        printf("\n%s\n", answers[rand() % 20]);
    }
    if (question) free(question);
    return 0;
}

extern crate rand;

use rand::prelude::*;
use std::io;

fn main() {
    let answers = [
        "It is certain",
        "It is decidedly so",
        "Without a doubt",
        "Yes, definitely",
        "You may rely on it",
        "As I see it, yes",
        "Most likely",
        "Outlook good",
        "Signs point to yes",
        "Yes",
        "Reply hazy, try again",
        "Ask again later",
        "Better not tell you now",
        "Cannot predict now",
        "Concentrate and ask again",
        "Don't bet on it",
        "My reply is no",
        "My sources say no",
        "Outlook not so good",
        "Very doubtful",
    ];
    let mut rng = rand::thread_rng();
    let mut input_line = String::new();

    println!("Please enter your question or a blank line to quit.\n");
    loop {
        io::stdin()
            .read_line(&mut input_line)
            .expect("The read line failed.");
        if input_line.trim() == "" {
            break;
        }
        println!("{}\n", answers.choose(&mut rng).unwrap());
        input_line.clear();
    }
}


Magic squares of odd order

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

int f(int n, int x, int y)
{
	return (x + y*2 + 1)%n;
}

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

	if(argc!=2) return 1;

	n = atoi(argv[1]);
	if (n < 3 || (n%2) == 0) return 2;

	for (i = 0; i < n; i++) {
		for (j = 0; j < n; j++)
			printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1);
		putchar('\n');
	}
	printf("\n Magic Constant: %d.\n", (n*n+1)/2*n);

	return 0;
}

fn main() {
    let n = 9;
    let mut square = vec![vec![0; n]; n];
    for (i, row) in square.iter_mut().enumerate() {
        for (j, e) in row.iter_mut().enumerate() {
            *e = n * (((i + 1) + (j + 1) - 1 + (n >> 1)) % n) + (((i + 1) + (2 * (j + 1)) - 2) % n) + 1;
            print!("{:3} ", e);
        }
        println!("");
    }
    let sum = n * (((n * n) + 1) / 2);
    println!("The sum of the square is {}.", sum);
}


Matrix digital rain

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

#define ROW_DELAY 40000

int get_rand_in_range(int min, int max)
{
  return (rand() % ((max + 1) - min) + min);
}

int main(void)
{

  srand(time(NULL));

  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

  int total_chars = sizeof(chars);

  initscr();
  noecho();
  curs_set(FALSE);

  start_color();
  init_pair(1, COLOR_GREEN, COLOR_BLACK);
  attron(COLOR_PAIR(1));

  int max_x = 0, max_y = 0;

  getmaxyx(stdscr, max_y, max_x);

  int columns_row[max_x];

  int columns_active[max_x];

  int i;

  for (i = 0; i < max_x; i++)
  {
    columns_row[i] = -1;
    columns_active[i] = 0;
  }

  while (1)
  {
    for (i = 0; i < max_x; i++)
    {
      if (columns_row[i] == -1)
      {

        columns_row[i] = get_rand_in_range(0, max_y);
        columns_active[i] = get_rand_in_range(0, 1);
      }
    }

    for (i = 0; i < max_x; i++)
    {
      if (columns_active[i] == 1)
      {

        int char_index = get_rand_in_range(0, total_chars);
        mvprintw(columns_row[i], i, "%c", chars[char_index]);
      }
      else
      {

        mvprintw(columns_row[i], i, " ");
      }

      columns_row[i]++;

      if (columns_row[i] >= max_y)
      {
        columns_row[i] = -1;
      }

      if (get_rand_in_range(0, 1000) == 0)
      {
        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
      }
    }

    usleep(ROW_DELAY);
    refresh();
  }

  endwin();
  return 0;
}


Optional parameters

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

typedef const char * String;
typedef struct sTable {
    String * *rows;
    int      n_rows,n_cols;
} *Table;

typedef int (*CompareFctn)(String a, String b);

struct {
   CompareFctn  compare;
   int   column;
   int   reversed;
} sortSpec;

int CmprRows( const void *aa, const void *bb)
{
   String *rA = *(String *const *)aa;
   String *rB = *(String *const *)bb;
   int sortCol = sortSpec.column;

   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];
   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];
   return sortSpec.compare( left, right );
}

int sortTable(Table tbl, const char* argSpec,... )
{
   va_list vl;
   const char *p;
   int c;
   sortSpec.compare = &strcmp;
   sortSpec.column = 0;
   sortSpec.reversed = 0;

   va_start(vl, argSpec);
   if (argSpec)
      for (p=argSpec; *p; p++) {
         switch (*p) {
         case 'o':
            sortSpec.compare = va_arg(vl,CompareFctn);
            break;
         case 'c':
            c = va_arg(vl,int);
            if ( 0<=c && c<tbl->n_cols)
               sortSpec.column  = c;
            break;
         case 'r':
            sortSpec.reversed = (0!=va_arg(vl,int));
            break;
         }
      }
   va_end(vl);
   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);
   return 0;
}

void printTable( Table tbl, FILE *fout, const char *colFmts[])
{
   int row, col;

   for (row=0; row<tbl->n_rows; row++) {
      fprintf(fout, "   ");
      for(col=0; col<tbl->n_cols; col++) {
         fprintf(fout, colFmts[col], tbl->rows[row][col]);
      }
      fprintf(fout, "\n");
   }
   fprintf(fout, "\n");
}

int ord(char v)
{
    return v-'0';
}

int cmprStrgs(String s1, String s2)
{
    const char *p1 = s1;
    const char *p2 = s2;
    const 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) {
                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, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);
    return (*p1 -*p2);
}

int main()
{
   const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"};
   String r1[] = { "a101", "red",  "Java" };
   String r2[] = { "ab40", "gren", "Smalltalk" };
   String r3[] = { "ab9",  "blue", "Fortran" };
   String r4[] = { "ab09", "ylow", "Python" };
   String r5[] = { "ab1a", "blak", "Factor" };
   String r6[] = { "ab1b", "brwn", "C Sharp" };
   String r7[] = { "Ab1b", "pink", "Ruby" };
   String r8[] = { "ab1",  "orng", "Scheme" };

   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };
   struct sTable table;
   table.rows = rows;
   table.n_rows = 8;
   table.n_cols = 3;

   sortTable(&table, "");
   printf("sort on col 0, ascending\n");
   printTable(&table, stdout, colFmts);

   sortTable(&table, "ro", 1, &cmprStrgs);
   printf("sort on col 0, reverse.special\n");
   printTable(&table, stdout, colFmts);

   sortTable(&table, "c", 1);
   printf("sort on col 1, ascending\n");
   printTable(&table, stdout, colFmts);

   sortTable(&table, "cr", 2, 1);
   printf("sort on col 2, reverse\n");
   printTable(&table, stdout, colFmts);
   return 0;
}

use std::cmp::Ordering;

struct Table {
    rows: Vec<Vec<String>>,
    ordering_function: fn(&str, &str) -> Ordering,
    ordering_column: usize,
    reverse: bool,
}

impl Table {
    fn new(rows: Vec<Vec<String>>) -> Table {
        Table {
            rows: rows,
            ordering_column: 0,
            reverse: false,
            ordering_function: |str1, str2| str1.cmp(str2),
        }
    }
}

impl Table {
    fn with_ordering_column(&mut self, ordering_column: usize) -> &mut Table {
        self.ordering_column = ordering_column;
        self
    }

    fn with_reverse(&mut self, reverse: bool) -> &mut Table {
        self.reverse = reverse;
        self
    }

    fn with_ordering_fun(&mut self, compare: fn(&str, &str) -> Ordering) -> &mut Table {
        self.ordering_function = compare;
        self
    }

    fn sort(&mut self) {
        let fun = &mut self.ordering_function;
        let idx = self.ordering_column;
        if self.reverse {
            self.rows
                .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]).reverse());
        } else {
            self.rows
                .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]));
        }
    }
}

#[cfg(test)]
mod test {
    use super::Table;

    fn generate_test_table() -> Table {
        Table::new(vec![
            vec!["0".to_string(), "fff".to_string()],
            vec!["2".to_string(), "aab".to_string()],
            vec!["1".to_string(), "ccc".to_string()],
        ])
    }

    #[test]
    fn test_simple_sort() {
        let mut table = generate_test_table();
        table.sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["0".to_string(), "fff".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["2".to_string(), "aab".to_string()],
            ],
        )
    }

    #[test]
    fn test_ordering_column() {
        let mut table = generate_test_table();
        table.with_ordering_column(1).sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }

    #[test]
    fn test_with_reverse() {
        let mut table = generate_test_table();
        table.with_reverse(true).sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }

    #[test]
    fn test_custom_ordering_fun() {
        let mut table = generate_test_table();

        table.with_ordering_fun(|x, y| x.cmp(y).reverse()).sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }

    #[test]
    fn test_everything_together() {
        let mut table = generate_test_table();

        table
            .with_ordering_fun(|x, y| x.cmp(y).reverse())
            .with_reverse(true)
            .with_ordering_column(1)
            .sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }
}


Peano curve

use svg::node::element::path::Data;
use svg::node::element::Path;

struct PeanoCurve {
    current_x: f64,
    current_y: f64,
    current_angle: i32,
    line_length: f64,
}

impl PeanoCurve {
    fn new(x: f64, y: f64, length: f64, angle: i32) -> PeanoCurve {
        PeanoCurve {
            current_x: x,
            current_y: y,
            current_angle: angle,
            line_length: length,
        }
    }
    fn rewrite(order: usize) -> String {
        let mut str = String::from("L");
        for _ in 0..order {
            let mut tmp = String::new();
            for ch in str.chars() {
                match ch {
                    'L' => tmp.push_str("LFRFL-F-RFLFR+F+LFRFL"),
                    'R' => tmp.push_str("RFLFR+F+LFRFL-F-RFLFR"),
                    _ => tmp.push(ch),
                }
            }
            str = tmp;
        }
        str
    }
    fn execute(&mut self, order: usize) -> Path {
        let mut data = Data::new().move_to((self.current_x, self.current_y));
        for ch in PeanoCurve::rewrite(order).chars() {
            match ch {
                'F' => data = self.draw_line(data),
                '+' => self.turn(90),
                '-' => self.turn(-90),
                _ => {}
            }
        }
        Path::new()
            .set("fill", "none")
            .set("stroke", "black")
            .set("stroke-width", "1")
            .set("d", data)
    }
    fn draw_line(&mut self, data: Data) -> Data {
        let theta = (self.current_angle as f64).to_radians();
        self.current_x += self.line_length * theta.cos();
        self.current_y += self.line_length * theta.sin();
        data.line_to((self.current_x, self.current_y))
    }
    fn turn(&mut self, angle: i32) {
        self.current_angle = (self.current_angle + angle) % 360;
    }
    fn save(file: &str, size: usize, order: usize) -> std::io::Result<()> {
        use svg::node::element::Rectangle;
        let rect = Rectangle::new()
            .set("width", "100%")
            .set("height", "100%")
            .set("fill", "white");
        let mut p = PeanoCurve::new(8.0, 8.0, 8.0, 90);
        let document = svg::Document::new()
            .set("width", size)
            .set("height", size)
            .add(rect)
            .add(p.execute(order));
        svg::save(file, &document)
    }
}

fn main() {
    PeanoCurve::save("peano_curve.svg", 656, 4).unwrap();
}


Permutation test

#include <stdio.h>

int data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,
                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };

int pick(int at, int remain, int accu, int treat)
{
        if (!remain) return (accu > treat) ? 1 : 0;

        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +
                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );
}

int main()
{
        int treat = 0, i;
        int le, gt;
        double total = 1;
        for (i = 0; i < 9; i++) treat += data[i];
        for (i = 19; i > 10; i--) total *= i;
        for (i = 9; i > 0; i--) total /= i;

        gt = pick(19, 9, 0, treat);
        le = total - gt;

        printf("<= : %f%%  %d\n > : %f%%  %d\n",
               100 * le / total, le, 100 * gt / total, gt);
        return 0;
}

fn main() {
    let treatment = vec![85, 88, 75, 66, 25, 29, 83, 39, 97];
    let control = vec![68, 41, 10, 49, 16, 65, 32, 92, 28, 98];

    let mut data_set = control.clone();
    data_set.extend_from_slice(&treatment);

    let greater = combinations(treatment.iter().sum(), treatment.len() as i64, &data_set) as f64;
    let lesser = combinations(control.iter().sum(), control.len() as i64, &data_set) as f64;
    let total = binomial(data_set.len() as i64, treatment.len() as i64) as f64;

    println!("<= : {}%", (lesser / total * 100.0));
    println!(" > : {}%", (greater / total * 100.0));
}

fn factorial(x: i64) -> i64 {
    let mut product = 1;
    for a in 1..(x + 1) {
        product *= a;
    }
    product
}

fn binomial(n: i64, k: i64) -> i64 {
    let numerator = factorial(n);
    let denominator = factorial(k) * factorial(n - k);
    numerator / denominator
}

fn combinations(total: i64, number: i64, data: &[i64]) -> i64 {
    if total < 0 {
        return binomial(data.len() as i64, number);
    }

    if number == 0 {
        return 0;
    }

    if number > data.len() as i64 {
        return 0;
    }

    if number == data.len() as i64 {
        if total < data.iter().sum() {
            return 1;
        } else {
            return 0;
        }
    }

    let tail = &data[1..];
    combinations(total - data[0], number - 1, &tail) + combinations(total, number, &tail)
}


Pythagoras tree

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

typedef struct{
	double x,y;
}point;

void pythagorasTree(point a,point b,int times){

	point c,d,e;

	c.x = b.x - (a.y -  b.y);
	c.y = b.y - (b.x - a.x);

	d.x = a.x - (a.y -  b.y);
	d.y = a.y - (b.x - a.x);

	e.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;
	e.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;

	if(times>0){
		setcolor(rand()%15 + 1);

		line(a.x,a.y,b.x,b.y);
		line(c.x,c.y,b.x,b.y);
		line(c.x,c.y,d.x,d.y);
		line(a.x,a.y,d.x,d.y);

		pythagorasTree(d,e,times-1);
		pythagorasTree(e,c,times-1);
	}
}

int main(){

	point a,b;
	double side;
	int iter;

	time_t t;

	printf("Enter initial side length : ");
	scanf("%lf",&side);

	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	a.x = 6*side/2 - side/2;
	a.y = 4*side;
	b.x = 6*side/2 + side/2;
	b.y = 4*side;

	initwindow(6*side,4*side,"Pythagoras Tree ?");

	srand((unsigned)time(&t));

	pythagorasTree(a,b,iter);

	getch();

	closegraph();

	return 0;

}

use svg::node::element::{Group, Polygon};

fn main() {
    let mut doc = svg::Document::new().set("stroke", "white");
    let mut base: Vec<[(f64, f64); 2]> = vec![[(-200.0, 0.0), (200.0, 0.0)]];
    for lvl in 0..12u8 {
        let rg = |step| lvl.wrapping_mul(step).wrapping_add(80 - step * 2);
        let mut group = Group::new().set("fill", format!("#{:02X}{:02X}18", rg(20), rg(30)));
        let mut next_base = Vec::new();
        for [a, b] in base {
            let v = (b.0 - a.0, b.1 - a.1);
            let c = (a.0 + v.1, a.1 - v.0);
            let d = (c.0 + v.0, c.1 + v.1);
            let e = (c.0 + 0.5 * (v.0 + v.1), c.1 + 0.5 * (v.1 - v.0));
            group = group.add(Polygon::new().set("points", vec![a, c, e, d, c, d, b]));
            next_base.extend([[c, e], [e, d]]);
        }
        base = next_base;
        doc = doc.add(group);
    }
    let (x0, y0) = (base.iter()).fold((0.0, 0.0), |(x0, y0), [(x, y), _]| (x.min(x0), y.min(y0)));
    let file = "pythagoras_tree.svg";
    match svg::save(file, &doc.set("viewBox", (x0, y0, -x0 * 2.0, -y0))) {
        Ok(_) => println!("{file} file written successfully!"),
        Err(e) => println!("failed to write {file}: {e}"),
    }
}


Pythagorean triples

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

typedef unsigned long long xint;
typedef unsigned long ulong;

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

int main()
{
    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;
    xint aa, bb, cc;

    for (a = 1; a <= max_p / 3; a++) {
        aa = (xint)a * a;
        printf("a = %lu\r", a);
        fflush(stdout);

        for (b = a + 1; b < max_p/2; b++) {
            bb = (xint)b * b;
            for (c = b + 1; c < max_p/2; c++) {
                cc = (xint)c * c;
                if (aa + bb < cc) break;
                if (a + b + c > max_p) break;

                if (aa + bb == cc) {
                    pytha++;
                    if (gcd(a, b) == 1) prim++;
                }
            }
        }
    }

    printf("Up to %lu, there are %lu triples, of which %lu are primitive\n",
        max_p, pytha, prim);

    return 0;
}

use std::thread;

fn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 {
    let mut primitive_count = 0;
    for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c],
                     [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c],
                     [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() {
        let l  = triangle[0] + triangle[1] + triangle[2];
        if l > d { continue; }
        primitive_count +=  1 + f1(triangle[0], triangle[1], triangle[2], d);
    }
    primitive_count
}

fn f2 (a : u64, b : u64, c : u64, d : u64) -> u64 {
    let mut triplet_count = 0;
    for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c],
                     [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c],
                     [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() {
        let l  = triangle[0] + triangle[1] + triangle[2];
        if l > d { continue; }
        triplet_count +=  (d/l) + f2(triangle[0], triangle[1], triangle[2], d);
    }
    triplet_count
}

fn main () {
    let new_th_1 = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || {
        let mut i = 100;
        while i <= 100_000_000_000 {
            println!(" Primitive triples below {} : {}", i, f1(3, 4, 5, i) + 1);
            i *= 10;
        }
    }).unwrap();

    let new_th_2 =thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || {
        let mut i = 100;
        while i <= 100_000_000_000 {
            println!(" Triples below {} : {}", i, f2(3, 4, 5, i) + i/12);
            i *= 10;
        }
    }).unwrap();

    new_th_1.join().unwrap();
    new_th_2.join().unwrap();
}


Range consolidation

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

typedef struct range_tag {
    double low;
    double high;
} range_t;

void normalize_range(range_t* range) {
    if (range->high < range->low) {
        double tmp = range->low;
        range->low = range->high;
        range->high = tmp;
    }
}

int range_compare(const void* p1, const void* p2) {
    const range_t* r1 = p1;
    const range_t* r2 = p2;
    if (r1->low < r2->low)
        return -1;
    if (r1->low > r2->low)
        return 1;
    if (r1->high < r2->high)
        return -1;
    if (r1->high > r2->high)
        return 1;
    return 0;
}

void normalize_ranges(range_t* ranges, size_t count) {
    for (size_t i = 0; i < count; ++i)
        normalize_range(&ranges[i]);
    qsort(ranges, count, sizeof(range_t), range_compare);
}

size_t consolidate_ranges(range_t* ranges, size_t count) {
    normalize_ranges(ranges, count);
    size_t out_index = 0;
    for (size_t i = 0; i < count; ) {
        size_t j = i;
        while (++j < count && ranges[j].low <= ranges[i].high) {
            if (ranges[i].high < ranges[j].high)
                ranges[i].high = ranges[j].high;
        }
        ranges[out_index++] = ranges[i];
        i = j;
    }
    return out_index;
}

void print_range(const range_t* range) {
    printf("[%g, %g]", range->low, range->high);
}

void print_ranges(const range_t* ranges, size_t count) {
    if (count == 0)
        return;
    print_range(&ranges[0]);
    for (size_t i = 1; i < count; ++i) {
        printf(", ");
        print_range(&ranges[i]);
    }
}

void test_consolidate_ranges(range_t* ranges, size_t count) {
    print_ranges(ranges, count);
    printf(" -> ");
    count = consolidate_ranges(ranges, count);
    print_ranges(ranges, count);
    printf("\n");
}

#define LENGTHOF(a) sizeof(a)/sizeof(a[0])

int main() {
    range_t test1[] = { {1.1, 2.2} };
    range_t test2[] = { {6.1, 7.2}, {7.2, 8.3} };
    range_t test3[] = { {4, 3}, {2, 1} };
    range_t test4[] = { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} };
    range_t test5[] = { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} };
    test_consolidate_ranges(test1, LENGTHOF(test1));
    test_consolidate_ranges(test2, LENGTHOF(test2));
    test_consolidate_ranges(test3, LENGTHOF(test3));
    test_consolidate_ranges(test4, LENGTHOF(test4));
    test_consolidate_ranges(test5, LENGTHOF(test5));
    return 0;
}

use std::fmt::{Display, Formatter};

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct ClosedRange<Idx> {
    start: Idx,
    end: Idx,
}

impl<Idx> ClosedRange<Idx> {
    pub fn start(&self) -> &Idx {
        &self.start
    }

    pub fn end(&self) -> &Idx {
        &self.end
    }
}

impl<Idx: PartialOrd> ClosedRange<Idx> {
    pub fn new(start: Idx, end: Idx) -> Self {
        if start <= end {
            Self { start, end }
        } else {
            Self {
                end: start,
                start: end,
            }
        }
    }
}

impl<Idx: PartialOrd> From<(Idx, Idx)> for ClosedRange<Idx> {
    fn from((start, end): (Idx, Idx)) -> Self {
        Self::new(start, end)
    }
}

impl<Idx: Display> Display for ClosedRange<Idx> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}, {}]", self.start, self.end)
    }
}

fn consolidate<Idx>(a: &ClosedRange<Idx>, b: &ClosedRange<Idx>) -> Option<ClosedRange<Idx>>
where
    Idx: PartialOrd + Clone,
{
    if a.start() <= b.start() {
        if b.end() <= a.end() {
            Some(a.clone())
        } else if a.end() < b.start() {
            None
        } else {
            Some(ClosedRange::new(a.start().clone(), b.end().clone()))
        }
    } else {
        consolidate(b, a)
    }
}

fn consolidate_all<Idx>(mut ranges: Vec<ClosedRange<Idx>>) -> Vec<ClosedRange<Idx>>
where
    Idx: PartialOrd + Clone,
{

    ranges.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let mut ranges = ranges.into_iter();
    let mut result = Vec::new();

    if let Some(current) = ranges.next() {
        let leftover = ranges.fold(current, |mut acc, next| {
            match consolidate(&acc, &next) {
                Some(merger) => {
                    acc = merger;
                }

                None => {
                    result.push(acc);
                    acc = next;
                }
            }

            acc
        });

        result.push(leftover);
    }

    result
}

#[cfg(test)]
mod tests {
    use super::{consolidate_all, ClosedRange};
    use std::fmt::{Display, Formatter};

    struct IteratorToDisplay<F>(F);

    impl<F, I> Display for IteratorToDisplay<F>
    where
        F: Fn() -> I,
        I: Iterator,
        I::Item: Display,
    {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            let mut items = self.0();

            if let Some(item) = items.next() {
                write!(f, "{}", item)?;
                for item in items {
                    write!(f, ", {}", item)?;
                }
            }

            Ok(())
        }
    }

    macro_rules! parameterized {
        ($($name:ident: $value:expr,)*) => {
            $(
                #[test]
                fn $name() {
                    let (input, expected) = $value;
                    let expected: Vec<_> = expected.into_iter().map(ClosedRange::from).collect();
                    let output = consolidate_all(input.into_iter().map(ClosedRange::from).collect());
                    println!("{}: {}", stringify!($name), IteratorToDisplay(|| output.iter()));
                    assert_eq!(expected, output);
                }
            )*
        }
    }

    parameterized! {
        single: (vec![(1.1, 2.2)], vec![(1.1, 2.2)]),
        touching: (vec![(6.1, 7.2), (7.2, 8.3)], vec![(6.1, 8.3)]),
        disjoint: (vec![(4, 3), (2, 1)], vec![(1, 2), (3, 4)]),
        overlap: (vec![(4.0, 3.0), (2.0, 1.0), (-1.0, -2.0), (3.9, 10.0)], vec![(-2.0, -1.0), (1.0, 2.0), (3.0, 10.0)]),
        integer: (vec![(1, 3), (-6, -1), (-4, -5), (8, 2), (-6, -6)], vec![(-6, -1), (1, 8)]),
    }
}

fn main() {

    consolidate_all(Vec::<ClosedRange<usize>>::new());

    println!("Run: cargo test -- --nocapture");
}


Ray-casting algorithm

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

typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;

#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}
#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }
BIN_V(sub, a.x - b.x, a.y - b.y);
BIN_V(add, a.x + b.x, a.y + b.y);
BIN_S(dot, a.x * b.x + a.y * b.y);
BIN_S(cross, a.x * b.y - a.y * b.x);

vec vmadd(vec a, double s, vec b)
{
	vec c;
	c.x = a.x + s * b.x;
	c.y = a.y + s * b.y;
	return c;
}

int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)
{
	vec dx = vsub(x1, x0), dy = vsub(y1, y0);
	double d = vcross(dy, dx), a;
	if (!d) return 0;

	a = (vcross(x0, dx) - vcross(y0, dx)) / d;
	if (sect)
		*sect = vmadd(y0, a, dy);

	if (a < -tol || a > 1 + tol) return -1;
	if (a < tol || a > 1 - tol) return 0;

	a = (vcross(x0, dy) - vcross(y0, dy)) / d;
	if (a < 0 || a > 1) return -1;

	return 1;
}

double dist(vec x, vec y0, vec y1, double tol)
{
	vec dy = vsub(y1, y0);
	vec x1, s;
	int r;

	x1.x = x.x + dy.y; x1.y = x.y - dy.x;
	r = intersect(x, x1, y0, y1, tol, &s);
	if (r == -1) return HUGE_VAL;
	s = vsub(s, x);
	return sqrt(vdot(s, s));
}

#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)

int inside(vec v, polygon p, double tol)
{

	int i, k, crosses, intersectResult;
	vec *pv;
	double min_x, max_x, min_y, max_y;

	for (i = 0; i < p->n; i++) {
		k = (i + 1) % p->n;
		min_x = dist(v, p->v[i], p->v[k], tol);
		if (min_x < tol) return 0;
	}

	min_x = max_x = p->v[0].x;
	min_y = max_y = p->v[1].y;

	for_v(i, pv, p) {
		if (pv->x > max_x) max_x = pv->x;
		if (pv->x < min_x) min_x = pv->x;
		if (pv->y > max_y) max_y = pv->y;
		if (pv->y < min_y) min_y = pv->y;
	}
	if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)
		return -1;

	max_x -= min_x; max_x *= 2;
	max_y -= min_y; max_y *= 2;
	max_x += max_y;

	vec e;
	while (1) {
		crosses = 0;

		e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;
		e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;

		for (i = 0; i < p->n; i++) {
			k = (i + 1) % p->n;
			intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);

			if (!intersectResult) break;

			if (intersectResult == 1) crosses++;
		}
		if (i == p->n) break;
	}
	return (crosses & 1) ? 1 : -1;
}

int main()
{
	vec vsq[] = {	{0,0}, {10,0}, {10,10}, {0,10},
			{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};

	polygon_t sq = { 4, vsq },
		sq_hole = { 8, vsq };

	vec c = { 10, 5 };
	vec d = { 5, 5 };

	printf("%d\n", inside(c, &sq, 1e-10));
	printf("%d\n", inside(c, &sq_hole, 1e-10));

	printf("%d\n", inside(d, &sq, 1e-10));
	printf("%d\n", inside(d, &sq_hole, 1e-10));

	return 0;
}

use std::f64;

const _EPS: f64 = 0.00001;
const _MIN: f64 = f64::MIN_POSITIVE;
const _MAX: f64 = f64::MAX;

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

#[derive(Clone)]
struct Edge {
    pt1: Point,
    pt2: Point,
}

impl Edge {
    fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge {
        Edge {
            pt1: Point { x: pt1.0, y: pt1.1 },
            pt2: Point { x: pt2.0, y: pt2.1 },
        }
    }
}

struct Polygon {
    edges: Vec<Edge>,
}

fn pt_in_polygon(pt: &Point, poly: &Polygon) -> bool {
    let count = poly.edges
        .iter()
        .filter(|edge| ray_intersect_seg(pt, edge))
        .count();

    count % 2 == 1
}

fn ray_intersect_seg(p: &Point, edge: &Edge) -> bool {
    let mut pt = p.clone();
    let (mut a, mut b): (&Point, &Point) = (&edge.pt1, &edge.pt2);
    if a.y > b.y {
        std::mem::swap(&mut a, &mut b);
    }
    if pt.y == a.y || pt.y == b.y {
        pt.y += _EPS;
    }

    if (pt.y > b.y || pt.y < a.y) || pt.x > a.x.max(b.x) {
        false
    } else if pt.x < a.x.min(b.x) {
        true
    } else {
        let m_red = if (a.x - b.x).abs() > _MIN {
            (b.y - a.y) / (b.x - a.x)
        } else {
            _MAX
        };
        let m_blue = if (a.x - pt.x).abs() > _MIN {
            (pt.y - a.y) / (pt.x - a.x)
        } else {
            _MAX
        };
        m_blue >= m_red
    }
}

fn main() {
    let p = |x, y| Point { x, y };
    let testpoints = [p(5.0, 5.0), p(5.0, 8.0), p(-10.0, 5.0), p(0.0, 5.0), p(10.0, 5.0), p(8.0, 5.0), p(10.0, 10.0)];
    let poly_square = Polygon {
        edges: vec![
            Edge::new((0.0, 0.0), (10.0, 0.0)),
            Edge::new((10.0, 0.0), (10.0, 10.0)),
            Edge::new((10.0, 10.0), (0.0, 10.0)),
            Edge::new((0.0, 10.0), (0.0, 0.0)),
        ],
    };
    let poly_square_hole = Polygon {
        edges: vec![
            Edge::new((0.0, 0.0), (10.0, 0.0)),
            Edge::new((10.0, 0.0), (10.0, 10.0)),
            Edge::new((10.0, 10.0), (0.0, 10.0)),
            Edge::new((0.0, 10.0), (0.0, 0.0)),
            Edge::new((2.5, 2.5), (7.5, 2.5)),
            Edge::new((7.5, 2.5), (7.5, 7.5)),
            Edge::new((7.5, 7.5), (2.5, 7.5)),
            Edge::new((2.5, 7.5), (2.5, 2.5)),
        ],
    };
    let poly_strange = Polygon {
        edges: vec![
            Edge::new((0.0, 0.0), (2.5, 2.5)),
            Edge::new((2.5, 2.5), (0.0, 10.0)),
            Edge::new((0.0, 10.0), (2.5, 7.5)),
            Edge::new((2.5, 7.5), (7.5, 7.5)),
            Edge::new((7.5, 7.5), (10.0, 10.0)),
            Edge::new((10.0, 10.0), (10.0, 0.0)),
            Edge::new((10.0, 0.0), (2.5, 2.5)),
        ],
    };
    let poly_hexagon = Polygon {
        edges: vec![
            Edge::new((3.0, 0.0), (7.0, 0.0)),
            Edge::new((7.0, 0.0), (10.0, 5.0)),
            Edge::new((10.0, 5.0), (7.0, 10.0)),
            Edge::new((7.0, 10.0), (3.0, 10.0)),
            Edge::new((3.0, 10.0), (0.0, 5.0)),
            Edge::new((0.0, 5.0), (3.0, 0.0)),
        ],
    };
    print!("\nSquare :");
    for pt in &testpoints {
        print!(" {:?}", pt_in_polygon(pt, &poly_square));
    }
    print!("\nSquare with hole:");
    for pt in &testpoints {
        print!(" {:?}", pt_in_polygon(pt, &poly_square_hole));
    }
    print!("\nStrange polygon :");
    for pt in &testpoints {
        print!(" {:?}", pt_in_polygon(pt, &poly_strange));
    }
    print!("\nHexagon :");
    for pt in &testpoints {
        print!(" {:?}", pt_in_polygon(pt, &poly_hexagon));
    }
    println!();
}


Read a configuration file

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

#define rosetta_uint8_t unsigned char

#define FALSE 0
#define TRUE 1

#define CONFIGS_TO_READ 5
#define INI_ARRAY_DELIMITER ','

struct configs {
	char *fullname;
	char *favouritefruit;
	rosetta_uint8_t needspeeling;
	rosetta_uint8_t seedsremoved;
	char **otherfamily;
	size_t otherfamily_len;
	size_t _configs_left_;
};

static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {

	*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);
	char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;
	if (!dest) { return NULL; }
	memcpy(dest + *arrlen, src, buffsize);
	char * iter = (char *) (dest + *arrlen);
	for (size_t idx = 0; idx < *arrlen; idx++) {
		dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);
		ini_string_parse(dest[idx], ini_format);
	}
	return dest;

}

static int configs_member_handler (IniDispatch *this, void *v_confs) {

	struct configs *confs = (struct configs *) v_confs;

	if (this->type != INI_KEY) {

		return 0;

	}

	if (ini_string_match_si("FULLNAME", this->data, this->format)) {

		if (confs->fullname) { return 0; }
		this->v_len = ini_string_parse(this->value, this->format);
		confs->fullname = strndup(this->value, this->v_len);
		confs->_configs_left_--;

	} else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) {

		if (confs->favouritefruit) { return 0; }
		this->v_len = ini_string_parse(this->value, this->format);
		confs->favouritefruit = strndup(this->value, this->v_len);
		confs->_configs_left_--;

	} else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) {

		if (~confs->needspeeling & 0x80) { return 0; }
		confs->needspeeling = ini_get_bool(this->value, TRUE);
		confs->_configs_left_--;

	} else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) {

		if (~confs->seedsremoved & 0x80) { return 0; }
		confs->seedsremoved = ini_get_bool(this->value, TRUE);
		confs->_configs_left_--;

	} else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) {

		if (confs->otherfamily) { return 0; }
		this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format);
		confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);
		confs->_configs_left_--;

	}

	return !confs->_configs_left_;

}

static int populate_configs (struct configs * confs) {

	IniFormat config_format = {
		.delimiter_symbol = INI_ANY_SPACE,
		.case_sensitive = FALSE,
		.semicolon_marker = INI_IGNORE,
		.hash_marker = INI_IGNORE,
		.multiline_nodes = INI_NO_MULTILINE,
		.section_paths = INI_NO_SECTIONS,
		.no_single_quotes = FALSE,
		.no_double_quotes = FALSE,
		.no_spaces_in_names = TRUE,
		.implicit_is_not_empty = TRUE,
		.do_not_collapse_values = FALSE,
		.preserve_empty_quotes = FALSE,
		.disabled_after_space = TRUE,
		.disabled_can_be_implicit = FALSE
	};

	*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };

	if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {

		fprintf(stderr, "Sorry, something went wrong :-(\n");
		return 1;

	}

	confs->needspeeling &= 0x7F;
	confs->seedsremoved &= 0x7F;

	return 0;

}

int main () {

	struct configs confs;

	ini_global_set_implicit_value("YES", 0);

	if (populate_configs(&confs)) {

		return 1;

	}

	printf(

		"Full name: %s\n"
		"Favorite fruit: %s\n"
		"Need spelling: %s\n"
		"Seeds removed: %s\n",

		confs.fullname,
		confs.favouritefruit,
		confs.needspeeling ? "True" : "False",
		confs.seedsremoved ? "True" : "False"

	);

	for (size_t idx = 0; idx < confs.otherfamily_len; idx++) {

		printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]);

	}

	#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }

	FREE_NON_NULL(confs.fullname);
	FREE_NON_NULL(confs.favouritefruit);
	FREE_NON_NULL(confs.otherfamily);

	return 0;

}

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::iter::FromIterator;
use std::path::Path;

fn main() {
    let path = String::from("file.conf");
    let cfg = config_from_file(path);
    println!("{:?}", cfg);
}

fn config_from_file(path: String) -> Config {
    let path = Path::new(&path);
    let file = File::open(path).expect("File not found or cannot be opened");
    let content = BufReader::new(&file);
    let mut cfg = Config::new();

    for line in content.lines() {
        let line = line.expect("Could not read the line");

        let line = line.trim();

        if line.starts_with("#") || line.starts_with(";") || line.is_empty() {
            continue;
        }

        let tokens = Vec::from_iter(line.split_whitespace());
        let name = tokens.first().unwrap();
        let tokens = tokens.get(1..).unwrap();

        let tokens = tokens.iter().filter(|t| !t.starts_with("="));

        let tokens = tokens.take_while(|t| !t.starts_with("#") && !t.starts_with(";"));

        let mut parameters = String::new();
        tokens.for_each(|t| { parameters.push_str(t); parameters.push(' '); });

        let parameters = parameters.split(',').map(|s| s.trim());

        let parameters: Vec<String> = parameters.map(|s| s.to_string()).collect();

        match name.to_lowercase().as_str() {
            "fullname" => cfg.full_name = parameters.get(0).cloned(),
            "favouritefruit" => cfg.favourite_fruit = parameters.get(0).cloned(),
            "needspeeling" => cfg.needs_peeling = true,
            "seedsremoved" => cfg.seeds_removed = true,
            "otherfamily" => cfg.other_family = Some(parameters),
            _ => (),
        }
    }

    cfg
}

#[derive(Clone, Debug)]
struct Config {
    full_name: Option<String>,
    favourite_fruit: Option<String>,
    needs_peeling: bool,
    seeds_removed: bool,
    other_family: Option<Vec<String>>,
}

impl Config {
    fn new() -> Config {
        Config {
            full_name: None,
            favourite_fruit: None,
            needs_peeling: false,
            seeds_removed: false,
            other_family: None,
        }
    }
}


Read a specific line from a file

#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>

int read_file_line(const char *path, int line_no)
{
	struct stat s;
	char *buf;
	off_t start = -1, end = -1;
	size_t i;
	int ln, fd, ret = 1;

	if (line_no == 1) start = 0;
	else if (line_no < 1){
		warn("line_no too small");
		return 0;
	}

	line_no--;

	fd = open(path, O_RDONLY);
	fstat(fd, &s);

	buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

	madvise(buf, s.st_size, MADV_SEQUENTIAL);

	for (i = ln = 0; i < s.st_size && ln <= line_no; i++) {
		if (buf[i] != '\n') continue;

		if (++ln == line_no) start = i + 1;
		else if (ln == line_no + 1) end = i + 1;
	}

	if (start >= s.st_size || start < 0) {
		warn("file does not have line %d", line_no + 1);
		ret = 0;
	} else {

	}

	munmap(buf, s.st_size);
	close(fd);

	return ret;
}

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Error;
use std::path::Path;

fn main() {
    let path = Path::new("file.txt");
    let line_num = 7usize;
    let line = get_line_at(&path, line_num - 1);
    println!("{}", line.unwrap());
}

fn get_line_at(path: &Path, line_num: usize) -> Result<String, Error> {
    let file = File::open(path).expect("File not found or cannot be opened");
    let content = BufReader::new(&file);
    let mut lines = content.lines();
    lines.nth(line_num).expect("No line found at that position")
}