Flatten a list

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

typedef struct list_t list_t, *list;
struct list_t{
	int is_list, ival;
	list *lst;
};

list new_list()
{
	list x = malloc(sizeof(list_t));
	x->ival = 0;
	x->is_list = 1;
	x->lst = 0;
	return x;
}

void append(list parent, list child)
{
	parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1));
	parent->lst[parent->ival++] = child;
}

list from_string(char *s, char **e, list parent)
{
	list ret = 0;
	if (!parent) parent = new_list();

	while (*s != '\0') {
		if (*s == ']') {
			if (e) *e = s + 1;
			return parent;
		}
		if (*s == '[') {
			ret = new_list();
			ret->is_list = 1;
			ret->ival = 0;
			append(parent, ret);
			from_string(s + 1, &s, ret);
			continue;
		}
		if (*s >= '0' && *s <= '9') {
			ret = new_list();
			ret->is_list = 0;
			ret->ival = strtol(s, &s, 10);
			append(parent, ret);
			continue;
		}
		s++;
	}

	if (e) *e = s;
	return parent;
}

void show_list(list l)
{
	int i;
	if (!l) return;
	if (!l->is_list) {
		printf("%d", l->ival);
		return;
	}

	printf("[");
	for (i = 0; i < l->ival; i++) {
		show_list(l->lst[i]);
		if (i < l->ival - 1) printf(", ");
	}
	printf("]");
}

list flatten(list from, list to)
{
	int i;
	list t;

	if (!to) to = new_list();
	if (!from->is_list) {
		t = new_list();
		*t = *from;
		append(to, t);
	} else
		for (i = 0; i < from->ival; i++)
			flatten(from->lst[i], to);
	return to;
}

void delete_list(list l)
{
	int i;
	if (!l) return;
	if (l->is_list && l->ival) {
		for (i = 0; i < l->ival; i++)
			delete_list(l->lst[i]);
		free(l->lst);
	}

	free(l);
}

int main()
{
	list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0);

	printf("Nested: ");
	show_list(l);
	printf("\n");

	list flat = flatten(l, 0);
	printf("Flattened: ");
	show_list(flat);

	return 0;
}

use std::{vec, mem, iter};

enum List<T> {
    Node(Vec<List<T>>),
    Leaf(T),
}

impl<T> IntoIterator for List<T> {
    type Item = List<T>;
    type IntoIter = ListIter<T>;
    fn into_iter(self) -> Self::IntoIter {
        match self {
            List::Node(vec) => ListIter::NodeIter(vec.into_iter()),
            leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)),
        }
    }
}

enum ListIter<T> {
    NodeIter(vec::IntoIter<List<T>>),
    LeafIter(iter::Once<List<T>>),
}

impl<T> ListIter<T> {
    fn flatten(self) -> Flatten<T> {
        Flatten {
            stack: Vec::new(),
            curr: self,
        }
    }
}

impl<T> Iterator for ListIter<T> {
    type Item = List<T>;
    fn next(&mut self) -> Option<Self::Item> {
        match *self {
            ListIter::NodeIter(ref mut v_iter) => v_iter.next(),
            ListIter::LeafIter(ref mut o_iter) => o_iter.next(),
        }
    }
}

struct Flatten<T> {
    stack: Vec<ListIter<T>>,
    curr: ListIter<T>,
}

impl<T> Iterator for Flatten<T> {
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.curr.next() {
                Some(list) => {
                    match list {
                        node @ List::Node(_) => {
                            self.stack.push(node.into_iter());
                            let len = self.stack.len();
                            mem::swap(&mut self.stack[len - 1], &mut self.curr);
                        }
                        List::Leaf(item) => return Some(item),
                    }
                }
                None => {
                    if let Some(next) = self.stack.pop() {
                        self.curr = next;
                    } else {
                        return None;
                    }
                }
            }
        }
    }
}

use List::*;
fn main() {
    let list = Node(vec![Node(vec![Leaf(1)]),
                         Leaf(2),
                         Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]),
                         Node(vec![Node(vec![Node(vec![])])]),
                         Node(vec![Node(vec![Node(vec![Leaf(6)])])]),
                         Leaf(7),
                         Leaf(8),
                         Node(vec![])]);

    for elem in list.into_iter().flatten() {
        print!("{} ", elem);
    }
    println!();

}


Floyd's triangle

#include <stdio.h>

void t(int n)
{
	int i, j, c, len;

	i = n * (n - 1) / 2;
	for (len = c = 1; c < i; c *= 10, len++);
	c -= i;

#define SPEED_MATTERS 0
#if SPEED_MATTERS
	char tmp[32], s[4096], *p;

	sprintf(tmp, "%*d", len, 0);

	inline void inc_numstr(void) {
		int k = len;

	redo:	if (!k--) return;

		if (tmp[k] == '9') {
			tmp[k] = '0';
			goto redo;
		}

		if (++tmp[k] == '!')
			tmp[k] = '1';
	}

	for (p = s, i = 1; i <= n; i++) {
		for (j = 1; j <= i; j++) {
			inc_numstr();
			__builtin_memcpy(p, tmp + 1 - (j >= c), len - (j < c));
			p += len - (j < c);

			*(p++) = (i - j)? ' ' : '\n';

			if (p - s + len >= 4096) {
				fwrite(s, 1, p - s, stdout);
				p = s;
			}
		}
	}

	fwrite(s, 1, p - s, stdout);
#else
	int num;
	for (num = i = 1; i <= n; i++)
		for (j = 1; j <= i; j++)
			printf("%*d%c",	len - (j < c), num++, i - j ? ' ':'\n');
#endif
}

int main(void)
{
	t(5), t(14);

	return 0;
}

fn main() {
    floyds_triangle(5);
    floyds_triangle(14);
}

fn floyds_triangle(n: u32) {
    let mut triangle: Vec<Vec<String>> = Vec::new();
    let mut current = 0;
    for i in 1..=n {
        let mut v = Vec::new();
        for _ in 0..i {
            current += 1;
            v.push(current);
        }
        let row = v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
        triangle.push(row);
    }

    for row in &triangle {
        let arranged_row: Vec<_> = row
            .iter()
            .enumerate()
            .map(|(i, number)| {
                let space_len = triangle.last().unwrap()[i].len() - number.len() + 1;
                let spaces = " ".repeat(space_len);
                let mut padded_number = spaces;
                padded_number.push_str(&number);
                padded_number
            })
            .collect();
        println!("{}", arranged_row.join(""))
    }
}


Floyd-Warshall algorithm

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

typedef struct{
    int sourceVertex, destVertex;
    int edgeWeight;
}edge;

typedef struct{
    int vertices, edges;
    edge* edgeMatrix;
}graph;

graph loadGraph(char* fileName){
    FILE* fp = fopen(fileName,"r");

    graph G;
    int i;

    fscanf(fp,"%d%d",&G.vertices,&G.edges);

    G.edgeMatrix = (edge*)malloc(G.edges*sizeof(edge));

    for(i=0;i<G.edges;i++)
        fscanf(fp,"%d%d%d",&G.edgeMatrix[i].sourceVertex,&G.edgeMatrix[i].destVertex,&G.edgeMatrix[i].edgeWeight);

    fclose(fp);

    return G;
}

void floydWarshall(graph g){
    int processWeights[g.vertices][g.vertices], processedVertices[g.vertices][g.vertices];
    int i,j,k;

    for(i=0;i<g.vertices;i++)
        for(j=0;j<g.vertices;j++){
            processWeights[i][j] = SHRT_MAX;
            processedVertices[i][j] = (i!=j)?j+1:0;
        }

    for(i=0;i<g.edges;i++)
        processWeights[g.edgeMatrix[i].sourceVertex-1][g.edgeMatrix[i].destVertex-1] = g.edgeMatrix[i].edgeWeight;

    for(i=0;i<g.vertices;i++)
        for(j=0;j<g.vertices;j++)
            for(k=0;k<g.vertices;k++){
                if(processWeights[j][i] + processWeights[i][k] < processWeights[j][k]){
                    processWeights[j][k] = processWeights[j][i] + processWeights[i][k];
                    processedVertices[j][k] = processedVertices[j][i];
                }
            }

    printf("pair    dist   path");
    for(i=0;i<g.vertices;i++)
        for(j=0;j<g.vertices;j++){
            if(i!=j){
                printf("\n%d -> %d %3d %5d",i+1,j+1,processWeights[i][j],i+1);
                k = i+1;
                do{
                    k = processedVertices[k-1][j];
                    printf("->%d",k);
                }while(k!=j+1);
            }
        }
}

int main(int argC,char* argV[]){
    if(argC!=2)
        printf("Usage : %s <file containing graph data>");
    else
        floydWarshall(loadGraph(argV[1]));
    return 0;
}

pub type Edge = (usize, usize);

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Graph<T> {
    size: usize,
    edges: Vec<Option<T>>,
}

impl<T> Graph<T> {
    pub fn new(size: usize) -> Self {
        Self {
            size,
            edges: std::iter::repeat_with(|| None).take(size * size).collect(),
        }
    }

    pub fn new_with(size: usize, f: impl FnMut(Edge) -> Option<T>) -> Self {
        let edges = (0..size)
            .flat_map(|i| (0..size).map(move |j| (i, j)))
            .map(f)
            .collect();

        Self { size, edges }
    }

    pub fn with_diagonal(mut self, mut f: impl FnMut(usize) -> Option<T>) -> Self {
        self.edges
            .iter_mut()
            .step_by(self.size + 1)
            .enumerate()
            .for_each(move |(vertex, edge)| *edge = f(vertex));

        self
    }

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

    pub fn edge(&self, edge: Edge) -> &Option<T> {
        let index = self.edge_index(edge);
        &self.edges[index]
    }

    pub fn edge_mut(&mut self, edge: Edge) -> &mut Option<T> {
        let index = self.edge_index(edge);
        &mut self.edges[index]
    }

    fn edge_index(&self, (row, col): Edge) -> usize {
        assert!(row < self.size && col < self.size);
        row * self.size() + col
    }
}

impl<T> std::ops::Index<Edge> for Graph<T> {
    type Output = Option<T>;

    fn index(&self, index: Edge) -> &Self::Output {
        self.edge(index)
    }
}

impl<T> std::ops::IndexMut<Edge> for Graph<T> {
    fn index_mut(&mut self, index: Edge) -> &mut Self::Output {
        self.edge_mut(index)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Paths(Graph<usize>);

impl Paths {
    pub fn new<T>(graph: &Graph<T>) -> Self {
        Self(Graph::new_with(graph.size(), |(i, j)| {
            graph[(i, j)].as_ref().map(|_| j)
        }))
    }

    pub fn vertices(&self, from: usize, to: usize) -> Path<'_> {
        assert!(from < self.0.size() && to < self.0.size());

        Path {
            graph: &self.0,
            from: Some(from),
            to,
        }
    }

    fn update(&mut self, from: usize, to: usize, via: usize) {
        self.0[(from, to)] = self.0[(from, via)];
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Path<'a> {
    graph: &'a Graph<usize>,
    from: Option<usize>,
    to: usize,
}

impl<'a> Iterator for Path<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        self.from.map(|from| {
            let result = from;

            self.from = if result != self.to {
                self.graph[(result, self.to)]
            } else {
                None
            };

            result
        })
    }
}

pub fn floyd_warshall<W>(mut result: Graph<W>) -> (Graph<W>, Option<Paths>)
where
    W: Copy + std::ops::Add<W, Output = W> + std::cmp::Ord + Default,
{
    let mut without_negative_cycles = true;
    let mut paths = Paths::new(&result);
    let n = result.size();

    for k in 0..n {
        for i in 0..n {
            for j in 0..n {

                if i == j && result[(i, j)].filter(|&it| it < W::default()).is_some() {
                    without_negative_cycles = false;
                    continue;
                }

                if let (Some(ik_weight), Some(kj_weight)) = (result[(i, k)], result[(k, j)]) {
                    let ij_edge = result.edge_mut((i, j));
                    let ij_weight = ik_weight + kj_weight;

                    if ij_edge.is_none() {
                        *ij_edge = Some(ij_weight);
                        paths.update(i, j, k);
                    } else {
                        ij_edge
                            .as_mut()
                            .filter(|it| ij_weight < **it)
                            .map_or((), |it| {
                                *it = ij_weight;
                                paths.update(i, j, k);
                            });
                    }
                }
            }
        }
    }

    (result, Some(paths).filter(|_| without_negative_cycles))
}

fn format_path<T: ToString>(path: impl Iterator<Item = T>) -> String {
    path.fold(String::new(), |mut acc, x| {
        if !acc.is_empty() {
            acc.push_str(" -> ");
        }

        acc.push_str(&x.to_string());
        acc
    })
}

