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 ...
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 ...
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,...
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...
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...
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!(...
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_...
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...
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"; ...
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], stri...
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); \ } \ pth...
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); ...
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...
#[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...
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 ...
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); } ...
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(unsi...
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) ...
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...
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; ...
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; con...
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 Compo...
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 vo...
#[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.part...
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(...
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...
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) { allo...
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![]; ...
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...
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...
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.e...
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...
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)...
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][use...
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!(co...
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); ...
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_c...
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(sSta...
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...
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; ...
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() {...
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_DG...
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}, ...
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...
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", "Septemb...
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_da...
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++) { i...
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')};...
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) = ...
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 ...
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...
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 ...
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(...
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 dele...
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!=fir...
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 ...
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 ...
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); ...
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 identi...
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!...
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* ...
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 = [ "", ".", ...
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{ ...
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; } ...
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; } ...
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() ...
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) { stru...
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_loc...
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...
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, ba...
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") #d...
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", ...
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++){...
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!( ...
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 ...
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 s...
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_pro...
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 = &pi...
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...
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 (...
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().coll...
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 fal...
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 = cur...
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...
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(); ...
Egyptian division
'---Ported from the c code example to BaCon by bigbass '================================================================================== FUNCTION EGYPTIAN_DIVISION(long dividend, long divisor, long remainder) TYPE long '================================================================================== '--- remaind...
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_whi...
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) \ ...
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: u3...
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 (stat...
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...
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, ".....
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); ...
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){ wherech...
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(...
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) {...
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 +=...
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, pli...
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 N...
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")...
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(f...
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), a...
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[...
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...
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;...
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::sl...
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())...
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, t...
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; cha...
#[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...
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...
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...
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) => $s...
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!("{}", fa...
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 * ...
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 (...
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)); } ...
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); ...
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...
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, ...
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 = ...
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...
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 ...
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");...
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...
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"))...
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", metada...
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[...
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 %...
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; } in...
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),...
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 scaleVe...
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...
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(s...
#[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....
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...
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" ]; ...
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) { re...
#![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.it...
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("...
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).wee...
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]...
#[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[...
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...
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()), ...
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...
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); } ...
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...
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(), ...
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 #ifn...
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 =...