name
stringlengths
2
74
C
stringlengths
7
6.19k
Rust
stringlengths
19
8.53k
Combinations
#include <stdio.h> typedef unsigned long marker; marker one = 1; void comb(int pool, int need, marker chosen, int at) { if (pool < need + at) return; if (!need) { for (at = 0; at < pool; at++) if (chosen & (one << at)) printf("%d ", at); printf("\n"); return; } comb(pool, need - 1, chosen | (one << at), at + 1); comb(pool, need, chosen, at + 1); } int main() { comb(5, 3, 0, 0); return 0; }
fn comb<T: std::fmt::Default>(arr: &[T], n: uint) { let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false); comb_intern(arr, n, incl_arr, 0); } fn comb_intern<T: std::fmt::Default>(arr: &[T], n: uint, incl_arr: &mut [bool], index: uint) { if (arr.len() < n + index) { return; } if (n == 0) { let mut it = arr.iter().zip(incl_arr.iter()).filter_map(|(val, incl)| if (*incl) { Some(val) } else { None } ); for val in it { print!("{} ", *val); } print("\n"); return; } incl_arr[index] = true; comb_intern(arr, n-1, incl_arr, index+1); incl_arr[index] = false; comb_intern(arr, n, incl_arr, index+1); } fn main() { let arr1 = ~[1, 2, 3, 4, 5]; comb(arr1, 3); let arr2 = ~["A", "B", "C", "D", "E"]; comb(arr2, 3); }
Combinations with repetitions
#include <stdio.h> const char *donuts[] = {"iced", "jam", "plain", "something completely different"}; int pos[] = {0, 0, 0, 0}; void printDonuts(int k) { for (size_t i = 1; i < k + 1; i += 1) printf("%s\t", donuts[pos[i]]); printf("\n"); } void combination_with_repetiton(int n, int k) { while (1) { for (int i = k; i > 0; i -= 1) { if (pos[i] > n - 1) { pos[i - 1] += 1; for (int j = i; j <= k; j += 1) pos[j] = pos[j - 1]; } } if (pos[0] > 0) break; printDonuts(k); pos[k] += 1; } } int main() { combination_with_repetiton(3, 2); return 0; }
struct CombinationsWithRepetitions<'a, T: 'a> { arr: &'a [T], k: u32, counts: Vec<u32>, remaining: bool, } impl<'a, T> CombinationsWithRepetitions<'a, T> { fn new(arr: &[T], k: u32) -> CombinationsWithRepetitions<T> { let mut counts = vec![0; arr.len()]; counts[arr.len() - 1] = k; CombinationsWithRepetitions { arr, k, counts, remaining: true, } } } impl<'a, T> Iterator for CombinationsWithRepetitions<'a, T> { type Item = Vec<&'a T>; fn next(&mut self) -> Option<Vec<&'a T>> { if !self.remaining { return None; } let mut comb = Vec::new(); for (count, item) in self.counts.iter().zip(self.arr.iter()) { for _ in 0..*count { comb.push(item); } } if self.counts[0] == self.k { self.remaining = false; } else { let n = self.counts.len(); for i in (1..n).rev() { if self.counts[i] > 0 { let original_value = self.counts[i]; self.counts[i - 1] += 1; for j in i..(n - 1) { self.counts[j] = 0; } self.counts[n - 1] = original_value - 1; break; } } } Some(comb) } } fn main() { let collection = vec!["iced", "jam", "plain"]; for comb in CombinationsWithRepetitions::new(&collection, 2) { for item in &comb { print!("{} ", item) } println!() } }
Comma quibbling
#include <stdio.h> #include <string.h> #include <stdlib.h> char *quib(const char **strs, size_t size) { size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0); size_t i; for (i = 0; i < size; i++) len += strlen(strs[i]); char *s = malloc(len * sizeof(*s)); if (!s) { perror("Can't allocate memory!\n"); exit(EXIT_FAILURE); } strcpy(s, "{"); switch (size) { case 0: break; case 1: strcat(s, strs[0]); break; default: for (i = 0; i < size - 1; i++) { strcat(s, strs[i]); if (i < size - 2) strcat(s, ", "); else strcat(s, " and "); } strcat(s, strs[i]); break; } strcat(s, "}"); return s; } int main(void) { const char *test[] = {"ABC", "DEF", "G", "H"}; char *s; for (size_t i = 0; i < 5; i++) { s = quib(test, i); printf("%s\n", s); free(s); } return EXIT_SUCCESS; }
fn quibble(seq: &[&str]) -> String { match seq.len() { 0 => "{}".to_string(), 1 => format!("{{{}}}", seq[0]), _ => { format!("{{{} and {}}}", seq[..seq.len() - 1].join(", "), seq.last().unwrap()) } } } fn main() { println!("{}", quibble(&[])); println!("{}", quibble(&["ABC"])); println!("{}", quibble(&["ABC", "DEF"])); println!("{}", quibble(&["ABC", "DEF", "G", "H"])); }
Command-line arguments
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
use std::env; fn main(){ let args: Vec<_> = env::args().collect(); println!("{:?}", args); }
Compare a list of strings
#include <stdbool.h> #include <string.h> static bool strings_are_equal(const char **strings, size_t nstrings) { for (size_t i = 1; i < nstrings; i++) if (strcmp(strings[0], strings[i]) != 0) return false; return true; } static bool strings_are_in_ascending_order(const char **strings, size_t nstrings) { for (size_t i = 1; i < nstrings; i++) if (strcmp(strings[i - 1], strings[i]) >= 0) return false; return true; }
fn strings_are_equal(seq: &[&str]) -> bool { match seq { &[] | &[_] => true, &[x, y, ref tail @ ..] if x == y => strings_are_equal(&[&[y], tail].concat()), _ => false } } fn asc_strings(seq: &[&str]) -> bool { match seq { &[] | &[_] => true, &[x, y, ref tail @ ..] if x < y => asc_strings(&[&[y], tail].concat()), _ => false } }
Compare length of two strings
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const int* a, const int* b) { return *b - *a; } void compareAndReportStringsLength(const char* strings[], const int n) { if (n > 0) { char* has_length = "has length"; char* predicate_max = "and is the longest string"; char* predicate_min = "and is the shortest string"; char* predicate_ave = "and is neither the longest nor the shortest string"; int* si = malloc(2 * n * sizeof(int)); if (si != NULL) { for (int i = 0; i < n; i++) { si[2 * i] = strlen(strings[i]); si[2 * i + 1] = i; } qsort(si, n, 2 * sizeof(int), cmp); int max = si[0]; int min = si[2 * (n - 1)]; for (int i = 0; i < n; i++) { int length = si[2 * i]; char* string = strings[si[2 * i + 1]]; char* predicate; if (length == max) predicate = predicate_max; else if (length == min) predicate = predicate_min; else predicate = predicate_ave; printf("\"%s\" %s %d %s\n", string, has_length, length, predicate); } free(si); } else { fputs("unable allocate memory buffer", stderr); } } } int main(int argc, char* argv[]) { char* list[] = { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(list, 4); return EXIT_SUCCESS; }
fn compare_and_report<T: ToString>(string1: T, string2: T) -> String { let strings = [string1.to_string(), string2.to_string()]; let difference = strings[0].len() as i32 - strings[1].len() as i32; if difference == 0 { format!("\"{}\" and \"{}\" are of equal length, {}", strings[0], strings[1], strings[0].len()) } else if difference > 1 { format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[0], strings[0].len(), strings[1], strings[1].len()) } else { format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[1], strings[1].len(), strings[0], strings[0].len()) } } fn main() { println!("{}", compare_and_report("a", "b")); println!("\n{}", compare_and_report("cd", "e")); println!("\n{}", compare_and_report("f", "gh")); }
Compile-time calculation
#include <stdio.h> #include <order/interpreter.h> #define ORDER_PP_DEF_8fac ORDER_PP_FN( \ 8fn(8X, 8seq_fold(8times, 1, 8seq_iota(1, 8inc(8X)))) ) int main(void) { printf("10! = %d\n", ORDER_PP( 8to_lit( 8fac(10) ) ) ); return 0; }
fn factorial(n: i64) -> i64 { let mut total = 1; for i in 1..n+1 { total *= i; } return total; } fn main() { println!("Factorial of 10 is {}.", factorial(10)); }
Compound data type
typedef struct Point { int x; int y; } Point;
struct Point<T> { x: T, y: T, } fn main() { let p = Point { x: 1.0, y: 2.5 }; println!("{}, {}", p.x, p.y); }
Concurrent computing
#include <stdio.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t condm = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int bang = 0; #define WAITBANG() do { \ pthread_mutex_lock(&condm); \ while( bang == 0 ) \ { \ pthread_cond_wait(&cond, &condm); \ } \ pthread_mutex_unlock(&condm); } while(0);\ void *t_enjoy(void *p) { WAITBANG(); printf("Enjoy\n"); pthread_exit(0); } void *t_rosetta(void *p) { WAITBANG(); printf("Rosetta\n"); pthread_exit(0); } void *t_code(void *p) { WAITBANG(); printf("Code\n"); pthread_exit(0); } typedef void *(*threadfunc)(void *); int main() { int i; pthread_t a[3]; threadfunc p[3] = {t_enjoy, t_rosetta, t_code}; for(i=0;i<3;i++) { pthread_create(&a[i], NULL, p[i], NULL); } sleep(1); bang = 1; pthread_cond_broadcast(&cond); for(i=0;i<3;i++) { pthread_join(a[i], NULL); } }
extern crate rand; use std::thread; use rand::thread_rng; use rand::distributions::{Range, IndependentSample}; fn main() { let mut rng = thread_rng(); let rng_range = Range::new(0u32, 100); for word in "Enjoy Rosetta Code".split_whitespace() { let snooze_time = rng_range.ind_sample(&mut rng); let local_word = word.to_owned(); std::thread::spawn(move || { thread::sleep_ms(snooze_time); println!("{}", local_word); }); } thread::sleep_ms(1000); }
Conditional structures
int a = 3; if (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } unless (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } switch (a) { case 2: puts ("a is 2"); break; case 3: puts ("a is 3"); break; case 4: puts ("a is 4"); break; default: puts("is neither"); }
#[cfg(target_os = "linux")] fn running_linux() { println!("This is linux"); } #[cfg(not(target_os = "linux"))] fn running_linux() { println!("This is not linux"); } #[cfg_attr(target_os = "linux", target_env = "gnu")] #[cfg(all( any(target_arch = "arm", target_endian = "little"), not(target_pointer_width = "32"), unix, test ))] fn highly_specific_function() {}
Constrained random points on a circle
#include <stdio.h> #include <stdlib.h> inline int randn(int m) { int rand_max = RAND_MAX - (RAND_MAX % m); int r; while ((r = rand()) > rand_max); return r / (rand_max / m); } int main() { int i, x, y, r2; unsigned long buf[31] = {0}; for (i = 0; i < 100; ) { x = randn(31) - 15; y = randn(31) - 15; r2 = x * x + y * y; if (r2 >= 100 && r2 <= 225) { buf[15 + y] |= 1 << (x + 15); i++; } } for (y = 0; y < 31; y++) { for (x = 0; x < 31; x++) printf((buf[y] & 1 << x) ? ". " : " "); printf("\n"); } return 0; }
extern crate rand; use rand::Rng; const POINTS_N: usize = 100; fn generate_point<R: Rng>(rng: &mut R) -> (i32, i32) { loop { let x = rng.gen_range(-15, 16); let y = rng.gen_range(-15, 16); let r2 = x * x + y * y; if r2 >= 100 && r2 <= 225 { return (x, y); } } } fn filtering_method<R: Rng>(rng: &mut R) { let mut rows = [[" "; 62]; 31]; for _ in 0..POINTS_N { let (x, y) = generate_point(rng); rows[(y + 15) as usize][(x + 15) as usize * 2] = "*"; } for row in &rows { println!("{}", row.concat()); } } fn precalculating_method<R: Rng>(rng: &mut R) { let mut possible_points = Vec::with_capacity(404); for y in -15..=15 { for x in -15..=15 { let r2 = x * x + y * y; if r2 >= 100 && r2 <= 225 { possible_points.push((x, y)); } } } let len = possible_points.len(); for i in (len - POINTS_N..len).rev() { let j = rng.gen_range(0, i + 1); possible_points.swap(i, j); } let mut rows = [[" "; 62]; 31]; for &(x, y) in &possible_points[len - POINTS_N..] { rows[(y + 15) as usize][(x + 15) as usize * 2] = "*"; } for row in &rows { println!("{}", row.concat()); } } fn main() { let mut rng = rand::weak_rng(); filtering_method(&mut rng); precalculating_method(&mut rng); }
Continued fraction
#include <stdio.h> typedef double (*coeff_func)(unsigned n); double calc(coeff_func f_a, coeff_func f_b, unsigned expansions) { double a, b, r; a = b = r = 0.0; unsigned i; for (i = expansions; i > 0; i--) { a = f_a(i); b = f_b(i); r = b / (a + r); } a = f_a(0); return a + r; } double sqrt2_a(unsigned n) { return n ? 2.0 : 1.0; } double sqrt2_b(unsigned n) { return 1.0; } double napier_a(unsigned n) { return n ? n : 2.0; } double napier_b(unsigned n) { return n > 1.0 ? n - 1.0 : 1.0; } double pi_a(unsigned n) { return n ? 6.0 : 3.0; } double pi_b(unsigned n) { double c = 2.0 * n - 1.0; return c * c; } int main(void) { double sqrt2, napier, pi; sqrt2 = calc(sqrt2_a, sqrt2_b, 1000); napier = calc(napier_a, napier_b, 1000); pi = calc(pi_a, pi_b, 1000); printf("%12.10g\n%12.10g\n%12.10g\n", sqrt2, napier, pi); return 0; }
use std::iter; macro_rules! continued_fraction { ($a:expr, $b:expr ; $iterations:expr) => ( ($a).zip($b) .take($iterations) .collect::<Vec<_>>().iter() .rev() .fold(0 as f64, |acc: f64, &(x, y)| { x as f64 + (y as f64 / acc) }) ); ($a:expr, $b:expr) => (continued_fraction!($a, $b ; 1000)); } fn main() { let sqrt2a = (1..2).chain(iter::repeat(2)); let sqrt2b = iter::repeat(1); println!("{}", continued_fraction!(sqrt2a, sqrt2b)); let napiera = (2..3).chain(1..); let napierb = (1..2).chain(1..); println!("{}", continued_fraction!(napiera, napierb)); let pia = (3..4).chain(iter::repeat(6)); let pib = (1i64..).map(|x| (2 * x - 1).pow(2)); println!("{}", continued_fraction!(pia, pib)); }
Continued fraction_Arithmetic_Construct from rational number
#include<stdio.h> typedef struct{ int num,den; }fraction; fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}}; fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}}; int r2cf(int *numerator,int *denominator) { int quotient=0,temp; if(denominator != 0) { quotient = *numerator / *denominator; temp = *numerator; *numerator = *denominator; *denominator = temp % *denominator; } return quotient; } int main() { int i; printf("Running the examples :"); for(i=0;i<sizeof(examples)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",examples[i].num,examples[i].den); while(examples[i].den != 0){ printf(" %d ",r2cf(&examples[i].num,&examples[i].den)); } } printf("\n\nRunning for %c2 :",251); for(i=0;i<sizeof(sqrt2)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",sqrt2[i].num,sqrt2[i].den); while(sqrt2[i].den != 0){ printf(" %d ",r2cf(&sqrt2[i].num,&sqrt2[i].den)); } } printf("\n\nRunning for %c :",227); for(i=0;i<sizeof(pi)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",pi[i].num,pi[i].den); while(pi[i].den != 0){ printf(" %d ",r2cf(&pi[i].num,&pi[i].den)); } } return 0; }
struct R2cf { n1: i64, n2: i64 } impl Iterator for R2cf { type Item = i64; fn next(&mut self) -> Option<i64> { if self.n2 == 0 { None } else { let t1 = self.n1 / self.n2; let t2 = self.n2; self.n2 = self.n1 - t1 * t2; self.n1 = t2; Some(t1) } } } fn r2cf(n1: i64, n2: i64) -> R2cf { R2cf { n1: n1, n2: n2 } } macro_rules! printcf { ($x:expr, $y:expr) => (println!("{:?}", r2cf($x, $y).collect::<Vec<_>>())); } fn main() { printcf!(1, 2); printcf!(3, 1); printcf!(23, 8); printcf!(13, 11); printcf!(22, 7); printcf!(-152, 77); printcf!(14_142, 10_000); printcf!(141_421, 100_000); printcf!(1_414_214, 1_000_000); printcf!(14_142_136, 10_000_000); printcf!(31, 10); printcf!(314, 100); printcf!(3142, 1000); printcf!(31_428, 10_000); printcf!(314_285, 100_000); printcf!(3_142_857, 1_000_000); printcf!(31_428_571, 10_000_000); printcf!(314_285_714, 100_000_000); }
Convert seconds to compound duration
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> char* seconds2string(unsigned long seconds) { int i; const unsigned long s = 1; const unsigned long m = 60 * s; const unsigned long h = 60 * m; const unsigned long d = 24 * h; const unsigned long w = 7 * d; const unsigned long coeff[5] = { w, d, h, m, s }; const char units[5][4] = { "wk", "d", "hr", "min", "sec" }; static char buffer[256]; char* ptr = buffer; for ( i = 0; i < 5; i++ ) { unsigned long value; value = seconds / coeff[i]; seconds = seconds % coeff[i]; if ( value ) { if ( ptr != buffer ) ptr += sprintf(ptr, ", "); ptr += sprintf(ptr,"%lu %s",value,units[i]); } } return buffer; } int main(int argc, char argv[]) { unsigned long seconds; if ( (argc < 2) && scanf( "%lu", &seconds ) || (argc >= 2) && sscanf( argv[1], "%lu", & seconds ) ) { printf( "%s\n", seconds2string(seconds) ); return EXIT_SUCCESS; } return EXIT_FAILURE; }
use std::fmt; struct CompoundTime { w: usize, d: usize, h: usize, m: usize, s: usize, } macro_rules! reduce { ($s: ident, $(($from: ident, $to: ident, $factor: expr)),+) => {{ $( $s.$to += $s.$from / $factor; $s.$from %= $factor; )+ }} } impl CompoundTime { #[inline] fn new(w: usize, d: usize, h: usize, m: usize, s: usize) -> Self{ CompoundTime { w: w, d: d, h: h, m: m, s: s, } } #[inline] fn balance(&mut self) { reduce!(self, (s, m, 60), (m, h, 60), (h, d, 24), (d, w, 7)); } } impl fmt::Display for CompoundTime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}w {}d {}h {}m {}s", self.w, self.d, self.h, self.m, self.s) } } fn main() { let mut ct = CompoundTime::new(0,3,182,345,2412); println!("Before: {}", ct); ct.balance(); println!("After: {}", ct); }
Convex hull
#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct tPoint { int x, y; } Point; bool ccw(const Point *a, const Point *b, const Point *c) { return (b->x - a->x) * (c->y - a->y) > (b->y - a->y) * (c->x - a->x); } int comparePoints(const void *lhs, const void *rhs) { const Point* lp = lhs; const Point* rp = rhs; if (lp->x < rp->x) return -1; if (rp->x < lp->x) return 1; if (lp->y < rp->y) return -1; if (rp->y < lp->y) return 1; return 0; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void printPoints(const Point* points, int len) { printf("["); if (len > 0) { const Point* ptr = points; const Point* end = points + len; printf("(%d, %d)", ptr->x, ptr->y); ++ptr; for (; ptr < end; ++ptr) printf(", (%d, %d)", ptr->x, ptr->y); } printf("]"); } Point* convexHull(Point p[], int len, int* hsize) { if (len == 0) { *hsize = 0; return NULL; } int i, size = 0, capacity = 4; Point* hull = xmalloc(capacity * sizeof(Point)); qsort(p, len, sizeof(Point), comparePoints); for (i = 0; i < len; ++i) { while (size >= 2 && !ccw(&hull[size - 2], &hull[size - 1], &p[i])) --size; if (size == capacity) { capacity *= 2; hull = xrealloc(hull, capacity * sizeof(Point)); } assert(size >= 0 && size < capacity); hull[size++] = p[i]; } int t = size + 1; for (i = len - 1; i >= 0; i--) { while (size >= t && !ccw(&hull[size - 2], &hull[size - 1], &p[i])) --size; if (size == capacity) { capacity *= 2; hull = xrealloc(hull, capacity * sizeof(Point)); } assert(size >= 0 && size < capacity); hull[size++] = p[i]; } --size; assert(size >= 0); hull = xrealloc(hull, size * sizeof(Point)); *hsize = size; return hull; } int main() { Point points[] = { {16, 3}, {12, 17}, { 0, 6}, {-4, -6}, {16, 6}, {16, -7}, {16, -3}, {17, -4}, { 5, 19}, {19, -8}, { 3, 16}, {12, 13}, { 3, -4}, {17, 5}, {-3, 15}, {-3, -9}, { 0, 11}, {-9, -3}, {-4, -2}, {12, 10} }; int hsize; Point* hull = convexHull(points, sizeof(points)/sizeof(Point), &hsize); printf("Convex Hull: "); printPoints(hull, hsize); printf("\n"); free(hull); return 0; }
#[derive(Debug, Clone)] struct Point { x: f32, y: f32 } fn calculate_convex_hull(points: &Vec<Point>) -> Vec<Point> { if points.len() < 3 { return points.clone(); } let mut hull = vec![]; let (left_most_idx, _) = points.iter() .enumerate() .min_by(|lhs, rhs| lhs.1.x.partial_cmp(&rhs.1.x).unwrap()) .expect("No left most point"); let mut p = left_most_idx; let mut q = 0_usize; loop { hull.push(points[p].clone()); q = (p + 1) % points.len(); for i in 0..points.len() { if orientation(&points[p], &points[i], &points[q]) == 2 { q = i; } } p = q; if p == left_most_idx { break; } } return hull; } fn orientation(p: &Point, q: &Point, r: &Point) -> usize { let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if val == 0. { return 0 }; if val > 0. { return 1; } else { return 2; } } fn main(){ let points = vec![pt(16,3), pt(12,17), pt(0,6), pt(-4,-6), pt(16,6), pt(16,-7), pt(16,-3), pt(17,-4), pt(5,19), pt(19,-8), pt(3,16), pt(12,13), pt(3,-4), pt(17,5), pt(-3,15), pt(-3,-9), pt(0,11), pt(-9,-3), pt(-4,-2), pt(12,10)]; let hull = calculate_convex_hull(&points); hull.iter() .for_each(|pt| println!("{:?}", pt)); } fn pt(x: i32, y: i32) -> Point { return Point {x:x as f32, y:y as f32}; }
Conway's Game of Life
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #define for_x for (int x = 0; x < w; x++) #define for_y for (int y = 0; y < h; y++) #define for_xy for_x for_y void show(void *u, int w, int h) { int (*univ)[w] = u; printf("\033[H"); for_y { for_x printf(univ[y][x] ? "\033[07m \033[m" : " "); printf("\033[E"); } fflush(stdout); } void evolve(void *u, int w, int h) { unsigned (*univ)[w] = u; unsigned new[h][w]; for_y for_x { int n = 0; for (int y1 = y - 1; y1 <= y + 1; y1++) for (int x1 = x - 1; x1 <= x + 1; x1++) if (univ[(y1 + h) % h][(x1 + w) % w]) n++; if (univ[y][x]) n--; new[y][x] = (n == 3 || (n == 2 && univ[y][x])); } for_y for_x univ[y][x] = new[y][x]; } void game(int w, int h) { unsigned univ[h][w]; for_xy univ[y][x] = rand() < RAND_MAX / 10 ? 1 : 0; while (1) { show(univ, w, h); evolve(univ, w, h); usleep(200000); } } int main(int c, char **v) { int w = 0, h = 0; if (c > 1) w = atoi(v[1]); if (c > 2) h = atoi(v[2]); if (w <= 0) w = 30; if (h <= 0) h = 30; game(w, h); }
use std::collections::HashMap; use std::collections::HashSet; type Cell = (i32, i32); type Colony = HashSet<Cell>; fn print_colony(col: &Colony, width: i32, height: i32) { for y in 0..height { for x in 0..width { print!("{} ", if col.contains(&(x, y)) {"O"} else {"."} ); } println!(); } } fn neighbours(&(x,y): &Cell) -> Vec<Cell> { vec![ (x-1,y-1), (x,y-1), (x+1,y-1), (x-1,y), (x+1,y), (x-1,y+1), (x,y+1), (x+1,y+1), ] } fn neighbour_counts(col: &Colony) -> HashMap<Cell, i32> { let mut ncnts = HashMap::new(); for cell in col.iter().flat_map(neighbours) { *ncnts.entry(cell).or_insert(0) += 1; } ncnts } fn generation(col: Colony) -> Colony { neighbour_counts(&col) .into_iter() .filter_map(|(cell, cnt)| match (cnt, col.contains(&cell)) { (2, true) | (3, ..) => Some(cell), _ => None }) .collect() } fn life(init: Vec<Cell>, iters: i32, width: i32, height: i32) { let mut col: Colony = init.into_iter().collect(); for i in 0..iters+1 { println!("({})", &i); if i != 0 { col = generation(col); } print_colony(&col, width, height); } } fn main() { let blinker = vec![ (1,0), (1,1), (1,2)]; life(blinker, 3, 3, 3); let glider = vec![ (1,0), (2,1), (0,2), (1,2), (2,2)]; life(glider, 20, 8, 8); }
Copy stdin to stdout
#include <stdio.h> int main(){ char c; while ( (c=getchar()) != EOF ){ putchar(c); } return 0; }
use std::io; fn main() { io::copy(&mut io::stdin().lock(), &mut io::stdout().lock()); }
Count in factors
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ULONG; ULONG get_prime(int idx) { static long n_primes = 0, alloc = 0; static ULONG *primes = 0; ULONG last, p; int i; if (idx >= n_primes) { if (n_primes >= alloc) { alloc += 16; primes = realloc(primes, sizeof(ULONG) * alloc); } if (!n_primes) { primes[0] = 2; primes[1] = 3; n_primes = 2; } last = primes[n_primes-1]; while (idx >= n_primes) { last += 2; for (i = 0; i < n_primes; i++) { p = primes[i]; if (p * p > last) { primes[n_primes++] = last; break; } if (last % p == 0) break; } } } return primes[idx]; } int main() { ULONG n, x, p; int i, first; for (x = 1; ; x++) { printf("%lld = ", n = x); for (i = 0, first = 1; ; i++) { p = get_prime(i); while (n % p == 0) { n /= p; if (!first) printf(" x "); first = 0; printf("%lld", p); } if (n <= p * p) break; } if (first) printf("%lld\n", n); else if (n > 1) printf(" x %lld\n", n); else printf("\n"); } return 0; }
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![n] }
Count in octal
#include <stdio.h> int main() { unsigned int i = 0; do { printf("%o\n", i++); } while(i); return 0; }
fn main() { for i in 0..std::usize::MAX { println!("{:o}", i); } }
Count the coins
#include <stdio.h> #include <stdlib.h> #include <stdint.h> typedef struct { uint64_t x[2]; } i128; void show(i128 v) { uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32}; int i, j = 0, len = 4; char buf[100]; do { uint64_t c = 0; for (i = len; i--; ) { c = (c << 32) + x[i]; x[i] = c / 10, c %= 10; } buf[j++] = c + '0'; for (len = 4; !x[len - 1]; len--); } while (len); while (j--) putchar(buf[j]); putchar('\n'); } i128 count(int sum, int *coins) { int n, i, k; for (n = 0; coins[n]; n++); i128 **v = malloc(sizeof(int*) * n); int *idx = malloc(sizeof(int) * n); for (i = 0; i < n; i++) { idx[i] = coins[i]; v[i] = calloc(sizeof(i128), coins[i]); } v[0][coins[0] - 1] = (i128) {{1, 0}}; for (k = 0; k <= sum; k++) { for (i = 0; i < n; i++) if (!idx[i]--) idx[i] = coins[i] - 1; i128 c = v[0][ idx[0] ]; for (i = 1; i < n; i++) { i128 *p = v[i] + idx[i]; p->x[0] += c.x[0]; p->x[1] += c.x[1]; if (p->x[0] < c.x[0]) p->x[1] ++; c = *p; } } i128 r = v[n - 1][idx[n-1]]; for (i = 0; i < n; i++) free(v[i]); free(v); free(idx); return r; } int count2(int sum, int *coins) { if (!*coins || sum < 0) return 0; if (!sum) return 1; return count2(sum - *coins, coins) + count2(sum, coins + 1); } int main(void) { int us_coins[] = { 100, 50, 25, 10, 5, 1, 0 }; int eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 }; show(count( 100, us_coins + 2)); show(count( 1000, us_coins)); show(count( 1000 * 100, us_coins)); show(count( 10000 * 100, us_coins)); show(count(100000 * 100, us_coins)); putchar('\n'); show(count( 1 * 100, eu_coins)); show(count( 1000 * 100, eu_coins)); show(count( 10000 * 100, eu_coins)); show(count(100000 * 100, eu_coins)); return 0; }
fn make_change(coins: &[usize], cents: usize) -> usize { let size = cents + 1; let mut ways = vec![0; size]; ways[0] = 1; for &coin in coins { for amount in coin..size { ways[amount] += ways[amount - coin]; } } ways[cents] } fn main() { println!("{}", make_change(&[1,5,10,25], 100)); println!("{}", make_change(&[1,5,10,25,50,100], 100_000)); }
Cramer's rule
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct { int n; double **elems; } SquareMatrix; SquareMatrix init_square_matrix(int n, double elems[n][n]) { SquareMatrix A = { .n = n, .elems = malloc(n * sizeof(double *)) }; for(int i = 0; i < n; ++i) { A.elems[i] = malloc(n * sizeof(double)); for(int j = 0; j < n; ++j) A.elems[i][j] = elems[i][j]; } return A; } SquareMatrix copy_square_matrix(SquareMatrix src) { SquareMatrix dest; dest.n = src.n; dest.elems = malloc(dest.n * sizeof(double *)); for(int i = 0; i < dest.n; ++i) { dest.elems[i] = malloc(dest.n * sizeof(double)); for(int j = 0; j < dest.n; ++j) dest.elems[i][j] = src.elems[i][j]; } return dest; } double det(SquareMatrix A) { double det = 1; for(int j = 0; j < A.n; ++j) { int i_max = j; for(int i = j; i < A.n; ++i) if(A.elems[i][j] > A.elems[i_max][j]) i_max = i; if(i_max != j) { for(int k = 0; k < A.n; ++k) { double tmp = A.elems[i_max][k]; A.elems[i_max][k] = A.elems[j][k]; A.elems[j][k] = tmp; } det *= -1; } if(abs(A.elems[j][j]) < 1e-12) { puts("Singular matrix!"); return NAN; } for(int i = j + 1; i < A.n; ++i) { double mult = -A.elems[i][j] / A.elems[j][j]; for(int k = 0; k < A.n; ++k) A.elems[i][k] += mult * A.elems[j][k]; } } for(int i = 0; i < A.n; ++i) det *= A.elems[i][i]; return det; } void deinit_square_matrix(SquareMatrix A) { for(int i = 0; i < A.n; ++i) free(A.elems[i]); free(A.elems); } double cramer_solve(SquareMatrix A, double det_A, double *b, int var) { SquareMatrix tmp = copy_square_matrix(A); for(int i = 0; i < tmp.n; ++i) tmp.elems[i][var] = b[i]; double det_tmp = det(tmp); deinit_square_matrix(tmp); return det_tmp / det_A; } int main(int argc, char **argv) { #define N 4 double elems[N][N] = { { 2, -1, 5, 1}, { 3, 2, 2, -6}, { 1, 3, 3, -1}, { 5, -2, -3, 3} }; SquareMatrix A = init_square_matrix(N, elems); SquareMatrix tmp = copy_square_matrix(A); int det_A = det(tmp); deinit_square_matrix(tmp); double b[] = {-3, -32, -47, 49}; for(int i = 0; i < N; ++i) printf("%7.3lf\n", cramer_solve(A, det_A, b, i)); deinit_square_matrix(A); return EXIT_SUCCESS; }
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
Create a file
#include <stdio.h> int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh); return 0; }
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
Create a two-dimensional array at runtime
#include <stdio.h> int main(int argc, char **argv) { int user1 = 0, user2 = 0; printf("Enter two integers. Space delimited, please: "); scanf("%d %d",&user1, &user2); int array[user1][user2]; array[user1/2][user2/2] = user1 + user2; printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]); return 0; }
use std::env; fn main() { let mut args = env::args().skip(1).flat_map(|num| num.parse()); let rows = args.next().expect("Expected number of rows as first argument"); let cols = args.next().expect("Expected number of columns as second argument"); assert_ne!(rows, 0, "rows were zero"); assert_ne!(cols, 0, "cols were zero"); let mut v = vec![vec![0; cols]; rows]; v[0][0] = 1; println!("{}", v[0][0]); }
Create an HTML table
#include <stdio.h> #include <stdlib.h> int main() { int i; printf("<table style=\"text-align:center; border: 1px solid\"><th></th>" "<th>X</th><th>Y</th><th>Z</th>"); for (i = 0; i < 4; i++) { printf("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>", i, rand() % 10000, rand() % 10000, rand() % 10000); } printf("</table>"); return 0; }
extern crate rand; use rand::Rng; fn random_cell<R: Rng>(rng: &mut R) -> u32 { rng.gen_range(0, 10_000) } fn main() { let mut rng = rand::thread_rng(); println!("<table><thead><tr><th></th><td>X</td><td>Y</td><td>Z</td></tr></thead>"); for row in 0..3 { let x = random_cell(&mut rng); let y = random_cell(&mut rng); let z = random_cell(&mut rng); println!("<tr><th>{}</th><td>{}</td><td>{}</td><td>{}</td></tr>", row, x, y, z); } println!("</table>"); }
Cumulative standard deviation
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef enum Action { STDDEV, MEAN, VAR, COUNT } Action; typedef struct stat_obj_struct { double sum, sum2; size_t num; Action action; } sStatObject, *StatObject; StatObject NewStatObject( Action action ) { StatObject so; so = malloc(sizeof(sStatObject)); so->sum = 0.0; so->sum2 = 0.0; so->num = 0; so->action = action; return so; } #define FREE_STAT_OBJECT(so) \ free(so); so = NULL double stat_obj_value(StatObject so, Action action) { double num, mean, var, stddev; if (so->num == 0.0) return 0.0; num = so->num; if (action==COUNT) return num; mean = so->sum/num; if (action==MEAN) return mean; var = so->sum2/num - mean*mean; if (action==VAR) return var; stddev = sqrt(var); if (action==STDDEV) return stddev; return 0; } double stat_object_add(StatObject so, double v) { so->num++; so->sum += v; so->sum2 += v*v; return stat_obj_value(so, so->action); }
pub struct CumulativeStandardDeviation { n: f64, sum: f64, sum_sq: f64 } impl CumulativeStandardDeviation { pub fn new() -> Self { CumulativeStandardDeviation { n: 0., sum: 0., sum_sq: 0. } } fn push(&mut self, x: f64) -> f64 { self.n += 1.; self.sum += x; self.sum_sq += x * x; (self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt() } } fn main() { let nums = [2, 4, 4, 4, 5, 5, 7, 9]; let mut cum_stdev = CumulativeStandardDeviation::new(); for num in nums.iter() { println!("{}", cum_stdev.push(*num as f64)); } }
Currency
mpf_set_d(burgerUnitPrice,5.50); mpf_set_d(milkshakePrice,2 * 2.86); mpf_set_d(burgerNum,4000000000000000); mpf_set_d(milkshakeNum,2);
extern crate num_bigint; extern crate num_rational; use num_bigint::BigInt; use num_rational::BigRational; use std::ops::{Add, Mul}; use std::fmt; fn main() { let hamburger = Currency::new(5.50); let milkshake = Currency::new(2.86); let pre_tax = hamburger * 4_000_000_000_000_000 + milkshake * 2; println!("Price before tax: {}", pre_tax); let tax = pre_tax.calculate_tax(); println!("Tax: {}", tax); let post_tax = pre_tax + tax; println!("Price after tax: {}", post_tax); } #[derive(Debug)] struct Currency { amount: BigRational, } impl Add for Currency { type Output = Self; fn add(self, other: Self) -> Self { Self { amount: self.amount + other.amount, } } } impl Mul<u64> for Currency { type Output = Self; fn mul(self, other: u64) -> Self { Self { amount: self.amount * BigInt::from(other), } } } impl fmt::Display for Currency { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let cents = (&self.amount * BigInt::from(100)).to_integer(); write!(f, "${}.{}", &cents / 100, &cents % 100) } } impl Currency { fn new(num: f64) -> Self { Self { amount: BigRational::new(((num * 100.0) as i64).into(), 100.into()) } } fn calculate_tax(&self) -> Self { let tax_val = BigRational::new(765.into(), 100.into()); let amount = (&self.amount * tax_val).ceil() / BigInt::from(100); Self { amount } } }
Currying
#include<stdarg.h> #include<stdio.h> long int factorial(int n){ if(n>1) return n*factorial(n-1); return 1; } long int sumOfFactorials(int num,...){ va_list vaList; long int sum = 0; va_start(vaList,num); while(num--) sum += factorial(va_arg(vaList,int)); va_end(vaList); return sum; } int main() { printf("\nSum of factorials of [1,5] : %ld",sumOfFactorials(5,1,2,3,4,5)); printf("\nSum of factorials of [3,5] : %ld",sumOfFactorials(3,3,4,5)); printf("\nSum of factorials of [1,3] : %ld",sumOfFactorials(3,1,2,3)); return 0; }
fn add_n(n : i32) -> impl Fn(i32) -> i32 { move |x| n + x } fn main() { let adder = add_n(40); println!("The answer to life is {}.", adder(2)); }
DNS query
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
use std::net::ToSocketAddrs; fn main() { let host = "www.kame.net"; let host_port = (host, 0); let ip_iter = host_port.to_socket_addrs().unwrap(); for ip_port in ip_iter { println!("{}", ip_port.ip()); } }
Damm algorithm
#include <stdbool.h> #include <stddef.h> #include <stdio.h> bool damm(unsigned char *input, size_t length) { static const unsigned char table[10][10] = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; unsigned char interim = 0; for (size_t i = 0; i < length; i++) { interim = table[interim][input[i]]; } return interim == 0; } int main() { unsigned char input[4] = {5, 7, 2, 4}; puts(damm(input, 4) ? "Checksum correct" : "Checksum incorrect"); return 0; }
fn damm(number: &str) -> u8 { static TABLE: [[u8; 10]; 10] = [ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2], [7, 0, 9, 2, 1, 5, 4, 8, 6, 3], [4, 2, 0, 6, 8, 7, 1, 3, 5, 9], [1, 7, 5, 0, 9, 8, 3, 4, 2, 6], [6, 1, 2, 3, 0, 4, 5, 9, 7, 8], [3, 6, 7, 4, 2, 0, 9, 5, 8, 1], [5, 8, 6, 9, 7, 2, 0, 1, 3, 4], [8, 9, 4, 5, 3, 6, 2, 0, 1, 7], [9, 4, 3, 8, 6, 1, 7, 2, 0, 5], [2, 5, 8, 1, 4, 3, 6, 7, 9, 0], ]; number.chars().fold(0, |row, digit| { let digit = digit.to_digit(10).unwrap(); TABLE[row as usize][digit as usize] }) } fn damm_validate(number: &str) -> bool { damm(number) == 0 } fn main() { let numbers = &["5724", "5727", "112946"]; for number in numbers { let is_valid = damm_validate(number); if is_valid { println!("{:>6} is valid", number); } else { println!("{:>6} is invalid", number); } } }
Date format
#include <stdlib.h> #include <stdio.h> #include <time.h> #define MAX_BUF 50 int main(void) { char buf[MAX_BUF]; time_t seconds = time(NULL); struct tm *now = localtime(&seconds); const char *months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday"}; (void) printf("%d-%d-%d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday); (void) printf("%s, %s %d, %d\n",days[now->tm_wday], months[now->tm_mon], now->tm_mday, now->tm_year + 1900); (void) strftime(buf, MAX_BUF, "%A, %B %e, %Y", now); (void) printf("%s\n", buf); return EXIT_SUCCESS; }
fn main() { let now = chrono::Utc::now(); println!("{}", now.format("%Y-%m-%d")); println!("{}", now.format("%A, %B %d, %Y")); }
Date manipulation
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST"; strptime(d, "%B %d %Y %I:%M%p %Z", &ts); t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); return EXIT_SUCCESS; }
use chrono::prelude::*; use chrono::Duration; fn main() { let ndt = NaiveDateTime::parse_from_str("March 7 2009 7:30pm EST", "%B %e %Y %l:%M%P %Z").unwrap(); let dt = chrono_tz::EST.from_local_datetime(&ndt).unwrap(); println!("Date parsed: {:?}", dt); let new_date = dt + Duration::hours(12); println!("+12 hrs in EST: {:?}", new_date); println!( "+12 hrs in CET: {:?}", new_date.with_timezone(&chrono_tz::CET) ); }
Day of the week
#include <stdio.h> int wday(int year, int month, int day) { int adjustment, mm, yy; adjustment = (14 - month) / 12; mm = month + 12 * adjustment - 2; yy = year - adjustment; return (day + (13 * mm - 1) / 5 + yy + yy / 4 - yy / 100 + yy / 400) % 7; } int main() { int y; for (y = 2008; y <= 2121; y++) { if (wday(y, 12, 25) == 0) printf("%04d-12-25\n", y); } return 0; }
extern crate chrono; use chrono::prelude::*; fn main() { let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::<Vec<i32>>(); println!("Years = {:?}", years); }
Days between dates
#include<stdbool.h> #include<string.h> #include<stdio.h> typedef struct{ int year, month, day; }date; date extractDate(char* str){ return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')}; } bool isValidDate(char* str){ date newDate; if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){ return false; } newDate = extractDate(str); if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) || ((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) || newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){ return false; } return true; } int diffDays(date date1,date date2){ int days1, days2; date1.month = (date1.month + 9)%12; date1.year = date1.year - date1.month/10; date2.month = (date2.month + 9)%12; date2.year = date2.year - date2.month/10; days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 ); days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 ); return days2 - days1; } int main(int argc,char** argv) { if(argc!=3){ return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]); } if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){ return printf("Dates are invalid.\n"); } printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2]))); return 0; }
use chrono::NaiveDate; fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() != 3 { eprintln!("usage: {} start-date end-date", args[0]); std::process::exit(1); } if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") { if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") { let d = end_date.signed_duration_since(start_date); println!("{}", d.num_days()); } else { eprintln!("Can't parse end date"); std::process::exit(1); } } else { eprintln!("Can't parse start date"); std::process::exit(1); } }
Deal cards for FreeCell
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
extern crate linear_congruential_generator; use linear_congruential_generator::{MsLcg, Rng, SeedableRng}; fn shuffle<T>(rng: &mut MsLcg, deck: &mut [T]) { let len = deck.len() as u32; for i in (1..len).rev() { let j = rng.next_u32() % (i + 1); deck.swap(i as usize, j as usize); } } fn gen_deck() -> Vec<String> { const RANKS: [char; 13] = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']; const SUITS: [char; 4] = ['C', 'D', 'H', 'S']; let render_card = |card: usize| { let (suit, rank) = (card % 4, card / 4); format!("{}{}", RANKS[rank], SUITS[suit]) }; (0..52).map(render_card).collect() } fn deal_ms_fc_board(seed: u32) -> Vec<String> { let mut rng = MsLcg::from_seed(seed); let mut deck = gen_deck(); shuffle(&mut rng, &mut deck); deck.reverse(); deck.chunks(8).map(|row| row.join(" ")).collect::<Vec<_>>() } fn main() { let seed = std::env::args() .nth(1) .and_then(|n| n.parse().ok()) .expect("A 32-bit seed is required"); for row in deal_ms_fc_board(seed) { println!(": {}", row); } }
Delegates
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef const char * (*Responder)( int p1); typedef struct sDelegate { Responder operation; } *Delegate; Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->operation = rspndr; return dl; } const char *DelegateThing(Delegate dl, int p1) { return (dl->operation)? (*dl->operation)(p1) : NULL; } typedef struct sDelegator { int param; char *phrase; Delegate delegate; } *Delegator; const char * defaultResponse( int p1) { return "default implementation"; } static struct sDelegate defaultDel = { &defaultResponse }; Delegator NewDelegator( int p, char *phrase) { Delegator d = malloc(sizeof(struct sDelegator)); d->param = p; d->phrase = phrase; d->delegate = &defaultDel; return d; } const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy) { const char *rtn; if (delroy) { rtn = DelegateThing(delroy, p1); if (!rtn) { rtn = DelegateThing(theDelegator->delegate, p1); } } else rtn = DelegateThing(theDelegator->delegate, p1); printf("%s\n", theDelegator->phrase ); return rtn; } const char *thing1( int p1) { printf("We're in thing1 with value %d\n" , p1); return "delegate implementation"; } int main() { Delegate del1 = NewDelegate(&thing1); Delegate del2 = NewDelegate(NULL); Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby."); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, NULL)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del1)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del2)); return 0; }
trait Thingable { fn thing(&self) -> &str; } struct Delegator<T>(Option<T>); struct Delegate {} impl Thingable for Delegate { fn thing(&self) -> &'static str { "Delegate implementation" } } impl<T: Thingable> Thingable for Delegator<T> { fn thing(&self) -> &str { self.0.as_ref().map(|d| d.thing()).unwrap_or("Default implmementation") } } fn main() { let d: Delegator<Delegate> = Delegator(None); println!("{}", d.thing()); let d: Delegator<Delegate> = Delegator(Some(Delegate {})); println!("{}", d.thing()); }
Delete a file
#include <stdio.h> int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
use std::io::{self, Write}; use std::fs::{remove_file,remove_dir}; use std::path::Path; use std::{process,display}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { delete(".").and(delete("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn delete<P>(root: P) -> io::Result<()> where P: AsRef<Path> { remove_file(root.as_ref().join(FILE_NAME)) .and(remove_dir(root.as_ref().join(DIR_NAME))) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "{:?}", error); process::exit(code) }
Department numbers
#include<stdio.h> int main() { int police,sanitation,fire; printf("Police Sanitation Fire\n"); printf("----------------------------------"); for(police=2;police<=6;police+=2){ for(sanitation=1;sanitation<=7;sanitation++){ for(fire=1;fire<=7;fire++){ if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){ printf("\n%d\t\t%d\t\t%d",police,sanitation,fire); } } } } return 0; }
extern crate num_iter; fn main() { println!("Police Sanitation Fire"); println!("----------------------"); for police in num_iter::range_step(2, 7, 2) { for sanitation in 1..8 { for fire in 1..8 { if police != sanitation && sanitation != fire && fire != police && police + fire + sanitation == 12 { println!("{:6}{:11}{:4}", police, sanitation, fire); } } } } }
Detect division by zero
#include <limits.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> static sigjmp_buf fpe_env; static void fpe_handler(int signal, siginfo_t *w, void *a) { siglongjmp(fpe_env, w->si_code); } void try_division(int x, int y) { struct sigaction act, old; int code; volatile int result; code = sigsetjmp(fpe_env, 1); if (code == 0) { act.sa_sigaction = fpe_handler; sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO; if (sigaction(SIGFPE, &act, &old) < 0) { perror("sigaction"); exit(1); } result = x / y; if (sigaction(SIGFPE, &old, NULL) < 0) { perror("sigaction"); exit(1); } printf("%d / %d is %d\n", x, y, result); } else { if (sigaction(SIGFPE, &old, NULL) < 0) { perror("sigaction"); exit(1); } switch (code) { case FPE_INTDIV: case FPE_FLTDIV: printf("%d / %d: caught division by zero!\n", x, y); break; default: printf("%d / %d: caught mysterious error!\n", x, y); break; } } } int main() { try_division(-44, 0); try_division(-44, 5); try_division(0, 5); try_division(0, 0); try_division(INT_MIN, -1); return 0; }
fn test_division(numerator: u32, denominator: u32) { match numerator.checked_div(denominator) { Some(result) => println!("{} / {} = {}", numerator, denominator, result), None => println!("{} / {} results in a division by zero", numerator, denominator) } } fn main() { test_division(5, 4); test_division(4, 0); }
Determine if a string has all the same characters
#include<string.h> #include<stdio.h> int main(int argc,char** argv) { int i,len; char reference; if(argc>2){ printf("Usage : %s <Test String>\n",argv[0]); return 0; } if(argc==1||strlen(argv[1])==1){ printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argc==1?"":argv[1],argc==1?0:(int)strlen(argv[1])); return 0; } reference = argv[1][0]; len = strlen(argv[1]); for(i=1;i<len;i++){ if(argv[1][i]!=reference){ printf("Input string : \"%s\"\nLength : %d\nFirst different character : \"%c\"(0x%x) at position : %d\n",argv[1],len,argv[1][i],argv[1][i],i+1); return 0; } } printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argv[1],len); return 0; }
fn test_string(input: &str) { println!("Checking string {:?} of length {}:", input, input.chars().count()); let mut chars = input.chars(); match chars.next() { Some(first) => { if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c != first).next() { println!("\tNot all characters are the same."); println!("\t{:?} (0x{:X}) at position {} differs.", character, character as u32, pos); return; } }, None => {} } println!("\tAll characters in the string are the same"); } fn main() { let tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]; for string in &tests { test_string(string); } }
Determine if a string has all unique characters
#include<stdbool.h> #include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct positionList{ int position; struct positionList *next; }positionList; typedef struct letterList{ char letter; int repititions; positionList* positions; struct letterList *next; }letterList; letterList* letterSet; bool duplicatesFound = false; void checkAndUpdateLetterList(char c,int pos){ bool letterOccurs = false; letterList *letterIterator,*newLetter; positionList *positionIterator,*newPosition; if(letterSet==NULL){ letterSet = (letterList*)malloc(sizeof(letterList)); letterSet->letter = c; letterSet->repititions = 0; letterSet->positions = (positionList*)malloc(sizeof(positionList)); letterSet->positions->position = pos; letterSet->positions->next = NULL; letterSet->next = NULL; } else{ letterIterator = letterSet; while(letterIterator!=NULL){ if(letterIterator->letter==c){ letterOccurs = true; duplicatesFound = true; letterIterator->repititions++; positionIterator = letterIterator->positions; while(positionIterator->next!=NULL) positionIterator = positionIterator->next; newPosition = (positionList*)malloc(sizeof(positionList)); newPosition->position = pos; newPosition->next = NULL; positionIterator->next = newPosition; } if(letterOccurs==false && letterIterator->next==NULL) break; else letterIterator = letterIterator->next; } if(letterOccurs==false){ newLetter = (letterList*)malloc(sizeof(letterList)); newLetter->letter = c; newLetter->repititions = 0; newLetter->positions = (positionList*)malloc(sizeof(positionList)); newLetter->positions->position = pos; newLetter->positions->next = NULL; newLetter->next = NULL; letterIterator->next = newLetter; } } } void printLetterList(){ positionList* positionIterator; letterList* letterIterator = letterSet; while(letterIterator!=NULL){ if(letterIterator->repititions>0){ printf("\n'%c' (0x%x) at positions :",letterIterator->letter,letterIterator->letter); positionIterator = letterIterator->positions; while(positionIterator!=NULL){ printf("%3d",positionIterator->position + 1); positionIterator = positionIterator->next; } } letterIterator = letterIterator->next; } printf("\n"); } int main(int argc,char** argv) { int i,len; if(argc>2){ printf("Usage : %s <Test string>\n",argv[0]); return 0; } if(argc==1||strlen(argv[1])==1){ printf("\"%s\" - Length %d - Contains only unique characters.\n",argc==1?"":argv[1],argc==1?0:1); return 0; } len = strlen(argv[1]); for(i=0;i<len;i++){ checkAndUpdateLetterList(argv[1][i],i); } printf("\"%s\" - Length %d - %s",argv[1],len,duplicatesFound==false?"Contains only unique characters.\n":"Contains the following duplicate characters :"); if(duplicatesFound==true) printLetterList(); return 0; }
fn unique(s: &str) -> Option<(usize, usize, char)> { s.chars().enumerate().find_map(|(i, c)| { s.chars() .enumerate() .skip(i + 1) .find(|(_, other)| c == *other) .map(|(j, _)| (i, j, c)) }) } fn main() { let strings = [ "", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X", "hétérogénéité", "🎆🎃🎇🎈", "😍😀🙌💃😍🙌", "🐠🐟🐡🦈🐬🐳🐋🐡", ]; for string in &strings { print!("\"{}\" (length {})", string, string.chars().count()); match unique(string) { None => println!(" is unique"), Some((i, j, c)) => println!( " is not unique\n\tfirst duplicate: \"{}\" (U+{:0>4X}) at indices {} and {}", c, c as usize, i, j ), } } }
Determine if a string is collapsible
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char* str1,char* str2){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
fn collapse_string(val: &str) -> String { let mut output = String::new(); let mut chars = val.chars().peekable(); while let Some(c) = chars.next() { while let Some(&b) = chars.peek() { if b == c { chars.next(); } else { break; } } output.push(c); } output } fn main() { let tests = [ "122333444455555666666777777788888888999999999", "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", ]; for s in &tests { println!("Old: {:>3} <<<{}>>>", s.len(), s); let collapsed = collapse_string(s); println!("New: {:>3} <<<{}>>>", collapsed.len(), collapsed); println!(); } }
Determine if a string is numeric
#include <ctype.h> #include <stdlib.h> int isNumeric (const char * s) { if (s == NULL || *s == '\0' || isspace(*s)) return 0; char * p; strtod (s, &p); return *p == '\0'; }
fn parsable<T: FromStr>(s: &str) -> bool { s.parse::<T>().is_ok() }
Determine if a string is squeezable
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a { let mut previous = None; s.chars().filter(move |c| match previous { Some(p) if p == squeezable && p == *c => false, _ => { previous = Some(*c); true } }) } fn main() { fn show(input: &str, c: char) { println!("Squeeze: '{}'", c); println!("Input ({} chars): \t{}", input.chars().count(), input); let output: String = squeezable_string(input, c).collect(); println!("Output ({} chars): \t{}", output.chars().count(), output); println!(); } let harry = r#"I never give 'em hell, I just tell the truth, and they think it's hell. --- Harry S Truman"#; #[rustfmt::skip] let inputs = [ ("", ' '), (r#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), (harry, ' '), (harry, '-'), (harry, 'r'), ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e'), ("headmistressship", 's'), ]; inputs.iter().for_each(|(input, c)| show(input, *c)); }
Determine if only one instance is running
#include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define INSTANCE_LOCK "rosetta-code-lock" void fail(const char *message) { perror(message); exit(1); } static char *ooi_path; void ooi_unlink(void) { unlink(ooi_path); } void only_one_instance(void) { struct flock fl; size_t dirlen; int fd; char *dir; dir = getenv("HOME"); if (dir == NULL || dir[0] != '/') { fputs("Bad home directory.\n", stderr); exit(1); } dirlen = strlen(dir); ooi_path = malloc(dirlen + sizeof("/" INSTANCE_LOCK)); if (ooi_path == NULL) fail("malloc"); memcpy(ooi_path, dir, dirlen); memcpy(ooi_path + dirlen, "/" INSTANCE_LOCK, sizeof("/" INSTANCE_LOCK)); fd = open(ooi_path, O_RDWR | O_CREAT, 0600); if (fd < 0) fail(ooi_path); fl.l_start = 0; fl.l_len = 0; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; if (fcntl(fd, F_SETLK, &fl) < 0) { fputs("Another instance of this program is running.\n", stderr); exit(1); } atexit(ooi_unlink); } int main() { int i; only_one_instance(); for(i = 10; i > 0; i--) { printf("%d...%s", i, i % 5 == 1 ? "\n" : " "); fflush(stdout); sleep(1); } puts("Fin!"); return 0; }
use std::net::TcpListener; fn create_app_lock(port: u16) -> TcpListener { match TcpListener::bind(("0.0.0.0", port)) { Ok(socket) => { socket }, Err(_) => { panic!("Couldn't lock port {}: another instance already running?", port); } } } fn remove_app_lock(socket: TcpListener) { drop(socket); } fn main() { let lock_socket = create_app_lock(12345); remove_app_lock(lock_socket); }
Digital root
#include <stdio.h> int droot(long long int x, int base, int *pers) { int d = 0; if (pers) for (*pers = 0; x >= base; x = d, (*pers)++) for (d = 0; x; d += x % base, x /= base); else if (x && !(d = x % (base - 1))) d = base - 1; return d; } int main(void) { int i, d, pers; long long x[] = {627615, 39390, 588225, 393900588225LL}; for (i = 0; i < 4; i++) { d = droot(x[i], 10, &pers); printf("%lld: pers %d, root %d\n", x[i], pers, d); } return 0; }
fn sum_digits(mut n: u64, base: u64) -> u64 { let mut sum = 0u64; while n > 0 { sum = sum + (n % base); n = n / base; } sum } fn digital_root(mut num: u64, base: u64) -> (u64, u64) { let mut pers = 0; while num >= base { pers = pers + 1; num = sum_digits(num, base); } (pers, num) } fn main() { let values = [627615u64, 39390u64, 588225u64, 393900588225u64]; for &value in values.iter() { let (pers, root) = digital_root(value, 10); println!("{} has digital root {} and additive persistance {}", value, root, pers); } println!(""); let values_base16 = [0x7e0, 0x14e344, 0xd60141, 0x12343210]; for &value in values_base16.iter() { let (pers, root) = digital_root(value, 16); println!("0x{:x} has digital root 0x{:x} and additive persistance 0x{:x}", value, root, pers); } }
Discordian date
#include <stdlib.h> #include <stdio.h> #include <time.h> #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange") #define season( x ) ((x) == 0 ? "Chaos" :\ (x) == 1 ? "Discord" :\ (x) == 2 ? "Confusion" :\ (x) == 3 ? "Bureaucracy" :\ "The Aftermath") #define date( x ) ((x)%73 == 0 ? 73 : (x)%73) #define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100)) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = malloc( 100 * sizeof( char ) ); if( leap_year( y ) ){ if( d == 60 ){ sprintf( result, "St. Tib's Day, YOLD %d", dyear ); return result; } else if( d >= 60 ){ -- d; } } sprintf( result, "%s, %s %d, YOLD %d", day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear ); return result; } int day_of_year( int y, int m, int d ){ int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; for( ; m > 1; m -- ){ d += month_lengths[ m - 2 ]; if( m == 3 && leap_year( y ) ){ ++ d; } } return d; } int main( int argc, char * argv[] ){ time_t now; struct tm * now_time; int year, doy; if( argc == 1 ){ now = time( NULL ); now_time = localtime( &now ); year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1; } else if( argc == 4 ){ year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) ); } char * result = ddate( year, doy ); puts( result ); free( result ); return 0; }
extern crate chrono; use chrono::NaiveDate; use std::str::FromStr; fn main() { let date = std::env::args().nth(1).expect("Please provide a YYYY-MM-DD date."); println!("{} is {}", date, NaiveDate::from_str(&date).unwrap().to_poee()); } const APOSTLES: [&str; 5] = ["Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"]; const HOLYDAYS: [&str; 5] = ["Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"]; const SEASONS: [&str; 5] = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]; const WEEKDAYS: [&str; 5] = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"]; const APOSTLE_HOLYDAY: usize = 5; const CURSE_OF_GREYFACE: i32 = 1166; const SEASON_DAYS: usize = 73; const SEASON_HOLYDAY: usize = 50; const ST_TIBS_DAY: usize = 59; const WEEK_DAYS: usize = 5; impl<T: Datelike> DiscordianDate for T {} pub trait DiscordianDate: Datelike { fn to_poee(&self) -> String { let day = self.ordinal0() as usize; let leap = self.year() % 4 == 0 && self.year() % 100 != 0 || self.year() % 400 == 0; let year = self.year() + CURSE_OF_GREYFACE; if leap && day == ST_TIBS_DAY { return format!("St. Tib's Day, in the YOLD {}", year); } let day_offset = if leap && day > ST_TIBS_DAY { day - 1 } else { day }; let day_of_season = day_offset % SEASON_DAYS + 1; let season = SEASONS[day_offset / SEASON_DAYS]; let weekday = WEEKDAYS[day_offset % WEEK_DAYS]; let holiday = if day_of_season == APOSTLE_HOLYDAY { format!("\nCelebrate {}", APOSTLES[day_offset / SEASON_DAYS]) } else if day_of_season == SEASON_HOLYDAY { format!("\nCelebrate {}", HOLYDAYS[day_offset / SEASON_DAYS]) } else { String::with_capacity(0) }; format!("{}, the {} day of {} in the YOLD {}{}", weekday, ordinalize(day_of_season), season, year, holiday) } } fn ordinalize(num: usize) -> String { let s = format!("{}", num); let suffix = if s.ends_with('1') && !s.ends_with("11") { "st" } else if s.ends_with('2') && !s.ends_with("12") { "nd" } else if s.ends_with('3') && !s.ends_with("13") { "rd" } else { "th" }; format!("{}{}", s, suffix) }
Display a linear combination
#include<stdlib.h> #include<stdio.h> #include<math.h> int main(int argC, char* argV[]) { int i,zeroCount= 0,firstNonZero = -1; double* vector; if(argC == 1){ printf("Usage : %s <Vector component coefficients seperated by single space>",argV[0]); } else{ printf("Vector for ["); for(i=1;i<argC;i++){ printf("%s,",argV[i]); } printf("\b] -> "); vector = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<=argC;i++){ vector[i-1] = atof(argV[i]); if(vector[i-1]==0.0) zeroCount++; if(vector[i-1]!=0.0 && firstNonZero==-1) firstNonZero = i-1; } if(zeroCount == argC){ printf("0"); } else{ for(i=0;i<argC;i++){ if(i==firstNonZero && vector[i]==1) printf("e%d ",i+1); else if(i==firstNonZero && vector[i]==-1) printf("- e%d ",i+1); else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])>0.0) printf("- %lf e%d ",fabs(vector[i]),i+1); else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])==0.0) printf("- %ld e%d ",labs(vector[i]),i+1); else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])>0.0) printf("%lf e%d ",vector[i],i+1); else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])==0.0) printf("%ld e%d ",vector[i],i+1); else if(fabs(vector[i])==1.0 && i!=0) printf("%c e%d ",(vector[i]==-1)?'-':'+',i+1); else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])>0.0) printf("%c %lf e%d ",(vector[i]<0)?'-':'+',fabs(vector[i]),i+1); else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])==0.0) printf("%c %ld e%d ",(vector[i]<0)?'-':'+',labs(vector[i]),i+1); } } } free(vector); return 0; }
use std::fmt::{Display, Formatter, Result}; use std::process::exit; struct Coefficient(usize, f64); impl Display for Coefficient { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let i = self.0; let c = self.1; if c == 0. { return Ok(()); } write!( f, " {} {}e({})", if c < 0. { "-" } else if f.alternate() { " " } else { "+" }, if (c.abs() - 1.).abs() < f64::EPSILON { "".to_string() } else { c.abs().to_string() + "*" }, i + 1 ) } } fn usage() { println!("Usage: display-linear-combination a1 [a2 a3 ...]"); } fn linear_combination(coefficients: &[f64]) -> String { let mut string = String::new(); let mut iter = coefficients.iter().enumerate(); loop { match iter.next() { Some((_, &c)) if c == 0. => { continue; } Some((i, &c)) => { string.push_str(format!("{:#}", Coefficient(i, c)).as_str()); break; } None => { string.push('0'); return string; } } } for (i, &c) in iter { string.push_str(format!("{}", Coefficient(i, c)).as_str()); } string } fn main() { let mut coefficients = Vec::new(); let mut args = std::env::args(); args.next(); for arg in args { let c = arg.parse::<f64>().unwrap_or_else(|e| { eprintln!("Failed to parse argument \"{}\": {}", arg, e); exit(-1); }); coefficients.push(c); } if coefficients.is_empty() { usage(); return; } println!("{}", linear_combination(&coefficients)); }
Documentation
int add(int a, int b) { return a + b; }
#![doc(html_favicon_url = "https: #![doc(html_logo_url = "https: pub const THINGY: u32 = 42; pub enum Whatsit { Yo(Whatchamabob), HoHo, } pub struct Whatchamabob { pub doodad: f64, pub thingamabob: bool } pub trait Frobnify { fn frob(&self); } impl Frobnify for Whatchamabob { fn frob(&self) { println!("Frobbed: {}", self.doodad); } } pub fn main() { let foo = Whatchamabob{ doodad: 1.2, thingamabob: false }; foo.frob(); }
Dot product
#include <stdio.h> #include <stdlib.h> int dot_product(int *, int *, size_t); int main(void) { int a[3] = {1, 3, -5}; int b[3] = {4, -2, -1}; printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0]))); return EXIT_SUCCESS; } int dot_product(int *a, int *b, size_t n) { int sum = 0; size_t i; for (i = 0; i < n; i++) { sum += a[i] * b[i]; } return sum; }
fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> { if a.len() != b.len() { return None } Some( a.iter() .zip( b.iter() ) .fold(0, |sum, (el_a, el_b)| sum + el_a*el_b) ) } fn main() { let v1 = vec![1, 3, -5]; let v2 = vec![4, -2, -1]; println!("{}", dot_product(&v1, &v2).unwrap()); }
Doubly-linked list_Element definition
struct Node { struct Node *next; struct Node *prev; void *data; };
use std::collections::LinkedList; fn main() { let list = LinkedList::<i32>::new(); }
Doubly-linked list_Element insertion
void insert(link* anchor, link* newlink) { newlink->next = anchor->next; newlink->prev = anchor; (newlink->next)->prev = newlink; anchor->next = newlink; }
use std::collections::LinkedList; fn main() { let mut list = LinkedList::new(); list.push_front(8); }
Dragon curve
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { long long tmp = dx - dy; dy = dx + dy; dx = tmp; scale *= 2; x *= 2; y *= 2; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / scale; double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long tmp; # define LEFT tmp = -dy; dy = dx; dx = tmp # define RIGHT tmp = dy; dy = -dx; dx = tmp while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("X+YF+", d - 1); continue; case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; case '+': RIGHT; continue; case '-': LEFT; continue; case 'F': clen ++; h_rgb(x/scale, y/scale); x += dx; y += dy; continue; } } } void dragon(long leng, int depth) { long i, d = leng / 3 + 1; long h = leng + 3, w = leng + d * 3 / 2 + 2; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = d; dx = leng; dy = 0; scale = 1; clen = 0; for (i = 0; i < depth; i++) sc_up(); iter_string("FX", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); dragon(size, depth * 2); return 0; }
use ggez::{ conf::{WindowMode, WindowSetup}, error::GameResult, event, graphics::{clear, draw, present, Color, MeshBuilder}, nalgebra::Point2, Context, }; use std::time::Duration; fn l_system_next_generation(current_generation: &str) -> String { let f_rule = "f-h"; let h_rule = "f+h"; let mut next_gen = String::new(); for char in current_generation.chars() { match char { 'f' => next_gen.push_str(f_rule), 'h' => next_gen.push_str(h_rule), '-' | '+' => next_gen.push(char), _ => panic!("Unknown char {}", char), } } next_gen } const WINDOW_WIDTH: f32 = 700.0; const WINDOW_HEIGHT: f32 = 700.0; const START_X: f32 = WINDOW_WIDTH / 6.0; const START_Y: f32 = WINDOW_HEIGHT / 6.0; const MAX_DEPTH: i32 = 15; const LINE_LENGTH: f32 = 20.0; struct MainState { start_gen: String, next_gen: String, line_length: f32, max_depth: i32, current_depth: i32, } impl MainState { fn new() -> GameResult<MainState> { let start_gen = "f"; let next_gen = String::new(); let line_length = LINE_LENGTH; let max_depth = MAX_DEPTH; let current_depth = 0; Ok(MainState { start_gen: start_gen.to_string(), next_gen, line_length, max_depth, current_depth, }) } } impl event::EventHandler for MainState { fn update(&mut self, _ctx: &mut Context) -> GameResult { if self.current_depth < self.max_depth { self.next_gen = l_system_next_generation(&self.start_gen); self.start_gen = self.next_gen.clone(); self.line_length -= (self.line_length / self.max_depth as f32) * 1.9; self.current_depth += 1; } ggez::timer::sleep(Duration::from_millis(500)); Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult { let grey = Color::from_rgb(77, 77, 77); let blue = Color::from_rgb(51, 153, 255); let initial_point_blue = Point2::new(START_X, START_Y); clear(ctx, grey); draw_lines( &self.next_gen, ctx, self.line_length, blue, initial_point_blue, )?; present(ctx)?; Ok(()) } } fn next_point(current_point: Point2<f32>, heading: f32, line_length: f32) -> Point2<f32> { let next_point = ( (current_point.x + (line_length * heading.to_radians().cos().trunc() as f32)), (current_point.y + (line_length * heading.to_radians().sin().trunc() as f32)), ); Point2::new(next_point.0, next_point.1) } fn draw_lines( instructions: &str, ctx: &mut Context, line_length: f32, colour: Color, initial_point: Point2<f32>, ) -> GameResult { let line_width = 2.0; let mut heading = 0.0; let turn_angle = 90.0; let mut start_point = initial_point; let mut line_builder = MeshBuilder::new(); for char in instructions.chars() { let end_point = next_point(start_point, heading, line_length); match char { 'f' | 'h' => { line_builder.line(&[start_point, end_point], line_width, colour)?; start_point = end_point; } '+' => heading += turn_angle, '-' => heading -= turn_angle, _ => panic!("Unknown char {}", char), } } let lines = line_builder.build(ctx)?; draw(ctx, &lines, (initial_point,))?; Ok(()) } fn main() -> GameResult { let cb = ggez::ContextBuilder::new("dragon curve", "huw") .window_setup(WindowSetup::default().title("Dragon curve")) .window_mode(WindowMode::default().dimensions(WINDOW_WIDTH, WINDOW_HEIGHT)); let (ctx, event_loop) = &mut cb.build()?; let state = &mut MainState::new()?; event::run(ctx, event_loop, state) }
Draw a clock
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #define PI 3.14159265 const char * shades = " .:-*ca&#%@"; double dist(double x, double y, double x0, double y0) { double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0); if (l > 1) { x -= x0; y -= y0; } else if (l >= 0) { x -= l * x0; y -= l * y0; } return sqrt(x * x + y * y); } enum { sec = 0, min, hur }; void draw(int size) { # define for_i for(int i = 0; i < size; i++) # define for_j for(int j = 0; j < size * 2; j++) double angle, cx = size / 2.; double sx[3], sy[3], sw[3]; double fade[] = { 1, .35, .35 }; struct timeval tv; struct tm *t; sw[sec] = size * .02; sw[min] = size * .03; sw[hur] = size * .05; every_second: gettimeofday(&tv, 0); t = localtime(&tv.tv_sec); angle = t->tm_sec * PI / 30; sy[sec] = -cx * cos(angle); sx[sec] = cx * sin(angle); angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI; sy[min] = -cx * cos(angle) * .8; sx[min] = cx * sin(angle) * .8; angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI; sy[hur] = -cx * cos(angle) * .6; sx[hur] = cx * sin(angle) * .6; printf("\033[s"); for_i { printf("\033[%d;0H", i); double y = i - cx; for_j { double x = (j - 2 * cx) / 2; int pix = 0; for (int k = hur; k >= sec; k--) { double d = dist(x, y, sx[k], sy[k]); if (d < sw[k] - .5) pix = 10 * fade[k]; else if (d < sw[k] + .5) pix = (5 + (sw[k] - d) * 10) * fade[k]; } putchar(shades[pix]); } } printf("\033[u"); fflush(stdout); sleep(1); goto every_second; } int main(int argc, char *argv[]) { int s; if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20; draw(s); return 0; }
extern crate time; use std::thread; use std::time::Duration; const TOP: &str = " ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀"; const BOT: &str = " ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀"; fn main() { let top: Vec<&str> = TOP.split_whitespace().collect(); let bot: Vec<&str> = BOT.split_whitespace().collect(); loop { let tm = &time::now().rfc822().to_string()[17..25]; let top_str: String = tm.chars().map(|x| top[x as usize - '0' as usize]).collect(); let bot_str: String = tm.chars().map(|x| bot[x as usize - '0' as usize]).collect(); clear_screen(); println!("{}", top_str); println!("{}", bot_str); thread::sleep(Duration::from_secs(1)); } } fn clear_screen() { println!("{}[H{}[J", 27 as char, 27 as char); }
Dutch national flag problem
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> #define NUMBALLS 5 int compar(const void *a, const void *b){ char c1=*(const char*)a, c2=*(const char*)b; return c1-c2; } _Bool issorted(char *balls){ int i,state; state=0; for(i=0;i<NUMBALLS;i++){ if(balls[i]<state)return false; if(balls[i]>state)state=balls[i]; } return true; } void printout(char *balls){ int i; char str[NUMBALLS+1]; for(i=0;i<NUMBALLS;i++)str[i]=balls[i]==0?'r':balls[i]==1?'w':'b'; printf("%s\n",str); } int main(void) { char balls[NUMBALLS]; int i; srand(time(NULL)); rand(); for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3; while(issorted(balls)){ printf("Accidentally still sorted: "); printout(balls); for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3; } printf("Non-sorted: "); printout(balls); qsort(balls,NUMBALLS,sizeof(char),compar); if(issorted(balls)){ printf("Sorted: "); printout(balls); } else { printf("Sort failed: "); printout(balls); } return 0; }
extern crate rand; use rand::Rng; #[derive(Eq,Ord,PartialOrd,PartialEq,Debug)] enum Color { Red, White, Blue } fn is_sorted(list: &Vec<Color>) -> bool { let mut state = &Color::Red; for current in list.iter() { if current < state { return false; } if current > state { state = current; } } true } fn main() { let mut rng = rand::thread_rng(); let mut colors: Vec<Color> = Vec::new(); for _ in 1..10 { let r = rng.gen_range(0, 3); if r == 0 { colors.push(Color::Red); } else if r == 1 { colors.push(Color::White); } else if r == 2 { colors.push(Color::Blue); } } while is_sorted(&colors) { rng.shuffle(&mut colors); } println!("Before: {:?}", colors); colors.sort(); println!("After: {:?}", colors); if !is_sorted(&colors) { println!("Oops, did not sort colors correctly!"); } }
Echo server
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <sys/wait.h> #include <signal.h> #define MAX_ENQUEUED 20 #define BUF_LEN 256 #define PORT_STR "12321" void wait_for_zombie(int s) { while(waitpid(-1, NULL, WNOHANG) > 0) ; } void echo_lines(int csock) { char buf[BUF_LEN]; int r; while( (r = read(csock, buf, BUF_LEN)) > 0 ) { (void)write(csock, buf, r); } exit(EXIT_SUCCESS); } void take_connections_forever(int ssock) { for(;;) { struct sockaddr addr; socklen_t addr_size = sizeof(addr); int csock; csock = accept(ssock, &addr, &addr_size); if ( csock == -1 ) { perror("accept"); } else if ( fork() == 0 ) { close(ssock); echo_lines(csock); } else { close(csock); } } } int main() { struct addrinfo hints, *res; struct sigaction sa; int sock; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) { perror("getaddrinfo"); exit(EXIT_FAILURE); } if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) { perror("socket"); exit(EXIT_FAILURE); } sa.sa_handler = wait_for_zombie; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) { perror("sigaction"); exit(EXIT_FAILURE); } if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) { perror("bind"); exit(EXIT_FAILURE); } freeaddrinfo(res); if ( listen(sock, MAX_ENQUEUED) != 0 ) { perror("listen"); exit(EXIT_FAILURE); } take_connections_forever(sock); return EXIT_SUCCESS; }
use std::net::{TcpListener, TcpStream}; use std::io::{BufReader, BufRead, Write}; use std::thread; fn main() { let listener = TcpListener::bind("127.0.0.1:12321").unwrap(); println!("server is running on 127.0.0.1:12321 ..."); for stream in listener.incoming() { let stream = stream.unwrap(); thread::spawn(move || handle_client(stream)); } } fn handle_client(stream: TcpStream) { let mut stream = BufReader::new(stream); loop { let mut buf = String::new(); if stream.read_line(&mut buf).is_err() { break; } stream .get_ref() .write(buf.as_bytes()) .unwrap(); } }
Egyptian division
'---Ported from the c code example to BaCon by bigbass '================================================================================== FUNCTION EGYPTIAN_DIVISION(long dividend, long divisor, long remainder) TYPE long '================================================================================== '--- remainder is the third parameter, pass 0 if you do not need the remainder DECLARE powers[64] TYPE long DECLARE doublings[64] TYPE long LOCAL i TYPE long FOR i = 0 TO 63 STEP 1 powers[i] = 1 << i doublings[i] = divisor << i IF (doublings[i] > dividend) THEN BREAK ENDIF NEXT LOCAL answer TYPE long LOCAL accumulator TYPE long answer = 0 accumulator = 0 WHILE i >= 0 '--- If the current value of the accumulator added to the '--- doublings cell would be less than or equal to the '--- dividend then add it to the accumulator IF (accumulator + doublings[i] <= dividend) THEN accumulator = accumulator + doublings[i] answer = answer + powers[i] ENDIF DECR i WEND IF remainder THEN remainder = dividend - accumulator PRINT dividend ," / ", divisor, " = " , answer ," remainder " , remainder PRINT "Decoded the answer to a standard fraction" PRINT (remainder + 0.0 )/ (divisor + 0.0) + answer PRINT ELSE PRINT dividend ," / ", divisor , " = " , answer ENDIF RETURN answer ENDFUNCTION '--- the large number divided by the smaller number '--- the third argument is 1 if you want to have a remainder '--- and 0 if you dont want to have a remainder EGYPTIAN_DIVISION(580,34,1) EGYPTIAN_DIVISION(580,34,0) EGYPTIAN_DIVISION(580,34,1)
fn egyptian_divide(dividend: u32, divisor: u32) -> (u32, u32) { let dividend = dividend as u64; let divisor = divisor as u64; let pows = (0..32).map(|p| 1 << p); let doublings = (0..32).map(|p| divisor << p); let (answer, sum) = doublings .zip(pows) .rev() .skip_while(|(i, _)| i > &dividend ) .fold((0, 0), |(answer, sum), (double, power)| { if sum + double < dividend { (answer + power, sum + double) } else { (answer, sum) } }); (answer as u32, (dividend - sum) as u32) } fn main() { let (div, rem) = egyptian_divide(580, 34); println!("580 divided by 34 is {} remainder {}", div, rem); }
Element-wise operations
#include <math.h> #define for_i for(i = 0; i < h; i++) #define for_j for(j = 0; j < w; j++) #define _M double** #define OPM(name, _op_) \ void eop_##name(_M a, _M b, _M c, int w, int h){int i,j;\ for_i for_j c[i][j] = a[i][j] _op_ b[i][j];} OPM(add, +);OPM(sub, -);OPM(mul, *);OPM(div, /); #define OPS(name, res) \ void eop_s_##name(_M a, double s, _M b, int w, int h) {double x;int i,j;\ for_i for_j {x = a[i][j]; b[i][j] = res;}} OPS(mul, x*s);OPS(div, x/s);OPS(add, x+s);OPS(sub, x-s);OPS(pow, pow(x, s));
struct Matrix { elements: Vec<f32>, pub height: u32, pub width: u32, } impl Matrix { fn new(elements: Vec<f32>, height: u32, width: u32) -> Matrix { Matrix { elements: elements, height: height, width: width, } } fn get(&self, row: u32, col: u32) -> f32 { let row = row as usize; let col = col as usize; self.elements[col + row * (self.width as usize)] } fn set(&mut self, row: u32, col: u32, value: f32) { let row = row as usize; let col = col as usize; self.elements[col + row * (self.width as usize)] = value; } fn print(&self) { for row in 0..self.height { for col in 0..self.width { print!("{:3.0}", self.get(row, col)); } println!(""); } println!(""); } } fn matrix_addition(first: &Matrix, second: &Matrix) -> Result<Matrix, String> { if first.width == second.width && first.height == second.height { let mut result = Matrix::new(vec![0.0f32; (first.height * first.width) as usize], first.height, first.width); for row in 0..first.height { for col in 0..first.width { let first_value = first.get(row, col); let second_value = second.get(row, col); result.set(row, col, first_value + second_value); } } Ok(result) } else { Err("Dimensions don't match".to_owned()) } } fn scalar_multiplication(scalar: f32, matrix: &Matrix) -> Matrix { let mut result = Matrix::new(vec![0.0f32; (matrix.height * matrix.width) as usize], matrix.height, matrix.width); for row in 0..matrix.height { for col in 0..matrix.width { let value = matrix.get(row, col); result.set(row, col, scalar * value); } } result } fn matrix_subtraction(first: &Matrix, second: &Matrix) -> Result<Matrix, String> { if first.width == second.width && first.height == second.height { let negative_matrix = scalar_multiplication(-1.0, second); let result = matrix_addition(first, &negative_matrix).unwrap(); Ok(result) } else { Err("Dimensions don't match".to_owned()) } } fn matrix_multiplication(first: &Matrix, second: &Matrix) -> Result<Matrix, String> { if first.width == second.height { let mut result = Matrix::new(vec![0.0f32; (first.height * second.width) as usize], first.height, second.width); for row in 0..result.height { for col in 0..result.width { let mut value = 0.0; for it in 0..first.width { value += first.get(row, it) * second.get(it, col); } result.set(row, col, value); } } Ok(result) } else { Err("Dimensions don't match. Width of first must equal height of second".to_owned()) } } fn main() { let height = 2; let width = 3; let matrix1 = Matrix::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], height, width); let matrix2 = Matrix::new(vec![6.0, 5.0, 4.0, 3.0, 2.0, 1.0], height, width); matrix_addition(&matrix1, &matrix2).unwrap().print(); scalar_multiplication(2.0, &matrix1).print(); matrix_subtraction(&matrix1, &matrix2).unwrap().print(); let matrix3 = Matrix::new(vec![1.0, 1.0, 1.0], width, 1); matrix_multiplication(&matrix1, &matrix3).unwrap().print(); }
Elementary cellular automaton
#include <stdio.h> #include <limits.h> typedef unsigned long long ull; #define N (sizeof(ull) * CHAR_BIT) #define B(x) (1ULL << (x)) void evolve(ull state, int rule) { int i; ull st; printf("Rule %d:\n", rule); do { st = state; for (i = N; i--; ) putchar(st & B(i) ? '#' : '.'); putchar('\n'); for (state = i = 0; i < N; i++) if (rule & B(7 & (st>>(i-1) | st<<(N+1-i)))) state |= B(i); } while (st != state); } int main(int argc, char **argv) { evolve(B(N/2), 90); evolve(B(N/4)|B(N - N/4), 30); return 0; }
fn main() { struct ElementaryCA { rule: u8, state: u64, } impl ElementaryCA { fn new(rule: u8) -> (u64, ElementaryCA) { let out = ElementaryCA { rule, state: 1, }; (out.state, out) } fn next(&mut self) -> u64 { let mut next_state = 0u64; let state = self.state; for i in 0..64 { next_state |= (((self.rule as u64)>>(7 & (state.rotate_left(1).rotate_right(i as u32)))) & 1)<<i; } self.state = next_state; self.state } } fn rep_u64(val: u64) -> String { let mut out = String::new(); for i in (0..64).rev() { if 1<<i & val != 0 { out = out + "\u{2588}"; } else { out = out + "-"; } } out } let (i, mut thirty) = ElementaryCA::new(154); println!("{}",rep_u64(i)); for _ in 0..32 { let s = thirty.next(); println!("{}", rep_u64(s)); } }
Empty directory
#include <stdio.h> #include <dirent.h> #include <string.h> int dir_empty(const char *path) { struct dirent *ent; int ret = 1; DIR *d = opendir(path); if (!d) { fprintf(stderr, "%s: ", path); perror(""); return -1; } while ((ent = readdir(d))) { if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, ".."))) continue; ret = 0; break; } closedir(d); return ret; } int main(int c, char **v) { int ret = 0, i; if (c < 2) return -1; for (i = 1; i < c; i++) { ret = dir_empty(v[i]); if (ret >= 0) printf("%s: %sempty\n", v[i], ret ? "" : "not "); } return 0; }
use std::fs::read_dir; use std::error::Error; fn main() { for path in std::env::args().skip(1) { match read_dir(path.as_str()) { Ok(contents) => { let len = contents.collect::<Vec<_>>().len(); if len == 0 { println!("{} is empty", path); } else { println!("{} is not empty", path); } }, Err(e) => { println!("Failed to read directory \"{}\": {}", path, e.description()); } } } }
Empty string
#include <string.h> const char *str = ""; if (str) { ... } if (str[0] == '\0') { ... } if ( (str == NULL) || (strlen(str) == 0)) { ... } if (strcmp(str, "") == 0) { ... }
let s = ""; println!("is empty: {}", s.is_empty()); let t = "x"; println!("is empty: {}", t.is_empty()); let a = String::new(); println!("is empty: {}", a.is_empty()); let b = "x".to_string(); println!("is empty: {}", b.is_empty()); println!("is not empty: {}", !b.is_empty());
Entropy
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 100 int makehist(unsigned char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ unsigned char S[MAXLEN]; int len,*hist,histlen; double H; scanf("%[^\n]",S); len=strlen(S); hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
fn entropy(s: &[u8]) -> f32 { let mut histogram = [0u64; 256]; for &b in s { histogram[b as usize] += 1; } histogram .iter() .cloned() .filter(|&h| h != 0) .map(|h| h as f32 / s.len() as f32) .map(|ratio| -ratio * ratio.log2()) .sum() } fn main() { let arg = std::env::args().nth(1).expect("Need a string."); println!("Entropy of {} is {}.", arg, entropy(arg.as_bytes())); }
Enumerations
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
enum Fruits { Apple, Banana, Cherry } enum FruitsWithNumbers { Strawberry = 0, Pear = 27, } fn main() { println!("{}", FruitsWithNumbers::Pear as u8); }
Environment variables
#include <stdlib.h> #include <stdio.h> int main() { puts(getenv("HOME")); puts(getenv("PATH")); puts(getenv("USER")); return 0; }
use std::env; fn main() { println!("{:?}", env::var("HOME")); println!(); for (k, v) in env::vars().filter(|(k, _)| k.starts_with('P')) { println!("{}: {}", k, v); } }
Equilibrium index
#include <stdio.h> #include <stdlib.h> int list[] = {-7, 1, 5, 2, -4, 3, 0}; int eq_idx(int *a, int len, int **ret) { int i, sum, s, cnt; cnt = s = sum = 0; *ret = malloc(sizeof(int) * len); for (i = 0; i < len; i++) sum += a[i]; for (i = 0; i < len; i++) { if (s * 2 + a[i] == sum) { (*ret)[cnt] = i; cnt++; } s += a[i]; } *ret = realloc(*ret, cnt * sizeof(int)); return cnt; } int main() { int i, cnt, *idx; cnt = eq_idx(list, sizeof(list) / sizeof(int), &idx); printf("Found:"); for (i = 0; i < cnt; i++) printf(" %d", idx[i]); printf("\n"); return 0; }
extern crate num; use num::traits::Zero; fn equilibrium_indices(v: &[i32]) -> Vec<usize> { let mut right = v.iter().sum(); let mut left = i32::zero(); v.iter().enumerate().fold(vec![], |mut out, (i, &el)| { right -= el; if left == right { out.push(i); } left += el; out }) } fn main() { let v = [-7i32, 1, 5, 2, -4, 3, 0]; let indices = equilibrium_indices(&v); println!("Equilibrium indices for {:?} are: {:?}", v, indices); }
Ethiopian multiplication
#include <stdio.h> #include <stdbool.h> void halve(int *x) { *x >>= 1; } void doublit(int *x) { *x <<= 1; } bool iseven(const int x) { return (x & 1) == 0; } int ethiopian(int plier, int plicand, const bool tutor) { int result=0; if (tutor) printf("ethiopian multiplication of %d by %d\n", plier, plicand); while(plier >= 1) { if ( iseven(plier) ) { if (tutor) printf("%4d %6d struck\n", plier, plicand); } else { if (tutor) printf("%4d %6d kept\n", plier, plicand); result += plicand; } halve(&plier); doublit(&plicand); } return result; } int main() { printf("%d\n", ethiopian(17, 34, true)); return 0; }
fn double(a: i32) -> i32 { 2*a } fn halve(a: i32) -> i32 { a/2 } fn is_even(a: i32) -> bool { a % 2 == 0 } fn ethiopian_multiplication(mut x: i32, mut y: i32) -> i32 { let mut sum = 0; while x >= 1 { print!("{} \t {}", x, y); match is_even(x) { true => println!("\t Not Kept"), false => { println!("\t Kept"); sum += y; } } x = halve(x); y = double(y); } sum } fn main() { let output = ethiopian_multiplication(17, 34); println!("---------------------------------"); println!("\t {}", output); }
Euler method
#include <stdio.h> #include <math.h> typedef double (*deriv_f)(double, double); #define FMT " %7.3f" void ivp_euler(deriv_f f, double y, int step, int end_t) { int t = 0; printf(" Step %2d: ", (int)step); do { if (t % 10 == 0) printf(FMT, y); y += step * f(t, y); } while ((t += step) <= end_t); printf("\n"); } void analytic() { double t; printf(" Time: "); for (t = 0; t <= 100; t += 10) printf(" %7g", t); printf("\nAnalytic: "); for (t = 0; t <= 100; t += 10) printf(FMT, 20 + 80 * exp(-0.07 * t)); printf("\n"); } double cooling(double t, double temp) { return -0.07 * (temp - 20); } int main() { analytic(); ivp_euler(cooling, 100, 2, 100); ivp_euler(cooling, 100, 5, 100); ivp_euler(cooling, 100, 10, 100); return 0; }
fn header() { print!(" Time: "); for t in (0..100).step_by(10) { print!(" {:7}", t); } println!(); } fn analytic() { print!("Analytic: "); for t in (0..=100).step_by(10) { print!(" {:7.3}", 20.0 + 80.0 * (-0.07 * f64::from(t)).exp()); } println!(); } fn euler<F: Fn(f64) -> f64>(f: F, mut y: f64, step: usize, end: usize) { print!(" Step {:2}: ", step); for t in (0..=end).step_by(step) { if t % 10 == 0 { print!(" {:7.3}", y); } y += step as f64 * f(y); } println!(); } fn main() { header(); analytic(); for &i in &[2, 5, 10] { euler(|temp| -0.07 * (temp - 20.0), 100.0, i, 100); } }
Euler's identity
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
use std::f64::consts::PI; extern crate num_complex; use num_complex::Complex; fn main() { println!("{:e}", Complex::new(0.0, PI).exp() + 1.0); }
Euler's sum of powers conjecture
#include <stdio.h> #include <time.h> typedef long long mylong; void compute(int N, char find_only_one_solution) { const int M = 30; int a, b, c, d, e; mylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M)); for(s=0; s < N; ++s) p5[s] = s * s, p5[s] *= p5[s] * s; for(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1); for(a = 1; a < N; ++a) for(b = a + 1; b < N; ++b) for(c = b + 1; c < N; ++c) for(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e) { for(e -= M; p5[e + M] <= s; e += M); if(p5[e] == s) { printf("%d %d %d %d %d\r\n", a, b, c, d, e); if(find_only_one_solution) goto onexit; } } onexit: free(p5); } int main(void) { int tm = clock(); compute(250, 0); printf("time=%d milliseconds\r\n", (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC)); return 0; }
const MAX_N : u64 = 250; fn eulers_sum_of_powers() -> (usize, usize, usize, usize, usize) { let pow5: Vec<u64> = (0..MAX_N).map(|i| i.pow(5)).collect(); let pow5_to_n = |pow| pow5.binary_search(&pow); for x0 in 1..MAX_N as usize { for x1 in 1..x0 { for x2 in 1..x1 { for x3 in 1..x2 { let pow_sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3]; if let Ok(n) = pow5_to_n(pow_sum) { return (x0, x1, x2, x3, n) } } } } } panic!(); } fn main() { let (x0, x1, x2, x3, y) = eulers_sum_of_powers(); println!("{}^5 + {}^5 + {}^5 + {}^5 == {}^5", x0, x1, x2, x3, y) }
Evaluate binomial coefficients
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
Even or odd
if (x & 1) { } else { }
let is_odd = |x: i32| x & 1 == 1; let is_even = |x: i32| x & 1 == 0;
Events
#include <stdio.h> #include <unistd.h> int main() { int p[2]; pipe(p); if (fork()) { close(p[0]); sleep(1); write(p[1], p, 1); wait(0); } else { close(p[1]); read(p[0], p + 1, 1); puts("received signal from pipe"); } return 0; }
use std::{sync::mpsc, thread, time::Duration}; fn main() -> Result<(), Box<dyn std::error::Error>> { println!("[1] Starting"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { println!("[2] Waiting for event"); rx.recv(); println!("[2] Received event"); }); thread::sleep(Duration::from_secs(1)); println!("[1] Sending event"); tx.send(())?; thread::sleep(Duration::from_secs(1)); Ok(()) }
Evolutionary algorithm
#include <stdio.h> #include <stdlib.h> #include <string.h> const char target[] = "METHINKS IT IS LIKE A WEASEL"; const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; #define CHOICE (sizeof(tbl) - 1) #define MUTATE 15 #define COPIES 30 int irand(int n) { int r, rand_max = RAND_MAX - (RAND_MAX % n); while((r = rand()) >= rand_max); return r / (rand_max / n); } int unfitness(const char *a, const char *b) { int i, sum = 0; for (i = 0; a[i]; i++) sum += (a[i] != b[i]); return sum; } void mutate(const char *a, char *b) { int i; for (i = 0; a[i]; i++) b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)]; b[i] = '\0'; } int main() { int i, best_i, unfit, best, iters = 0; char specimen[COPIES][sizeof(target) / sizeof(char)]; for (i = 0; target[i]; i++) specimen[0][i] = tbl[irand(CHOICE)]; specimen[0][i] = 0; do { for (i = 1; i < COPIES; i++) mutate(specimen[0], specimen[i]); for (best_i = i = 0; i < COPIES; i++) { unfit = unfitness(target, specimen[i]); if(unfit < best || !i) { best = unfit; best_i = i; } } if (best_i) strcpy(specimen[0], specimen[best_i]); printf("iter %d, score %d: %s\n", iters++, best, specimen[0]); } while (best); return 0; }
extern crate rand; use rand::Rng; fn main() { let target = "METHINKS IT IS LIKE A WEASEL"; let copies = 100; let mutation_rate = 20; let mut rng = rand::weak_rng(); let start = mutate(&mut rng, target, 1); println!("{}", target); println!("{}", start); evolve(&mut rng, target, start, copies, mutation_rate); } fn evolve<R: Rng>( rng: &mut R, target: &str, mut parent: String, copies: usize, mutation_rate: u32, ) -> usize { let mut counter = 0; let mut parent_fitness = target.len() + 1; loop { counter += 1; let (best_fitness, best_sentence) = (0..copies) .map(|_| { let sentence = mutate(rng, &parent, mutation_rate); (fitness(target, &sentence), sentence) }) .min_by_key(|&(f, _)| f) .unwrap(); if best_fitness < parent_fitness { parent = best_sentence; parent_fitness = best_fitness; println!( "{} : generation {} with fitness {}", parent, counter, best_fitness ); if best_fitness == 0 { return counter; } } } } fn fitness(target: &str, sentence: &str) -> usize { sentence .chars() .zip(target.chars()) .filter(|&(c1, c2)| c1 != c2) .count() } fn mutate<R: Rng>(rng: &mut R, sentence: &str, mutation_rate: u32) -> String { let maybe_mutate = |c| { if rng.gen_weighted_bool(mutation_rate) { random_char(rng) } else { c } }; sentence.chars().map(maybe_mutate).collect() } fn random_char<R: Rng>(rng: &mut R) -> char { match rng.gen_range(b'A', b'Z' + 2) { c if c == b'Z' + 1 => ' ', c => c as char, } }
Exceptions_Catch an exception thrown in a nested call
#include <stdio.h> #include <stdlib.h> typedef struct exception { int extype; char what[128]; } exception; typedef struct exception_ctx { exception * exs; int size; int pos; } exception_ctx; exception_ctx * Create_Ex_Ctx(int length) { const int safety = 8; char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length); if (! tmp) return NULL; exception_ctx * ctx = (exception_ctx*)tmp; ctx->size = length; ctx->pos = -1; ctx->exs = (exception*) (tmp + sizeof(exception_ctx)); return ctx; } void Free_Ex_Ctx(exception_ctx * ctx) { free(ctx); } int Has_Ex(exception_ctx * ctx) { return (ctx->pos >= 0) ? 1 : 0; } int Is_Ex_Type(exception_ctx * exctx, int extype) { return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0; } void Pop_Ex(exception_ctx * ctx) { if (ctx->pos >= 0) --ctx->pos; } const char * Get_What(exception_ctx * ctx) { if (ctx->pos >= 0) return ctx->exs[ctx->pos].what; return NULL; } int Push_Ex(exception_ctx * exctx, int extype, const char * msg) { if (++exctx->pos == exctx->size) { --exctx->pos; fprintf(stderr, "*** Error: Overflow in exception context.\n"); } snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), "%s", msg); exctx->exs[exctx->pos].extype = extype; return -1; } exception_ctx * GLOBALEX = NULL; enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR }; void baz(int n) { if (! n) { Push_Ex(GLOBALEX, U0_DRINK_ERROR , "U0 Drink Error. Insufficient drinks in bar Baz."); return; } else { Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , "U1 Bartender Error. Bartender kicked customer out of bar Baz."); return; } } void bar(int n) { fprintf(stdout, "Bar door is open.\n"); baz(n); if (Has_Ex(GLOBALEX)) goto bar_cleanup; fprintf(stdout, "Baz has been called without errors.\n"); bar_cleanup: fprintf(stdout, "Bar door is closed.\n"); } void foo() { fprintf(stdout, "Foo entering bar.\n"); bar(0); while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); Pop_Ex(GLOBALEX); } if (Has_Ex(GLOBALEX)) return; fprintf(stdout, "Foo left the bar.\n"); fprintf(stdout, "Foo entering bar again.\n"); bar(1); while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); Pop_Ex(GLOBALEX); } if (Has_Ex(GLOBALEX)) return; fprintf(stdout, "Foo left the bar.\n"); } int main(int argc, char ** argv) { exception_ctx * ctx = Create_Ex_Ctx(5); GLOBALEX = ctx; foo(); if (Has_Ex(ctx)) goto main_ex; fprintf(stdout, "No errors encountered.\n"); main_ex: while (Has_Ex(ctx)) { fprintf(stderr, "*** Error: %s\n", Get_What(ctx)); Pop_Ex(ctx); } Free_Ex_Ctx(ctx); return 0; }
#[derive(Debug)] enum U { U0(i32), U1(String), } fn baz(i: u8) -> Result<(), U> { match i { 0 => Err(U::U0(42)), 1 => Err(U::U1("This will be returned from main".into())), _ => Ok(()), } } fn bar(i: u8) -> Result<(), U> { baz(i) } fn foo() -> Result<(), U> { for i in 0..2 { match bar(i) { Ok(()) => {}, Err(U::U0(n)) => eprintln!("Caught U0 in foo: {}", n), Err(e) => return Err(e), } } Ok(()) } fn main() -> Result<(), U> { foo() }
Execute a system command
#include <stdlib.h> int main() { system("ls"); return 0; }
use std::process::Command; fn main() { let output = Command::new("ls").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) }); println!("{}", String::from_utf8_lossy(&output.stdout)); }
Exponentiation operator
#include <stdio.h> #include <assert.h> int ipow(int base, int exp) { int pow = base; int v = 1; if (exp < 0) { assert (base != 0); return (base*base != 1)? 0: (exp&1)? base : 1; } while(exp > 0 ) { if (exp & 1) v *= pow; pow *= pow; exp >>= 1; } return v; } double dpow(double base, int exp) { double v=1.0; double pow = (exp <0)? 1.0/base : base; if (exp < 0) exp = - exp; while(exp > 0 ) { if (exp & 1) v *= pow; pow *= pow; exp >>= 1; } return v; } int main() { printf("2^6 = %d\n", ipow(2,6)); printf("2^-6 = %d\n", ipow(2,-6)); printf("2.71^6 = %lf\n", dpow(2.71,6)); printf("2.71^-6 = %lf\n", dpow(2.71,-6)); }
extern crate num; use num::traits::One; use std::ops::Mul; fn pow<T>(mut base: T, mut exp: usize) -> T where T: Clone + One + Mul<T, Output=T> { if exp == 0 { return T::one() } while exp & 1 == 0 { base = base.clone() * base; exp >>= 1; } if exp == 1 { return base } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = base.clone() * base; if exp & 1 == 1 { acc = acc * base.clone(); } } acc }
Exponentiation order
#include<stdio.h> #include<math.h> int main() { printf("(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2)); printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2))); return 0; }
fn main() { println!("5**3**2 = {:7}", 5u32.pow(3).pow(2)); println!("(5**3)**2 = {:7}", (5u32.pow(3)).pow(2)); println!("5**(3**2) = {:7}", 5u32.pow(3u32.pow(2))); }
Extend your language
#define if2(firsttest,secondtest,bothtrue,firsttrue,secondtrue,bothfalse)\ switch(((firsttest)?0:2)+((secondtest)?0:1)) {\ case 0: bothtrue; break;\ case 1: firsttrue; break;\ case 2: secondtrue; break;\ case 3: bothfalse; break;\ }
#![allow(unused_variables)] macro_rules! if2 { ($cond1: expr, $cond2: expr => $both:expr => $first: expr => $second:expr => $none:expr) => { match ($cond1, $cond2) { (true, true) => $both, (true, _ ) => $first, (_ , true) => $second, _ => $none } } } fn main() { let i = 1; let j = 2; if2!(i > j, i + j >= 3 => { let k = i + j; println!("both were true") } => println!("the first was true") => println!("the second was true") => println!("neither were true") ) }
Factorial
int factorial(int n) { int result = 1; for (int i = 1; i <= n; ++i) result *= i; return result; }
fn factorial_recursive (n: u64) -> u64 { match n { 0 => 1, _ => n * factorial_recursive(n-1) } } fn factorial_iterative(n: u64) -> u64 { (1..=n).product() } fn main () { for i in 1..10 { println!("{}", factorial_recursive(i)) } for i in 1..10 { println!("{}", factorial_iterative(i)) } }
Factors of a Mersenne number
int isPrime(int n){ if (n%2==0) return n==2; if (n%3==0) return n==3; int d=5; while(d*d<=n){ if(n%d==0) return 0; d+=2; if(n%d==0) return 0; d+=4;} return 1;} main() {int i,d,p,r,q=929; if (!isPrime(q)) return 1; r=q; while(r>0) r<<=1; d=2*q+1; do { for(p=r, i= 1; p; p<<= 1){ i=((long long)i * i) % d; if (p < 0) i *= 2; if (i > d) i -= d;} if (i != 1) d += 2*q; else break; } while(1); printf("2^%d - 1 = 0 (mod %d)\n", q, d);}
fn bit_count(mut n: usize) -> usize { let mut count = 0; while n > 0 { n >>= 1; count += 1; } count } fn mod_pow(p: usize, n: usize) -> usize { let mut square = 1; let mut bits = bit_count(p); while bits > 0 { square = square * square; bits -= 1; if (p & (1 << bits)) != 0 { square <<= 1; } square %= n; } return square; } fn is_prime(n: usize) -> bool { if n < 2 { return false; } if n % 2 == 0 { return n == 2; } if n % 3 == 0 { return n == 3; } let mut p = 5; while p * p <= n { if n % p == 0 { return false; } p += 2; if n % p == 0 { return false; } p += 4; } true } fn find_mersenne_factor(p: usize) -> usize { let mut k = 0; loop { k += 1; let q = 2 * k * p + 1; if q % 8 == 1 || q % 8 == 7 { if mod_pow(p, q) == 1 && is_prime(p) { return q; } } } } fn main() { println!("{}", find_mersenne_factor(929)); }
Factors of an integer
#include <stdio.h> #include <stdlib.h> typedef struct { int *list; short count; } Factors; void xferFactors( Factors *fctrs, int *flist, int flix ) { int ix, ij; int newSize = fctrs->count + flix; if (newSize > flix) { fctrs->list = realloc( fctrs->list, newSize * sizeof(int)); } else { fctrs->list = malloc( newSize * sizeof(int)); } for (ij=0,ix=fctrs->count; ix<newSize; ij++,ix++) { fctrs->list[ix] = flist[ij]; } fctrs->count = newSize; } Factors *factor( int num, Factors *fctrs) { int flist[301], flix; int dvsr; flix = 0; fctrs->count = 0; free(fctrs->list); fctrs->list = NULL; for (dvsr=1; dvsr*dvsr < num; dvsr++) { if (num % dvsr != 0) continue; if ( flix == 300) { xferFactors( fctrs, flist, flix ); flix = 0; } flist[flix++] = dvsr; flist[flix++] = num/dvsr; } if (dvsr*dvsr == num) flist[flix++] = dvsr; if (flix > 0) xferFactors( fctrs, flist, flix ); return fctrs; } int main(int argc, char*argv[]) { int nums2factor[] = { 2059, 223092870, 3135, 45 }; Factors ftors = { NULL, 0}; char sep; int i,j; for (i=0; i<4; i++) { factor( nums2factor[i], &ftors ); printf("\nfactors of %d are:\n ", nums2factor[i]); sep = ' '; for (j=0; j<ftors.count; j++) { printf("%c %d", sep, ftors.list[j]); sep = ','; } printf("\n"); } return 0; }
fn main() { assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100)); assert_eq!(vec![1, 101], factor(101)); } fn factor(num: i32) -> Vec<i32> { let mut factors: Vec<i32> = Vec::new(); for i in 1..((num as f32).sqrt() as i32 + 1) { if num % i == 0 { factors.push(i); factors.push(num/i); } } factors.sort(); factors }
Fast Fourier transform
#include <stdio.h> #include <math.h> #include <complex.h> double PI; typedef double complex cplx; void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2); for (int i = 0; i < n; i += 2 * step) { cplx t = cexp(-I * PI * i / n) * out[i + step]; buf[i / 2] = out[i] + t; buf[(i + n)/2] = out[i] - t; } } } void fft(cplx buf[], int n) { cplx out[n]; for (int i = 0; i < n; i++) out[i] = buf[i]; _fft(buf, out, n, 1); } void show(const char * s, cplx buf[]) { printf("%s", s); for (int i = 0; i < 8; i++) if (!cimag(buf[i])) printf("%g ", creal(buf[i])); else printf("(%g, %g) ", creal(buf[i]), cimag(buf[i])); } int main() { PI = atan2(1, 1) * 4; cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0}; show("Data: ", buf); fft(buf, 8); show("\nFFT : ", buf); return 0; }
extern crate num; use num::complex::Complex; use std::f64::consts::PI; const I: Complex<f64> = Complex { re: 0.0, im: 1.0 }; pub fn fft(input: &[Complex<f64>]) -> Vec<Complex<f64>> { fn fft_inner( buf_a: &mut [Complex<f64>], buf_b: &mut [Complex<f64>], n: usize, step: usize, ) { if step >= n { return; } fft_inner(buf_b, buf_a, n, step * 2); fft_inner(&mut buf_b[step..], &mut buf_a[step..], n, step * 2); let (left, right) = buf_a.split_at_mut(n / 2); for i in (0..n).step_by(step * 2) { let t = (-I * PI * (i as f64) / (n as f64)).exp() * buf_b[i + step]; left[i / 2] = buf_b[i] + t; right[i / 2] = buf_b[i] - t; } } let n_orig = input.len(); let n = n_orig.next_power_of_two(); let mut buf_a = input.to_vec(); buf_a.append(&mut vec![Complex { re: 0.0, im: 0.0 }; n - n_orig]); let mut buf_b = buf_a.clone(); fft_inner(&mut buf_a, &mut buf_b, n, 1); buf_a } fn show(label: &str, buf: &[Complex<f64>]) { println!("{}", label); let string = buf .into_iter() .map(|x| format!("{:.4}{:+.4}i", x.re, x.im)) .collect::<Vec<_>>() .join(", "); println!("{}", string); } fn main() { let input: Vec<_> = [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0] .into_iter() .map(|x| Complex::from(x)) .collect(); show("input:", &input); let output = fft(&input); show("output:", &output); }
Fibonacci n-step number sequences
#include<stdlib.h> #include<stdio.h> int * anynacci (int *seedArray, int howMany) { int *result = malloc (howMany * sizeof (int)); int i, j, initialCardinality; for (i = 0; seedArray[i] != 0; i++); initialCardinality = i; for (i = 0; i < initialCardinality; i++) result[i] = seedArray[i]; for (i = initialCardinality; i < howMany; i++) { result[i] = 0; for (j = i - initialCardinality; j < i; j++) result[i] += result[j]; } return result; } int main () { int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 }; int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10), *lucas = anynacci(luca, 10); int i; printf ("\nFibonacci\tTribonacci\tTetranacci\tLucas\n"); for (i = 0; i < 10; i++) printf ("\n%d\t\t%d\t\t%d\t\t%d", fibonacci[i], tribonacci[i], tetranacci[i], lucas[i]); return 0; }
struct GenFibonacci { buf: Vec<u64>, sum: u64, idx: usize, } impl Iterator for GenFibonacci { type Item = u64; fn next(&mut self) -> Option<u64> { let result = Some(self.sum); self.sum -= self.buf[self.idx]; self.buf[self.idx] += self.sum; self.sum += self.buf[self.idx]; self.idx = (self.idx + 1) % self.buf.len(); result } } fn print(buf: Vec<u64>, len: usize) { let mut sum = 0; for &elt in buf.iter() { sum += elt; print!("\t{}", elt); } let iter = GenFibonacci { buf: buf, sum: sum, idx: 0 }; for x in iter.take(len) { print!("\t{}", x); } } fn main() { print!("Fib2:"); print(vec![1,1], 10 - 2); print!("\nFib3:"); print(vec![1,1,2], 10 - 3); print!("\nFib4:"); print(vec![1,1,2,4], 10 - 4); print!("\nLucas:"); print(vec![2,1], 10 - 2); }
Fibonacci sequence
fun fibb loop a = funparam[0] break (a < 2) a-- a -> stack funparam[0] = a call fibb b = funparam[0] stack -> a b -> stack a-- funparam[0] = a call fibb c = funparam[0] stack -> b b += c a = b funparam[0] = a break end end
fn main() { let mut prev = 0; let mut curr = 1usize; while let Some(n) = curr.checked_add(prev) { prev = curr; curr = n; println!("{}", n); } }
File input_output
#include <stdio.h> int main(int argc, char **argv) { FILE *in, *out; int c; in = fopen("input.txt", "r"); if (!in) { fprintf(stderr, "Error opening input.txt for reading.\n"); return 1; } out = fopen("output.txt", "w"); if (!out) { fprintf(stderr, "Error opening output.txt for writing.\n"); fclose(in); return 1; } while ((c = fgetc(in)) != EOF) { fputc(c, out); } fclose(out); fclose(in); return 0; }
use std::fs::File; use std::io::{Read, Write}; fn main() { let mut file = File::open("input.txt").unwrap(); let mut data = Vec::new(); file.read_to_end(&mut data).unwrap(); let mut file = File::create("output.txt").unwrap(); file.write_all(&data).unwrap(); }
File modification time
#include <sys/stat.h> #include <stdio.h> #include <time.h> #include <utime.h> const char *filename = "input.txt"; int main() { struct stat foo; time_t mtime; struct utimbuf new_times; if (stat(filename, &foo) < 0) { perror(filename); return 1; } mtime = foo.st_mtime; new_times.actime = foo.st_atime; new_times.modtime = time(NULL); if (utime(filename, &new_times) < 0) { perror(filename); return 1; } return 0; }
use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; if let Ok(time) = metadata.accessed() { println!("{:?}", time); } else { println!("Not supported on this platform"); } Ok(()) }
File size
#include <stdlib.h> #include <stdio.h> long getFileSize(const char *filename) { long result; FILE *fh = fopen(filename, "rb"); fseek(fh, 0, SEEK_END); result = ftell(fh); fclose(fh); return result; } int main(void) { printf("%ld\n", getFileSize("input.txt")); printf("%ld\n", getFileSize("/input.txt")); return 0; }
use std::{env, fs, process}; use std::io::{self, Write}; use std::fmt::Display; fn main() { let file_name = env::args().nth(1).unwrap_or_else(|| exit_err("No file name supplied", 1)); let metadata = fs::metadata(file_name).unwrap_or_else(|e| exit_err(e, 2)); println!("Size of file.txt is {} bytes", metadata.len()); } #[inline] fn exit_err<T: Display>(msg: T, code: i32) -> ! { writeln!(&mut io::stderr(), "Error: {}", msg).expect("Could not write to stdout"); process::exit(code) } }
Filter
#include <stdio.h> #include <stdlib.h> int even_sel(int x) { return !(x & 1); } int tri_sel(int x) { return x % 3; } int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace) { int i, j, *out; if (inplace) out = in; else out = malloc(sizeof(int) * len); for (i = j = 0; i < len; i++) if (sel(in[i])) out[j++] = in[i]; if (!inplace && j < len) out = realloc(out, sizeof(int) * j); *outlen = j; return out; } int main() { int in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int i, len; int *even = grep(in, 10, &len, even_sel, 0); printf("Filtered even:"); for (i = 0; i < len; i++) printf(" %d", even[i]); printf("\n"); grep(in, 8, &len, tri_sel, 1); printf("In-place filtered not multiple of 3:"); for (i = 0; i < len; i++) printf(" %d", in[i]); printf("\n"); return 0; }
fn main() { println!("new vec filtered: "); let nums: Vec<i32> = (1..20).collect(); let evens: Vec<i32> = nums.iter().cloned().filter(|x| x % 2 == 0).collect(); println!("{:?}", evens); println!("original vec filtered: "); let mut nums: Vec<i32> = (1..20).collect(); nums.retain(|x| x % 2 == 0); println!("{:?}", nums); }
Find common directory path
#include <stdio.h> int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue; while (pos > 0 && names[0][--pos] != sep); return pos; } } return 0; } int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]); return 0; }
use std::path::{Path, PathBuf}; fn main() { let paths = [ Path::new("/home/user1/tmp/coverage/test"), Path::new("/home/user1/tmp/covert/operator"), Path::new("/home/user1/tmp/coven/members"), ]; match common_path(&paths) { Some(p) => println!("The common path is: {:#?}", p), None => println!("No common paths found"), } } fn common_path<I, P>(paths: I) -> Option<PathBuf> where I: IntoIterator<Item = P>, P: AsRef<Path>, { let mut iter = paths.into_iter(); let mut ret = iter.next()?.as_ref().to_path_buf(); for path in iter { if let Some(r) = common(ret, path.as_ref()) { ret = r; } else { return None; } } Some(ret) } fn common<A: AsRef<Path>, B: AsRef<Path>>(a: A, b: B) -> Option<PathBuf> { let a = a.as_ref().components(); let b = b.as_ref().components(); let mut ret = PathBuf::new(); let mut found = false; for (one, two) in a.zip(b) { if one == two { ret.push(one); found = true; } else { break; } } if found { Some(ret) } else { None } }
Find limit of recursion
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
fn recurse(n: i32) { println!("depth: {}", n); recurse(n + 1) } fn main() { recurse(0); }
Find the intersection of a line with a plane
#include<stdio.h> typedef struct{ double x,y,z; }vector; vector addVectors(vector a,vector b){ return (vector){a.x+b.x,a.y+b.y,a.z+b.z}; } vector subVectors(vector a,vector b){ return (vector){a.x-b.x,a.y-b.y,a.z-b.z}; } double dotProduct(vector a,vector b){ return a.x*b.x + a.y*b.y + a.z*b.z; } vector scaleVector(double l,vector a){ return (vector){l*a.x,l*a.y,l*a.z}; } vector intersectionPoint(vector lineVector, vector linePoint, vector planeNormal, vector planePoint){ vector diff = subVectors(linePoint,planePoint); return addVectors(addVectors(diff,planePoint),scaleVector(-dotProduct(diff,planeNormal)/dotProduct(lineVector,planeNormal),lineVector)); } int main(int argC,char* argV[]) { vector lV,lP,pN,pP,iP; if(argC!=5) printf("Usage : %s <line direction, point on line, normal to plane and point on plane given as (x,y,z) tuples separated by space>"); else{ sscanf(argV[1],"(%lf,%lf,%lf)",&lV.x,&lV.y,&lV.z); sscanf(argV[3],"(%lf,%lf,%lf)",&pN.x,&pN.y,&pN.z); if(dotProduct(lV,pN)==0) printf("Line and Plane do not intersect, either parallel or line is on the plane"); else{ sscanf(argV[2],"(%lf,%lf,%lf)",&lP.x,&lP.y,&lP.z); sscanf(argV[4],"(%lf,%lf,%lf)",&pP.x,&pP.y,&pP.z); iP = intersectionPoint(lV,lP,pN,pP); printf("Intersection point is (%lf,%lf,%lf)",iP.x,iP.y,iP.z); } } return 0; }
use std::ops::{Add, Div, Mul, Sub}; #[derive(Copy, Clone, Debug, PartialEq)] struct V3<T> { x: T, y: T, z: T, } impl<T> V3<T> { fn new(x: T, y: T, z: T) -> Self { V3 { x, y, z } } } fn zip_with<F, T, U>(f: F, a: V3<T>, b: V3<T>) -> V3<U> where F: Fn(T, T) -> U, { V3 { x: f(a.x, b.x), y: f(a.y, b.y), z: f(a.z, b.z), } } impl<T> Add for V3<T> where T: Add<Output = T>, { type Output = Self; fn add(self, other: Self) -> Self { zip_with(<T>::add, self, other) } } impl<T> Sub for V3<T> where T: Sub<Output = T>, { type Output = Self; fn sub(self, other: Self) -> Self { zip_with(<T>::sub, self, other) } } impl<T> Mul for V3<T> where T: Mul<Output = T>, { type Output = Self; fn mul(self, other: Self) -> Self { zip_with(<T>::mul, self, other) } } impl<T> V3<T> where T: Mul<Output = T> + Add<Output = T>, { fn dot(self, other: Self) -> T { let V3 { x, y, z } = self * other; x + y + z } } impl<T> V3<T> where T: Mul<Output = T> + Copy, { fn scale(self, scalar: T) -> Self { self * V3 { x: scalar, y: scalar, z: scalar, } } } fn intersect<T>( ray_vector: V3<T>, ray_point: V3<T>, plane_normal: V3<T>, plane_point: V3<T>, ) -> V3<T> where T: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Copy, { let diff = ray_point - plane_point; let prod1 = diff.dot(plane_normal); let prod2 = ray_vector.dot(plane_normal); let prod3 = prod1 / prod2; ray_point - ray_vector.scale(prod3) } fn main() { let rv = V3::new(0.0, -1.0, -1.0); let rp = V3::new(0.0, 0.0, 10.0); let pn = V3::new(0.0, 0.0, 1.0); let pp = V3::new(0.0, 0.0, 5.0); println!("{:?}", intersect(rv, rp, pn, pp)); }
Find the intersection of two lines
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double lineSlope(point a,point b){ if(a.x-b.x == 0.0) return NAN; else return (a.y-b.y)/(a.x-b.x); } point extractPoint(char* str){ int i,j,start,end,length; char* holder; point c; for(i=0;str[i]!=00;i++){ if(str[i]=='(') start = i; if(str[i]==','||str[i]==')') { end = i; length = end - start; holder = (char*)malloc(length*sizeof(char)); for(j=0;j<length-1;j++) holder[j] = str[start + j + 1]; holder[j] = 00; if(str[i]==','){ start = i; c.x = atof(holder); } else c.y = atof(holder); } } return c; } point intersectionPoint(point a1,point a2,point b1,point b2){ point c; double slopeA = lineSlope(a1,a2), slopeB = lineSlope(b1,b2); if(slopeA==slopeB){ c.x = NAN; c.y = NAN; } else if(isnan(slopeA) && !isnan(slopeB)){ c.x = a1.x; c.y = (a1.x-b1.x)*slopeB + b1.y; } else if(isnan(slopeB) && !isnan(slopeA)){ c.x = b1.x; c.y = (b1.x-a1.x)*slopeA + a1.y; } else{ c.x = (slopeA*a1.x - slopeB*b1.x + b1.y - a1.y)/(slopeA - slopeB); c.y = slopeB*(c.x - b1.x) + b1.y; } return c; } int main(int argC,char* argV[]) { point c; if(argC < 5) printf("Usage : %s <four points specified as (x,y) separated by a space>",argV[0]); else{ c = intersectionPoint(extractPoint(argV[1]),extractPoint(argV[2]),extractPoint(argV[3]),extractPoint(argV[4])); if(isnan(c.x)) printf("The lines do not intersect, they are either parallel or co-incident."); else printf("Point of intersection : (%lf,%lf)",c.x,c.y); } return 0; }
#[derive(Copy, Clone, Debug)] struct Point { x: f64, y: f64, } impl Point { pub fn new(x: f64, y: f64) -> Self { Point { x, y } } } #[derive(Copy, Clone, Debug)] struct Line(Point, Point); impl Line { pub fn intersect(self, other: Self) -> Option<Point> { let a1 = self.1.y - self.0.y; let b1 = self.0.x - self.1.x; let c1 = a1 * self.0.x + b1 * self.0.y; let a2 = other.1.y - other.0.y; let b2 = other.0.x - other.1.x; let c2 = a2 * other.0.x + b2 * other.0.y; let delta = a1 * b2 - a2 * b1; if delta == 0.0 { return None; } Some(Point { x: (b2 * c1 - b1 * c2) / delta, y: (a1 * c2 - a2 * c1) / delta, }) } } fn main() { let l1 = Line(Point::new(4.0, 0.0), Point::new(6.0, 10.0)); let l2 = Line(Point::new(0.0, 3.0), Point::new(10.0, 7.0)); println!("{:?}", l1.intersect(l2)); let l1 = Line(Point::new(0.0, 0.0), Point::new(1.0, 1.0)); let l2 = Line(Point::new(1.0, 2.0), Point::new(4.0, 5.0)); println!("{:?}", l1.intersect(l2)); }
Find the missing permutation
#include <stdio.h> #define N 4 const char *perms[] = { "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB", }; int main() { int i, j, n, cnt[N]; char miss[N]; for (n = i = 1; i < N; i++) n *= i; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cnt[j] = 0; for (j = 0; j < sizeof(perms)/sizeof(const char*); j++) cnt[perms[j][i] - 'A']++; for (j = 0; j < N && cnt[j] == n; j++); miss[i] = j + 'A'; } printf("Missing: %.*s\n", N, miss); return 0; }
const GIVEN_PERMUTATIONS: [&str; 23] = [ "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" ]; fn main() { const PERMUTATION_LEN: usize = GIVEN_PERMUTATIONS[0].len(); let mut bytes_result: [u8; PERMUTATION_LEN] = [0; PERMUTATION_LEN]; for permutation in &GIVEN_PERMUTATIONS { for (i, val) in permutation.bytes().enumerate() { bytes_result[i] ^= val; } } println!("{}", std::str::from_utf8(&bytes_result).unwrap()); }
First-class functions
#include <stdlib.h> #include <stdio.h> #include <math.h> typedef double (*Class2Func)(double); double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); } double Function1( Class2Func f2, double val ) { return f2(val); } Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; } Class2Func funcListA[] = {&functionA, &sin, &cos, &tan }; Class2Func funcListB[] = {&functionB, &asin, &acos, &atan }; double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); } typedef struct sComposition { Class2Func f1; Class2Func f2; } *Composition; Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; } double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); } int main(int argc, char *argv[]) { int ix; Composition c; printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0)); for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9)); } return 0; }
#![feature(conservative_impl_trait)] fn main() { let cube = |x: f64| x.powi(3); let cube_root = |x: f64| x.powf(1.0 / 3.0); let flist : [&Fn(f64) -> f64; 3] = [&cube , &f64::sin , &f64::cos ]; let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos]; let result = flist.iter() .zip(&invlist) .map(|(f,i)| compose(f,i)(0.5)) .collect::<Vec<_>>(); println!("{:?}", result); } fn compose<'a, F, G, T, U, V>(f: F, g: G) -> impl 'a + Fn(T) -> V where F: 'a + Fn(T) -> U, G: 'a + Fn(U) -> V, { move |x| g(f(x)) }
Five weekends
#include <stdio.h> #include <time.h> static const char *months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; static int long_months[] = {0, 2, 4, 6, 7, 9, 11}; int main() { int n = 0, y, i, m; struct tm t = {0}; printf("Months with five weekends:\n"); for (y = 1900; y <= 2100; y++) { for (i = 0; i < 7; i++) { m = long_months[i]; t.tm_year = y-1900; t.tm_mon = m; t.tm_mday = 1; if (mktime(&t) == -1) { printf("Error: %d %s\n", y, months[m]); continue; } if (t.tm_wday == 5) { printf(" %d %s\n", y, months[m]); n++; } } } printf("%d total\n", n); return 0; }
extern crate chrono; use chrono::prelude::*; const LONGMONTHS: [u32; 7] = [1, 3, 5, 7, 8, 10, 12]; fn five_weekends(start: i32, end: i32) -> Vec<(i32, u32)> { let mut out = vec![]; for year in start..=end { for month in LONGMONTHS.iter() { if Local.ymd(year, *month, 1).weekday() == Weekday::Fri { out.push((year, *month)); } } } out } fn main() { let out = five_weekends(1900, 2100); let len = out.len(); println!( "There are {} months of which the first and last five are:", len ); for (y, m) in &out[..5] { println!("\t{} / {}", y, m); } println!("..."); for (y, m) in &out[(len - 5..)] { println!("\t{} / {}", y, m); } } #[test] fn test() { let out = five_weekends(1900, 2100); assert_eq!(out.len(), 201); }
Fivenum
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
#[derive(Debug)] struct FiveNum { minimum: f64, lower_quartile: f64, median: f64, upper_quartile: f64, maximum: f64, } fn median(samples: &[f64]) -> f64 { let n = samples.len(); let m = n / 2; if n % 2 == 0 { (samples[m] + samples[m - 1]) / 2.0 } else { samples[m] } } fn fivenum(samples: &[f64]) -> FiveNum { let mut xs = samples.to_vec(); xs.sort_by(|x, y| x.partial_cmp(y).unwrap()); let m = xs.len() / 2; FiveNum { minimum: xs[0], lower_quartile: median(&xs[0..(m + (xs.len() % 2))]), median: median(&xs), upper_quartile: median(&xs[m..]), maximum: xs[xs.len() - 1], } } fn main() { let inputs = vec![ vec![15., 6., 42., 41., 7., 36., 49., 40., 39., 47., 43.], vec![36., 40., 7., 39., 41., 15.], vec![ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, ], ]; for input in inputs { let result = fivenum(&input); println!("Fivenum",); println!(" Minumum: {}", result.minimum); println!(" Lower quartile: {}", result.lower_quartile); println!(" Median: {}", result.median); println!(" Upper quartile: {}", result.upper_quartile); println!(" Maximum: {}", result.maximum); } }
FizzBuzz
int i = 0 ; char B[88] ; while ( i++ < 100 ) !sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" ) ? sprintf( B, "%d", i ):0, printf( ", %s", B );
fn main() { for i in 1..=100 { match (i % 3, i % 5) { (0, 0) => println!("fizzbuzz"), (0, _) => println!("fizz"), (_, 0) => println!("buzz"), (_, _) => println!("{}", i), } } }
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(); }