fn print_results<W, V>(weights: &Graph<W>, paths: Option<&Paths>, vertex: impl Fn(usize) -> V)
where
    W: std::fmt::Display + Default + Eq,
    V: std::fmt::Display,
{
    let n = weights.size();

    for from in 0..n {
        for to in 0..n {
            if let Some(weight) = &weights[(from, to)] {

                if from == to && *weight == W::default() {
                    continue;
                }

                println!(
                    "{} -> {}: {} \t{}",
                    vertex(from),
                    vertex(to),
                    weight,
                    format_path(paths.iter().flat_map(|p| p.vertices(from, to)).map(&vertex))
                );
            }
        }
    }
}

fn main() {
    let graph = {
        let mut g = Graph::new(4).with_diagonal(|_| Some(0));
        g[(0, 2)] = Some(-2);
        g[(1, 0)] = Some(4);
        g[(1, 2)] = Some(3);
        g[(2, 3)] = Some(2);
        g[(3, 1)] = Some(-1);
        g
    };

    let (weights, paths) = floyd_warshall(graph);

    print_results(&weights, paths.as_ref(), |index| index + 1);
}


Forest fire

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

#include <SDL.h>

#define PROB_TREE 0.55
#define PROB_F 0.00001
#define PROB_P 0.001

#define TIMERFREQ 100

#ifndef WIDTH
#  define WIDTH 640
#endif
#ifndef HEIGHT
#  define HEIGHT 480
#endif
#ifndef BPP
#  define BPP 32
#endif

#if BPP != 32
  #warning This program could not work with BPP different from 32
#endif

uint8_t *field[2], swapu;
double prob_f = PROB_F, prob_p = PROB_P, prob_tree = PROB_TREE;

enum cell_state {
  VOID, TREE, BURNING
};

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

void init_field(void)
{
  int i, j;
  swapu = 0;
  for(i = 0; i < WIDTH; i++)
  {
    for(j = 0; j < HEIGHT; j++)
    {
      *(field[0] + j*WIDTH + i) = prand() > prob_tree ? VOID : TREE;
    }
  }
}

bool burning_neighbor(int, int);
pthread_mutex_t synclock = PTHREAD_MUTEX_INITIALIZER;
static uint32_t simulate(uint32_t iv, void *p)
{
  int i, j;

  pthread_mutex_lock(&synclock);

  for(i = 0; i < WIDTH; i++) {
    for(j = 0; j < HEIGHT; j++) {
      enum cell_state s = *(field[swapu] + j*WIDTH + i);
      switch(s)
      {
      case BURNING:
	*(field[swapu^1] + j*WIDTH + i) = VOID;
	break;
      case VOID:
	*(field[swapu^1] + j*WIDTH + i) = prand() > prob_p ? VOID : TREE;
	break;
      case TREE:
	if (burning_neighbor(i, j))
	  *(field[swapu^1] + j*WIDTH + i) = BURNING;
	else
	  *(field[swapu^1] + j*WIDTH + i) = prand() > prob_f ? TREE : BURNING;
	break;
      default:
	fprintf(stderr, "corrupted field\n");
	break;
      }
    }
  }
  swapu ^= 1;
  pthread_mutex_unlock(&synclock);
  return iv;
}

#define NB(I,J) (((I)<WIDTH)&&((I)>=0)&&((J)<HEIGHT)&&((J)>=0) \
		 ? (*(field[swapu] + (J)*WIDTH + (I)) == BURNING) : false)
bool burning_neighbor(int i, int j)
{
  return NB(i-1,j-1) || NB(i-1, j) || NB(i-1, j+1) ||
    NB(i, j-1) || NB(i, j+1) ||
    NB(i+1, j-1) || NB(i+1, j) || NB(i+1, j+1);
}

void show(SDL_Surface *s)
{
  int i, j;
  uint8_t *pixels = (uint8_t *)s->pixels;
  uint32_t color;
  SDL_PixelFormat *f = s->format;

  pthread_mutex_lock(&synclock);
  for(i = 0; i < WIDTH; i++) {
    for(j = 0; j < HEIGHT; j++) {
      switch(*(field[swapu] + j*WIDTH + i)) {
      case VOID:
	color = SDL_MapRGBA(f, 0,0,0,255);
	break;
      case TREE:
	color = SDL_MapRGBA(f, 0,255,0,255);
	break;
      case BURNING:
	color = SDL_MapRGBA(f, 255,0,0,255);
	break;
      }
      *(uint32_t*)(pixels + j*s->pitch + i*(BPP>>3)) = color;
    }
  }
  pthread_mutex_unlock(&synclock);
}

int main(int argc, char **argv)
{
  SDL_Surface *scr = NULL;
  SDL_Event event[1];
  bool quit = false, running = false;
  SDL_TimerID tid;

  srand(time(NULL));

  double *p;
  for(argv++, argc--; argc > 0; argc--, argv++)
  {
    if ( strcmp(*argv, "prob_f") == 0 && argc > 1 )
    {
      p = &prob_f;
    } else if ( strcmp(*argv, "prob_p") == 0 && argc > 1 ) {
      p = &prob_p;
    } else if ( strcmp(*argv, "prob_tree") == 0 && argc > 1 ) {
      p = &prob_tree;
    } else  continue;

    argv++; argc--;
    char *s = NULL;
    double t = strtod(*argv, &s);
    if (s != *argv) *p = t;
  }

  printf("prob_f %lf\nprob_p %lf\nratio %lf\nprob_tree %lf\n",
	 prob_f, prob_p, prob_p/prob_f,
	 prob_tree);

  if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0 ) return EXIT_FAILURE;
  atexit(SDL_Quit);

  field[0] = malloc(WIDTH*HEIGHT);
  if (field[0] == NULL) exit(EXIT_FAILURE);
  field[1] = malloc(WIDTH*HEIGHT);
  if (field[1] == NULL) { free(field[0]); exit(EXIT_FAILURE); }

  scr = SDL_SetVideoMode(WIDTH, HEIGHT, BPP, SDL_HWSURFACE|SDL_DOUBLEBUF);
  if (scr == NULL) {
    fprintf(stderr, "SDL_SetVideoMode: %s\n", SDL_GetError());
    free(field[0]); free(field[1]);
    exit(EXIT_FAILURE);
  }

  init_field();

  tid = SDL_AddTimer(TIMERFREQ, simulate, NULL);
  running = true;

  event->type = SDL_VIDEOEXPOSE;
  SDL_PushEvent(event);

  while(SDL_WaitEvent(event) && !quit)
  {
    switch(event->type)
    {
    case SDL_VIDEOEXPOSE:
      while(SDL_LockSurface(scr) != 0) SDL_Delay(1);
      show(scr);
      SDL_UnlockSurface(scr);
      SDL_Flip(scr);
      event->type = SDL_VIDEOEXPOSE;
      SDL_PushEvent(event);
      break;
    case SDL_KEYDOWN:
      switch(event->key.keysym.sym)
      {
      case SDLK_q:
	quit = true;
	break;
      case SDLK_p:
	if (running)
	{
	  running = false;
	  pthread_mutex_lock(&synclock);
	  SDL_RemoveTimer(tid);
	  pthread_mutex_unlock(&synclock);
	} else {
	  running = true;
	  tid = SDL_AddTimer(TIMERFREQ, simulate, NULL);

	}
	break;
      }
    case SDL_QUIT:
      quit = true;
      break;
    }
  }

  if (running) {
    pthread_mutex_lock(&synclock);
    SDL_RemoveTimer(tid);
    pthread_mutex_unlock(&synclock);
  }
  free(field[0]); free(field[1]);
  exit(EXIT_SUCCESS);
}

extern crate rand;
extern crate ansi_term;

#[derive(Copy, Clone, PartialEq)]
enum Tile {
    Empty,
    Tree,
    Burning,
    Heating,
}

impl fmt::Display for Tile {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let output = match *self {
            Empty => Black.paint(" "),
            Tree => Green.bold().paint("T"),
            Burning => Red.bold().paint("B"),
            Heating => Yellow.bold().paint("T"),
        };
        write!(f, "{}", output)
    }
}

trait Contains<T> {
    fn contains(&self, T) -> bool;
}

impl<T: PartialOrd> Contains<T> for std::ops::Range<T> {
    fn contains(&self, elt: T) -> bool {
        self.start <= elt && elt < self.end
    }
}

const NEW_TREE_PROB: f32 = 0.01;
const INITIAL_TREE_PROB: f32 = 0.5;
const FIRE_PROB: f32 = 0.001;

const FOREST_WIDTH: usize = 60;
const FOREST_HEIGHT: usize = 30;

const SLEEP_MILLIS: u64 = 25;

use std::fmt;
use std::io;
use std::io::prelude::*;
use std::io::BufWriter;
use std::io::Stdout;
use std::process::Command;
use std::time::Duration;
use rand::Rng;
use ansi_term::Colour::*;

use Tile::{Empty, Tree, Burning, Heating};

fn main() {
    let sleep_duration = Duration::from_millis(SLEEP_MILLIS);
    let mut forest = [[Tile::Empty; FOREST_WIDTH]; FOREST_HEIGHT];

    prepopulate_forest(&mut forest);
    print_forest(forest, 0);

    std::thread::sleep(sleep_duration);

    for generation in 1.. {

        for row in forest.iter_mut() {
            for tile in row.iter_mut() {
                update_tile(tile);
            }
        }

        for y in 0..FOREST_HEIGHT {
            for x in 0..FOREST_WIDTH {
                if forest[y][x] == Burning {
                    heat_neighbors(&mut forest, y, x);
                }
            }
        }

        print_forest(forest, generation);

        std::thread::sleep(sleep_duration);
    }
}

fn prepopulate_forest(forest: &mut [[Tile; FOREST_WIDTH]; FOREST_HEIGHT]) {
    for row in forest.iter_mut() {
        for tile in row.iter_mut() {
            *tile = if prob_check(INITIAL_TREE_PROB) {
                Tree
            } else {
                Empty
            };
        }
    }
}

fn update_tile(tile: &mut Tile) {
    *tile = match *tile {
        Empty => {
            if prob_check(NEW_TREE_PROB) == true {
                Tree
            } else {
                Empty
            }
        }
        Tree => {
            if prob_check(FIRE_PROB) == true {
                Burning
            } else {
                Tree
            }
        }
        Burning => Empty,
        Heating => Burning,
    }
}

fn heat_neighbors(forest: &mut [[Tile; FOREST_WIDTH]; FOREST_HEIGHT], y: usize, x: usize) {
    let neighbors = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)];

    for &(xoff, yoff) in neighbors.iter() {
        let nx: i32 = (x as i32) + xoff;
        let ny: i32 = (y as i32) + yoff;
        if (0..FOREST_WIDTH as i32).contains(nx) && (0..FOREST_HEIGHT as i32).contains(ny) &&
           forest[ny as usize][nx as usize] == Tree {
            forest[ny as usize][nx as usize] = Heating
        }
    }
}

fn prob_check(chance: f32) -> bool {
    let roll = rand::thread_rng().gen::<f32>();
    if chance - roll > 0.0 {
        true
    } else {
        false
    }
}

fn print_forest(forest: [[Tile; FOREST_WIDTH]; FOREST_HEIGHT], generation: u32) {
    let mut writer = BufWriter::new(io::stdout());
    clear_screen(&mut writer);
    writeln!(writer, "Generation: {}", generation + 1).unwrap();
    for row in forest.iter() {
        for tree in row.iter() {
            write!(writer, "{}", tree).unwrap();
        }
        writer.write(b"\n").unwrap();
    }
}

fn clear_screen(writer: &mut BufWriter<Stdout>) {
    let output = Command::new("clear").output().unwrap();
    write!(writer, "{}", String::from_utf8_lossy(&output.stdout)).unwrap();
}


Fork

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <err.h>

int main()
{
	pid_t pid;

	if (!(pid = fork())) {
		usleep(10000);
		printf("\tchild process: done\n");
	} else if (pid < 0) {
		err(1, "fork error");
	} else {
		printf("waiting for child %d...\n", (int)pid);
		printf("child %d finished\n", (int)wait(0));
	}

	return 0;
}

use nix::unistd::{fork, ForkResult};
use std::process::id;

fn main() {
    match fork() {
        Ok(ForkResult::Parent { child, .. }) => {
            println!(
                "This is the original process(pid: {}). New child has pid: {}",
                id(),
                child
            );
        }
        Ok(ForkResult::Child) => println!("This is the new process(pid: {}).", id()),
        Err(_) => println!("Something went wrong."),
    }
}


Forward difference

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

double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
	unsigned int i, j;
	double* y;

	if (order >= len) return 0;

	y = malloc(sizeof(double) * len);
	if (!order) {
		memcpy(y, x, sizeof(double) * len);
		return y;
	}

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

	y = realloc(y, sizeof(double) * len);
	return y;
}

int main(void)
{
	double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
	int i, len = sizeof(x) / sizeof(x[0]);

	y = fwd_diff(x, len, 1);
	for (i = 0; i < len - 1; i++)
		printf("%g ", y[i]);
	putchar('\n');

	return 0;
}

fn forward_difference(input_seq: Vec<i32>, order: u32) -> Vec<i32> {
    match order {
        0 => input_seq,
        1 => {
            let input_seq_iter = input_seq.into_iter();
            let clone_of_input_seq_iter = input_seq_iter.clone();
            input_seq_iter.zip(clone_of_input_seq_iter.skip(1)).map(|(current, next)| next - current).collect()
        },
        _ => forward_difference(forward_difference(input_seq, order - 1), 1),
    }
}

fn main() {
    let mut sequence = vec![90, 47, 58, 29, 22, 32, 55, 5, 55, 73];
    loop {
        println!("{:?}", sequence);
        sequence = forward_difference(sequence, 1);
        if sequence.is_empty() {
            break;
        }
    }
}


Four bit adder

#include <stdio.h>

typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))

#define NOT(X) (~(X)&1)

#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))

void halfadder(IN a, IN b, OUT s, OUT c)
{
  V(s) = XOR(V(a), V(b));
  V(c) = V(a) & V(b);
}

void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
  PIN(ps); PIN(pc); PIN(tc);

  halfadder(a, b, ps, pc);
  halfadder(ps, ic, s, tc);
  V(oc) = V(tc) | V(pc);
}

void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
		   IN b0, IN b1, IN b2, IN b3,
		   OUT o0, OUT o1, OUT o2, OUT o3,
		   OUT overflow)
{
  PIN(zero); V(zero) = 0;
  PIN(tc0); PIN(tc1); PIN(tc2);

  fulladder(a0, b0, zero, o0, tc0);
  fulladder(a1, b1, tc0,  o1, tc1);
  fulladder(a2, b2, tc1,  o2, tc2);
  fulladder(a3, b3, tc2,  o3, overflow);
}

int main()
{
  PIN(a0); PIN(a1); PIN(a2); PIN(a3);
  PIN(b0); PIN(b1); PIN(b2); PIN(b3);
  PIN(s0); PIN(s1); PIN(s2); PIN(s3);
  PIN(overflow);

  V(a3) = 0; V(b3) = 1;
  V(a2) = 0; V(b2) = 1;
  V(a1) = 1; V(b1) = 1;
  V(a0) = 0; V(b0) = 0;

  fourbitsadder(a0, a1, a2, a3,
		b0, b1, b2, b3,
		s0, s1, s2, s3,
		overflow);

  printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
	 V(a3), V(a2), V(a1), V(a0),
	 V(b3), V(b2), V(b1), V(b0),
	 V(s3), V(s2), V(s1), V(s0),
	 V(overflow));

  return 0;
}

fn half_adder(a: usize, b: usize) -> (usize, usize) {
    return (a ^ b, a & b);
}

fn full_adder(a: usize, b: usize, c_in: usize) -> (usize, usize) {
    let (s0, c0) = half_adder(a, b);
    let (s1, c1) = half_adder(s0, c_in);
    return (s1, c0 | c1);
}

fn four_bit_adder (
    a: (usize, usize, usize, usize),
    b: (usize, usize, usize, usize)
)
    ->

    (usize, usize, usize, usize)
{

    let a = a.reverse();
    let b = b.reverse();

    let (sum, carry) = half_adder(a.0, b.0);
    let out0 = sum;
    let (sum, carry) = full_adder(a.1, b.1, carry);
    let out1 = sum;
    let (sum, carry) = full_adder(a.2, b.2, carry);
    let out2 = sum;
    let (sum, _) = full_adder(a.3, b.3, carry);
    let out3 = sum;
    return (out3, out2, out1, out0);
}

fn main() {
    let a: (usize, usize, usize, usize) = (0, 1, 1, 0);
    let b: (usize, usize, usize, usize) = (0, 1, 1, 0);
    assert_eq!(four_bit_adder(a, b), (1, 1, 0, 0));

}

trait Reverse<A, B, C, D> {
    fn reverse(self) -> (D, C, B, A);
}

impl<A, B, C, D> Reverse<A, B, C, D> for (A, B, C, D) {
    fn reverse(self) -> (D, C, B, A){
        return (self.3, self.2, self.1, self.0)
    }
}


Function composition

#include <stdlib.h>

typedef struct double_to_double {
  double (*fn)(struct double_to_double *, double);
} double_to_double;

#define CALL(f, x) f->fn(f, x)

typedef struct compose_functor {
  double (*fn)(struct compose_functor *, double);
  double_to_double *f;
  double_to_double *g;
} compose_functor;

double compose_call(compose_functor *this, double x) {
  return CALL(this->f, CALL(this->g, x));
}

double_to_double *compose(double_to_double *f,
                          double_to_double *g) {
  compose_functor *result = malloc(sizeof(compose_functor));
  result->fn = &compose_call;
  result->f = f;
  result->g = g;
  return (double_to_double *)result;
}

#include <math.h>

double sin_call(double_to_double *this, double x) {
  return sin(x);
}
double asin_call(double_to_double *this, double x) {
  return asin(x);
}

#include <stdio.h>

int main() {
  double_to_double *my_sin = malloc(sizeof(double_to_double));
  my_sin->fn = &sin_call;
  double_to_double *my_asin = malloc(sizeof(double_to_double));
  my_asin->fn = &asin_call;

  double_to_double *sin_asin = compose(my_sin, my_asin);

  printf("%f\n", CALL(sin_asin, 0.5));

  free(sin_asin);
  free(my_sin);
  free(my_asin);

  return 0;
}

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


Fusc sequence

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

int fusc(int n){
        if(n==0||n==1)
                return n;
        else if(n%2==0)
                return fusc(n/2);
        else
                return fusc((n-1)/2) + fusc((n+1)/2);
}

int numLen(int n){
        int sum = 1;

        while(n>9){
                n = n/10;
                sum++;
        }

        return sum;
}

void printLargeFuscs(int limit){
        int i,f,len,maxLen = 1;

        printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);

        for(i=0;i<=limit;i++){
                f = fusc(i);
                len = numLen(f);

                if(len>maxLen){
                        maxLen = len;
                        printf("\n%5d%12d",i,f);
                }
        }
}

int main()
{
        int i;

        printf("Index-------Value");
        for(i=0;i<61;i++)
                printf("\n%5d%12d",i,fusc(i));
        printLargeFuscs(INT_MAX);
        return 0;
}

fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> {
    let mut sequence = vec![0, 1];
    let mut n = 0;
    std::iter::from_fn(move || {
        if n > 1 {
            sequence.push(match n % 2 {
                0 => sequence[n / 2],
                _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2],
            });
        }
        let result = sequence[n];
        n += 1;
        Some(result)
    })
}

fn main() {
    println!("First 61 fusc numbers:");
    for n in fusc_sequence().take(61) {
        print!("{} ", n)
    }
    println!();

    let limit = 1000000000;
    println!(
        "Fusc numbers up to {} that are longer than any previous one:",
        limit
    );
    let mut max = 0;
    for (index, n) in fusc_sequence().take(limit).enumerate() {
        if n >= max {
            max = std::cmp::max(10, max * 10);
            println!("index = {}, fusc number = {}", index, n);
        }
    }
}


Gaussian elimination

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

#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))

void swap_row(double *a, double *b, int r1, int r2, int n)
{
	double tmp, *p1, *p2;
	int i;

	if (r1 == r2) return;
	for (i = 0; i < n; i++) {
		p1 = mat_elem(a, r1, i, n);
		p2 = mat_elem(a, r2, i, n);
		tmp = *p1, *p1 = *p2, *p2 = tmp;
	}
	tmp = b[r1], b[r1] = b[r2], b[r2] = tmp;
}

void gauss_eliminate(double *a, double *b, double *x, int n)
{
#define A(y, x) (*mat_elem(a, y, x, n))
	int i, j, col, row, max_row,dia;
	double max, tmp;

	for (dia = 0; dia < n; dia++) {
		max_row = dia, max = A(dia, dia);

		for (row = dia + 1; row < n; row++)
			if ((tmp = fabs(A(row, dia))) > max)
				max_row = row, max = tmp;

		swap_row(a, b, dia, max_row, n);

		for (row = dia + 1; row < n; row++) {
			tmp = A(row, dia) / A(dia, dia);
			for (col = dia+1; col < n; col++)
				A(row, col) -= tmp * A(dia, col);
			A(row, dia) = 0;
			b[row] -= tmp * b[dia];
		}
	}
	for (row = n - 1; row >= 0; row--) {
		tmp = b[row];
		for (j = n - 1; j > row; j--)
			tmp -= x[j] * A(row, j);
		x[row] = tmp / A(row, row);
	}
#undef A
}

int main(void)
{
	double a[] = {
		1.00, 0.00, 0.00,  0.00,  0.00, 0.00,
		1.00, 0.63, 0.39,  0.25,  0.16, 0.10,
		1.00, 1.26, 1.58,  1.98,  2.49, 3.13,
		1.00, 1.88, 3.55,  6.70, 12.62, 23.80,
		1.00, 2.51, 6.32, 15.88, 39.90, 100.28,
		1.00, 3.14, 9.87, 31.01, 97.41, 306.02
	};
	double b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 };
	double x[6];
	int i;

	gauss_eliminate(a, b, x, 6);

	for (i = 0; i < 6; i++)
		printf("%g\n", x[i]);

	return 0;
}


General FizzBuzz

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

struct replace_info {
    int n;
    char *text;
};

int compare(const void *a, const void *b)
{
    struct replace_info *x = (struct replace_info *) a;
    struct replace_info *y = (struct replace_info *) b;
    return x->n - y->n;
}

void generic_fizz_buzz(int max, struct replace_info *info, int info_length)
{
    int i, it;
    int found_word;

    for (i = 1; i < max; ++i) {
        found_word = 0;

        for (it = 0; it < info_length; ++it) {
            if (0 == i % info[it].n) {
                printf("%s", info[it].text);
                found_word = 1;
            }
        }

        if (0 == found_word)
            printf("%d", i);

        printf("\n");
    }
}

int main(void)
{
    struct replace_info info[3] = {
        {5, "Buzz"},
        {7, "Baxx"},
        {3, "Fizz"}
    };

    qsort(info, 3, sizeof(struct replace_info), compare);

    generic_fizz_buzz(20, info, 3);
    return 0;
}

use std::io;
use std::io::BufRead;

fn parse_entry(l: &str) -> (i32, String) {
    let params: Vec<&str> = l.split(' ').collect();

    let divisor = params[0].parse::<i32>().unwrap();
    let word = params[1].to_string();
    (divisor, word)
}

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(|l| l.unwrap());

    let l = lines.next().unwrap();
    let high = l.parse::<i32>().unwrap();

    let mut entries = Vec::new();
    for l in lines {
        if &l == "" { break }
        let entry = parse_entry(&l);
        entries.push(entry);
    }

    for i in 1..(high + 1) {
        let mut line = String::new();
        for &(divisor, ref word) in &entries {
            if i % divisor == 0 {
                line = line + &word;
            }
        }
        if line == "" {
            println!("{}", i);
        } else {
            println!("{}", line);
        }
    }
}


Generate lower case ASCII alphabet

#include <stdlib.h>

#define N 26

int main() {
    unsigned char lower[N];

    for (size_t i = 0; i < N; i++) {
        lower[i] = i + 'a';
    }

    return EXIT_SUCCESS;
}

fn main() {

    let ascii_iter = (0..26)
        .map(|x| (x + b'a') as char);

    println!("{:?}", ascii_iter.collect::<Vec<char>>());
}


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

#include <libco.h>

struct gen64 {
	cothread_t giver;
	cothread_t taker;
	int64_t given;
	void (*free)(struct gen64 *);
	void *garbage;
};

inline void
yield64(struct gen64 *gen, int64_t value)
{
	gen->given = value;
	co_switch(gen->taker);
}

inline int64_t
next64(struct gen64 *gen)
{
	gen->taker = co_active();
	co_switch(gen->giver);
	return gen->given;
}

static void
gen64_free(struct gen64 *gen)
{
	co_delete(gen->giver);
}

struct gen64 *entry64;

inline void
gen64_init(struct gen64 *gen, void (*entry)(void))
{
	if ((gen->giver = co_create(4096, entry)) == NULL) {

		fputs("co_create: Cannot create cothread\n", stderr);
		exit(1);
	}
	gen->free = gen64_free;
	entry64 = gen;
}

void
powers(struct gen64 *gen, int64_t m)
{
	int64_t base, exponent, n, result;

	for (n = 0;; n++) {

		base = n;
		exponent = m;
		for (result = 1; exponent != 0; exponent >>= 1) {
			if (exponent & 1) result *= base;
			base *= base;
		}
		yield64(gen, result);
	}

}

#define ENTRY(name, code) static void name(void) { code; }
ENTRY(enter_squares, powers(entry64, 2))
ENTRY(enter_cubes, powers(entry64, 3))

struct swc {
	struct gen64 cubes;
	struct gen64 squares;
	void (*old_free)(struct gen64 *);
};

static void
swc_free(struct gen64 *gen)
{
	struct swc *f = gen->garbage;
	f->cubes.free(&f->cubes);
	f->squares.free(&f->squares);
	f->old_free(gen);
}

void
squares_without_cubes(struct gen64 *gen)
{
	struct swc f;
	int64_t c, s;

	gen64_init(&f.cubes, enter_cubes);
	c = next64(&f.cubes);

	gen64_init(&f.squares, enter_squares);
	s = next64(&f.squares);

	f.old_free = gen->free;
	gen->garbage = &f;
	gen->free = swc_free;

	for (;;) {
		while (c < s)
			c = next64(&f.cubes);
		if (c != s)
			yield64(gen, s);
		s = next64(&f.squares);
	}

}

ENTRY(enter_squares_without_cubes, squares_without_cubes(entry64))

int
main()
{
	struct gen64 gen;
	int i;

	gen64_init(&gen, enter_squares_without_cubes);

	for (i = 0; i < 20; i++)
		next64(&gen);
	for (i = 0; i < 9; i++)
		printf("%" PRId64 ", ", next64(&gen));
	printf("%" PRId64 "\n", next64(&gen));

	gen.free(&gen);
	return 0;
}

use std::cmp::Ordering;
use std::iter::Peekable;

fn powers(m: u32) -> impl Iterator<Item = u64> {
    (0u64..).map(move |x| x.pow(m))
}

fn noncubic_squares() -> impl Iterator<Item = u64> {
    NoncubicSquares {
        squares: powers(2).peekable(),
        cubes: powers(3).peekable(),
    }
}

struct NoncubicSquares<T: Iterator<Item = u64>, U: Iterator<Item = u64>> {
    squares: Peekable<T>,
    cubes: Peekable<U>,
}

impl<T: Iterator<Item = u64>, U: Iterator<Item = u64>> Iterator for NoncubicSquares<T, U> {
    type Item = u64;
    fn next(&mut self) -> Option<u64> {
        loop {
            match self.squares.peek()?.cmp(self.cubes.peek()?) {
                Ordering::Equal => self.squares.next(),
                Ordering::Greater => self.cubes.next(),
                Ordering::Less => return self.squares.next(),
            };
        }
    }
}

fn main() {
    noncubic_squares()
        .skip(20)
        .take(10)
        .for_each(|x| print!("{} ", x));
    println!();
}


Generic swap

void swap(void *va, void *vb, size_t s)
{
  char t, *a = (char*)va, *b = (char*)vb;
  while(s--)
    t = a[s], a[s] = b[s], b[s] = t;
}

fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
    std::mem::swap(var1, var2)
}


Get system command output

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

int main(int argc, char **argv)
{
    if (argc < 2) return 1;

    FILE *fd;
    fd = popen(argv[1], "r");
    if (!fd) return 1;

    char   buffer[256];
    size_t chread;

    size_t comalloc = 256;
    size_t comlen   = 0;
    char  *comout   = malloc(comalloc);

    while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) {
        if (comlen + chread >= comalloc) {
            comalloc *= 2;
            comout = realloc(comout, comalloc);
        }
        memmove(comout + comlen, buffer, chread);
        comlen += chread;
    }

    fwrite(comout, 1, comlen, stdout);
    free(comout);
    pclose(fd);
    return 0;
}

use std::process::Command;
use std::io::{Write, self};

fn main() {
    let output = Command::new("/bin/cat")
                            .arg("/etc/fstab")
                            .output()
                            .expect("failed to execute process");

    io::stdout().write(&output.stdout);
}


Globally replace text in several files

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

char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
	ptrdiff_t i;
	char *start = buf;
	while (start + len < buf_end) {
		for (i = 0; i < len; i++)
			if (start[i] != pat[i]) break;

		if (i == len) return (char *)start;
		start++;
	}
	return 0;
}

int replace(const char *from, const char *to, const char *fname)
{
#define bail(msg) { warn(msg" '%s'", fname); goto done; }
	struct stat st;
	int ret = 0;
	char *buf = 0, *start, *end;
	size_t len = strlen(from), nlen = strlen(to);
	int fd = open(fname, O_RDWR);

	if (fd == -1) bail("Can't open");
	if (fstat(fd, &st) == -1) bail("Can't stat");
	if (!(buf = malloc(st.st_size))) bail("Can't alloc");
	if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read");

	start = buf;
	end = find_match(start, buf + st.st_size, from, len);
	if (!end) goto done;

	ftruncate(fd, 0);
	lseek(fd, 0, 0);
	do {
		write(fd, start, end - start);
		write(fd, to, nlen);
		start = end + len;

		end = find_match(start, buf + st.st_size, from, len);
	} while (end);

	if (start < buf + st.st_size)
		write(fd, start, buf + st.st_size - start);

done:
	if (fd != -1) close(fd);
	if (buf) free(buf);
	return ret;
}

int main()
{
	const char *from = "Goodbye, London!";
	const char *to   = "Hello, New York!";
	const char * files[] = { "test1.txt", "test2.txt", "test3.txt" };
	int i;

	for (i = 0; i < sizeof(files)/sizeof(char*); i++)
		replace(from, to, files[i]);

	return 0;
}

use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Write;

fn main() {

    let out_fd = OpenOptions::new()
        .write(true)
        .create(true)
        .open("resources/output.txt");

    let write_line = |line: &str| match out_fd {
        Ok(ref v) => {
            let mut writer = BufWriter::new(v);
            writer.write_all(line.as_bytes()).unwrap();
        }
        Err(ref e) => {
            println!("Error:{}", e);
        }
    };

    match File::open("resources/paragraph.txt") {
        Ok(handle) => {
            let mut reader = BufReader::new(handle);
            let mut line = String::new();

            reader.read_line(&mut line).unwrap();

            while line.trim() != "" {
                let mut replaced_line = line.trim().replace("Goodbye London!", "Hello New York!");
                replaced_line += "\n";
                write_line(&replaced_line[..]);
                line.clear();
                reader.read_line(&mut line).unwrap();
            }
        }
        Err(e) => println!("Error:{}", e),
    }
}


Greatest common divisor

int
gcd_iter(int u, int v) {
  if (u < 0) u = -u;
  if (v < 0) v = -v;
  if (v) while ((u %= v) && (v %= u));
  return (u + v);
}

extern crate num;
use num::integer::gcd;


Greatest element of a list

#include <assert.h>

float max(unsigned int count, float values[]) {
     assert(count > 0);
     size_t idx;
     float themax = values[0];
     for(idx = 1; idx < count; ++idx) {
          themax = values[idx] > themax ? values[idx] : themax;
     }
     return themax;
}

fn main() {
    let nums = [1,2,39,34,20];
    println!("{:?}", nums.iter().max());
    println!("{}", nums.iter().max().unwrap());
}


Greatest subsequential sum

#include "stdio.h"

typedef struct Range {
    int start, end, sum;
} Range;

Range maxSubseq(const int sequence[], const int len) {
    int maxSum = 0, thisSum = 0, i = 0;
    int start = 0, end = -1, j;

    for (j = 0; j < len; j++) {
        thisSum += sequence[j];
        if (thisSum < 0) {
            i = j + 1;
            thisSum = 0;
        } else if (thisSum > maxSum) {
            maxSum = thisSum;
            start = i;
            end   = j;
        }
    }

    Range r;
    if (start <= end && start >= 0 && end >= 0) {
        r.start = start;
        r.end = end + 1;
        r.sum = maxSum;
    } else {
        r.start = 0;
        r.end = 0;
        r.sum = 0;
    }
    return r;
}

int main(int argc, char **argv) {
    int a[] = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1};
    int alength = sizeof(a)/sizeof(a[0]);

    Range r = maxSubseq(a, alength);
    printf("Max sum = %d\n", r.sum);
    int i;
    for (i = r.start; i < r.end; i++)
        printf("%d ", a[i]);
    printf("\n");

    return 0;
}

fn main() {
    let nums = [1,2,39,34,20, -20, -16, 35, 0];

    let mut max = 0;
    let mut boundaries = 0..0;

    for length in 0..nums.len() {
        for start in 0..nums.len()-length {
            let sum = (&nums[start..start+length]).iter()
                .fold(0, |sum, elem| sum+elem);
            if sum > max {
                max = sum;
                boundaries = start..start+length;
            }
        }
    }

    println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);;
}


Guess the number

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

int main(void)
{
    int n;
    int g;
    char c;

    srand(time(NULL));
    n = 1 + (rand() % 10);

    puts("I'm thinking of a number between 1 and 10.");
    puts("Try to guess it:");

    while (1) {
        if (scanf("%d", &g) != 1) {

		scanf("%c", &c);
		continue;
	}

        if (g == n) {
	    puts("Correct!");
	    return 0;
	}
        puts("That's not my number. Try another guess:");
    }
}

extern crate rand;

fn main() {
    println!("Type in an integer between 1 and 10 and press enter.");

    let n = rand::random::<u32>() % 10 + 1;
    loop {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let option: Result<u32,_> = line.trim().parse();
        match option {
            Ok(guess) => {
                if guess < 1 || guess > 10 {
                    println!("Guess is out of bounds; try again.");
                } else if guess == n {
                    println!("Well guessed!");
                    break;
                } else {
                    println!("Wrong! Try again.");
                }
            },
            Err(_) => println!("Invalid input; try again.")
        }
    }
}


Guess the number_With feedback

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

#define lower_limit 0
#define upper_limit 100

int main(){
  int number, guess;

  srand( time( 0 ) );
  number = lower_limit + rand() % (upper_limit - lower_limit + 1);

  printf( "Guess the number between %d and %d: ", lower_limit, upper_limit );

  while( scanf( "%d", &guess ) == 1 ){
    if( number == guess ){
      printf( "You guessed correctly!\n" );
      break;
    }
    printf( "Your guess was too %s.\nTry again: ", number < guess ? "high" : "low" );
  }

  return 0;
}

use rand::Rng;
use std::cmp::Ordering;
use std::io;

const LOWEST: u32 = 1;
const HIGHEST: u32 = 100;

fn main() {
    let secret_number = rand::thread_rng().gen_range(1..101);

    println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

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

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}


Guess the number_With feedback (player)

#include <stdio.h>

int main(){
  int bounds[ 2 ] = {1, 100};
  char input[ 2 ] = "  ";

  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;

  printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );

  do{
    switch( input[ 0 ] ){
      case 'H':
        bounds[ 1 ] = choice;
        break;
      case 'L':
        bounds[ 0 ] = choice;
        break;
      case 'Y':
        printf( "\nAwwwright\n" );
        return 0;
    }
    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;

    printf( "Is the number %d? (Y/H/L) ", choice );
  }while( scanf( "%1s", input ) == 1 );

  return 0;
}

use std::io::stdin;

const MIN: isize = 1;
const MAX: isize = 100;

fn main() {
    loop {
        let mut min = MIN;
        let mut max = MAX;
        let mut num_guesses = 1;
        println!("Please think of a number between {} and {}", min, max);
        loop {
            let guess = (min + max) / 2;
            println!("Is it {}?", guess);
            println!("(type h if my guess is too high, l if too low, e if equal and q to quit)");

            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            match Some(line.chars().next().unwrap().to_uppercase().next().unwrap()) {
                Some('H') => {
                    max = guess - 1;
                    num_guesses += 1;
                },
                Some('L')=> {
                    min = guess + 1;
                    num_guesses += 1;
                },
                Some('E') => {
                    if num_guesses == 1 {
                        println!("\n*** That was easy! Got it in one guess! ***\n");
                    } else {
                        println!("\n*** I knew it! Got it in only {} guesses! ***\n", num_guesses);
                    }
                    break;
                },
                Some('Q') => return,
                _ => println!("Sorry, I didn't quite get that. Please try again.")
            }
        }
    }
}


HTTP

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

int
main(void)
{
        CURL *curl;
        char buffer[CURL_ERROR_SIZE];

        if ((curl = curl_easy_init()) != NULL) {
                curl_easy_setopt(curl, CURLOPT_URL, "http:
                curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
                curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
                if (curl_easy_perform(curl) != CURLE_OK) {
                        fprintf(stderr, "%s\n", buffer);
                        return EXIT_FAILURE;
                }
                curl_easy_cleanup(curl);
        }
        return EXIT_SUCCESS;
}

extern crate hyper;

use std::io::Read;
use hyper::client::Client;

fn main() {
    let client = Client::new();
    let mut resp = client.get("http:
    let mut body = String::new();
    resp.read_to_string(&mut body).unwrap();
    println!("{}", body);
}


HTTPS

#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
CURL *curl;
char buffer[CURL_ERROR_SIZE];
int main(void) {
    if ((curl = curl_easy_init()) != NULL) {
        curl_easy_setopt(curl, CURLOPT_URL, "https:
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
        if (curl_easy_perform(curl) != CURLE_OK) {
            fprintf(stderr, "%s\n", buffer);
            return EXIT_FAILURE;
        }
        curl_easy_cleanup(curl);
    }
    return EXIT_SUCCESS;
}

extern crate reqwest;

fn main() {
    let response = match reqwest::blocking::get("https:
        Ok(response) => response,
        Err(e) => panic!("error encountered while making request: {:?}", e),
    };

    println!("{}", response.text().unwrap());
}


Hailstone sequence

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

int hailstone(int n, int *arry)
{
    int hs = 1;

    while (n!=1) {
        hs++;
        if (arry) *arry++ = n;
        n = (n&1) ? (3*n+1) : (n/2);
    }
    if (arry) *arry++ = n;
    return hs;
}

int main()
{
    int j, hmax = 0;
    int jatmax, n;
    int *arry;

    for (j=1; j<100000; j++) {
       n = hailstone(j, NULL);
       if (hmax < n) {
           hmax = n;
           jatmax = j;
       }
    }
    n = hailstone(27, NULL);
    arry = malloc(n*sizeof(int));
    n = hailstone(27, arry);

    printf("[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\n",
        arry[0],arry[1],arry[2],arry[3],
        arry[n-4], arry[n-3], arry[n-2], arry[n-1], n);
    printf("Max %d at j= %d\n", hmax, jatmax);
    free(arry);

    return 0;
}

fn hailstone(start : u32) -> Vec<u32> {
    let mut res = Vec::new();
    let mut next = start;

    res.push(start);

    while next != 1  {
        next = if next % 2 == 0 { next/2 } else { 3*next+1 };
        res.push(next);
    }
    res
}

fn main() {
    let test_num = 27;
    let test_hailseq = hailstone(test_num);

    println!("For {} number of elements is {} ", test_num, test_hailseq.len());

    let fst_slice = test_hailseq[0..4].iter()
                        .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " });
    let last_slice = test_hailseq[test_hailseq.len()-4..].iter()
                        .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " });

    println!("  hailstone starting with {} ending with {} ", fst_slice, last_slice);

    let max_range = 100000;
    let mut max_len = 0;
    let mut max_seed = 0;
    for i_seed in 1..max_range {
        let i_len = hailstone(i_seed).len();

        if i_len > max_len {
            max_len = i_len;
            max_seed = i_seed;
        }
    }
    println!("Longest sequence is {} element long for seed {}", max_len, max_seed);
}


Hamming numbers

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

typedef unsigned long long ham;

size_t alloc = 0, n = 1;
ham *q = 0;

void qpush(ham h)
{
	int i, j;
	if (alloc <= n) {
		alloc = alloc ? alloc * 2 : 16;
		q = realloc(q, sizeof(ham) * alloc);
	}

	for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j);
	q[i] = h;
}

ham qpop()
{
	int i, j;
	ham r, t;

	for (r = q[1]; n > 1 && r == q[1]; q[i] = t) {

		for (i = 1, t = q[--n]; (j = i * 2) < n;) {
			if (j + 1 < n && q[j] > q[j+1]) j++;
			if (t <= q[j]) break;
			q[i] = q[j], i = j;
		}
	}

	return r;
}

int main()
{
	int i;
	ham h;

	for (qpush(i = 1); i <= 1691; i++) {

		h = qpop();
		qpush(h * 2);
		qpush(h * 3);
		qpush(h * 5);

		if (i <= 20 || i == 1691)
			printf("%6d: %llu\n", i, h);
	}

	return 0;
}

extern crate num;
num::bigint::BigUint;

use std::time::Instant;

fn basic_hamming(n: usize) -> BigUint {
    let two = BigUint::from(2u8);
    let three = BigUint::from(3u8);
    let five = BigUint::from(5u8);
    let mut h = vec![BigUint::from(0u8); n];
    h[0] = BigUint::from(1u8);
    let mut x2 = BigUint::from(2u8);
    let mut x3 = BigUint::from(3u8);
    let mut x5 = BigUint::from(5u8);
    let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;

    fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
        let (cs, r1) = if y == z { (0x6, y) }
                        else if y < z { (2, y) } else { (4, z) };
        if x == r1 { (cs | 1, x.clone()) }
        else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
    }

    let mut c = 1;
    while c < n {
        let (cs, e1) = { min3(&x2, &x3, &x5) };
        h[c] = e1;
        if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
        if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
        if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
        c += 1;
    }

    match h.pop() {
        Some(v) => v,
        _ => panic!("basic_hamming: arg is zero; no elements")
    }
}

fn main() {
    print!("[");
    for (i, h) in (1..21).map(basic_hamming).enumerate() {
        if i != 0 { print!(",") }
        print!(" {}", h)
    }
    println!(" ]");
    println!("{}", basic_hamming(1691));

    let strt = Instant::now();

    let rslt = basic_hamming(1000000);

    let elpsd = strt.elapsed();
    let secs = elpsd.as_secs();
    let millis = (elpsd.subsec_nanos() / 1000000)as u64;
    let dur = secs * 1000 + millis;

    let rs = rslt.to_str_radix(10);
    let mut s = rs.as_str();
    println!("{} digits:", s.len());
        while s.len() > 100 {
            let (f, r) = s.split_at(100);
            s = r;
            println!("{}", f);
        }
        println!("{}", s);

    println!("This last took {} milliseconds", dur);
}


Handle a signal

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

volatile sig_atomic_t gotint = 0;

void handleSigint() {

    gotint = 1;
}

int main() {
    clock_t startTime = clock();
    signal(SIGINT, handleSigint);
    int i=0;
    for (;;) {
        if (gotint)
            break;
        usleep(500000);
        if (gotint)
            break;
	printf("%d\n", ++i);
    }
    clock_t endTime = clock();
    double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
    printf("Program has run for %5.3f seconds\n", td);
    return 0;
}

#[cfg(unix)]
fn main() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::thread;
    use std::time::{Duration, Instant};

    use libc::{sighandler_t, SIGINT};

    let duration = Duration::from_secs(1) / 2;

    static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);

    unsafe {

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

        unsafe fn handle_sigint() {

            GOT_SIGINT.store(true, Ordering::Release);
        }

        libc::signal(SIGINT, handle_sigint as sighandler_t);
    }

    let start = Instant::now();

    let mut i = 0u32;

    loop {
        thread::sleep(duration);

        if unsafe { GOT_SIGINT.load(Ordering::Acquire) } {
            break;
        }

        i += 1;
        println!("{}", i);
    }

    let elapsed = start.elapsed();

    println!("Program has run for {} seconds", elapsed.as_secs());
}

#[cfg(not(unix))]
fn main() {
    println!("Not supported on this platform");
}


Happy numbers

#include <stdio.h>

#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};

int happy(int n)
{
	int sum = 0, x, nn;
	if (n < CACHE) {
		if (buf[n]) return 2 - buf[n];
		buf[n] = h_no;
	}

	for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;

	x = happy(sum);
	if (n < CACHE) buf[n] = 2 - x;
	return x;
}

int main()
{
	int i, cnt = 8;
	for (i = 1; cnt || !printf("\n"); i++)
		if (happy(i)) --cnt, printf("%d ", i);

	printf("The %dth happy number: ", cnt = 1000000);
	for (i = 1; cnt; i++)
		if (happy(i)) --cnt || printf("%d\n", i);

	return 0;
}

#![feature(core)]

fn sumsqd(mut n: i32) -> i32 {
    let mut sq = 0;
    while n > 0 {
        let d = n % 10;
        sq += d*d;
        n /= 10
    }
    sq
}

use std::num::Int;
fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T {
    let mut t = a;
    let mut h = f(a);

    while t != h {
        t = f(t);
        h = f(f(h))
    }
    t
}

fn ishappy(n: i32) -> bool {
    cycle(n, sumsqd) == 1
}

fn main() {
    let happy = std::iter::count(1, 1)
                    .filter(|&n| ishappy(n))
                    .take(8)
                    .collect::<Vec<i32>>();

    println!("{:?}", happy)
}


Harshad or Niven series

#include <stdio.h>

static int digsum(int n)
{
    int sum = 0;
    do { sum += n % 10; } while (n /= 10);
    return sum;
}

int main(void)
{
    int n, done, found;

    for (n = 1, done = found = 0; !done; ++n) {
        if (n % digsum(n) == 0) {
            if (found++ < 20) printf("%d ", n);
            if (n > 1000) done = printf("\n%d\n", n);
        }
    }

    return 0;
}

fn is_harshad (n : u32) -> bool {
    let sum_digits = n.to_string()
                      .chars()
                      .map(|c| c.to_digit(10).unwrap())
                      .fold(0, |a, b| a+b);
    n % sum_digits == 0
}

fn main() {
    for i in (1u32..).filter(|num| is_harshad(*num)).take(20) {
        println!("Harshad : {}", i);
    }
    for i in (1_001u32..).filter(|num| is_harshad(*num)).take(1) {
        println!("First Harshad bigger than 1_000 : {}", i);
    }
}


Hash from two arrays

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

#define KeyType const char *
#define ValType int

#define HASH_SIZE 4096

unsigned strhashkey( const char * key, int max)
{
    unsigned h=0;
    unsigned hl, hr;

    while(*key) {
        h += *key;
        hl= 0x5C5 ^ (h&0xfff00000 )>>18;
        hr =(h&0x000fffff );
        h = hl ^ hr ^ *key++;
    }
    return h % max;
}

typedef struct sHme {
    KeyType    key;
    ValType    value;
    struct sHme  *link;
} *MapEntry;

typedef struct he {
    MapEntry  first, last;
} HashElement;

HashElement hash[HASH_SIZE];

typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);

void HashAddH( KeyType key, ValType value,
        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
    unsigned hix = (*hashKey)(key, HASH_SIZE);
    MapEntry m_ent;

    for (m_ent= hash[hix].first;
            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
    if (m_ent) {
        (*copyVal)(&m_ent->value, value);
    }
    else {
        MapEntry last;
        MapEntry hme = malloc(sizeof(struct sHme));
        (*copyKey)(&hme->key, key);
        (*copyVal)(&hme->value, value);
        hme->link = NULL;
        last = hash[hix].last;
        if (last) {

            last->link = hme;
        }
        else
            hash[hix].first = hme;
        hash[hix].last = hme;
    }
}

int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
    unsigned hix = (*hashKey)(key, HASH_SIZE);
    MapEntry m_ent;
    for (m_ent= hash[hix].first;
            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
    if (m_ent) {
        *val = m_ent->value;
    }
    return (m_ent != NULL);
}

void copyStr(const char**dest, const char *src)
{
    *dest = strdup(src);
}
void copyInt( int *dest, int src)
{
    *dest = src;
}
int strCompare( const char *key1, const char *key2)
{
    return strcmp(key1, key2) == 0;
}

void HashAdd( KeyType key, ValType value )
{
    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);
}

int HashGet(ValType *val, KeyType key)
{
    return HashGetH( val, key, &strhashkey, &strCompare);
}

int main()
{
    static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
    static int valuList[] = {1,43,640, 747, 42, 42};
    int ix;

    for (ix=0; ix<6; ix++) {
        HashAdd(keyList[ix], valuList[ix]);
    }
    return 0;
}

use std::collections::HashMap;

fn main() {
    let keys = ["a", "b", "c"];
    let values = [1, 2, 3];

    let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
    println!("{:?}", hash);
}


Haversine formula

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

#define R 6371
#define TO_RAD (3.1415926536 / 180)
double dist(double th1, double ph1, double th2, double ph2)
{
	double dx, dy, dz;
	ph1 -= ph2;
	ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;

	dz = sin(th1) - sin(th2);
	dx = cos(ph1) * cos(th1) - cos(th2);
	dy = sin(ph1) * cos(th1);
	return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R;
}

int main()
{
	double d = dist(36.12, -86.67, 33.94, -118.4);

	printf("dist: %.1f km (%.1f mi.)\n", d, d / 1.609344);

	return 0;
}

struct Point {
    lat: f64,
    lon: f64,
}

fn haversine(origin: Point, destination: Point) -> f64 {
    const R: f64 = 6372.8;

    let lat1 = origin.lat.to_radians();
    let lat2 = destination.lat.to_radians();
    let d_lat = lat2 - lat1;
    let d_lon = (destination.lon - origin.lon).to_radians();

    let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos();
    let c = 2.0 * a.sqrt().asin();
    R * c
}

#[cfg(test)]
mod test {
    use super::{Point, haversine};

    #[test]
    fn test_haversine() {
        let origin: Point = Point {
            lat: 36.12,
            lon: -86.67
        };
        let destination: Point = Point {
            lat: 33.94,
            lon: -118.4
        };
        let d: f64 = haversine(origin, destination);
        println!("Distance: {} km ({} mi)", d, d / 1.609344);
        assert_eq!(d, 2887.2599506071106);
    }

}


Hello world_Graphical

#include <gtk/gtk.h>

int main (int argc, char **argv) {
  GtkWidget *window;
  gtk_init(&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Goodbye, World");
  g_signal_connect (G_OBJECT (window), "delete-event", gtk_main_quit, NULL);
  gtk_widget_show_all (window);

  gtk_main();
  return 0;
}

extern crate gtk;
use gtk::traits::*;
use gtk::{Window, WindowType, WindowPosition};
use gtk::signal::Inhibit;

fn main() {
    gtk::init().unwrap();
    let window = Window::new(WindowType::Toplevel).unwrap();

    window.set_title("Goodbye, World!");
    window.set_border_width(10);
    window.set_window_position(WindowPosition::Center);
    window.set_default_size(350, 70);
    window.connect_delete_event(|_,_| {
        gtk::main_quit();
        Inhibit(false)
    });

    window.show_all();
    gtk::main();
}


Hello world_Newline omission

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

int main(int argc, char *argv[]) {
  (void) printf("Goodbye, World!");
  return EXIT_SUCCESS;
}

fn main () {
    print!("Goodbye, World!");
}


Hello world_Standard error

#include <stdio.h>

int main()
{
	fprintf(stderr, "Goodbye, ");
	fputs("World!\n", stderr);

	return 0;
}

fn main() {
    eprintln!("Hello, {}!", "world");
}


Hello world_Text

const hello = "Hello world!\n"

print(hello)

fn main() {
   print!("Hello world!");
}


Hello world_Web server

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>

char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><title>Bye-bye baby bye-bye</title>"
""
"
Goodbye, world!
\r\n";

int main()
{
  int one = 1, client_fd;
  struct sockaddr_in svr_addr, cli_addr;
  socklen_t sin_len = sizeof(cli_addr);

  int sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0)
    err(1, "can't open socket");

  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));

  int port = 8080;
  svr_addr.sin_family = AF_INET;
  svr_addr.sin_addr.s_addr = INADDR_ANY;
  svr_addr.sin_port = htons(port);

  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
    close(sock);
    err(1, "Can't bind");
  }

  listen(sock, 5);
  while (1) {
    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
    printf("got connection\n");

    if (client_fd == -1) {
      perror("Can't accept");
      continue;
    }

    write(client_fd, response, sizeof(response) - 1);
    close(client_fd);
  }
}

use std::net::{Shutdown, TcpListener};
use std::thread;
use std::io::Write;

const RESPONSE: &'static [u8] = b"HTTP/1.1 200 OK\r
Content-Type: text/html; charset=UTF-8\r\n\r
<!DOCTYPE html><title>Bye-bye baby bye-bye</title>

Goodbye, world!
\r";

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    for stream in listener.incoming() {
        thread::spawn(move || {
            let mut stream = stream.unwrap();
            match stream.write(RESPONSE) {
                Ok(_) => println!("Response sent!"),
                Err(e) => println!("Failed sending response: {}!", e),
            }
            stream.shutdown(Shutdown::Write).unwrap();
        });
    }
}


Heronian triangles

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

typedef struct{
	int a,b,c;
	int perimeter;
	double area;
}triangle;

typedef struct elem{
	triangle t;
	struct elem* next;
}cell;

typedef cell* list;

void addAndOrderList(list *a,triangle t){
	list iter,temp;
	int flag = 0;

	if(*a==NULL){
		*a = (list)malloc(sizeof(cell));
		(*a)->t = t;
		(*a)->next = NULL;
	}

	else{
		temp = (list)malloc(sizeof(cell));

			iter = *a;
			while(iter->next!=NULL){
				if(((iter->t.area<t.area)||(iter->t.area==t.area && iter->t.perimeter<t.perimeter)||(iter->t.area==t.area && iter->t.perimeter==t.perimeter && iter->t.a<=t.a))
				&&
				(iter->next==NULL||(t.area<iter->next->t.area || t.perimeter<iter->next->t.perimeter || t.a<iter->next->t.a))){
					temp->t = t;
					temp->next = iter->next;
					iter->next = temp;
					flag = 1;
					break;
				}

				iter = iter->next;
			}

			if(flag!=1){
				temp->t = t;
				temp->next = NULL;
				iter->next = temp;
			}
	}
}

int gcd(int a,int b){
	if(b!=0)
		return gcd(b,a%b);
	return a;
}

void calculateArea(triangle *t){
	(*t).perimeter = (*t).a + (*t).b + (*t).c;
	(*t).area = sqrt(0.5*(*t).perimeter*(0.5*(*t).perimeter - (*t).a)*(0.5*(*t).perimeter - (*t).b)*(0.5*(*t).perimeter - (*t).c));
}

list generateTriangleList(int maxSide,int *count){
	int a,b,c;
	triangle t;
	list herons = NULL;

	*count = 0;

	for(a=1;a<=maxSide;a++){
		for(b=1;b<=a;b++){
			for(c=1;c<=b;c++){
				if(c+b > a && gcd(gcd(a,b),c)==1){
					t = (triangle){a,b,c};
					calculateArea(&t);
					if(t.area/(int)t.area == 1){
						addAndOrderList(&herons,t);
						(*count)++;
					}
				}
			}
		}
	}

	return herons;
}

void printList(list a,int limit,int area){
	list iter = a;
	int count = 1;

	printf("\nDimensions\tPerimeter\tArea");

	while(iter!=NULL && count!=limit+1){
		if(area==-1 ||(area==iter->t.area)){
			printf("\n%d x %d x %d\t%d\t\t%d",iter->t.a,iter->t.b,iter->t.c,iter->t.perimeter,(int)iter->t.area);
			count++;
		}
		iter = iter->next;
	}
}

int main(int argC,char* argV[])
{
	int count;
	list herons = NULL;

	if(argC!=4)
		printf("Usage : %s <Max side, max triangles to print and area, -1 for area to ignore>",argV[0]);
	else{
		herons = generateTriangleList(atoi(argV[1]),&count);
		printf("Triangles found : %d",count);
		(atoi(argV[3])==-1)?printf("\nPrinting first %s triangles.",argV[2]):printf("\nPrinting triangles with area %s square units.",argV[3]);
		printList(herons,atoi(argV[2]),atoi(argV[3]));
		free(herons);
	}
	return 0;
}

use num_integer::Integer;
use std::{f64, usize};

const MAXSIZE: usize = 200;

#[derive(Debug)]
struct HerionanTriangle {
    a: usize,
    b: usize,
    c: usize,
    area: usize,
    perimeter: usize,
}

fn get_area(a: &usize, b: &usize, c: &usize) -> f64 {
    let s = (a + b + c) as f64 / 2.;
    (s * (s - *a as f64) * (s - *b as f64) * (s - *c as f64)).sqrt()
}

fn is_heronian(a: &usize, b: &usize, c: &usize) -> bool {
    let area = get_area(a, b, c);

    area != 0. && area.fract() == 0.
}

fn main() {
    let mut heronians: Vec<HerionanTriangle> = vec![];

    (1..=MAXSIZE).into_iter().for_each(|a| {
        (a..=MAXSIZE).into_iter().for_each(|b| {
            (b..=MAXSIZE).into_iter().for_each(|c| {
                if a + b > c && a.gcd(&b).gcd(&c) == 1 && is_heronian(&a, &b, &c) {
                    heronians.push(HerionanTriangle {
                        a,
                        b,
                        c,
                        perimeter: a + b + c,
                        area: get_area(&a, &b, &c) as usize,
                    })
                }
            })
        })
    });

    heronians.sort_unstable_by(|x, y| {
        x.area
            .cmp(&y.area)
            .then(x.perimeter.cmp(&y.perimeter))
            .then((x.a.max(x.b).max(x.c)).cmp(&y.a.max(y.b).max(y.c)))
    });

    println!(
        "Primitive Heronian triangles with sides up to 200: {}",
        heronians.len()
    );

    println!("\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:");
    heronians.iter().take(10).for_each(|h| println!("{:?}", h));

    println!("\nAll with area 210 subject to the previous ordering:");
    heronians
        .iter()
        .filter(|h| h.area == 210)
        .for_each(|h| println!("{:?}", h));
}


Higher-order functions

void myFuncSimple( void (*funcParameter)(void) )
{

    (*funcParameter)();
    funcParameter();

}

fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 {
	f(10)
}

fn square(n: u64) -> u64 {
	n*n
}

fn main() {
	println!("{}", execute_with_10(|n| n*n ));
	println!("{}", execute_with_10(square));
}


Hilbert curve

#include <stdio.h>

#define N 32
#define K 3
#define MAX N * K

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

void rot(int n, point *p, int rx, int ry) {
    int t;
    if (!ry) {
        if (rx == 1) {
            p->x = n - 1 - p->x;
            p->y = n - 1 - p->y;
        }
        t = p->x;
        p->x = p->y;
        p->y = t;
    }
}

void d2pt(int n, int d, point *p) {
    int s = 1, t = d, rx, ry;
    p->x = 0;
    p->y = 0;
    while (s < n) {
        rx = 1 & (t / 2);
        ry = 1 & (t ^ rx);
        rot(s, p, rx, ry);
        p->x += s * rx;
        p->y += s * ry;
        t /= 4;
        s *= 2;
    }
}

int main() {
    int d, x, y, cx, cy, px, py;
    char pts[MAX][MAX];
    point curr, prev;
    for (x = 0; x < MAX; ++x)
        for (y = 0; y < MAX; ++y) pts[x][y] = ' ';
    prev.x = prev.y = 0;
    pts[0][0] = '.';
    for (d = 1; d < N * N; ++d) {
        d2pt(N, d, &curr);
        cx = curr.x * K;
        cy = curr.y * K;
        px = prev.x * K;
        py = prev.y * K;
        pts[cx][cy] = '.';
        if (cx == px ) {
            if (py < cy)
                for (y = py + 1; y < cy; ++y) pts[cx][y] = '|';
            else
                for (y = cy + 1; y < py; ++y) pts[cx][y] = '|';
        }
        else {
            if (px < cx)
                for (x = px + 1; x < cx; ++x) pts[x][cy] = '_';
            else
                for (x = cx + 1; x < px; ++x) pts[x][cy] = '_';
        }
        prev = curr;
    }
    for (x = 0; x < MAX; ++x) {
        for (y = 0; y < MAX; ++y) printf("%c", pts[y][x]);
        printf("\n");
    }
    return 0;
}

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

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

impl HilbertCurve {
    fn new(x: f64, y: f64, length: f64, angle: i32) -> HilbertCurve {
        HilbertCurve {
            current_x: x,
            current_y: y,
            current_angle: angle,
            line_length: length,
        }
    }
    fn rewrite(order: usize) -> String {
        let mut str = String::from("A");
        for _ in 0..order {
            let mut tmp = String::new();
            for ch in str.chars() {
                match ch {
                    'A' => tmp.push_str("-BF+AFA+FB-"),
                    'B' => tmp.push_str("+AF-BFB-FA+"),
                    _ => 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 HilbertCurve::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 x = 10.0;
        let y = 10.0;
        let rect = Rectangle::new()
            .set("width", "100%")
            .set("height", "100%")
            .set("fill", "white");
        let mut hilbert = HilbertCurve::new(x, y, 10.0, 0);
        let document = svg::Document::new()
            .set("width", size)
            .set("height", size)
            .add(rect)
            .add(hilbert.execute(order));
        svg::save(file, &document)
    }
}

fn main() {
    HilbertCurve::save("hilbert_curve.svg", 650, 6).unwrap();
}


Hofstadter Figure-Figure sequences

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

typedef unsigned long long xint;

typedef struct {
	size_t len, alloc;
	xint *buf;
} xarray;

xarray rs, ss;

void setsize(xarray *a, size_t size)
{
	size_t n = a->alloc;
	if (!n) n = 1;

	while (n < size) n <<= 1;
	if (a->alloc < n) {
		a->buf = realloc(a->buf, sizeof(xint) * n);
		if (!a->buf) abort();
		a->alloc = n;
	}
}

void push(xarray *a, xint v)
{
	while (a->alloc <= a->len)
		setsize(a, a->alloc * 2);

	a->buf[a->len++] = v;
}

void RS_append(void);

xint R(int n)
{
	while (n > rs.len) RS_append();
	return rs.buf[n - 1];
}

xint S(int n)
{
	while (n > ss.len) RS_append();
	return ss.buf[n - 1];
}

void RS_append()
{
	int n = rs.len;
	xint r = R(n) + S(n);
	xint s = S(ss.len);

	push(&rs, r);
	while (++s < r) push(&ss, s);
	push(&ss, r + 1);
}

int main(void)
{
	push(&rs, 1);
	push(&ss, 2);

	int i;
	printf("R(1 .. 10):");
	for (i = 1; i <= 10; i++)
		printf(" %llu", R(i));

	char seen[1001] = { 0 };
	for (i = 1; i <=  40; i++) seen[ R(i) ] = 1;
	for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
	for (i = 1; i <= 1000 && seen[i]; i++);

	if (i <= 1000) {
		fprintf(stderr, "%d not seen\n", i);
		abort();
	}

	puts("\nfirst 1000 ok");
	return 0;
}

use std::collections::HashMap;

struct Hffs {
    sequence_r: HashMap<usize, usize>,
    sequence_s: HashMap<usize, usize>,
}

impl Hffs {
    fn new() -> Hffs {
        Hffs {
            sequence_r: HashMap::new(),
            sequence_s: HashMap::new(),
        }
    }
    fn ffr(&mut self, n: usize) -> usize {

        let new_r = if let Some(result) = self.sequence_r.get(&n) {
            *result
        } else if n == 0 {
            1
        } else {

            self.ffr(n - 1) + self.ffs(n - 1)
        };

        *self.sequence_r.entry(n).or_insert(new_r)
    }

    fn ffs(&mut self, n: usize) -> usize {

        let new_s = if let Some(result) = self.sequence_s.get(&n) {
            *result
        } else if n == 0 {
            2
        } else {
            let lower = self.ffs(n - 1) + 1_usize;
            let upper = self.ffr(n) + 1_usize;
            let mut min_s: usize = 0;

            for i in lower..=upper {
                if !self.sequence_r.values().any(|&val| val == i) {
                    min_s = i;
                    break;
                }
            }
            min_s
        };

        *self.sequence_s.entry(n).or_insert(new_s)
    }
}

impl Default for Hffs {
    fn default() -> Self {
        Self::new()
    }
}
fn main() {
    let mut hof = Hffs::new();

    for i in 0..10 {
        println!("H:{} -> R: {}, S: {}", i, hof.ffr(i), hof.ffs(i));
    }

    let r40 = (0..40).map(|i| hof.ffr(i)).collect::<Vec<_>>();
    let mut s960 = (0..960).map(|i| hof.ffs(i)).collect::<Vec<_>>();

    s960.extend(&r40);
    s960.sort_unstable();
    let f1000 = (1_usize..=1000).collect::<Vec<_>>();

    assert_eq!(f1000, s960, "Does NOT match");
}


Hofstadter-Conway $10,000 sequence

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

int a_list[1<<20 + 1];

int doSqnc( int m)
{
    int max_df = 0;
    int p2_max = 2;
    int v, n;
    int k1 = 2;
    int lg2 = 1;
    double amax = 0;
    a_list[0] = -50000;
    a_list[1] = a_list[2] = 1;
    v = a_list[2];

    for (n=3; n <= m;  n++) {
        v = a_list[n] = a_list[v] + a_list[n-v];
        if ( amax < v*1.0/n) amax = v*1.0/n;
        if ( 0 == (k1&n)) {
            printf("Maximum between 2^%d and 2^%d was %f\n", lg2,lg2+1, amax);
            amax = 0;
            lg2++;
        }
        k1 = n;
    }
    return 1;
}

struct HofstadterConway {
    current: usize,
    sequence: Vec<usize>,
}

impl HofstadterConway {

    fn new() -> HofstadterConway {
        HofstadterConway {
            current: 0,
            sequence: vec![1, 1],
        }
    }
}

impl Default for HofstadterConway {
    fn default() -> Self {
        Self::new()
    }
}

impl Iterator for HofstadterConway {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        let max_index = self.sequence.len() - 1;
        let last_value = self.sequence[max_index];

        if self.current > max_index {
            let new_x = self.sequence[last_value - 1] + self.sequence[max_index - last_value + 1];
            self.sequence.push(new_x);
        }
        self.current += 1;
        Some(self.sequence[self.current - 1])
    }
}

#[allow(clippy::cast_precision_loss)]
fn main() {
    let mut hof = HofstadterConway::new();
    let mut winning_num = 0_usize;

    for p in 0..20 {
        let max_hof = (2_usize.pow(p)..2_usize.pow(p + 1))
            .map(|n| (n, hof.next().unwrap() as f64 / n as f64))
            .fold(f64::NAN, |a, (n, b)| {
                if b >= 0.55 {
                    winning_num = n;
                }
                a.max(b)
            });

        println!("2^{:>2}-2^{:>2}, {:>.8}", p, p + 1, max_hof);
    }

    println!("Winning number: {}", winning_num);
}


Holidays related to Easter

#include <stdio.h>

typedef int year_t, month_t, week_t, day_t;

typedef struct{
  year_t year;
  month_t month;  day_t month_day; day_t week_day; } date_t;

const char *mon_fmt[] =      {0, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
const char *week_day_fmt[] = {0, "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"};

day_t month_days(year_t year, month_t month)
  { day_t days[]={0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return (month==2) ? 28 + (( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0) : days[month];
  }

day_t year_days(year_t year)
  { return (month_days(year, 2) == 28) ? 365 : 366; }

month_t year_months = 12;
week_t week_days = 7;

date_t plusab(date_t *date, day_t days)
    {

       while(days < 0){
         date->year -= 1;
         days += year_days(date->year);
       };
       while(days > year_days(date->year)){
         days -= year_days(date->year);
         date->year += 1;
       };
       date->month_day += days;

       while(date->month_day > month_days(date->year, date->month)){
          date->month_day -= month_days(date->year, date->month);
          date->month += 1;
          if(date->month > year_months){
             date->month -= year_months;
             date->year += 1;
          }
       }
       date->week_day = week_day(*date);
       return *date;
    }

date_t easter (year_t year)
   {

      date_t date; date.year = year;
      int c = year / 100, n = year % 19;
      int i = (c - c / 4 - (c - (c - 17) / 25) / 3 + 19 * n + 15) % 30;
      i -= (i / 28) * (1 - (i / 28) * (29 / (i + 1)) * ((21 - n) / 11));
      int l = i - (year + year / 4 + i + 2 - c + c / 4) % 7;
      date.month = 3 + (l + 40) / 44;
      date.month_day = l + 28 - 31 * (date.month / 4);
      date.week_day = week_day(date);
      return date;
   }

day_t week_day (date_t date)

   {
      int year = date.year, month = date.month, month_day = date.month_day, c;
      if(month <= 2){month += 12; year -= 1;}
      c = year / 100;
      year %= 100;
      return 1 + ((month_day + ((month + 1) * 26) / 10
         + year + year / 4 + c / 4 - 2 * c) % 7 + 7) % 7;
   }

#define wdmdm_fmt "%s %2d %s"

typedef struct{date_t easter, ascension, pentecost, trinity, corpus_christi;}easter_related_t;

easter_related_t easter_related_init (year_t year)
{
   date_t date;
   easter_related_t holidays;

   holidays.easter = date = easter(year);

   holidays.ascension = plusab(&date, 39);

   holidays.pentecost = plusab(&date, 10);

   holidays.trinity = plusab(&date, 7);

   holidays.corpus_christi = plusab(&date, 4);
   return holidays;
}

#define easter_related_fmt "%4d Easter: "wdmdm_fmt", Ascension: "wdmdm_fmt\
    ", Pentecost: "wdmdm_fmt", Trinity: "wdmdm_fmt", Corpus: "wdmdm_fmt"\n"

void easter_related_print(year_t year)
{
  easter_related_t holidays = easter_related_init(year);
#define wdmdm(date) week_day_fmt[date.week_day], date.month_day, mon_fmt[date.month]
  printf(easter_related_fmt, year,
    wdmdm(holidays.easter),  wdmdm(holidays.ascension), wdmdm(holidays.pentecost),
    wdmdm(holidays.trinity), wdmdm(holidays.corpus_christi));
}

int main(){
  year_t year;

  printf ("Christian holidays, related to Easter, for each centennial from 400 to 2100 CE:\n");
  for(year=400; year<=2100; year+=100){ easter_related_print(year); }

  printf ("\nChristian holidays, related to Easter, for years from 2010 to 2020 CE:\n");
  for(year=2010; year<=2020; year++){ easter_related_print(year); }
  return 0;
}

use std::ops::Add;

use chrono::{prelude::*, Duration};

#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_wrap)]
fn get_easter_day(year: u32) -> chrono::NaiveDate {
    let k = (f64::from(year) / 100.).floor();
    let d = (19 * (year % 19)
        + ((15 - ((13. + 8. * k) / 25.).floor() as u32 + k as u32 - (k / 4.).floor() as u32) % 30))
        % 30;
    let e =
        (2 * (year % 4) + 4 * (year % 7) + 6 * d + ((4 + k as u32 - (k / 4.).floor() as u32) % 7))
            % 7;

    let (month, day) = match d {
        29 if e == 6 => (4, 19),
        28 if e == 6 => (4, 18),
        _ if d + e < 10 => (3, 22 + d + e),
        _ => (4, d + e - 9),
    };

    NaiveDate::from_ymd(year as i32, month, day)
}
fn main() {
    let holidays = vec![
        ("Easter", Duration::days(0)),
        ("Ascension", Duration::days(39)),
        ("Pentecost", Duration::days(49)),
        ("Trinity", Duration::days(56)),
        ("Corpus Christi", Duration::days(60)),
    ];
    for year in (400..=2100).step_by(100).chain(2010..=2020) {
        print!("{}: ", year);
        for (name, offset) in &holidays {
            print!(
                "{}: {}, ",
                name,
                get_easter_day(year).add(*offset).format("%a %d %h")
            );
        }
        println!();
    }
}


Horizontal sundial calculations

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

#define PICKVALUE(TXT, VM) do {			\
    printf("%s: ", TXT);			\
    scanf("%lf", &VM);				\
  } while(0);

#if !defined(M_PI)
#define M_PI 3.14159265358979323846
#endif

#define DR(X) ((X)*M_PI/180.0)
#define RD(X) ((X)*180.0/M_PI)

int main()
{
  double lat, slat, lng, ref;
  int h;

  PICKVALUE("Enter latitude", lat);
  PICKVALUE("Enter longitude", lng);
  PICKVALUE("Enter legal meridian", ref);
  printf("\n");

  slat = sin(DR(lat));
  printf("sine of latitude: %.3f\n", slat);
  printf("diff longitude: %.3f\n\n", lng - ref);

  printf("Hour, sun hour angle, dial hour line angle from 6am to 6pm\n");

  for(h = -6; h <= 6; h++)
  {
    double hla, hra;
    hra = 15.0*h;
    hra = hra - lng + ref;
    hla = RD(atan(slat * tan(DR(hra))));
    printf("HR= %3d;  \t  HRA=%7.3f;  \t  HLA= %7.3f\n",
	   h, hra, hla);
  }

  return 0;
}

use std::io;
struct SundialCalculation {
    hour_angle: f64,
    hour_line_angle: f64,
}

fn get_input(prompt: &str) -> Result<f64, Box<dyn std::error::Error>> {
    println!("{}", prompt);
    let mut input = String::new();
    let stdin = io::stdin();
    stdin.read_line(&mut input)?;
    Ok(input.trim().parse::<f64>()?)
}

fn calculate_sundial(hour: i8, lat: f64, lng: f64, meridian: f64) -> SundialCalculation {
    let diff = lng - meridian;
    let hour_angle = f64::from(hour) * 15. - diff;
    let hour_line_angle = (hour_angle.to_radians().tan() * lat.to_radians().sin())
        .atan()
        .to_degrees();

    SundialCalculation {
        hour_angle,
        hour_line_angle,
    }
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lat = get_input("Enter latitude       => ")?;
    let lng = get_input("Enter longitude      => ")?;
    let meridian = get_input("Enter legal meridian => ")?;
    let diff = lng - meridian;

    let sine_lat = lat.to_radians().sin();
    println!("Sine of latitude: {:.5}", sine_lat);
    println!("Diff longitude: {}", diff);

    println!("  Hrs Angle   Hour Line Angle");
    (-6..=6).for_each(|hour| {
        let sd = calculate_sundial(hour, lat, lng, meridian);
        println!(
            "{:>3}{} {:>5}   {:>+15.5}",
            if hour == 0 { 12 } else { (hour + 12) % 12 },
            if hour <= 6 { "pm" } else { "am" },
            sd.hour_angle,
            sd.hour_line_angle
        );
    });
    Ok(())
}


Horner's rule for polynomial evaluation

#include <stdio.h>

double horner(double *coeffs, int s, double x)
{
  int i;
  double res = 0.0;

  for(i=s-1; i >= 0; i--)
  {
    res = res * x + coeffs[i];
  }
  return res;
}

int main()
{
  double coeffs[] = { -19.0, 7.0, -4.0, 6.0 };

  printf("%5.1f\n", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0));
  return 0;
}


Host introspection

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

int main() {
    int one = 1;

    printf("word size = %d bits\n", (int)(CHAR_BIT * sizeof(size_t)));

    if (*(char *)&one)
        printf("little endian\n");
    else
        printf("big endian\n");
    return 0;
}

#[derive(Copy, Clone, Debug)]
enum Endianness {
    Big, Little,
}

impl Endianness {
    fn target() -> Self {
        #[cfg(target_endian = "big")]
        {
            Endianness::Big
        }
        #[cfg(not(target_endian = "big"))]
        {
            Endianness::Little
        }
    }
}

fn main() {
    println!("Word size: {} bytes", std::mem::size_of::<usize>());
    println!("Endianness: {:?}", Endianness::target());
}


Hostname

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

int main(void)
{
 char name[_POSIX_HOST_NAME_MAX + 1];
 return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}

fn main() {
    match hostname::get_hostname() {
        Some(host) => println!("hostname: {}", host),
        None => eprintln!("Could not get hostname!"),
    }
}


Huffman coding

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

#define BYTES 256

struct huffcode {
  int nbits;
  int code;
};
typedef struct huffcode huffcode_t;

struct huffheap {
  int *h;
  int n, s, cs;
  long *f;
};
typedef struct huffheap heap_t;

static heap_t *_heap_create(int s, long *f)
{
  heap_t *h;
  h = malloc(sizeof(heap_t));
  h->h = malloc(sizeof(int)*s);
  h->s = h->cs = s;
  h->n = 0;
  h->f = f;
  return h;
}

static void _heap_destroy(heap_t *heap)
{
  free(heap->h);
  free(heap);
}

#define swap_(I,J) do { int t_; t_ = a[(I)];	\
      a[(I)] = a[(J)]; a[(J)] = t_; } while(0)
static void _heap_sort(heap_t *heap)
{
  int i=1, j=2;
  int *a = heap->h;

  while(i < heap->n) {
    if ( heap->f[a[i-1]] >= heap->f[a[i]] ) {
      i = j; j++;
    } else {
      swap_(i-1, i);
      i--;
      i = (i==0) ? j++ : i;
    }
  }
}
#undef swap_

static void _heap_add(heap_t *heap, int c)
{
  if ( (heap->n + 1) > heap->s ) {
    heap->h = realloc(heap->h, heap->s + heap->cs);
    heap->s += heap->cs;
  }
  heap->h[heap->n] = c;
  heap->n++;
  _heap_sort(heap);
}

static int _heap_remove(heap_t *heap)
{
  if ( heap->n > 0 ) {
    heap->n--;
    return heap->h[heap->n];
  }
  return -1;
}

huffcode_t **create_huffman_codes(long *freqs)
{
  huffcode_t **codes;
  heap_t *heap;
  long efreqs[BYTES*2];
  int preds[BYTES*2];
  int i, extf=BYTES;
  int r1, r2;

  memcpy(efreqs, freqs, sizeof(long)*BYTES);
  memset(&efreqs[BYTES], 0, sizeof(long)*BYTES);

  heap = _heap_create(BYTES*2, efreqs);
  if ( heap == NULL ) return NULL;

  for(i=0; i < BYTES; i++) if ( efreqs[i] > 0 ) _heap_add(heap, i);

  while( heap->n > 1 )
  {
    r1 = _heap_remove(heap);
    r2 = _heap_remove(heap);
    efreqs[extf] = efreqs[r1] + efreqs[r2];
    _heap_add(heap, extf);
    preds[r1] = extf;
    preds[r2] = -extf;
    extf++;
  }
  r1 = _heap_remove(heap);
  preds[r1] = r1;
  _heap_destroy(heap);

  codes = malloc(sizeof(huffcode_t *)*BYTES);

  int bc, bn, ix;
  for(i=0; i < BYTES; i++) {
    bc=0; bn=0;
    if ( efreqs[i] == 0 ) { codes[i] = NULL; continue; }
    ix = i;
    while( abs(preds[ix]) != ix ) {
      bc |= ((preds[ix] >= 0) ? 1 : 0 ) << bn;
      ix = abs(preds[ix]);
      bn++;
    }
    codes[i] = malloc(sizeof(huffcode_t));
    codes[i]->nbits = bn;
    codes[i]->code = bc;
  }
  return codes;
}

void free_huffman_codes(huffcode_t **c)
{
  int i;

  for(i=0; i < BYTES; i++) free(c[i]);
  free(c);
}

#define MAXBITSPERCODE 100

void inttobits(int c, int n, char *s)
{
  s[n] = 0;
  while(n > 0) {
    s[n-1] = (c%2) + '0';
    c >>= 1; n--;
  }
}

const char *test = "this is an example for huffman encoding";

int main()
{
  huffcode_t **r;
  int i;
  char strbit[MAXBITSPERCODE];
  const char *p;
  long freqs[BYTES];

  memset(freqs, 0, sizeof freqs);

  p = test;
  while(*p != '\0') freqs[*p++]++;

  r = create_huffman_codes(freqs);

  for(i=0; i < BYTES; i++) {
    if ( r[i] != NULL ) {
      inttobits(r[i]->code, r[i]->nbits, strbit);
      printf("%c (%d) %s\n", i, r[i]->code, strbit);
    }
  }

  free_huffman_codes(r);

  return 0;
}

use std::collections::BTreeMap;
use std::collections::binary_heap::BinaryHeap;

#[derive(Debug, Eq, PartialEq)]
enum NodeKind {
    Internal(Box<Node>, Box<Node>),
    Leaf(char),
}

#[derive(Debug, Eq, PartialEq)]
struct Node {
    frequency: usize,
    kind: NodeKind,
}

impl Ord for Node {
    fn cmp(&self, rhs: &Self) -> std::cmp::Ordering {
        rhs.frequency.cmp(&self.frequency)
    }
}

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

type HuffmanCodeMap = BTreeMap<char, Vec<u8>>;

fn main() {
    let text = "this is an example for huffman encoding";

    let mut frequencies = BTreeMap::new();
    for ch in text.chars() {
        *frequencies.entry(ch).or_insert(0) += 1;
    }

    let mut prioritized_frequencies = BinaryHeap::new();
    for counted_char in frequencies {
        prioritized_frequencies.push(Node {
            frequency: counted_char.1,
            kind: NodeKind::Leaf(counted_char.0),
        });
    }

    while prioritized_frequencies.len() > 1 {
        let left_child = prioritized_frequencies.pop().unwrap();
        let right_child = prioritized_frequencies.pop().unwrap();
        prioritized_frequencies.push(Node {
            frequency: right_child.frequency + left_child.frequency,
            kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)),
        });
    }

    let mut codes = HuffmanCodeMap::new();
    generate_codes(
        prioritized_frequencies.peek().unwrap(),
        vec![0u8; 0],
        &mut codes,
    );

    for item in codes {
        print!("{}: ", item.0);
        for bit in item.1 {
            print!("{}", bit);
        }
        println!();
    }
}

fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) {
    match node.kind {
        NodeKind::Internal(ref left_child, ref right_child) => {
            let mut left_prefix = prefix.clone();
            left_prefix.push(0);
            generate_codes(&left_child, left_prefix, out_codes);

            let mut right_prefix = prefix;
            right_prefix.push(1);
            generate_codes(&right_child, right_prefix, out_codes);
        }
        NodeKind::Leaf(ch) => {
            out_codes.insert(ch, prefix);
        }
    }
}


ISBN13 check digit

fn main() {
    let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
    isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}

fn check_isbn(isbn: &str) -> bool {
    if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
            return false;
    }
    let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
        .zip([1, 3].iter().cycle())
        .fold(0, |acc, (val, fac)| acc + val * fac);
    checksum % 10 == 0
}


Identity matrix

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char** argv) {
   if (argc < 2) {
      printf("usage: identitymatrix <number of rows>\n");
      exit(EXIT_FAILURE);
   }
   int rowsize = atoi(argv[1]);
   if (rowsize < 0) {
      printf("Dimensions of matrix cannot be negative\n");
      exit(EXIT_FAILURE);
   }
   int numElements = rowsize * rowsize;
   if (numElements < rowsize) {
      printf("Squaring %d caused result to overflow to %d.\n", rowsize, numElements);
      abort();
   }
   int** matrix = calloc(numElements, sizeof(int*));
   if (!matrix) {
      printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int*));
      abort();
   }
   for (unsigned int row = 0;row < rowsize;row++) {
      matrix[row] = calloc(numElements, sizeof(int));
      if (!matrix[row]) {
         printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int));
         abort();
      }
      matrix[row][row] = 1;
   }
   printf("Matrix is: \n");
   for (unsigned int row = 0;row < rowsize;row++) {
      for (unsigned int column = 0;column < rowsize;column++) {
         printf("%d ", matrix[row][column]);
      }
      printf("\n");
   }
}

extern crate num;
struct Matrix<T> {
    data: Vec<T>,
    size: usize,
}

impl<T> Matrix<T>
where
    T: num::Num + Clone + Copy,
{
    fn new(size: usize) -> Self {
        Self {
            data: vec![T::zero(); size * size],
            size: size,
        }
    }
    fn get(&mut self, x: usize, y: usize) -> T {
        self.data[x + self.size * y]
    }
    fn identity(&mut self) {
        for (i, item) in self.data.iter_mut().enumerate() {
            *item = if i % (self.size + 1) == 0 {
                T::one()
            } else {
                T::zero()
            }
        }
    }
}

fn main() {
    let size = std::env::args().nth(1).unwrap().parse().unwrap();
    let mut matrix = Matrix::<i32>::new(size);
    matrix.identity();
    for y in 0..size {
        for x in 0..size {
            print!("{} ", matrix.get(x, y));
        }
        println!();
    }
}


Increment a numerical string

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

char * incr(char *s)
{
	int i, begin, tail, len;
	int neg = (*s == '-');
	char tgt = neg ? '0' : '9';

	if (!strcmp(s, "-1")) {
		s[0] = '0', s[1] = '\0';
		return s;
	}

	len = strlen(s);
	begin = (*s == '-' || *s == '+') ? 1 : 0;

	for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);

	if (tail < begin && !neg) {

		if (!begin) s = realloc(s, len + 2);
		s[0] = '1';
		for (i = 1; i <= len - begin; i++) s[i] = '0';
		s[len + 1] = '\0';
	} else if (tail == begin && neg && s[1] == '1') {

		for (i = 1; i < len - begin; i++) s[i] = '9';
		s[len - 1] = '\0';
	} else {
		for (i = len - 1; i > tail; i--)
			s[i] = neg ? '9' : '0';
		s[tail] += neg ? -1 : 1;
	}

	return s;
}

void string_test(const char *s)
{
	char *ret = malloc(strlen(s));
	strcpy(ret, s);

	printf("text: %s\n", ret);
	printf("  ->: %s\n", ret = incr(ret));
	free(ret);
}

int main()
{
	string_test("+0");
	string_test("-1");
	string_test("-41");
	string_test("+41");
	string_test("999");
	string_test("+999");
	string_test("109999999999999999999999999999999999999999");
	string_test("-100000000000000000000000000000000000000000000");

	return 0;
}

fn next_string(input: &str) -> String {
    (input.parse::<i64>().unwrap() + 1).to_string()
}

fn main() {
    let s = "-1";
    let s2 = next_string(s);
    println!("{:?}", s2);
}


Infinity

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

double inf(void) {
  return HUGE_VAL;
}

int main() {
  printf("%g\n", inf());
  return 0;
}

fn main() {
    let inf = f32::INFINITY;
    println!("{}", inf);
}


typedef struct{
	double focalLength;
	double resolution;
	double memory;
}Camera;

typedef struct{
	double balance;
	double batteryLevel;
	char** contacts;
}Phone;

typedef struct{
	Camera cameraSample;
	Phone phoneSample;
}CameraPhone;

trait Camera {}
trait MobilePhone {}
trait CameraPhone: Camera + MobilePhone {}


Input loop

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

char *get_line(FILE* fp)
{
	int len = 0, got = 0, c;
	char *buf = 0;

	while ((c = fgetc(fp)) != EOF) {
		if (got + 1 >= len) {
			len *= 2;
			if (len < 4) len = 4;
			buf = realloc(buf, len);
		}
		buf[got++] = c;
		if (c == '\n') break;
	}
	if (c == EOF && !got) return 0;

	buf[got++] = '\0';
	return buf;
}

int main()
{
	char *s;
	while ((s = get_line(stdin))) {
		printf("%s",s);
		free(s);
	}
	return 0;
}

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

fn main() {
    print_by_line(io::stdin())
        .expect("Could not read from stdin");

    File::open("/etc/fstab")
        .and_then(print_by_line)
        .expect("Could not read from file");
}

fn print_by_line<T: Read>(reader: T) -> io::Result<()> {
    let buffer = BufReader::new(reader);
    for line in buffer.lines() {
        println!("{}", line?)
    }
    Ok(())
}