name
stringlengths
2
74
C
stringlengths
7
6.19k
Rust
stringlengths
19
8.53k
Fork
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <err.h> int main() { pid_t pid; if (!(pid = fork())) { usleep(10000); printf("\tchild process: done\n"); } else if (pid < 0) { err(1, "fork error"); } else { printf("waiting for child %d...\n", (int)pid); printf("child %d finished\n", (int)wait(0)); } return 0; }
use nix::unistd::{fork, ForkResult}; use std::process::id; fn main() { match fork() { Ok(ForkResult::Parent { child, .. }) => { println!( "This is the original process(pid: {}). New child has pid: {}", id(), child ); } Ok(ForkResult::Child) => println!("This is the new process(pid: {}).", id()), Err(_) => println!("Something went wrong."), } }
Formatted numeric output
#include <stdio.h> main(){ float r=7.125; printf(" %9.3f\n",-r); printf(" %9.3f\n",r); printf(" %-9.3f\n",r); printf(" %09.3f\n",-r); printf(" %09.3f\n",r); printf(" %-09.3f\n",r); return 0; }
fn main() { let x = 7.125; println!("{:9}", x); println!("{:09}", x); println!("{:9}", -x); println!("{:09}", -x); }
Forward difference
#include <stdlib.h> #include <string.h> #include <stdio.h> double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf("%g ", y[i]); putchar('\n'); return 0; }
fn forward_difference(input_seq: Vec<i32>, order: u32) -> Vec<i32> { match order { 0 => input_seq, 1 => { let input_seq_iter = input_seq.into_iter(); let clone_of_input_seq_iter = input_seq_iter.clone(); input_seq_iter.zip(clone_of_input_seq_iter.skip(1)).map(|(current, next)| next - current).collect() }, _ => forward_difference(forward_difference(input_seq, order - 1), 1), } } fn main() { let mut sequence = vec![90, 47, 58, 29, 22, 32, 55, 5, 55, 73]; loop { println!("{:?}", sequence); sequence = forward_difference(sequence, 1); if sequence.is_empty() { break; } } }
Four bit adder
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
fn half_adder(a: usize, b: usize) -> (usize, usize) { return (a ^ b, a & b); } fn full_adder(a: usize, b: usize, c_in: usize) -> (usize, usize) { let (s0, c0) = half_adder(a, b); let (s1, c1) = half_adder(s0, c_in); return (s1, c0 | c1); } fn four_bit_adder ( a: (usize, usize, usize, usize), b: (usize, usize, usize, usize) ) -> (usize, usize, usize, usize) { let a = a.reverse(); let b = b.reverse(); let (sum, carry) = half_adder(a.0, b.0); let out0 = sum; let (sum, carry) = full_adder(a.1, b.1, carry); let out1 = sum; let (sum, carry) = full_adder(a.2, b.2, carry); let out2 = sum; let (sum, _) = full_adder(a.3, b.3, carry); let out3 = sum; return (out3, out2, out1, out0); } fn main() { let a: (usize, usize, usize, usize) = (0, 1, 1, 0); let b: (usize, usize, usize, usize) = (0, 1, 1, 0); assert_eq!(four_bit_adder(a, b), (1, 1, 0, 0)); } trait Reverse<A, B, C, D> { fn reverse(self) -> (D, C, B, A); } impl<A, B, C, D> Reverse<A, B, C, D> for (A, B, C, D) { fn reverse(self) -> (D, C, B, A){ return (self.3, self.2, self.1, self.0) } }
Function composition
#include <stdlib.h> typedef struct double_to_double { double (*fn)(struct double_to_double *, double); } double_to_double; #define CALL(f, x) f->fn(f, x) typedef struct compose_functor { double (*fn)(struct compose_functor *, double); double_to_double *f; double_to_double *g; } compose_functor; double compose_call(compose_functor *this, double x) { return CALL(this->f, CALL(this->g, x)); } double_to_double *compose(double_to_double *f, double_to_double *g) { compose_functor *result = malloc(sizeof(compose_functor)); result->fn = &compose_call; result->f = f; result->g = g; return (double_to_double *)result; } #include <math.h> double sin_call(double_to_double *this, double x) { return sin(x); } double asin_call(double_to_double *this, double x) { return asin(x); } #include <stdio.h> int main() { double_to_double *my_sin = malloc(sizeof(double_to_double)); my_sin->fn = &sin_call; double_to_double *my_asin = malloc(sizeof(double_to_double)); my_asin->fn = &asin_call; double_to_double *sin_asin = compose(my_sin, my_asin); printf("%f\n", CALL(sin_asin, 0.5)); free(sin_asin); free(my_sin); free(my_asin); return 0; }
fn compose<'a,F,G,T,U,V>(f: F, g: G) -> Box<Fn(T) -> V + 'a> where F: Fn(U) -> V + 'a, G: Fn(T) -> U + 'a, { Box::new(move |x| f(g(x))) }
Fusc sequence
#include<limits.h> #include<stdio.h> int fusc(int n){ if(n==0||n==1) return n; else if(n%2==0) return fusc(n/2); else return fusc((n-1)/2) + fusc((n+1)/2); } int numLen(int n){ int sum = 1; while(n>9){ n = n/10; sum++; } return sum; } void printLargeFuscs(int limit){ int i,f,len,maxLen = 1; printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit); for(i=0;i<=limit;i++){ f = fusc(i); len = numLen(f); if(len>maxLen){ maxLen = len; printf("\n%5d%12d",i,f); } } } int main() { int i; printf("Index-------Value"); for(i=0;i<61;i++) printf("\n%5d%12d",i,fusc(i)); printLargeFuscs(INT_MAX); return 0; }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Gaussian elimination
#include <stdio.h> #include <stdlib.h> #include <math.h> #define mat_elem(a, y, x, n) (a + ((y) * (n) + (x))) void swap_row(double *a, double *b, int r1, int r2, int n) { double tmp, *p1, *p2; int i; if (r1 == r2) return; for (i = 0; i < n; i++) { p1 = mat_elem(a, r1, i, n); p2 = mat_elem(a, r2, i, n); tmp = *p1, *p1 = *p2, *p2 = tmp; } tmp = b[r1], b[r1] = b[r2], b[r2] = tmp; } void gauss_eliminate(double *a, double *b, double *x, int n) { #define A(y, x) (*mat_elem(a, y, x, n)) int i, j, col, row, max_row,dia; double max, tmp; for (dia = 0; dia < n; dia++) { max_row = dia, max = A(dia, dia); for (row = dia + 1; row < n; row++) if ((tmp = fabs(A(row, dia))) > max) max_row = row, max = tmp; swap_row(a, b, dia, max_row, n); for (row = dia + 1; row < n; row++) { tmp = A(row, dia) / A(dia, dia); for (col = dia+1; col < n; col++) A(row, col) -= tmp * A(dia, col); A(row, dia) = 0; b[row] -= tmp * b[dia]; } } for (row = n - 1; row >= 0; row--) { tmp = b[row]; for (j = n - 1; j > row; j--) tmp -= x[j] * A(row, j); x[row] = tmp / A(row, row); } #undef A } int main(void) { double a[] = { 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 }; double b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 }; double x[6]; int i; gauss_eliminate(a, b, x, 6); for (i = 0; i < 6; i++) printf("%g\n", x[i]); return 0; }
const SIZE: usize = 6; pub fn eliminate(mut system: [[f32; SIZE+1]; SIZE]) -> Option<Vec<f32>> { for i in 0..SIZE-1 { for j in i..SIZE-1 { if system[i][i] == 0f32 { continue; } else { let factor = system[j + 1][i] as f32 / system[i][i] as f32; for k in i..SIZE+1 { system[j + 1][k] -= factor * system[i][k] as f32; } } } } for i in (1..SIZE).rev() { if system[i][i] == 0f32 { continue; } else { for j in (1..i+1).rev() { let factor = system[j - 1][i] as f32 / system[i][i] as f32; for k in (0..SIZE+1).rev() { system[j - 1][k] -= factor * system[i][k] as f32; } } } } let mut solutions: Vec<f32> = vec![]; for i in 0..SIZE { if system[i][i] == 0f32 { return None; } else { system[i][SIZE] /= system[i][i] as f32; system[i][i] = 1f32; println!("X{} = {}", i + 1, system[i][SIZE]); solutions.push(system[i][SIZE]) } } return Some(solutions); } #[cfg(test)] mod tests { use super::*; #[test] fn eliminate_seven_by_six() { let system: [[f32; SIZE +1]; SIZE] = [ [1.00 , 0.00 , 0.00 , 0.00 , 0.00 , 0.00 , -0.01 ] , [1.00 , 0.63 , 0.39 , 0.25 , 0.16 , 0.10 , 0.61 ] , [1.00 , 1.26 , 1.58 , 1.98 , 2.49 , 3.13 , 0.91 ] , [1.00 , 1.88 , 3.55 , 6.70 , 12.62 , 23.80 , 0.99 ] , [1.00 , 2.51 , 6.32 , 15.88 , 39.90 , 100.28 , 0.60 ] , [1.00 , 3.14 , 9.87 , 31.01 , 97.41 , 306.02 , 0.02 ] ] ; let solutions = eliminate(system).unwrap(); assert_eq!(6, solutions.len()); let assert_solns = vec![-0.01, 1.60278, -1.61320, 1.24549, -0.49098, 0.06576]; for (ans, key) in solutions.iter().zip(assert_solns.iter()) { if (ans - key).abs() > 1E-4 { panic!("Test Failed!") } } } }
General FizzBuzz
#include <stdio.h> #include <stdlib.h> struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf("%s", info[it].text); found_word = 1; } } if (0 == found_word) printf("%d", i); printf("\n"); } } int main(void) { struct replace_info info[3] = { {5, "Buzz"}, {7, "Baxx"}, {3, "Fizz"} }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
use std::io; use std::io::BufRead; fn parse_entry(l: &str) -> (i32, String) { let params: Vec<&str> = l.split(' ').collect(); let divisor = params[0].parse::<i32>().unwrap(); let word = params[1].to_string(); (divisor, word) } fn main() { let stdin = io::stdin(); let mut lines = stdin.lock().lines().map(|l| l.unwrap()); let l = lines.next().unwrap(); let high = l.parse::<i32>().unwrap(); let mut entries = Vec::new(); for l in lines { if &l == "" { break } let entry = parse_entry(&l); entries.push(entry); } for i in 1..(high + 1) { let mut line = String::new(); for &(divisor, ref word) in &entries { if i % divisor == 0 { line = line + &word; } } if line == "" { println!("{}", i); } else { println!("{}", line); } } }
Generate lower case ASCII alphabet
#include <stdlib.h> #define N 26 int main() { unsigned char lower[N]; for (size_t i = 0; i < N; i++) { lower[i] = i + 'a'; } return EXIT_SUCCESS; }
fn main() { let ascii_iter = (0..26) .map(|x| (x + b'a') as char); println!("{:?}", ascii_iter.collect::<Vec<char>>()); }
Generator_Exponential
#include <inttypes.h> #include <stdlib.h> #include <stdio.h> #include <libco.h> struct gen64 { cothread_t giver; cothread_t taker; int64_t given; void (*free)(struct gen64 *); void *garbage; }; inline void yield64(struct gen64 *gen, int64_t value) { gen->given = value; co_switch(gen->taker); } inline int64_t next64(struct gen64 *gen) { gen->taker = co_active(); co_switch(gen->giver); return gen->given; } static void gen64_free(struct gen64 *gen) { co_delete(gen->giver); } struct gen64 *entry64; inline void gen64_init(struct gen64 *gen, void (*entry)(void)) { if ((gen->giver = co_create(4096, entry)) == NULL) { fputs("co_create: Cannot create cothread\n", stderr); exit(1); } gen->free = gen64_free; entry64 = gen; } void powers(struct gen64 *gen, int64_t m) { int64_t base, exponent, n, result; for (n = 0;; n++) { base = n; exponent = m; for (result = 1; exponent != 0; exponent >>= 1) { if (exponent & 1) result *= base; base *= base; } yield64(gen, result); } } #define ENTRY(name, code) static void name(void) { code; } ENTRY(enter_squares, powers(entry64, 2)) ENTRY(enter_cubes, powers(entry64, 3)) struct swc { struct gen64 cubes; struct gen64 squares; void (*old_free)(struct gen64 *); }; static void swc_free(struct gen64 *gen) { struct swc *f = gen->garbage; f->cubes.free(&f->cubes); f->squares.free(&f->squares); f->old_free(gen); } void squares_without_cubes(struct gen64 *gen) { struct swc f; int64_t c, s; gen64_init(&f.cubes, enter_cubes); c = next64(&f.cubes); gen64_init(&f.squares, enter_squares); s = next64(&f.squares); f.old_free = gen->free; gen->garbage = &f; gen->free = swc_free; for (;;) { while (c < s) c = next64(&f.cubes); if (c != s) yield64(gen, s); s = next64(&f.squares); } } ENTRY(enter_squares_without_cubes, squares_without_cubes(entry64)) int main() { struct gen64 gen; int i; gen64_init(&gen, enter_squares_without_cubes); for (i = 0; i < 20; i++) next64(&gen); for (i = 0; i < 9; i++) printf("%" PRId64 ", ", next64(&gen)); printf("%" PRId64 "\n", next64(&gen)); gen.free(&gen); return 0; }
use std::cmp::Ordering; use std::iter::Peekable; fn powers(m: u32) -> impl Iterator<Item = u64> { (0u64..).map(move |x| x.pow(m)) } fn noncubic_squares() -> impl Iterator<Item = u64> { NoncubicSquares { squares: powers(2).peekable(), cubes: powers(3).peekable(), } } struct NoncubicSquares<T: Iterator<Item = u64>, U: Iterator<Item = u64>> { squares: Peekable<T>, cubes: Peekable<U>, } impl<T: Iterator<Item = u64>, U: Iterator<Item = u64>> Iterator for NoncubicSquares<T, U> { type Item = u64; fn next(&mut self) -> Option<u64> { loop { match self.squares.peek()?.cmp(self.cubes.peek()?) { Ordering::Equal => self.squares.next(), Ordering::Greater => self.cubes.next(), Ordering::Less => return self.squares.next(), }; } } } fn main() { noncubic_squares() .skip(20) .take(10) .for_each(|x| print!("{} ", x)); println!(); }
Generic swap
void swap(void *va, void *vb, size_t s) { char t, *a = (char*)va, *b = (char*)vb; while(s--) t = a[s], a[s] = b[s], b[s] = t; }
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) { std::mem::swap(var1, var2) }
Get system command output
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { if (argc < 2) return 1; FILE *fd; fd = popen(argv[1], "r"); if (!fd) return 1; char buffer[256]; size_t chread; size_t comalloc = 256; size_t comlen = 0; char *comout = malloc(comalloc); while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) { if (comlen + chread >= comalloc) { comalloc *= 2; comout = realloc(comout, comalloc); } memmove(comout + comlen, buffer, chread); comlen += chread; } fwrite(comout, 1, comlen, stdout); free(comout); pclose(fd); return 0; }
use std::process::Command; use std::io::{Write, self}; fn main() { let output = Command::new("/bin/cat") .arg("/etc/fstab") .output() .expect("failed to execute process"); io::stdout().write(&output.stdout); }
Globally replace text in several files
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <err.h> #include <string.h> char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len) { ptrdiff_t i; char *start = buf; while (start + len < buf_end) { for (i = 0; i < len; i++) if (start[i] != pat[i]) break; if (i == len) return (char *)start; start++; } return 0; } int replace(const char *from, const char *to, const char *fname) { #define bail(msg) { warn(msg" '%s'", fname); goto done; } struct stat st; int ret = 0; char *buf = 0, *start, *end; size_t len = strlen(from), nlen = strlen(to); int fd = open(fname, O_RDWR); if (fd == -1) bail("Can't open"); if (fstat(fd, &st) == -1) bail("Can't stat"); if (!(buf = malloc(st.st_size))) bail("Can't alloc"); if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read"); start = buf; end = find_match(start, buf + st.st_size, from, len); if (!end) goto done; ftruncate(fd, 0); lseek(fd, 0, 0); do { write(fd, start, end - start); write(fd, to, nlen); start = end + len; end = find_match(start, buf + st.st_size, from, len); } while (end); if (start < buf + st.st_size) write(fd, start, buf + st.st_size - start); done: if (fd != -1) close(fd); if (buf) free(buf); return ret; } int main() { const char *from = "Goodbye, London!"; const char *to = "Hello, New York!"; const char * files[] = { "test1.txt", "test2.txt", "test3.txt" }; int i; for (i = 0; i < sizeof(files)/sizeof(char*); i++) replace(from, to, files[i]); return 0; }
use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Write; fn main() { let out_fd = OpenOptions::new() .write(true) .create(true) .open("resources/output.txt"); let write_line = |line: &str| match out_fd { Ok(ref v) => { let mut writer = BufWriter::new(v); writer.write_all(line.as_bytes()).unwrap(); } Err(ref e) => { println!("Error:{}", e); } }; match File::open("resources/paragraph.txt") { Ok(handle) => { let mut reader = BufReader::new(handle); let mut line = String::new(); reader.read_line(&mut line).unwrap(); while line.trim() != "" { let mut replaced_line = line.trim().replace("Goodbye London!", "Hello New York!"); replaced_line += "\n"; write_line(&replaced_line[..]); line.clear(); reader.read_line(&mut line).unwrap(); } } Err(e) => println!("Error:{}", e), } }
Greatest common divisor
int gcd_iter(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) while ((u %= v) && (v %= u)); return (u + v); }
extern crate num; use num::integer::gcd;
Greatest element of a list
#include <assert.h> float max(unsigned int count, float values[]) { assert(count > 0); size_t idx; float themax = values[0]; for(idx = 1; idx < count; ++idx) { themax = values[idx] > themax ? values[idx] : themax; } return themax; }
fn main() { let nums = [1,2,39,34,20]; println!("{:?}", nums.iter().max()); println!("{}", nums.iter().max().unwrap()); }
Greatest subsequential sum
#include "stdio.h" typedef struct Range { int start, end, sum; } Range; Range maxSubseq(const int sequence[], const int len) { int maxSum = 0, thisSum = 0, i = 0; int start = 0, end = -1, j; for (j = 0; j < len; j++) { thisSum += sequence[j]; if (thisSum < 0) { i = j + 1; thisSum = 0; } else if (thisSum > maxSum) { maxSum = thisSum; start = i; end = j; } } Range r; if (start <= end && start >= 0 && end >= 0) { r.start = start; r.end = end + 1; r.sum = maxSum; } else { r.start = 0; r.end = 0; r.sum = 0; } return r; } int main(int argc, char **argv) { int a[] = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1}; int alength = sizeof(a)/sizeof(a[0]); Range r = maxSubseq(a, alength); printf("Max sum = %d\n", r.sum); int i; for (i = r.start; i < r.end; i++) printf("%d ", a[i]); printf("\n"); return 0; }
fn main() { let nums = [1,2,39,34,20, -20, -16, 35, 0]; let mut max = 0; let mut boundaries = 0..0; for length in 0..nums.len() { for start in 0..nums.len()-length { let sum = (&nums[start..start+length]).iter() .fold(0, |sum, elem| sum+elem); if sum > max { max = sum; boundaries = start..start+length; } } } println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);; }
Guess the number
#include <stdlib.h> #include <stdio.h> #include <time.h> int main(void) { int n; int g; char c; srand(time(NULL)); n = 1 + (rand() % 10); puts("I'm thinking of a number between 1 and 10."); puts("Try to guess it:"); while (1) { if (scanf("%d", &g) != 1) { scanf("%c", &c); continue; } if (g == n) { puts("Correct!"); return 0; } puts("That's not my number. Try another guess:"); } }
extern crate rand; fn main() { println!("Type in an integer between 1 and 10 and press enter."); let n = rand::random::<u32>() % 10 + 1; loop { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let option: Result<u32,_> = line.trim().parse(); match option { Ok(guess) => { if guess < 1 || guess > 10 { println!("Guess is out of bounds; try again."); } else if guess == n { println!("Well guessed!"); break; } else { println!("Wrong! Try again."); } }, Err(_) => println!("Invalid input; try again.") } } }
Guess the number_With feedback
#include <stdlib.h> #include <stdio.h> #include <time.h> #define lower_limit 0 #define upper_limit 100 int main(){ int number, guess; srand( time( 0 ) ); number = lower_limit + rand() % (upper_limit - lower_limit + 1); printf( "Guess the number between %d and %d: ", lower_limit, upper_limit ); while( scanf( "%d", &guess ) == 1 ){ if( number == guess ){ printf( "You guessed correctly!\n" ); break; } printf( "Your guess was too %s.\nTry again: ", number < guess ? "high" : "low" ); } return 0; }
use rand::Rng; use std::cmp::Ordering; use std::io; const LOWEST: u32 = 1; const HIGHEST: u32 = 100; fn main() { let secret_number = rand::thread_rng().gen_range(1..101); println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
Guess the number_With feedback (player)
#include <stdio.h> int main(){ int bounds[ 2 ] = {1, 100}; char input[ 2 ] = " "; int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); do{ switch( input[ 0 ] ){ case 'H': bounds[ 1 ] = choice; break; case 'L': bounds[ 0 ] = choice; break; case 'Y': printf( "\nAwwwright\n" ); return 0; } choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Is the number %d? (Y/H/L) ", choice ); }while( scanf( "%1s", input ) == 1 ); return 0; }
use std::io::stdin; const MIN: isize = 1; const MAX: isize = 100; fn main() { loop { let mut min = MIN; let mut max = MAX; let mut num_guesses = 1; println!("Please think of a number between {} and {}", min, max); loop { let guess = (min + max) / 2; println!("Is it {}?", guess); println!("(type h if my guess is too high, l if too low, e if equal and q to quit)"); let mut line = String::new(); stdin().read_line(&mut line).unwrap(); match Some(line.chars().next().unwrap().to_uppercase().next().unwrap()) { Some('H') => { max = guess - 1; num_guesses += 1; }, Some('L')=> { min = guess + 1; num_guesses += 1; }, Some('E') => { if num_guesses == 1 { println!("\n*** That was easy! Got it in one guess! ***\n"); } else { println!("\n*** I knew it! Got it in only {} guesses! ***\n", num_guesses); } break; }, Some('Q') => return, _ => println!("Sorry, I didn't quite get that. Please try again.") } } } }
HTTP
#include <stdio.h> #include <stdlib.h> #include <curl/curl.h> int main(void) { CURL *curl; char buffer[CURL_ERROR_SIZE]; if ((curl = curl_easy_init()) != NULL) { curl_easy_setopt(curl, CURLOPT_URL, "http: curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer); if (curl_easy_perform(curl) != CURLE_OK) { fprintf(stderr, "%s\n", buffer); return EXIT_FAILURE; } curl_easy_cleanup(curl); } return EXIT_SUCCESS; }
extern crate hyper; use std::io::Read; use hyper::client::Client; fn main() { let client = Client::new(); let mut resp = client.get("http: let mut body = String::new(); resp.read_to_string(&mut body).unwrap(); println!("{}", body); }
HTTPS
#include <stdio.h> #include <stdlib.h> #include <curl/curl.h> CURL *curl; char buffer[CURL_ERROR_SIZE]; int main(void) { if ((curl = curl_easy_init()) != NULL) { curl_easy_setopt(curl, CURLOPT_URL, "https: curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer); if (curl_easy_perform(curl) != CURLE_OK) { fprintf(stderr, "%s\n", buffer); return EXIT_FAILURE; } curl_easy_cleanup(curl); } return EXIT_SUCCESS; }
extern crate reqwest; fn main() { let response = match reqwest::blocking::get("https: Ok(response) => response, Err(e) => panic!("error encountered while making request: {:?}", e), }; println!("{}", response.text().unwrap()); }
Hailstone sequence
#include <stdio.h> #include <stdlib.h> int hailstone(int n, int *arry) { int hs = 1; while (n!=1) { hs++; if (arry) *arry++ = n; n = (n&1) ? (3*n+1) : (n/2); } if (arry) *arry++ = n; return hs; } int main() { int j, hmax = 0; int jatmax, n; int *arry; for (j=1; j<100000; j++) { n = hailstone(j, NULL); if (hmax < n) { hmax = n; jatmax = j; } } n = hailstone(27, NULL); arry = malloc(n*sizeof(int)); n = hailstone(27, arry); printf("[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\n", arry[0],arry[1],arry[2],arry[3], arry[n-4], arry[n-3], arry[n-2], arry[n-1], n); printf("Max %d at j= %d\n", hmax, jatmax); free(arry); return 0; }
fn hailstone(start : u32) -> Vec<u32> { let mut res = Vec::new(); let mut next = start; res.push(start); while next != 1 { next = if next % 2 == 0 { next/2 } else { 3*next+1 }; res.push(next); } res } fn main() { let test_num = 27; let test_hailseq = hailstone(test_num); println!("For {} number of elements is {} ", test_num, test_hailseq.len()); let fst_slice = test_hailseq[0..4].iter() .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " }); let last_slice = test_hailseq[test_hailseq.len()-4..].iter() .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " }); println!(" hailstone starting with {} ending with {} ", fst_slice, last_slice); let max_range = 100000; let mut max_len = 0; let mut max_seed = 0; for i_seed in 1..max_range { let i_len = hailstone(i_seed).len(); if i_len > max_len { max_len = i_len; max_seed = i_seed; } } println!("Longest sequence is {} element long for seed {}", max_len, max_seed); }
Halt and catch fire
int main(){int a=0, b=0, c=a/b;}
fn main(){panic!("");}
Hamming numbers
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
extern crate num; num::bigint::BigUint; use std::time::Instant; fn basic_hamming(n: usize) -> BigUint { let two = BigUint::from(2u8); let three = BigUint::from(3u8); let five = BigUint::from(5u8); let mut h = vec![BigUint::from(0u8); n]; h[0] = BigUint::from(1u8); let mut x2 = BigUint::from(2u8); let mut x3 = BigUint::from(3u8); let mut x5 = BigUint::from(5u8); let mut i = 0usize; let mut j = 0usize; let mut k = 0usize; fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) { let (cs, r1) = if y == z { (0x6, y) } else if y < z { (2, y) } else { (4, z) }; if x == r1 { (cs | 1, x.clone()) } else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) } } let mut c = 1; while c < n { let (cs, e1) = { min3(&x2, &x3, &x5) }; h[c] = e1; if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] } if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] } if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] } c += 1; } match h.pop() { Some(v) => v, _ => panic!("basic_hamming: arg is zero; no elements") } } fn main() { print!("["); for (i, h) in (1..21).map(basic_hamming).enumerate() { if i != 0 { print!(",") } print!(" {}", h) } println!(" ]"); println!("{}", basic_hamming(1691)); let strt = Instant::now(); let rslt = basic_hamming(1000000); let elpsd = strt.elapsed(); let secs = elpsd.as_secs(); let millis = (elpsd.subsec_nanos() / 1000000)as u64; let dur = secs * 1000 + millis; let rs = rslt.to_str_radix(10); let mut s = rs.as_str(); println!("{} digits:", s.len()); while s.len() > 100 { let (f, r) = s.split_at(100); s = r; println!("{}", f); } println!("{}", s); println!("This last took {} milliseconds", dur); }
Handle a signal
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <time.h> #include <unistd.h> volatile sig_atomic_t gotint = 0; void handleSigint() { gotint = 1; } int main() { clock_t startTime = clock(); signal(SIGINT, handleSigint); int i=0; for (;;) { if (gotint) break; usleep(500000); if (gotint) break; printf("%d\n", ++i); } clock_t endTime = clock(); double td = (endTime - startTime) / (double)CLOCKS_PER_SEC; printf("Program has run for %5.3f seconds\n", td); return 0; }
#[cfg(unix)] fn main() { use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; use std::time::{Duration, Instant}; use libc::{sighandler_t, SIGINT}; let duration = Duration::from_secs(1) / 2; static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false); unsafe { GOT_SIGINT.store(false, Ordering::Release); unsafe fn handle_sigint() { GOT_SIGINT.store(true, Ordering::Release); } libc::signal(SIGINT, handle_sigint as sighandler_t); } let start = Instant::now(); let mut i = 0u32; loop { thread::sleep(duration); if unsafe { GOT_SIGINT.load(Ordering::Acquire) } { break; } i += 1; println!("{}", i); } let elapsed = start.elapsed(); println!("Program has run for {} seconds", elapsed.as_secs()); } #[cfg(not(unix))] fn main() { println!("Not supported on this platform"); }
Happy numbers
#include <stdio.h> #define CACHE 256 enum { h_unknown = 0, h_yes, h_no }; unsigned char buf[CACHE] = {0, h_yes, 0}; int happy(int n) { int sum = 0, x, nn; if (n < CACHE) { if (buf[n]) return 2 - buf[n]; buf[n] = h_no; } for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x; x = happy(sum); if (n < CACHE) buf[n] = 2 - x; return x; } int main() { int i, cnt = 8; for (i = 1; cnt || !printf("\n"); i++) if (happy(i)) --cnt, printf("%d ", i); printf("The %dth happy number: ", cnt = 1000000); for (i = 1; cnt; i++) if (happy(i)) --cnt || printf("%d\n", i); return 0; }
#![feature(core)] fn sumsqd(mut n: i32) -> i32 { let mut sq = 0; while n > 0 { let d = n % 10; sq += d*d; n /= 10 } sq } use std::num::Int; fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T { let mut t = a; let mut h = f(a); while t != h { t = f(t); h = f(f(h)) } t } fn ishappy(n: i32) -> bool { cycle(n, sumsqd) == 1 } fn main() { let happy = std::iter::count(1, 1) .filter(|&n| ishappy(n)) .take(8) .collect::<Vec<i32>>(); println!("{:?}", happy) }
Harshad or Niven series
#include <stdio.h> static int digsum(int n) { int sum = 0; do { sum += n % 10; } while (n /= 10); return sum; } int main(void) { int n, done, found; for (n = 1, done = found = 0; !done; ++n) { if (n % digsum(n) == 0) { if (found++ < 20) printf("%d ", n); if (n > 1000) done = printf("\n%d\n", n); } } return 0; }
fn is_harshad (n : u32) -> bool { let sum_digits = n.to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .fold(0, |a, b| a+b); n % sum_digits == 0 } fn main() { for i in (1u32..).filter(|num| is_harshad(*num)).take(20) { println!("Harshad : {}", i); } for i in (1_001u32..).filter(|num| is_harshad(*num)).take(1) { println!("First Harshad bigger than 1_000 : {}", i); } }
Hash from two arrays
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KeyType const char * #define ValType int #define HASH_SIZE 4096 unsigned strhashkey( const char * key, int max) { unsigned h=0; unsigned hl, hr; while(*key) { h += *key; hl= 0x5C5 ^ (h&0xfff00000 )>>18; hr =(h&0x000fffff ); h = hl ^ hr ^ *key++; } return h % max; } typedef struct sHme { KeyType key; ValType value; struct sHme *link; } *MapEntry; typedef struct he { MapEntry first, last; } HashElement; HashElement hash[HASH_SIZE]; typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc); typedef void (*ValCopyF)(ValType *vdest, ValType vsrc); typedef unsigned (*KeyHashF)( KeyType key, int upperBound ); typedef int (*KeyCmprF)(KeyType key1, KeyType key2); void HashAddH( KeyType key, ValType value, KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { (*copyVal)(&m_ent->value, value); } else { MapEntry last; MapEntry hme = malloc(sizeof(struct sHme)); (*copyKey)(&hme->key, key); (*copyVal)(&hme->value, value); hme->link = NULL; last = hash[hix].last; if (last) { last->link = hme; } else hash[hix].first = hme; hash[hix].last = hme; } } int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { *val = m_ent->value; } return (m_ent != NULL); } void copyStr(const char**dest, const char *src) { *dest = strdup(src); } void copyInt( int *dest, int src) { *dest = src; } int strCompare( const char *key1, const char *key2) { return strcmp(key1, key2) == 0; } void HashAdd( KeyType key, ValType value ) { HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare); } int HashGet(ValType *val, KeyType key) { return HashGetH( val, key, &strhashkey, &strCompare); } int main() { static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" }; static int valuList[] = {1,43,640, 747, 42, 42}; int ix; for (ix=0; ix<6; ix++) { HashAdd(keyList[ix], valuList[ix]); } return 0; }
use std::collections::HashMap; fn main() { let keys = ["a", "b", "c"]; let values = [1, 2, 3]; let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>(); println!("{:?}", hash); }
Haversine formula
#include <stdio.h> #include <stdlib.h> #include <math.h> #define R 6371 #define TO_RAD (3.1415926536 / 180) double dist(double th1, double ph1, double th2, double ph2) { double dx, dy, dz; ph1 -= ph2; ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD; dz = sin(th1) - sin(th2); dx = cos(ph1) * cos(th1) - cos(th2); dy = sin(ph1) * cos(th1); return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R; } int main() { double d = dist(36.12, -86.67, 33.94, -118.4); printf("dist: %.1f km (%.1f mi.)\n", d, d / 1.609344); return 0; }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Hello world_Graphical
#include <gtk/gtk.h> int main (int argc, char **argv) { GtkWidget *window; gtk_init(&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (GTK_WINDOW (window), "Goodbye, World"); g_signal_connect (G_OBJECT (window), "delete-event", gtk_main_quit, NULL); gtk_widget_show_all (window); gtk_main(); return 0; }
extern crate gtk; use gtk::traits::*; use gtk::{Window, WindowType, WindowPosition}; use gtk::signal::Inhibit; fn main() { gtk::init().unwrap(); let window = Window::new(WindowType::Toplevel).unwrap(); window.set_title("Goodbye, World!"); window.set_border_width(10); window.set_window_position(WindowPosition::Center); window.set_default_size(350, 70); window.connect_delete_event(|_,_| { gtk::main_quit(); Inhibit(false) }); window.show_all(); gtk::main(); }
Hello world_Newline omission
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { (void) printf("Goodbye, World!"); return EXIT_SUCCESS; }
fn main () { print!("Goodbye, World!"); }
Hello world_Standard error
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr); return 0; }
fn main() { eprintln!("Hello, {}!", "world"); }
Hello world_Text
const hello = "Hello world!\n" print(hello)
fn main() { print!("Hello world!"); }
Hello world_Web server
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
use std::net::{Shutdown, TcpListener}; use std::thread; use std::io::Write; const RESPONSE: &'static [u8] = b"HTTP/1.1 200 OK\r Content-Type: text/html; charset=UTF-8\r\n\r <!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title> <style>body { background-color: #111 } h1 { font-size:4cm; text-align: center; color: black; text-shadow: 0 0 2mm red}</style></head> <body><h1>Goodbye, world!</h1></body></html>\r"; fn main() { let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); for stream in listener.incoming() { thread::spawn(move || { let mut stream = stream.unwrap(); match stream.write(RESPONSE) { Ok(_) => println!("Response sent!"), Err(e) => println!("Failed sending response: {}!", e), } stream.shutdown(Shutdown::Write).unwrap(); }); } }
Heronian triangles
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ int a,b,c; int perimeter; double area; }triangle; typedef struct elem{ triangle t; struct elem* next; }cell; typedef cell* list; void addAndOrderList(list *a,triangle t){ list iter,temp; int flag = 0; if(*a==NULL){ *a = (list)malloc(sizeof(cell)); (*a)->t = t; (*a)->next = NULL; } else{ temp = (list)malloc(sizeof(cell)); iter = *a; while(iter->next!=NULL){ if(((iter->t.area<t.area)||(iter->t.area==t.area && iter->t.perimeter<t.perimeter)||(iter->t.area==t.area && iter->t.perimeter==t.perimeter && iter->t.a<=t.a)) && (iter->next==NULL||(t.area<iter->next->t.area || t.perimeter<iter->next->t.perimeter || t.a<iter->next->t.a))){ temp->t = t; temp->next = iter->next; iter->next = temp; flag = 1; break; } iter = iter->next; } if(flag!=1){ temp->t = t; temp->next = NULL; iter->next = temp; } } } int gcd(int a,int b){ if(b!=0) return gcd(b,a%b); return a; } void calculateArea(triangle *t){ (*t).perimeter = (*t).a + (*t).b + (*t).c; (*t).area = sqrt(0.5*(*t).perimeter*(0.5*(*t).perimeter - (*t).a)*(0.5*(*t).perimeter - (*t).b)*(0.5*(*t).perimeter - (*t).c)); } list generateTriangleList(int maxSide,int *count){ int a,b,c; triangle t; list herons = NULL; *count = 0; for(a=1;a<=maxSide;a++){ for(b=1;b<=a;b++){ for(c=1;c<=b;c++){ if(c+b > a && gcd(gcd(a,b),c)==1){ t = (triangle){a,b,c}; calculateArea(&t); if(t.area/(int)t.area == 1){ addAndOrderList(&herons,t); (*count)++; } } } } } return herons; } void printList(list a,int limit,int area){ list iter = a; int count = 1; printf("\nDimensions\tPerimeter\tArea"); while(iter!=NULL && count!=limit+1){ if(area==-1 ||(area==iter->t.area)){ printf("\n%d x %d x %d\t%d\t\t%d",iter->t.a,iter->t.b,iter->t.c,iter->t.perimeter,(int)iter->t.area); count++; } iter = iter->next; } } int main(int argC,char* argV[]) { int count; list herons = NULL; if(argC!=4) printf("Usage : %s <Max side, max triangles to print and area, -1 for area to ignore>",argV[0]); else{ herons = generateTriangleList(atoi(argV[1]),&count); printf("Triangles found : %d",count); (atoi(argV[3])==-1)?printf("\nPrinting first %s triangles.",argV[2]):printf("\nPrinting triangles with area %s square units.",argV[3]); printList(herons,atoi(argV[2]),atoi(argV[3])); free(herons); } return 0; }
use num_integer::Integer; use std::{f64, usize}; const MAXSIZE: usize = 200; #[derive(Debug)] struct HerionanTriangle { a: usize, b: usize, c: usize, area: usize, perimeter: usize, } fn get_area(a: &usize, b: &usize, c: &usize) -> f64 { let s = (a + b + c) as f64 / 2.; (s * (s - *a as f64) * (s - *b as f64) * (s - *c as f64)).sqrt() } fn is_heronian(a: &usize, b: &usize, c: &usize) -> bool { let area = get_area(a, b, c); area != 0. && area.fract() == 0. } fn main() { let mut heronians: Vec<HerionanTriangle> = vec![]; (1..=MAXSIZE).into_iter().for_each(|a| { (a..=MAXSIZE).into_iter().for_each(|b| { (b..=MAXSIZE).into_iter().for_each(|c| { if a + b > c && a.gcd(&b).gcd(&c) == 1 && is_heronian(&a, &b, &c) { heronians.push(HerionanTriangle { a, b, c, perimeter: a + b + c, area: get_area(&a, &b, &c) as usize, }) } }) }) }); heronians.sort_unstable_by(|x, y| { x.area .cmp(&y.area) .then(x.perimeter.cmp(&y.perimeter)) .then((x.a.max(x.b).max(x.c)).cmp(&y.a.max(y.b).max(y.c))) }); println!( "Primitive Heronian triangles with sides up to 200: {}", heronians.len() ); println!("\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:"); heronians.iter().take(10).for_each(|h| println!("{:?}", h)); println!("\nAll with area 210 subject to the previous ordering:"); heronians .iter() .filter(|h| h.area == 210) .for_each(|h| println!("{:?}", h)); }
Higher-order functions
void myFuncSimple( void (*funcParameter)(void) ) { (*funcParameter)(); funcParameter(); }
fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 { f(10) } fn square(n: u64) -> u64 { n*n } fn main() { println!("{}", execute_with_10(|n| n*n )); println!("{}", execute_with_10(square)); }
Hilbert curve
#include <stdio.h> #define N 32 #define K 3 #define MAX N * K typedef struct { int x; int y; } point; void rot(int n, point *p, int rx, int ry) { int t; if (!ry) { if (rx == 1) { p->x = n - 1 - p->x; p->y = n - 1 - p->y; } t = p->x; p->x = p->y; p->y = t; } } void d2pt(int n, int d, point *p) { int s = 1, t = d, rx, ry; p->x = 0; p->y = 0; while (s < n) { rx = 1 & (t / 2); ry = 1 & (t ^ rx); rot(s, p, rx, ry); p->x += s * rx; p->y += s * ry; t /= 4; s *= 2; } } int main() { int d, x, y, cx, cy, px, py; char pts[MAX][MAX]; point curr, prev; for (x = 0; x < MAX; ++x) for (y = 0; y < MAX; ++y) pts[x][y] = ' '; prev.x = prev.y = 0; pts[0][0] = '.'; for (d = 1; d < N * N; ++d) { d2pt(N, d, &curr); cx = curr.x * K; cy = curr.y * K; px = prev.x * K; py = prev.y * K; pts[cx][cy] = '.'; if (cx == px ) { if (py < cy) for (y = py + 1; y < cy; ++y) pts[cx][y] = '|'; else for (y = cy + 1; y < py; ++y) pts[cx][y] = '|'; } else { if (px < cx) for (x = px + 1; x < cx; ++x) pts[x][cy] = '_'; else for (x = cx + 1; x < px; ++x) pts[x][cy] = '_'; } prev = curr; } for (x = 0; x < MAX; ++x) { for (y = 0; y < MAX; ++y) printf("%c", pts[y][x]); printf("\n"); } return 0; }
use svg::node::element::path::Data; use svg::node::element::Path; struct HilbertCurve { current_x: f64, current_y: f64, current_angle: i32, line_length: f64, } impl HilbertCurve { fn new(x: f64, y: f64, length: f64, angle: i32) -> HilbertCurve { HilbertCurve { current_x: x, current_y: y, current_angle: angle, line_length: length, } } fn rewrite(order: usize) -> String { let mut str = String::from("A"); for _ in 0..order { let mut tmp = String::new(); for ch in str.chars() { match ch { 'A' => tmp.push_str("-BF+AFA+FB-"), 'B' => tmp.push_str("+AF-BFB-FA+"), _ => tmp.push(ch), } } str = tmp; } str } fn execute(&mut self, order: usize) -> Path { let mut data = Data::new().move_to((self.current_x, self.current_y)); for ch in HilbertCurve::rewrite(order).chars() { match ch { 'F' => data = self.draw_line(data), '+' => self.turn(90), '-' => self.turn(-90), _ => {} } } Path::new() .set("fill", "none") .set("stroke", "black") .set("stroke-width", "1") .set("d", data) } fn draw_line(&mut self, data: Data) -> Data { let theta = (self.current_angle as f64).to_radians(); self.current_x += self.line_length * theta.cos(); self.current_y -= self.line_length * theta.sin(); data.line_to((self.current_x, self.current_y)) } fn turn(&mut self, angle: i32) { self.current_angle = (self.current_angle + angle) % 360; } fn save(file: &str, size: usize, order: usize) -> std::io::Result<()> { use svg::node::element::Rectangle; let x = 10.0; let y = 10.0; let rect = Rectangle::new() .set("width", "100%") .set("height", "100%") .set("fill", "white"); let mut hilbert = HilbertCurve::new(x, y, 10.0, 0); let document = svg::Document::new() .set("width", size) .set("height", size) .add(rect) .add(hilbert.execute(order)); svg::save(file, &document) } } fn main() { HilbertCurve::save("hilbert_curve.svg", 650, 6).unwrap(); }
Hofstadter Figure-Figure sequences
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
use std::collections::HashMap; struct Hffs { sequence_r: HashMap<usize, usize>, sequence_s: HashMap<usize, usize>, } impl Hffs { fn new() -> Hffs { Hffs { sequence_r: HashMap::new(), sequence_s: HashMap::new(), } } fn ffr(&mut self, n: usize) -> usize { let new_r = if let Some(result) = self.sequence_r.get(&n) { *result } else if n == 0 { 1 } else { self.ffr(n - 1) + self.ffs(n - 1) }; *self.sequence_r.entry(n).or_insert(new_r) } fn ffs(&mut self, n: usize) -> usize { let new_s = if let Some(result) = self.sequence_s.get(&n) { *result } else if n == 0 { 2 } else { let lower = self.ffs(n - 1) + 1_usize; let upper = self.ffr(n) + 1_usize; let mut min_s: usize = 0; for i in lower..=upper { if !self.sequence_r.values().any(|&val| val == i) { min_s = i; break; } } min_s }; *self.sequence_s.entry(n).or_insert(new_s) } } impl Default for Hffs { fn default() -> Self { Self::new() } } fn main() { let mut hof = Hffs::new(); for i in 0..10 { println!("H:{} -> R: {}, S: {}", i, hof.ffr(i), hof.ffs(i)); } let r40 = (0..40).map(|i| hof.ffr(i)).collect::<Vec<_>>(); let mut s960 = (0..960).map(|i| hof.ffs(i)).collect::<Vec<_>>(); s960.extend(&r40); s960.sort_unstable(); let f1000 = (1_usize..=1000).collect::<Vec<_>>(); assert_eq!(f1000, s960, "Does NOT match"); }
Hofstadter-Conway $10,000 sequence
#include <stdio.h> #include <stdlib.h> int a_list[1<<20 + 1]; int doSqnc( int m) { int max_df = 0; int p2_max = 2; int v, n; int k1 = 2; int lg2 = 1; double amax = 0; a_list[0] = -50000; a_list[1] = a_list[2] = 1; v = a_list[2]; for (n=3; n <= m; n++) { v = a_list[n] = a_list[v] + a_list[n-v]; if ( amax < v*1.0/n) amax = v*1.0/n; if ( 0 == (k1&n)) { printf("Maximum between 2^%d and 2^%d was %f\n", lg2,lg2+1, amax); amax = 0; lg2++; } k1 = n; } return 1; }
struct HofstadterConway { current: usize, sequence: Vec<usize>, } impl HofstadterConway { fn new() -> HofstadterConway { HofstadterConway { current: 0, sequence: vec![1, 1], } } } impl Default for HofstadterConway { fn default() -> Self { Self::new() } } impl Iterator for HofstadterConway { type Item = usize; fn next(&mut self) -> Option<usize> { let max_index = self.sequence.len() - 1; let last_value = self.sequence[max_index]; if self.current > max_index { let new_x = self.sequence[last_value - 1] + self.sequence[max_index - last_value + 1]; self.sequence.push(new_x); } self.current += 1; Some(self.sequence[self.current - 1]) } } #[allow(clippy::cast_precision_loss)] fn main() { let mut hof = HofstadterConway::new(); let mut winning_num = 0_usize; for p in 0..20 { let max_hof = (2_usize.pow(p)..2_usize.pow(p + 1)) .map(|n| (n, hof.next().unwrap() as f64 / n as f64)) .fold(f64::NAN, |a, (n, b)| { if b >= 0.55 { winning_num = n; } a.max(b) }); println!("2^{:>2}-2^{:>2}, {:>.8}", p, p + 1, max_hof); } println!("Winning number: {}", winning_num); }
Holidays related to Easter
#include <stdio.h> typedef int year_t, month_t, week_t, day_t; typedef struct{ year_t year; month_t month; day_t month_day; day_t week_day; } date_t; const char *mon_fmt[] = {0, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; const char *week_day_fmt[] = {0, "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"}; day_t month_days(year_t year, month_t month) { day_t days[]={0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; return (month==2) ? 28 + (( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0) : days[month]; } day_t year_days(year_t year) { return (month_days(year, 2) == 28) ? 365 : 366; } month_t year_months = 12; week_t week_days = 7; date_t plusab(date_t *date, day_t days) { while(days < 0){ date->year -= 1; days += year_days(date->year); }; while(days > year_days(date->year)){ days -= year_days(date->year); date->year += 1; }; date->month_day += days; while(date->month_day > month_days(date->year, date->month)){ date->month_day -= month_days(date->year, date->month); date->month += 1; if(date->month > year_months){ date->month -= year_months; date->year += 1; } } date->week_day = week_day(*date); return *date; } date_t easter (year_t year) { date_t date; date.year = year; int c = year / 100, n = year % 19; int i = (c - c / 4 - (c - (c - 17) / 25) / 3 + 19 * n + 15) % 30; i -= (i / 28) * (1 - (i / 28) * (29 / (i + 1)) * ((21 - n) / 11)); int l = i - (year + year / 4 + i + 2 - c + c / 4) % 7; date.month = 3 + (l + 40) / 44; date.month_day = l + 28 - 31 * (date.month / 4); date.week_day = week_day(date); return date; } day_t week_day (date_t date) { int year = date.year, month = date.month, month_day = date.month_day, c; if(month <= 2){month += 12; year -= 1;} c = year / 100; year %= 100; return 1 + ((month_day + ((month + 1) * 26) / 10 + year + year / 4 + c / 4 - 2 * c) % 7 + 7) % 7; } #define wdmdm_fmt "%s %2d %s" typedef struct{date_t easter, ascension, pentecost, trinity, corpus_christi;}easter_related_t; easter_related_t easter_related_init (year_t year) { date_t date; easter_related_t holidays; holidays.easter = date = easter(year); holidays.ascension = plusab(&date, 39); holidays.pentecost = plusab(&date, 10); holidays.trinity = plusab(&date, 7); holidays.corpus_christi = plusab(&date, 4); return holidays; } #define easter_related_fmt "%4d Easter: "wdmdm_fmt", Ascension: "wdmdm_fmt\ ", Pentecost: "wdmdm_fmt", Trinity: "wdmdm_fmt", Corpus: "wdmdm_fmt"\n" void easter_related_print(year_t year) { easter_related_t holidays = easter_related_init(year); #define wdmdm(date) week_day_fmt[date.week_day], date.month_day, mon_fmt[date.month] printf(easter_related_fmt, year, wdmdm(holidays.easter), wdmdm(holidays.ascension), wdmdm(holidays.pentecost), wdmdm(holidays.trinity), wdmdm(holidays.corpus_christi)); } int main(){ year_t year; printf ("Christian holidays, related to Easter, for each centennial from 400 to 2100 CE:\n"); for(year=400; year<=2100; year+=100){ easter_related_print(year); } printf ("\nChristian holidays, related to Easter, for years from 2010 to 2020 CE:\n"); for(year=2010; year<=2020; year++){ easter_related_print(year); } return 0; }
use std::ops::Add; use chrono::{prelude::*, Duration}; #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_wrap)] fn get_easter_day(year: u32) -> chrono::NaiveDate { let k = (f64::from(year) / 100.).floor(); let d = (19 * (year % 19) + ((15 - ((13. + 8. * k) / 25.).floor() as u32 + k as u32 - (k / 4.).floor() as u32) % 30)) % 30; let e = (2 * (year % 4) + 4 * (year % 7) + 6 * d + ((4 + k as u32 - (k / 4.).floor() as u32) % 7)) % 7; let (month, day) = match d { 29 if e == 6 => (4, 19), 28 if e == 6 => (4, 18), _ if d + e < 10 => (3, 22 + d + e), _ => (4, d + e - 9), }; NaiveDate::from_ymd(year as i32, month, day) } fn main() { let holidays = vec![ ("Easter", Duration::days(0)), ("Ascension", Duration::days(39)), ("Pentecost", Duration::days(49)), ("Trinity", Duration::days(56)), ("Corpus Christi", Duration::days(60)), ]; for year in (400..=2100).step_by(100).chain(2010..=2020) { print!("{}: ", year); for (name, offset) in &holidays { print!( "{}: {}, ", name, get_easter_day(year).add(*offset).format("%a %d %h") ); } println!(); } }
Horizontal sundial calculations
#include <stdio.h> #include <math.h> #define PICKVALUE(TXT, VM) do { \ printf("%s: ", TXT); \ scanf("%lf", &VM); \ } while(0); #if !defined(M_PI) #define M_PI 3.14159265358979323846 #endif #define DR(X) ((X)*M_PI/180.0) #define RD(X) ((X)*180.0/M_PI) int main() { double lat, slat, lng, ref; int h; PICKVALUE("Enter latitude", lat); PICKVALUE("Enter longitude", lng); PICKVALUE("Enter legal meridian", ref); printf("\n"); slat = sin(DR(lat)); printf("sine of latitude: %.3f\n", slat); printf("diff longitude: %.3f\n\n", lng - ref); printf("Hour, sun hour angle, dial hour line angle from 6am to 6pm\n"); for(h = -6; h <= 6; h++) { double hla, hra; hra = 15.0*h; hra = hra - lng + ref; hla = RD(atan(slat * tan(DR(hra)))); printf("HR= %3d; \t HRA=%7.3f; \t HLA= %7.3f\n", h, hra, hla); } return 0; }
use std::io; struct SundialCalculation { hour_angle: f64, hour_line_angle: f64, } fn get_input(prompt: &str) -> Result<f64, Box<dyn std::error::Error>> { println!("{}", prompt); let mut input = String::new(); let stdin = io::stdin(); stdin.read_line(&mut input)?; Ok(input.trim().parse::<f64>()?) } fn calculate_sundial(hour: i8, lat: f64, lng: f64, meridian: f64) -> SundialCalculation { let diff = lng - meridian; let hour_angle = f64::from(hour) * 15. - diff; let hour_line_angle = (hour_angle.to_radians().tan() * lat.to_radians().sin()) .atan() .to_degrees(); SundialCalculation { hour_angle, hour_line_angle, } } fn main() -> Result<(), Box<dyn std::error::Error>> { let lat = get_input("Enter latitude => ")?; let lng = get_input("Enter longitude => ")?; let meridian = get_input("Enter legal meridian => ")?; let diff = lng - meridian; let sine_lat = lat.to_radians().sin(); println!("Sine of latitude: {:.5}", sine_lat); println!("Diff longitude: {}", diff); println!(" Hrs Angle Hour Line Angle"); (-6..=6).for_each(|hour| { let sd = calculate_sundial(hour, lat, lng, meridian); println!( "{:>3}{} {:>5} {:>+15.5}", if hour == 0 { 12 } else { (hour + 12) % 12 }, if hour <= 6 { "pm" } else { "am" }, sd.hour_angle, sd.hour_line_angle ); }); Ok(()) }
Horner's rule for polynomial evaluation
#include <stdio.h> double horner(double *coeffs, int s, double x) { int i; double res = 0.0; for(i=s-1; i >= 0; i--) { res = res * x + coeffs[i]; } return res; } int main() { double coeffs[] = { -19.0, 7.0, -4.0, 6.0 }; printf("%5.1f\n", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0)); return 0; }
fn horner(v: &[f64], x: f64) -> f64 { v.iter().rev().fold(0.0, |acc, coeff| acc*x + coeff) } fn main() { let v = [-19., 7., -4., 6.]; println!("result: {}", horner(&v, 3.0)); }
Host introspection
#include <stdio.h> #include <stddef.h> #include <limits.h> int main() { int one = 1; printf("word size = %d bits\n", (int)(CHAR_BIT * sizeof(size_t))); if (*(char *)&one) printf("little endian\n"); else printf("big endian\n"); return 0; }
#[derive(Copy, Clone, Debug)] enum Endianness { Big, Little, } impl Endianness { fn target() -> Self { #[cfg(target_endian = "big")] { Endianness::Big } #[cfg(not(target_endian = "big"))] { Endianness::Little } } } fn main() { println!("Word size: {} bytes", std::mem::size_of::<usize>()); println!("Endianness: {:?}", Endianness::target()); }
Hostname
#include <stdlib.h> #include <stdio.h> #include <limits.h> #include <unistd.h> int main(void) { char name[_POSIX_HOST_NAME_MAX + 1]; return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS; }
fn main() { match hostname::get_hostname() { Some(host) => println!("hostname: {}", host), None => eprintln!("Could not get hostname!"), } }
Huffman coding
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BYTES 256 struct huffcode { int nbits; int code; }; typedef struct huffcode huffcode_t; struct huffheap { int *h; int n, s, cs; long *f; }; typedef struct huffheap heap_t; static heap_t *_heap_create(int s, long *f) { heap_t *h; h = malloc(sizeof(heap_t)); h->h = malloc(sizeof(int)*s); h->s = h->cs = s; h->n = 0; h->f = f; return h; } static void _heap_destroy(heap_t *heap) { free(heap->h); free(heap); } #define swap_(I,J) do { int t_; t_ = a[(I)]; \ a[(I)] = a[(J)]; a[(J)] = t_; } while(0) static void _heap_sort(heap_t *heap) { int i=1, j=2; int *a = heap->h; while(i < heap->n) { if ( heap->f[a[i-1]] >= heap->f[a[i]] ) { i = j; j++; } else { swap_(i-1, i); i--; i = (i==0) ? j++ : i; } } } #undef swap_ static void _heap_add(heap_t *heap, int c) { if ( (heap->n + 1) > heap->s ) { heap->h = realloc(heap->h, heap->s + heap->cs); heap->s += heap->cs; } heap->h[heap->n] = c; heap->n++; _heap_sort(heap); } static int _heap_remove(heap_t *heap) { if ( heap->n > 0 ) { heap->n--; return heap->h[heap->n]; } return -1; } huffcode_t **create_huffman_codes(long *freqs) { huffcode_t **codes; heap_t *heap; long efreqs[BYTES*2]; int preds[BYTES*2]; int i, extf=BYTES; int r1, r2; memcpy(efreqs, freqs, sizeof(long)*BYTES); memset(&efreqs[BYTES], 0, sizeof(long)*BYTES); heap = _heap_create(BYTES*2, efreqs); if ( heap == NULL ) return NULL; for(i=0; i < BYTES; i++) if ( efreqs[i] > 0 ) _heap_add(heap, i); while( heap->n > 1 ) { r1 = _heap_remove(heap); r2 = _heap_remove(heap); efreqs[extf] = efreqs[r1] + efreqs[r2]; _heap_add(heap, extf); preds[r1] = extf; preds[r2] = -extf; extf++; } r1 = _heap_remove(heap); preds[r1] = r1; _heap_destroy(heap); codes = malloc(sizeof(huffcode_t *)*BYTES); int bc, bn, ix; for(i=0; i < BYTES; i++) { bc=0; bn=0; if ( efreqs[i] == 0 ) { codes[i] = NULL; continue; } ix = i; while( abs(preds[ix]) != ix ) { bc |= ((preds[ix] >= 0) ? 1 : 0 ) << bn; ix = abs(preds[ix]); bn++; } codes[i] = malloc(sizeof(huffcode_t)); codes[i]->nbits = bn; codes[i]->code = bc; } return codes; } void free_huffman_codes(huffcode_t **c) { int i; for(i=0; i < BYTES; i++) free(c[i]); free(c); } #define MAXBITSPERCODE 100 void inttobits(int c, int n, char *s) { s[n] = 0; while(n > 0) { s[n-1] = (c%2) + '0'; c >>= 1; n--; } } const char *test = "this is an example for huffman encoding"; int main() { huffcode_t **r; int i; char strbit[MAXBITSPERCODE]; const char *p; long freqs[BYTES]; memset(freqs, 0, sizeof freqs); p = test; while(*p != '\0') freqs[*p++]++; r = create_huffman_codes(freqs); for(i=0; i < BYTES; i++) { if ( r[i] != NULL ) { inttobits(r[i]->code, r[i]->nbits, strbit); printf("%c (%d) %s\n", i, r[i]->code, strbit); } } free_huffman_codes(r); return 0; }
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
IBAN
#include <alloca.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define V(cc, exp) if (!strncmp(iban, cc, 2)) return len == exp int valid_cc(const char *iban, int len) { V("AL", 28); V("AD", 24); V("AT", 20); V("AZ", 28); V("BE", 16); V("BH", 22); V("BA", 20); V("BR", 29); V("BG", 22); V("CR", 21); V("HR", 21); V("CY", 28); V("CZ", 24); V("DK", 18); V("DO", 28); V("EE", 20); V("FO", 18); V("FI", 18); V("FR", 27); V("GE", 22); V("DE", 22); V("GI", 23); V("GR", 27); V("GL", 18); V("GT", 28); V("HU", 28); V("IS", 26); V("IE", 22); V("IL", 23); V("IT", 27); V("KZ", 20); V("KW", 30); V("LV", 21); V("LB", 28); V("LI", 21); V("LT", 20); V("LU", 20); V("MK", 19); V("MT", 31); V("MR", 27); V("MU", 30); V("MC", 27); V("MD", 24); V("ME", 22); V("NL", 18); V("NO", 15); V("PK", 24); V("PS", 29); V("PL", 28); V("PT", 25); V("RO", 24); V("SM", 27); V("SA", 24); V("RS", 22); V("SK", 24); V("SI", 19); V("ES", 24); V("SE", 24); V("CH", 21); V("TN", 24); V("TR", 26); V("AE", 23); V("GB", 22); V("VG", 24); return 0; } int strip(char *s) { int i = -1, m = 0; while(s[++i]) { s[i - m] = s[i]; m += s[i] <= 32; } s[i - m] = 0; return i - m; } int mod97(const char *s, int len) { int i, j, parts = len / 7; char rem[10] = "00"; for (i = 1; i <= parts + (len % 7 != 0); ++i) { strncpy(rem + 2, s + (i - 1) * 7, 7); j = atoi(rem) % 97; rem[0] = j / 10 + '0'; rem[1] = j % 10 + '0'; } return atoi(rem) % 97; } int valid_iban(char *iban) { int i, j, l = 0, sz = strip(iban); char *rot, *trans; for (i = 0; i < sz; ++i) { if (!isdigit(iban[i]) && !isupper(iban[i])) return 0; l += !!isupper(iban[i]); } if (!valid_cc(iban, sz)) return 0; rot = alloca(sz); strcpy(rot, iban + 4); strncpy(rot + sz - 4, iban, 4); trans = alloca(sz + l + 1); trans[sz + l] = 0; for (i = j = 0; i < sz; ++i, ++j) { if (isdigit(rot[i])) trans[j] = rot[i]; else { trans[j] = (rot[i] - 55) / 10 + '0'; trans[++j] = (rot[i] - 55) % 10 + '0'; } } return mod97(trans, sz + l) == 1; } int main(int _, char **argv) { while (--_, *++argv) printf("%s is %svalid.\n", *argv, valid_iban(*argv) ? "" : "in"); return 0; }
fn main() { for iban in [ "", "x", "QQ82", "QQ82W", "GB82 TEST 1234 5698 7654 322", "gb82 WEST 1234 5698 7654 32", "GB82 WEST 1234 5698 7654 32", "GB82 TEST 1234 5698 7654 32", "GB81 WEST 1234 5698 7654 32", "SA03 8000 0000 6080 1016 7519", "CH93 0076 2011 6238 5295 7", ].iter() { println!( "'{}' is {}valid", iban, if validate_iban(iban) { "" } else { "NOT " } ); } } fn validate_iban(iban: &str) -> bool { let iso_len = [ ("AL", 28), ("AD", 24), ("AT", 20), ("AZ", 28), ("BE", 16), ("BH", 22), ("BA", 20), ("BR", 29), ("BG", 22), ("HR", 21), ("CY", 28), ("CZ", 24), ("DK", 18), ("DO", 28), ("EE", 20), ("FO", 18), ("FI", 18), ("FR", 27), ("GE", 22), ("DE", 22), ("GI", 23), ("GL", 18), ("GT", 28), ("HU", 28), ("IS", 26), ("IE", 22), ("IL", 23), ("IT", 27), ("KZ", 20), ("KW", 30), ("LV", 21), ("LB", 28), ("LI", 21), ("LT", 20), ("LU", 20), ("MK", 19), ("MT", 31), ("MR", 27), ("MU", 30), ("MC", 27), ("MD", 24), ("ME", 22), ("NL", 18), ("NO", 15), ("PK", 24), ("PS", 29), ("PL", 28), ("PT", 25), ("RO", 24), ("SM", 27), ("SA", 24), ("RS", 22), ("SK", 24), ("SI", 19), ("ES", 24), ("SE", 24), ("CH", 21), ("TN", 24), ("TR", 26), ("AE", 23), ("GB", 22), ("VG", 24), ("GR", 27), ("CR", 21), ]; let trimmed_iban = iban.chars() .filter(|&ch| ch != ' ') .collect::<String>() .to_uppercase(); if trimmed_iban.len() < 4 { return false; } let prefix = &trimmed_iban[0..2]; if let Some(pair) = iso_len.iter().find(|&&(code, _)| code == prefix) { if pair.1 != trimmed_iban.len() { return false; } } else { return false; } let reversed_iban = format!("{}{}", &trimmed_iban[4..], &trimmed_iban[0..4]); let mut expanded_iban = String::new(); for ch in reversed_iban.chars() { expanded_iban.push_str(&if ch.is_numeric() { format!("{}", ch) } else { format!("{}", ch as u8 - 'A' as u8 + 10u8) }); } expanded_iban.bytes().fold(0, |acc, ch| { (acc * 10 + ch as u32 - '0' as u32) % 97 }) == 1 }
ISBN13 check digit
#include <stdio.h> int check_isbn13(const char *isbn) { int ch = *isbn, count = 0, sum = 0; for ( ; ch != 0; ch = *++isbn, ++count) { if (ch == ' ' || ch == '-') { --count; continue; } if (ch < '0' || ch > '9') { return 0; } if (count & 1) { sum += 3 * (ch - '0'); } else { sum += ch - '0'; } } if (count != 13) return 0; return !(sum%10); } int main() { int i; const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}; for (i = 0; i < 4; ++i) { printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad"); } return 0; }
fn main() { let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]; isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn))); } fn check_isbn(isbn: &str) -> bool { if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 { return false; } let checksum = isbn.chars().filter_map(|c| c.to_digit(10)) .zip([1, 3].iter().cycle()) .fold(0, |acc, (val, fac)| acc + val * fac); checksum % 10 == 0 }
Identity matrix
#include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { if (argc < 2) { printf("usage: identitymatrix <number of rows>\n"); exit(EXIT_FAILURE); } int rowsize = atoi(argv[1]); if (rowsize < 0) { printf("Dimensions of matrix cannot be negative\n"); exit(EXIT_FAILURE); } int numElements = rowsize * rowsize; if (numElements < rowsize) { printf("Squaring %d caused result to overflow to %d.\n", rowsize, numElements); abort(); } int** matrix = calloc(numElements, sizeof(int*)); if (!matrix) { printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int*)); abort(); } for (unsigned int row = 0;row < rowsize;row++) { matrix[row] = calloc(numElements, sizeof(int)); if (!matrix[row]) { printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int)); abort(); } matrix[row][row] = 1; } printf("Matrix is: \n"); for (unsigned int row = 0;row < rowsize;row++) { for (unsigned int column = 0;column < rowsize;column++) { printf("%d ", matrix[row][column]); } printf("\n"); } }
extern crate num; struct Matrix<T> { data: Vec<T>, size: usize, } impl<T> Matrix<T> where T: num::Num + Clone + Copy, { fn new(size: usize) -> Self { Self { data: vec![T::zero(); size * size], size: size, } } fn get(&mut self, x: usize, y: usize) -> T { self.data[x + self.size * y] } fn identity(&mut self) { for (i, item) in self.data.iter_mut().enumerate() { *item = if i % (self.size + 1) == 0 { T::one() } else { T::zero() } } } } fn main() { let size = std::env::args().nth(1).unwrap().parse().unwrap(); let mut matrix = Matrix::<i32>::new(size); matrix.identity(); for y in 0..size { for x in 0..size { print!("{} ", matrix.get(x, y)); } println!(); } }
Increment a numerical string
#include <stdio.h> #include <string.h> #include <stdlib.h> char * incr(char *s) { int i, begin, tail, len; int neg = (*s == '-'); char tgt = neg ? '0' : '9'; if (!strcmp(s, "-1")) { s[0] = '0', s[1] = '\0'; return s; } len = strlen(s); begin = (*s == '-' || *s == '+') ? 1 : 0; for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--); if (tail < begin && !neg) { if (!begin) s = realloc(s, len + 2); s[0] = '1'; for (i = 1; i <= len - begin; i++) s[i] = '0'; s[len + 1] = '\0'; } else if (tail == begin && neg && s[1] == '1') { for (i = 1; i < len - begin; i++) s[i] = '9'; s[len - 1] = '\0'; } else { for (i = len - 1; i > tail; i--) s[i] = neg ? '9' : '0'; s[tail] += neg ? -1 : 1; } return s; } void string_test(const char *s) { char *ret = malloc(strlen(s)); strcpy(ret, s); printf("text: %s\n", ret); printf(" ->: %s\n", ret = incr(ret)); free(ret); } int main() { string_test("+0"); string_test("-1"); string_test("-41"); string_test("+41"); string_test("999"); string_test("+999"); string_test("109999999999999999999999999999999999999999"); string_test("-100000000000000000000000000000000000000000000"); return 0; }
fn next_string(input: &str) -> String { (input.parse::<i64>().unwrap() + 1).to_string() } fn main() { let s = "-1"; let s2 = next_string(s); println!("{:?}", s2); }
Infinity
#include <math.h> #include <stdio.h> double inf(void) { return HUGE_VAL; } int main() { printf("%g\n", inf()); return 0; }
fn main() { let inf = f32::INFINITY; println!("{}", inf); }
Inheritance_Multiple
typedef struct{ double focalLength; double resolution; double memory; }Camera; typedef struct{ double balance; double batteryLevel; char** contacts; }Phone; typedef struct{ Camera cameraSample; Phone phoneSample; }CameraPhone;
trait Camera {} trait MobilePhone {} trait CameraPhone: Camera + MobilePhone {}
Input loop
#include <stdlib.h> #include <stdio.h> char *get_line(FILE* fp) { int len = 0, got = 0, c; char *buf = 0; while ((c = fgetc(fp)) != EOF) { if (got + 1 >= len) { len *= 2; if (len < 4) len = 4; buf = realloc(buf, len); } buf[got++] = c; if (c == '\n') break; } if (c == EOF && !got) return 0; buf[got++] = '\0'; return buf; } int main() { char *s; while ((s = get_line(stdin))) { printf("%s",s); free(s); } return 0; }
use std::io::{self, BufReader, Read, BufRead}; use std::fs::File; fn main() { print_by_line(io::stdin()) .expect("Could not read from stdin"); File::open("/etc/fstab") .and_then(print_by_line) .expect("Could not read from file"); } fn print_by_line<T: Read>(reader: T) -> io::Result<()> { let buffer = BufReader::new(reader); for line in buffer.lines() { println!("{}", line?) } Ok(()) }
Integer comparison
#include <stdio.h> int main() { int a, b; scanf("%d %d", &a, &b); if (a < b) printf("%d is less than %d\n", a, b); if (a == b) printf("%d is equal to %d\n", a, b); if (a > b) printf("%d is greater than %d\n", a, b); return 0; }
use std::io::{self, BufRead}; fn main() { let mut reader = io::stdin(); let mut buffer = String::new(); let mut lines = reader.lock().lines().take(2); let nums: Vec<i32>= lines.map(|string| string.unwrap().trim().parse().unwrap() ).collect(); let a: i32 = nums[0]; let b: i32 = nums[1]; if a < b { println!("{} is less than {}" , a , b) } else if a == b { println!("{} equals {}" , a , b) } else if a > b { println!("{} is greater than {}" , a , b) }; }
Integer overflow
#include <stdio.h> int main (int argc, char *argv[]) { printf("Signed 32-bit:\n"); printf("%d\n", -(-2147483647-1)); printf("%d\n", 2000000000 + 2000000000); printf("%d\n", -2147483647 - 2147483647); printf("%d\n", 46341 * 46341); printf("%d\n", (-2147483647-1) / -1); printf("Signed 64-bit:\n"); printf("%ld\n", -(-9223372036854775807-1)); printf("%ld\n", 5000000000000000000+5000000000000000000); printf("%ld\n", -9223372036854775807 - 9223372036854775807); printf("%ld\n", 3037000500 * 3037000500); printf("%ld\n", (-9223372036854775807-1) / -1); printf("Unsigned 32-bit:\n"); printf("%u\n", -4294967295U); printf("%u\n", 3000000000U + 3000000000U); printf("%u\n", 2147483647U - 4294967295U); printf("%u\n", 65537U * 65537U); printf("Unsigned 64-bit:\n"); printf("%lu\n", -18446744073709551615LU); printf("%lu\n", 10000000000000000000LU + 10000000000000000000LU); printf("%lu\n", 9223372036854775807LU - 18446744073709551615LU); printf("%lu\n", 4294967296LU * 4294967296LU); return 0; }
let i32_1 : i32 = -(-2_147_483_647 - 1); let i32_2 : i32 = 2_000_000_000 + 2_000_000_000; let i32_3 : i32 = -2_147_483_647 - 2_147_483_647; let i32_4 : i32 = 46341 * 46341; let i32_5 : i32 = (-2_147_483_647 - 1) / -1; let i64_1 : i64 = -(-9_223_372_036_854_775_807 - 1); let i64_2 : i64 = 5_000_000_000_000_000_000 + 5_000_000_000_000_000_000; let i64_3 : i64 = -9_223_372_036_854_775_807 - 9_223_372_036_854_775_807; let i64_4 : i64 = 3_037_000_500 * 3_037_000_500; let i64_5 : i64 = (-9_223_372_036_854_775_807 - 1) / -1;
Integer sequence
#include <stdio.h> int main() { unsigned int i = 0; while (++i) printf("%u\n", i); return 0; }
fn main() { for i in 0.. { println!("{}", i); } }
Inverted index
#include <stdio.h> #include <stdlib.h> char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./"; int chr_idx[256] = {0}; char idx_chr[256] = {0}; #define FNAME 0 typedef struct trie_t *trie, trie_t; struct trie_t { trie next[sizeof(chr_legal)]; int eow; }; trie trie_new() { return calloc(sizeof(trie_t), 1); } #define find_word(r, w) trie_trav(r, w, 1) trie trie_trav(trie root, const char * str, int no_create) { int c; while (root) { if ((c = str[0]) == '\0') { if (!root->eow && no_create) return 0; break; } if (! (c = chr_idx[c]) ) { str++; continue; } if (!root->next[c]) { if (no_create) return 0; root->next[c] = trie_new(); } root = root->next[c]; str++; } return root; } int trie_all(trie root, char path[], int depth, int (*callback)(char *)) { int i; if (root->eow && !callback(path)) return 0; for (i = 1; i < sizeof(chr_legal); i++) { if (!root->next[i]) continue; path[depth] = idx_chr[i]; path[depth + 1] = '\0'; if (!trie_all(root->next[i], path, depth + 1, callback)) return 0; } return 1; } void add_index(trie root, const char *word, const char *fname) { trie x = trie_trav(root, word, 0); x->eow = 1; if (!x->next[FNAME]) x->next[FNAME] = trie_new(); x = trie_trav(x->next[FNAME], fname, 0); x->eow = 1; } int print_path(char *path) { printf(" %s", path); return 1; } const char *files[] = { "f1.txt", "source/f2.txt", "other_file" }; const char *text[][5] ={{ "it", "is", "what", "it", "is" }, { "what", "is", "it", 0 }, { "it", "is", "a", "banana", 0 }}; trie init_tables() { int i, j; trie root = trie_new(); for (i = 0; i < sizeof(chr_legal); i++) { chr_idx[(int)chr_legal[i]] = i + 1; idx_chr[i + 1] = chr_legal[i]; } #define USE_ADVANCED_FILE_HANDLING 0 #if USE_ADVANCED_FILE_HANDLING void read_file(const char * fname) { char cmd[1024]; char word[1024]; sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname); FILE *in = popen(cmd, "r"); while (!feof(in)) { fscanf(in, "%1000s", word); add_index(root, word, fname); } pclose(in); }; read_file("f1.txt"); read_file("source/f2.txt"); read_file("other_file"); #else for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) { if (!text[i][j]) break; add_index(root, text[i][j], files[i]); } } #endif return root; } void search_index(trie root, const char *word) { char path[1024]; printf("Search for \"%s\": ", word); trie found = find_word(root, word); if (!found) printf("not found\n"); else { trie_all(found->next[FNAME], path, 0, print_path); printf("\n"); } } int main() { trie root = init_tables(); search_index(root, "what"); search_index(root, "is"); search_index(root, "banana"); search_index(root, "boo"); return 0; }
use std::{ borrow::Borrow, collections::{BTreeMap, BTreeSet}, }; #[derive(Debug, Default)] pub struct InvertedIndex<T> { indexed: BTreeMap<String, BTreeSet<usize>>, sources: Vec<T>, } impl<T> InvertedIndex<T> { pub fn add<I, V>(&mut self, source: T, tokens: I) where I: IntoIterator<Item = V>, V: Into<String>, { let source_id = self.sources.len(); self.sources.push(source); for token in tokens { self.indexed .entry(token.into()) .or_insert_with(BTreeSet::new) .insert(source_id); } } pub fn search<'a, I, K>(&self, tokens: I) -> impl Iterator<Item = &T> where String: Borrow<K>, K: Ord + ?Sized + 'a, I: IntoIterator<Item = &'a K>, { let mut tokens = tokens.into_iter(); tokens .next() .and_then(|token| self.indexed.get(token).cloned()) .and_then(|first| { tokens.try_fold(first, |found, token| { self.indexed .get(token) .map(|sources| { found .intersection(sources) .cloned() .collect::<BTreeSet<_>>() }) .filter(|update| !update.is_empty()) }) }) .unwrap_or_else(BTreeSet::new) .into_iter() .map(move |source| &self.sources[source]) } pub fn tokens(&self) -> impl Iterator<Item = &str> { self.indexed.keys().map(|it| it.as_str()) } pub fn sources(&self) -> &[T] { &self.sources } } use std::{ ffi::OsString, fmt::{Debug, Display}, fs::{read_dir, DirEntry, File, ReadDir}, io::{self, stdin, Read}, path::{Path, PathBuf}, }; #[derive(Debug)] pub struct Files { dirs: Vec<ReadDir>, } impl Files { pub fn walk<P: AsRef<Path>>(path: P) -> io::Result<Self> { Ok(Files { dirs: vec![read_dir(path)?], }) } } impl Iterator for Files { type Item = DirEntry; fn next(&mut self) -> Option<Self::Item> { 'outer: while let Some(mut current) = self.dirs.pop() { while let Some(entry) = current.next() { if let Ok(entry) = entry { let path = entry.path(); if !path.is_dir() { self.dirs.push(current); return Some(entry); } else if let Ok(dir) = read_dir(path) { self.dirs.push(current); self.dirs.push(dir); continue 'outer; } } } } None } } fn tokenize<'a>(input: &'a str) -> impl Iterator<Item = String> + 'a { input .split(|c: char| !c.is_alphanumeric()) .filter(|token| !token.is_empty()) .map(|token| token.to_lowercase()) } fn tokenize_file<P: AsRef<Path>>(path: P) -> io::Result<BTreeSet<String>> { let mut buffer = Vec::new(); File::open(path)?.read_to_end(&mut buffer)?; let text = String::from_utf8_lossy(&buffer); Ok(tokenize(&text).collect::<BTreeSet<_>>()) } fn tokenize_query(input: &str) -> Vec<String> { let result = tokenize(input).collect::<BTreeSet<_>>(); let mut result = result.into_iter().collect::<Vec<_>>(); result.sort_by_key(|item| usize::MAX - item.len()); result } fn args() -> io::Result<(OsString, BTreeSet<OsString>)> { let mut args = std::env::args_os().skip(1); let path = args .next() .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "missing path"))?; let extensions = args.collect::<BTreeSet<_>>(); Ok((path, extensions)) } fn print_hits<'a, T>(hits: impl Iterator<Item = T>) where T: Display, { let mut found_none = true; for (number, hit) in hits.enumerate() { println!(" [{}] {}", number + 1, hit); found_none = false; } if found_none { println!("(none)") } } fn main() -> io::Result<()> { let (path, extensions) = args()?; let mut files = InvertedIndex::<PathBuf>::default(); let mut content = InvertedIndex::<PathBuf>::default(); println!( "Indexing {:?} files in '{}'", extensions, path.to_string_lossy() ); for path in Files::walk(path)?.map(|file| file.path()).filter(|path| { path.extension() .filter(|&ext| extensions.is_empty() || extensions.contains(ext)) .is_some() }) { files.add(path.clone(), tokenize(&path.to_string_lossy())); match tokenize_file(&path) { Ok(tokens) => content.add(path, tokens), Err(e) => eprintln!("Skipping a file {}: {}", path.display(), e), } } println!( "Indexed {} tokens in {} files.", content.tokens().count(), content.sources.len() ); let mut query = String::new(); loop { query.clear(); println!("Enter search query:"); if stdin().read_line(&mut query).is_err() || query.trim().is_empty() { break; } match query.trim() { "/exit" | "/quit" | "" => break, "/tokens" => { println!("Tokens:"); for token in content.tokens() { println!("{}", token); } println!(); } "/files" => { println!("Sources:"); for source in content.sources() { println!("{}", source.display()); } println!(); } _ => { let query = tokenize_query(&query); println!(); println!("Found hits:"); print_hits(content.search(query.iter()).map(|it| it.display())); println!("Found file names:"); print_hits(files.search(query.iter()).map(|it| it.display())); println!(); } } } Ok(()) }
Isqrt (integer square root) of X
#include <stdint.h> #include <stdio.h> int64_t isqrt(int64_t x) { int64_t q = 1, r = 0; while (q <= x) { q <<= 2; } while (q > 1) { int64_t t; q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; } int main() { int64_t p; int n; printf("Integer square root for numbers 0 to 65:\n"); for (n = 0; n <= 65; n++) { printf("%lld ", isqrt(n)); } printf("\n\n"); printf("Integer square roots of odd powers of 7 from 1 to 21:\n"); printf(" n | 7 ^ n | isqrt(7 ^ n)\n"); p = 7; for (n = 1; n <= 21; n += 2, p *= 49) { printf("%2d | %18lld | %12lld\n", n, p, isqrt(p)); } }
use num::BigUint; use num::CheckedSub; use num_traits::{One, Zero}; fn isqrt(number: &BigUint) -> BigUint { let mut q: BigUint = One::one(); while q <= *number { q <<= &2; } let mut z = number.clone(); let mut result: BigUint = Zero::zero(); while q > One::one() { q >>= &2; let t = z.checked_sub(&result).and_then(|diff| diff.checked_sub(&q)); result >>= &1; if let Some(t) = t { z = t; result += &q; } } result } fn with_thousand_separator(s: &str) -> String { let digits: Vec<_> = s.chars().rev().collect(); let chunks: Vec<_> = digits .chunks(3) .map(|chunk| chunk.iter().collect::<String>()) .collect(); chunks.join(",").chars().rev().collect::<String>() } fn main() { println!("The integer square roots of integers from 0 to 65 are:"); (0_u32..=65).for_each(|n| print!("{} ", isqrt(&n.into()))); println!("\nThe integer square roots of odd powers of 7 from 7^1 up to 7^74 are:"); (1_u32..75).step_by(2).for_each(|exp| { println!( "7^{:>2}={:>83} ISQRT: {:>42} ", exp, with_thousand_separator(&BigUint::from(7_u8).pow(exp).to_string()), with_thousand_separator(&isqrt(&BigUint::from(7_u8).pow(exp)).to_string()) ) }); }
Iterated digits squaring
#include <stdio.h> typedef unsigned long long ull; int is89(int x) { while (1) { int s = 0; do s += (x%10)*(x%10); while ((x /= 10)); if (s == 89) return 1; if (s == 1) return 0; x = s; } } int main(void) { ull sums[32*81 + 1] = {1, 0}; for (int n = 1; ; n++) { for (int i = n*81; i; i--) { for (int j = 1; j < 10; j++) { int s = j*j; if (s > i) break; sums[i] += sums[i-s]; } } ull count89 = 0; for (int i = 1; i < n*81 + 1; i++) { if (!is89(i)) continue; if (sums[i] > ~0ULL - count89) { printf("counter overflow for 10^%d\n", n); return 0; } count89 += sums[i]; } printf("1->10^%d: %llu\n", n, count89); } return 0; }
fn digit_square_sum(mut num: usize) -> usize { let mut sum = 0; while num != 0 { sum += (num % 10).pow(2); num /= 10; } sum } fn last_in_chain(num: usize) -> usize { match num { 1 | 89 => num, _ => last_in_chain(digit_square_sum(num)), } } fn main() { let count = (1..100_000_000).filter(|&n| last_in_chain(n) == 89).count(); println!("{}", count); }
JSON
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <yajl/yajl_tree.h> #include <yajl/yajl_gen.h> static void print_callback (void *ctx, const char *str, size_t len) { FILE *f = (FILE *) ctx; fwrite (str, 1, len, f); } static void check_status (yajl_gen_status status) { if (status != yajl_gen_status_ok) { fprintf (stderr, "yajl_gen_status was %d\n", (int) status); exit (EXIT_FAILURE); } } static void serialize_value (yajl_gen gen, yajl_val val, int parse_numbers) { size_t i; switch (val->type) { case yajl_t_string: check_status (yajl_gen_string (gen, (const unsigned char *) val->u.string, strlen (val->u.string))); break; case yajl_t_number: if (parse_numbers && YAJL_IS_INTEGER (val)) check_status (yajl_gen_integer (gen, YAJL_GET_INTEGER (val))); else if (parse_numbers && YAJL_IS_DOUBLE (val)) check_status (yajl_gen_double (gen, YAJL_GET_DOUBLE (val))); else check_status (yajl_gen_number (gen, YAJL_GET_NUMBER (val), strlen (YAJL_GET_NUMBER (val)))); break; case yajl_t_object: check_status (yajl_gen_map_open (gen)); for (i = 0 ; i < val->u.object.len ; i++) { check_status (yajl_gen_string (gen, (const unsigned char *) val->u.object.keys[i], strlen (val->u.object.keys[i]))); serialize_value (gen, val->u.object.values[i], parse_numbers); } check_status (yajl_gen_map_close (gen)); break; case yajl_t_array: check_status (yajl_gen_array_open (gen)); for (i = 0 ; i < val->u.array.len ; i++) serialize_value (gen, val->u.array.values[i], parse_numbers); check_status (yajl_gen_array_close (gen)); break; case yajl_t_true: check_status (yajl_gen_bool (gen, 1)); break; case yajl_t_false: check_status (yajl_gen_bool (gen, 0)); break; case yajl_t_null: check_status (yajl_gen_null (gen)); break; default: fprintf (stderr, "unexpectedly got type %d\n", (int) val->type); exit (EXIT_FAILURE); } } static void print_tree (FILE *f, yajl_val tree, int parse_numbers) { yajl_gen gen; gen = yajl_gen_alloc (NULL); if (! gen) { fprintf (stderr, "yajl_gen_alloc failed\n"); exit (EXIT_FAILURE); } if (0 == yajl_gen_config (gen, yajl_gen_beautify, 1) || 0 == yajl_gen_config (gen, yajl_gen_validate_utf8, 1) || 0 == yajl_gen_config (gen, yajl_gen_print_callback, print_callback, f)) { fprintf (stderr, "yajl_gen_config failed\n"); exit (EXIT_FAILURE); } serialize_value (gen, tree, parse_numbers); yajl_gen_free (gen); } int main (int argc, char **argv) { char err_buf[200]; const char *json = "{\"pi\": 3.14, \"large number\": 123456789123456789123456789, " "\"an array\": [-1, true, false, null, \"foo\"]}"; yajl_val tree; tree = yajl_tree_parse (json, err_buf, sizeof (err_buf)); if (! tree) { fprintf (stderr, "parsing failed because: %s\n", err_buf); return EXIT_FAILURE; } printf ("Treating numbers as strings...\n"); print_tree (stdout, tree, 0); printf ("Parsing numbers to long long or double...\n"); print_tree (stdout, tree, 1); yajl_tree_free (tree); return EXIT_SUCCESS; }
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Point { x: i32, y: i32, }
Jensen's Device
#include <stdio.h> int i; double sum(int *i, int lo, int hi, double (*term)()) { double temp = 0; for (*i = lo; *i <= hi; (*i)++) temp += term(); return temp; } double term_func() { return 1.0 / i; } int main () { printf("%f\n", sum(&i, 1, 100, term_func)); return 0; }
use std::f32; fn harmonic_sum<F>(lo: usize, hi: usize, term: F) -> f32 where F: Fn(f32) -> f32, { (lo..hi + 1).fold(0.0, |acc, item| acc + term(item as f32)) } fn main() { println!("{}", harmonic_sum(1, 100, |i| 1.0 / i)); }
Jewels and stones
#include <stdio.h> #include <string.h> int count_jewels(const char *s, const char *j) { int count = 0; for ( ; *s; ++s) if (strchr(j, *s)) ++count; return count; } int main() { printf("%d\n", count_jewels("aAAbbbb", "aA")); printf("%d\n", count_jewels("ZZ", "z")); return 0; }
fn count_jewels(stones: &str, jewels: &str) -> u8 { let mut count: u8 = 0; for cur_char in stones.chars() { if jewels.contains(cur_char) { count += 1; } } count } fn main() { println!("{}", count_jewels("aAAbbbb", "aA")); println!("{}", count_jewels("ZZ", "z")); }
JortSort
#include <stdio.h> #include <stdlib.h> int number_of_digits(int x){ int NumberOfDigits; for(NumberOfDigits=0;x!=0;NumberOfDigits++){ x=x/10; } return NumberOfDigits; } int* convert_array(char array[], int NumberOfElements) { int *convertedArray=malloc(NumberOfElements*sizeof(int)); int originalElement, convertedElement; for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++) { convertedArray[convertedElement]=atoi(&array[originalElement]); originalElement+=number_of_digits(convertedArray[convertedElement])+1; } return convertedArray; } int isSorted(int array[], int numberOfElements){ int sorted=1; for(int counter=0;counter<numberOfElements;counter++){ if(counter!=0 && array[counter-1]>array[counter]) sorted--; } return sorted; } int main(int argc, char* argv[]) { int* convertedArray; convertedArray=convert_array(*(argv+1), argc-1); if(isSorted(convertedArray, argc-1)==1) printf("Did you forgot to turn on your brain?! This array is already sorted!\n"); else if(argc-1<=10) printf("Am I really supposed to sort this? Sort it by yourself!\n"); else printf("Am I really supposed to sort this? Bhahahaha!\n"); free(convertedArray); return 0; }
use std::cmp::{Ord, Eq}; fn jort_sort<T: Ord + Eq + Clone>(array: Vec<T>) -> bool { let mut sorted_array = array.to_vec(); sorted_array.sort(); for i in 0..array.len() { if array[i] != sorted_array[i] { return false; } } return true; }
Josephus problem
#include <stdio.h> int jos(int n, int k, int m) { int a; for (a = m + 1; a <= n; a++) m = (m + k) % a; return m; } typedef unsigned long long xint; xint jos_large(xint n, xint k, xint m) { if (k <= 1) return n - m - 1; xint a = m; while (a < n) { xint q = (a - m + k - 2) / (k - 1); if (a + q > n) q = n - a; else if (!q) q = 1; m = (m + q * k) % (a += q); } return m; } int main(void) { xint n, k, i; n = 41; k = 3; printf("n = %llu, k = %llu, final survivor: %d\n", n, k, jos(n, k, 0)); n = 9876543210987654321ULL; k = 12031; printf("n = %llu, k = %llu, three survivors:", n, k); for (i = 3; i--; ) printf(" %llu", jos_large(n, k, i)); putchar('\n'); return 0; }
const N: usize = 41; const K: usize = 3; const M: usize = 3; const POSITION: usize = 5; fn main() { let mut prisoners: Vec<usize> = Vec::new(); let mut executed: Vec<usize> = Vec::new(); for pos in 0..N { prisoners.push(pos); } let mut to_kill: usize = 0; let mut len: usize = prisoners.len(); while len > M { to_kill = (to_kill + K - 1) % len; executed.push(prisoners.remove(to_kill)); len -= 1; } println!("JOSEPHUS n={}, k={}, m={}", N, K, M); println!("Executed: {:?}", executed); println!("Executed position number {}: {}", POSITION, executed[POSITION - 1]); println!("Survivors: {:?}", prisoners); }
Julia set
#include<graphics.h> #include<stdlib.h> #include<math.h> typedef struct{ double x,y; }complex; complex add(complex a,complex b){ complex c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } complex sqr(complex a){ complex c; c.x = a.x*a.x - a.y*a.y; c.y = 2*a.x*a.y; return c; } double mod(complex a){ return sqrt(a.x*a.x + a.y*a.y); } complex mapPoint(int width,int height,double radius,int x,int y){ complex c; int l = (width<height)?width:height; c.x = 2*radius*(x - width/2.0)/l; c.y = 2*radius*(y - height/2.0)/l; return c; } void juliaSet(int width,int height,complex c,double radius,int n){ int x,y,i; complex z0,z1; for(x=0;x<=width;x++) for(y=0;y<=height;y++){ z0 = mapPoint(width,height,radius,x,y); for(i=1;i<=n;i++){ z1 = add(sqr(z0),c); if(mod(z1)>radius){ putpixel(x,y,i%15+1); break; } z0 = z1; } if(i>n) putpixel(x,y,0); } } int main(int argC, char* argV[]) { int width, height; complex c; if(argC != 7) printf("Usage : %s <width and height of screen, real and imaginary parts of c, limit radius and iterations>"); else{ width = atoi(argV[1]); height = atoi(argV[2]); c.x = atof(argV[3]); c.y = atof(argV[4]); initwindow(width,height,"Julia Set"); juliaSet(width,height,c,atof(argV[5]),atoi(argV[6])); getch(); } return 0; }
extern crate image; use image::{ImageBuffer, Pixel, Rgb}; fn main() { let width = 8000; let height = 6000; let mut img = ImageBuffer::new(width as u32, height as u32); let cx = -0.9; let cy = 0.27015; let iterations = 110; for x in 0..width { for y in 0..height { let inner_height = height as f32; let inner_width = width as f32; let inner_y = y as f32; let inner_x = x as f32; let mut zx = 3.0 * (inner_x - 0.5 * inner_width) / (inner_width); let mut zy = 2.0 * (inner_y - 0.5 * inner_height) / (inner_height); let mut i = iterations; while zx * zx + zy * zy < 4.0 && i > 1 { let tmp = zx * zx - zy * zy + cx; zy = 2.0 * zx * zy + cy; zx = tmp; i -= 1; } let r = (i << 3) as u8; let g = (i << 5) as u8; let b = (i << 4) as u8; let pixel = Rgb::from_channels(r, g, b, 0); img.put_pixel(x as u32, y as u32, pixel); } } let _ = img.save("output.png"); }
Kernighans large earthquake problem
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { FILE *fp; char *line = NULL; size_t len = 0; ssize_t read; char *lw, *lt; fp = fopen("data.txt", "r"); if (fp == NULL) { printf("Unable to open file\n"); exit(1); } printf("Those earthquakes with a magnitude > 6.0 are:\n\n"); while ((read = getline(&line, &len, fp)) != EOF) { if (read < 2) continue; lw = strrchr(line, ' '); lt = strrchr(line, '\t'); if (!lw && !lt) continue; if (lt > lw) lw = lt; if (atof(lw + 1) > 6.0) printf("%s", line); } fclose(fp); if (line) free(line); return 0; }
fn main() -> Result<(), Box<dyn std::error::Error>> { use std::io::{BufRead, BufReader}; for line in BufReader::new(std::fs::OpenOptions::new().read(true).open("data.txt")?).lines() { let line = line?; let magnitude = line .split_whitespace() .nth(2) .and_then(|it| it.parse::<f32>().ok()) .ok_or_else(|| format!("Could not parse scale: {}", line))?; if magnitude > 6.0 { println!("{}", line); } } Ok(()) }
Knapsack problem_0-1
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; int weight; int value; } item_t; item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, }; int *knapsack (item_t *items, int n, int w) { int i, j, a, b, *mm, **m, *s; mm = calloc((n + 1) * (w + 1), sizeof (int)); m = malloc((n + 1) * sizeof (int *)); m[0] = mm; for (i = 1; i <= n; i++) { m[i] = &mm[i * (w + 1)]; for (j = 0; j <= w; j++) { if (items[i - 1].weight > j) { m[i][j] = m[i - 1][j]; } else { a = m[i - 1][j]; b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value; m[i][j] = a > b ? a : b; } } } s = calloc(n, sizeof (int)); for (i = n, j = w; i > 0; i--) { if (m[i][j] > m[i - 1][j]) { s[i - 1] = 1; j -= items[i - 1].weight; } } free(mm); free(m); return s; } int main () { int i, n, tw = 0, tv = 0, *s; n = sizeof (items) / sizeof (item_t); s = knapsack(items, n, 400); for (i = 0; i < n; i++) { if (s[i]) { printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value); tw += items[i].weight; tv += items[i].value; } } printf("%-22s %5d %5d\n", "totals:", tw, tv); return 0; }
use std::cmp; struct Item { name: &'static str, weight: usize, value: usize } fn knapsack01_dyn(items: &[Item], max_weight: usize) -> Vec<&Item> { let mut best_value = vec![vec![0; max_weight + 1]; items.len() + 1]; for (i, it) in items.iter().enumerate() { for w in 1 .. max_weight + 1 { best_value[i + 1][w] = if it.weight > w { best_value[i][w] } else { cmp::max(best_value[i][w], best_value[i][w - it.weight] + it.value) } } } let mut result = Vec::with_capacity(items.len()); let mut left_weight = max_weight; for (i, it) in items.iter().enumerate().rev() { if best_value[i + 1][left_weight] != best_value[i][left_weight] { result.push(it); left_weight -= it.weight; } } result } fn main () { const MAX_WEIGHT: usize = 400; const ITEMS: &[Item] = &[ Item { name: "map", weight: 9, value: 150 }, Item { name: "compass", weight: 13, value: 35 }, Item { name: "water", weight: 153, value: 200 }, Item { name: "sandwich", weight: 50, value: 160 }, Item { name: "glucose", weight: 15, value: 60 }, Item { name: "tin", weight: 68, value: 45 }, Item { name: "banana", weight: 27, value: 60 }, Item { name: "apple", weight: 39, value: 40 }, Item { name: "cheese", weight: 23, value: 30 }, Item { name: "beer", weight: 52, value: 10 }, Item { name: "suntancream", weight: 11, value: 70 }, Item { name: "camera", weight: 32, value: 30 }, Item { name: "T-shirt", weight: 24, value: 15 }, Item { name: "trousers", weight: 48, value: 10 }, Item { name: "umbrella", weight: 73, value: 40 }, Item { name: "waterproof trousers", weight: 42, value: 70 }, Item { name: "waterproof overclothes", weight: 43, value: 75 }, Item { name: "note-case", weight: 22, value: 80 }, Item { name: "sunglasses", weight: 7, value: 20 }, Item { name: "towel", weight: 18, value: 12 }, Item { name: "socks", weight: 4, value: 50 }, Item { name: "book", weight: 30, value: 10 } ]; let items = knapsack01_dyn(ITEMS, MAX_WEIGHT); for it in items.iter().rev() { println!("{}", it.name); } println!("Total weight: {}", items.iter().map(|w| w.weight).sum::<usize>()); println!("Total value: {}", items.iter().map(|w| w.value).sum::<usize>()); }
Knapsack problem_Continuous
#include <stdio.h> #include <stdlib.h> struct item { double w, v; const char *name; } items[] = { { 3.8, 36, "beef" }, { 5.4, 43, "pork" }, { 3.6, 90, "ham" }, { 2.4, 45, "greaves" }, { 4.0, 30, "flitch" }, { 2.5, 56, "brawn" }, { 3.7, 67, "welt" }, { 3.0, 95, "salami" }, { 5.9, 98, "sausage" }, }; int item_cmp(const void *aa, const void *bb) { const struct item *a = aa, *b = bb; double ua = a->v / a->w, ub = b->v / b->w; return ua < ub ? -1 : ua > ub; } int main() { struct item *it; double space = 15; qsort(items, 9, sizeof(struct item), item_cmp); for (it = items + 9; it---items && space > 0; space -= it->w) if (space >= it->w) printf("take all %s\n", it->name); else printf("take %gkg of %g kg of %s\n", space, it->w, it->name); return 0; }
fn main() { let items: [(&str, f32, u8); 9] = [ ("beef", 3.8, 36), ("pork", 5.4, 43), ("ham", 3.6, 90), ("greaves", 2.4, 45), ("flitch", 4.0, 30), ("brawn", 2.5, 56), ("welt", 3.7, 67), ("salami", 3.0, 95), ("sausage", 5.9, 98), ]; let mut weight: f32 = 15.0; let mut values: Vec<(&str, f32, f32)> = Vec::new(); for item in &items { values.push((item.0, f32::from(item.2) / item.1, item.1)); } values.sort_by(|a, b| (a.1).partial_cmp(&b.1).unwrap()); values.reverse(); for choice in values { if choice.2 <= weight { println!("Grab {:.1} kgs of {}", choice.2, choice.0); weight -= choice.2; if (choice.2 - weight).abs() < std::f32::EPSILON { return; } } else { println!("Grab {:.1} kgs of {}", weight, choice.0); return; } } }
Knight's tour
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> typedef unsigned char cell; int dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 }; int dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 }; void init_board(int w, int h, cell **a, cell **b) { int i, j, k, x, y, p = w + 4, q = h + 4; a[0] = (cell*)(a + q); b[0] = a[0] + 2; for (i = 1; i < q; i++) { a[i] = a[i-1] + p; b[i] = a[i] + 2; } memset(a[0], 255, p * q); for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { for (k = 0; k < 8; k++) { x = j + dx[k], y = i + dy[k]; if (b[i+2][j] == 255) b[i+2][j] = 0; b[i+2][j] += x >= 0 && x < w && y >= 0 && y < h; } } } } #define E "\033[" int walk_board(int w, int h, int x, int y, cell **b) { int i, nx, ny, least; int steps = 0; printf(E"H"E"J"E"%d;%dH"E"32m[]"E"m", y + 1, 1 + 2 * x); while (1) { b[y][x] = 255; for (i = 0; i < 8; i++) b[ y + dy[i] ][ x + dx[i] ]--; least = 255; for (i = 0; i < 8; i++) { if (b[ y + dy[i] ][ x + dx[i] ] < least) { nx = x + dx[i]; ny = y + dy[i]; least = b[ny][nx]; } } if (least > 7) { printf(E"%dH", h + 2); return steps == w * h - 1; } if (steps++) printf(E"%d;%dH[]", y + 1, 1 + 2 * x); x = nx, y = ny; printf(E"%d;%dH"E"31m[]"E"m", y + 1, 1 + 2 * x); fflush(stdout); usleep(120000); } } int solve(int w, int h) { int x = 0, y = 0; cell **a, **b; a = malloc((w + 4) * (h + 4) + sizeof(cell*) * (h + 4)); b = malloc((h + 4) * sizeof(cell*)); while (1) { init_board(w, h, a, b); if (walk_board(w, h, x, y, b + 2)) { printf("Success!\n"); return 1; } if (++x >= w) x = 0, y++; if (y >= h) { printf("Failed to find a solution\n"); return 0; } printf("Any key to try next start position"); getchar(); } } int main(int c, char **v) { int w, h; if (c < 2 || (w = atoi(v[1])) <= 0) w = 8; if (c < 3 || (h = atoi(v[2])) <= 0) h = w; solve(w, h); return 0; }
use std::fmt; const SIZE: usize = 8; const MOVES: [(i32, i32); 8] = [ (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1), ]; #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)] struct Point { x: i32, y: i32, } impl Point { fn mov(&self, &(dx, dy): &(i32, i32)) -> Self { Self { x: self.x + dx, y: self.y + dy, } } } struct Board { field: [[i32; SIZE]; SIZE], } impl Board { fn new() -> Self { Self { field: [[0; SIZE]; SIZE], } } fn available(&self, p: Point) -> bool { 0 <= p.x && p.x < SIZE as i32 && 0 <= p.y && p.y < SIZE as i32 && self.field[p.x as usize][p.y as usize] == 0 } fn count_degree(&self, p: Point) -> i32 { let mut count = 0; for dir in MOVES.iter() { let next = p.mov(dir); if self.available(next) { count += 1; } } count } } impl fmt::Display for Board { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for row in self.field.iter() { for x in row.iter() { write!(f, "{:3} ", x)?; } write!(f, "\n")?; } Ok(()) } } fn knights_tour(x: i32, y: i32) -> Option<Board> { let mut board = Board::new(); let mut p = Point { x: x, y: y }; let mut step = 1; board.field[p.x as usize][p.y as usize] = step; step += 1; while step <= (SIZE * SIZE) as i32 { let mut candidates = vec![]; for dir in MOVES.iter() { let adj = p.mov(dir); if board.available(adj) { let degree = board.count_degree(adj); candidates.push((degree, adj)); } } match candidates.iter().min() { Some(&(_, adj)) => p = adj, None => return None, }; board.field[p.x as usize][p.y as usize] = step; step += 1; } Some(board) } fn main() { let (x, y) = (3, 1); println!("Board size: {}", SIZE); println!("Starting position: ({}, {})", x, y); match knights_tour(x, y) { Some(b) => print!("{}", b), None => println!("Fail!"), } }
Knuth shuffle
#include <stdlib.h> #include <string.h> int rrand(int m) { return (int)((double)m * ( rand() / (RAND_MAX+1.0) )); } #define BYTE(X) ((unsigned char *)(X)) void shuffle(void *obj, size_t nmemb, size_t size) { void *temp = malloc(size); size_t n = nmemb; while ( n > 1 ) { size_t k = rrand(n--); memcpy(temp, BYTE(obj) + n*size, size); memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size); memcpy(BYTE(obj) + k*size, temp, size); } free(temp); }
use rand::Rng; extern crate rand; fn knuth_shuffle<T>(v: &mut [T]) { let mut rng = rand::thread_rng(); let l = v.len(); for n in 0..l { let i = rng.gen_range(0, l - n); v.swap(i, l - n - 1); } } fn main() { let mut v: Vec<_> = (0..10).collect(); println!("before: {:?}", v); knuth_shuffle(&mut v); println!("after: {:?}", v); }
Kronecker product
#include<stdlib.h> #include<stdio.h> int main(){ char input[100],output[100]; int i,j,k,l,rowA,colA,rowB,colB,rowC,colC,startRow,startCol; double **matrixA,**matrixB,**matrixC; printf("Enter full path of input file : "); fscanf(stdin,"%s",input); printf("Enter full path of output file : "); fscanf(stdin,"%s",output); FILE* inputFile = fopen(input,"r"); fscanf(inputFile,"%d%d",&rowA,&colA); matrixA = (double**)malloc(rowA * sizeof(double*)); for(i=0;i<rowA;i++){ matrixA[i] = (double*)malloc(colA*sizeof(double)); for(j=0;j<colA;j++){ fscanf(inputFile,"%lf",&matrixA[i][j]); } } fscanf(inputFile,"%d%d",&rowB,&colB); matrixB = (double**)malloc(rowB * sizeof(double*)); for(i=0;i<rowB;i++){ matrixB[i] = (double*)malloc(colB*sizeof(double)); for(j=0;j<colB;j++){ fscanf(inputFile,"%lf",&matrixB[i][j]); } } fclose(inputFile); rowC = rowA*rowB; colC = colA*colB; matrixC = (double**)malloc(rowC*sizeof(double*)); for(i=0;i<rowA*rowB;i++){ matrixC[i] = (double*)malloc(colA*colB*sizeof(double)); } for(i=0;i<rowA;i++){ for(j=0;j<colA;j++){ startRow = i*rowB; startCol = j*colB; for(k=0;k<rowB;k++){ for(l=0;l<colB;l++){ matrixC[startRow+k][startCol+l] = matrixA[i][j]*matrixB[k][l]; } } } } FILE* outputFile = fopen(output,"w"); for(i=0;i<rowC;i++){ for(j=0;j<colC;j++){ fprintf(outputFile,"%lf\t",matrixC[i][j]); } fprintf(outputFile,"\n"); } fclose(outputFile); printf("\n\n\nKronecker product of the two matrices written to %s.",output); }
fn main() { let mut a = vec![vec![1., 2.], vec![3., 4.]]; let mut b = vec![vec![0., 5.], vec![6., 7.]]; let mut a_ref = &mut a; let a_rref = &mut a_ref; let mut b_ref = &mut b; let b_rref = &mut b_ref; let ab = kronecker_product(a_rref, b_rref); println!("Kronecker product of\n"); for i in a { println!("{:?}", i); } println!("\nand\n"); for i in b { println!("{:?}", i); } println!("\nis\n"); for i in ab { println!("{:?}", i); } println!("\n\n"); let mut a = vec![vec![0., 1., 0.], vec![1., 1., 1.], vec![0., 1., 0.]]; let mut b = vec![vec![1., 1., 1., 1.], vec![1., 0., 0., 1.], vec![1., 1., 1., 1.]]; let mut a_ref = &mut a; let a_rref = &mut a_ref; let mut b_ref = &mut b; let b_rref = &mut b_ref; let ab = kronecker_product(a_rref, b_rref); println!("Kronecker product of\n"); for i in a { println!("{:?}", i); } println!("\nand\n"); for i in b { println!("{:?}", i); } println!("\nis\n"); for i in ab { println!("{:?}", i); } println!("\n\n"); } fn kronecker_product(a: &mut Vec<Vec<f64>>, b: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>> { let m = a.len(); let n = a[0].len(); let p = b.len(); let q = b[0].len(); let rtn = m * p; let ctn = n * q; let mut r = zero_matrix(rtn, ctn); for i in 0..m { for j in 0..n { for k in 0..p { for l in 0..q { r[p * i + k][q * j + l] = a[i][j] * b[k][l]; } } } } r } fn zero_matrix(rows: usize, cols: usize) -> Vec<Vec<f64>> { let mut matrix = Vec::with_capacity(cols); for _ in 0..rows { let mut col: Vec<f64> = Vec::with_capacity(rows); for _ in 0..cols { col.push(0.0); } matrix.push(col); } matrix }
Langton's ant
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int w = 0, h = 0; unsigned char *pix; void refresh(int x, int y) { int i, j, k; printf("\033[H"); for (i = k = 0; i < h; putchar('\n'), i++) for (j = 0; j < w; j++, k++) putchar(pix[k] ? '#' : ' '); } void walk() { int dx = 0, dy = 1, i, k; int x = w / 2, y = h / 2; pix = calloc(1, w * h); printf("\033[H\033[J"); while (1) { i = (y * w + x); if (pix[i]) k = dx, dx = -dy, dy = k; else k = dy, dy = -dx, dx = k; pix[i] = !pix[i]; printf("\033[%d;%dH%c", y + 1, x + 1, pix[i] ? '#' : ' '); x += dx, y += dy; k = 0; if (x < 0) { memmove(pix + 1, pix, w * h - 1); for (i = 0; i < w * h; i += w) pix[i] = 0; x++, k = 1; } else if (x >= w) { memmove(pix, pix + 1, w * h - 1); for (i = w-1; i < w * h; i += w) pix[i] = 0; x--, k = 1; } if (y >= h) { memmove(pix, pix + w, w * (h - 1)); memset(pix + w * (h - 1), 0, w); y--, k = 1; } else if (y < 0) { memmove(pix + w, pix, w * (h - 1)); memset(pix, 0, w); y++, k = 1; } if (k) refresh(x, y); printf("\033[%d;%dH\033[31m@\033[m", y + 1, x + 1); fflush(stdout); usleep(10000); } } int main(int c, char **v) { if (c > 1) w = atoi(v[1]); if (c > 2) h = atoi(v[2]); if (w < 40) w = 40; if (h < 25) h = 25; walk(); return 0; }
struct Ant { x: usize, y: usize, dir: Direction } #[derive(Clone,Copy)] enum Direction { North, East, South, West } use Direction::*; impl Ant { fn mv(&mut self, vec: &mut Vec<Vec<u8>>) { let pointer = &mut vec[self.y][self.x]; match *pointer { 0 => self.dir = self.dir.right(), 1 => self.dir = self.dir.left(), _ => panic!("Unexpected colour in grid") } *pointer ^= 1; match self.dir { North => self.y -= 1, South => self.y += 1, East => self.x += 1, West => self.x -= 1, } } } impl Direction { fn right(self) -> Direction { match self { North => East, East => South, South => West, West => North, } } fn left(self) -> Direction { self.right().right().right() } } fn main(){ let mut grid: Vec<Vec<u8>> = vec![vec![0; 100]; 100]; let mut ant = Ant { x: 50, y: 50, dir: Direction::North }; while ant.x < 100 && ant.y < 100 { ant.mv(&mut grid); } for each in grid.iter() { let string = each.iter() .map(|&x| if x == 0 { " " } else { "#" }) .fold(String::new(), |x, y| x+y); println!("{}", string); } }
Largest int from concatenated ints
#include <stdio.h> #include <stdlib.h> #include <string.h> int catcmp(const void *a, const void *b) { char ab[32], ba[32]; sprintf(ab, "%d%d", *(int*)a, *(int*)b); sprintf(ba, "%d%d", *(int*)b, *(int*)a); return strcmp(ba, ab); } void maxcat(int *a, int len) { int i; qsort(a, len, sizeof(int), catcmp); for (i = 0; i < len; i++) printf("%d", a[i]); putchar('\n'); } int main(void) { int x[] = {1, 34, 3, 98, 9, 76, 45, 4}; int y[] = {54, 546, 548, 60}; maxcat(x, sizeof(x)/sizeof(x[0])); maxcat(y, sizeof(y)/sizeof(y[0])); return 0; }
fn maxcat(a: &mut [u32]) { a.sort_by(|x, y| { let xy = format!("{}{}", x, y); let yx = format!("{}{}", y, x); xy.cmp(&yx).reverse() }); for x in a { print!("{}", x); } println!(); } fn main() { maxcat(&mut [1, 34, 3, 98, 9, 76, 45, 4]); maxcat(&mut [54, 546, 548, 60]); }
Last Friday of each month
#include <stdio.h> #include <stdlib.h> int main(int c, char *v[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (c < 2 || (y = atoi(v[1])) <= 1700) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 6; for(m = 0; m < 12; m++) { w = (w + days[m]) % 7; printf("%d-%02d-%d\n", y, m + 1, days[m] + (w < 5 ? -2 : 5) - w); } return 0; }
use std::env::args; use time::{Date, Duration}; fn main() { let year = args().nth(1).unwrap().parse::<i32>().unwrap(); (1..=12) .map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1)) .filter_map(|date| date.ok()) .for_each(|date| { let days_back = Duration::days(((date.weekday().number_from_sunday() as i64) % 7) + 1); println!("{}", date - days_back); }); }
Last letter-first letter
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <inttypes.h> typedef struct { uint16_t index; char last_char, first_char; } Ref; Ref* longest_path_refs; size_t longest_path_refs_len; Ref* refs; size_t refs_len; size_t n_solutions; const char** longest_path; size_t longest_path_len; void search(size_t curr_len) { if (curr_len == longest_path_refs_len) { n_solutions++; } else if (curr_len > longest_path_refs_len) { n_solutions = 1; longest_path_refs_len = curr_len; memcpy(longest_path_refs, refs, curr_len * sizeof(Ref)); } intptr_t last_char = refs[curr_len - 1].last_char; for (size_t i = curr_len; i < refs_len; i++) if (refs[i].first_char == last_char) { Ref aux = refs[curr_len]; refs[curr_len] = refs[i]; refs[i] = aux; search(curr_len + 1); refs[i] = refs[curr_len]; refs[curr_len] = aux; } } void find_longest_chain(const char* items[], size_t items_len) { refs_len = items_len; refs = calloc(refs_len, sizeof(Ref)); longest_path_refs_len = 0; longest_path_refs = calloc(refs_len, sizeof(Ref)); for (size_t i = 0; i < items_len; i++) { size_t itemsi_len = strlen(items[i]); if (itemsi_len <= 1) exit(1); refs[i].index = (uint16_t)i; refs[i].last_char = items[i][itemsi_len - 1]; refs[i].first_char = items[i][0]; } for (size_t i = 0; i < items_len; i++) { Ref aux = refs[0]; refs[0] = refs[i]; refs[i] = aux; search(1); refs[i] = refs[0]; refs[0] = aux; } longest_path_len = longest_path_refs_len; longest_path = calloc(longest_path_len, sizeof(const char*)); for (size_t i = 0; i < longest_path_len; i++) longest_path[i] = items[longest_path_refs[i].index]; free(longest_path_refs); free(refs); } int main() { const char* pokemon[] = {"audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", "relicanth", "remoraid", "rufflet", "sableye", "scolipede", "scrafty", "seaking", "sealeo", "silcoon", "simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", "wailord", "wartortle", "whismur", "wingull", "yamask"}; size_t pokemon_len = sizeof(pokemon) / sizeof(pokemon[0]); find_longest_chain(pokemon, pokemon_len); printf("Maximum path length: %u\n", longest_path_len); printf("Paths of that length: %u\n", n_solutions); printf("Example path of that length:\n"); for (size_t i = 0; i < longest_path_len; i += 7) { printf(" "); for (size_t j = i; j < (i+7) && j < longest_path_len; j++) printf("%s ", longest_path[j]); printf("\n"); } free(longest_path); return 0; }
fn first_char(string: &str) -> char { string.chars().next().unwrap() } fn first_and_last_char(string: &str) -> (char, char) { ( first_char(string), first_char(string.rmatches(|_: char| true).next().unwrap()), ) } struct Pokemon { name: &'static str, first: char, last: char, } impl Pokemon { fn new(name: &'static str) -> Pokemon { let (first, last) = first_and_last_char(name); Pokemon { name, first, last } } } #[derive(Default)] struct App { max_path_length: usize, max_path_length_count: usize, max_path_example: Vec<&'static str>, pokemon: Vec<Pokemon>, } impl App { fn search(&mut self, offset: usize) { if offset > self.max_path_length { self.max_path_length = offset; self.max_path_length_count = 1; } else if offset == self.max_path_length { self.max_path_length_count += 1; self.max_path_example.clear(); self.max_path_example.extend( self.pokemon[0..offset] .iter() .map(|Pokemon { name, .. }| *name), ); } let last_char = self.pokemon[offset - 1].last; for i in offset..self.pokemon.len() { if self.pokemon[i].first == last_char { self.pokemon.swap(offset, i); self.search(offset + 1); self.pokemon.swap(offset, i); } } } } fn main() { let pokemon_names = [ "audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", "relicanth", "remoraid", "rufflet", "sableye", "scolipede", "scrafty", "seaking", "sealeo", "silcoon", "simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", "wailord", "wartortle", "whismur", "wingull", "yamask", ]; let mut app = App { pokemon: pokemon_names .iter() .map(|name| Pokemon::new(name)) .collect(), ..App::default() }; for i in 0..app.pokemon.len() { app.pokemon.swap(0, i); app.search(1); app.pokemon.swap(0, i); } println!("Maximum path length: {}", app.max_path_length); println!("Paths of that length: {}", app.max_path_length_count); println!( "Example path of that length: {}", app.max_path_example.join(" "), ); }
Leap year
#include <stdio.h> int is_leap_year(unsigned year) { return !(year & (year % 100 ? 3 : 15)); } int main(void) { const unsigned test_case[] = { 1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100 }; const unsigned n = sizeof test_case / sizeof test_case[0]; for (unsigned i = 0; i != n; ++i) { unsigned year = test_case[i]; printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not "); } return 0; }
fn is_leap(year: i32) -> bool { let factor = |x| year % x == 0; factor(4) && (!factor(100) || factor(400)) }
Least common multiple
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
use std::cmp::{max, min}; fn gcd(a: usize, b: usize) -> usize { match ((a, b), (a & 1, b & 1)) { ((x, y), _) if x == y => y, ((0, x), _) | ((x, 0), _) => x, ((x, y), (0, 1)) | ((y, x), (1, 0)) => gcd(x >> 1, y), ((x, y), (0, 0)) => gcd(x >> 1, y >> 1) << 1, ((x, y), (1, 1)) => { let (x, y) = (min(x, y), max(x, y)); gcd((y - x) >> 1, x) } _ => unreachable!(), } } fn lcm(a: usize, b: usize) -> usize { a * b / gcd(a, b) } fn main() { println!("{}", lcm(6324, 234)) }
Leonardo numbers
#include<stdio.h> void leonardo(int a,int b,int step,int num){ int i,temp; printf("First 25 Leonardo numbers : \n"); for(i=1;i<=num;i++){ if(i==1) printf(" %d",a); else if(i==2) printf(" %d",b); else{ printf(" %d",a+b+step); temp = a; a = b; b = temp+b+step; } } } int main() { int a,b,step; printf("Enter first two Leonardo numbers and increment step : "); scanf("%d%d%d",&a,&b,&step); leonardo(a,b,step,25); return 0; }
fn leonardo(mut n0: u32, mut n1: u32, add: u32) -> impl std::iter::Iterator<Item = u32> { std::iter::from_fn(move || { let n = n0; n0 = n1; n1 += n + add; Some(n) }) } fn main() { println!("First 25 Leonardo numbers:"); for i in leonardo(1, 1, 1).take(25) { print!("{} ", i); } println!(); println!("First 25 Fibonacci numbers:"); for i in leonardo(0, 1, 0).take(25) { print!("{} ", i); } println!(); }
Letter frequency
int frequency[26]; int ch; FILE* txt_file = fopen ("a_text_file.txt", "rt"); for (ch = 0; ch < 26; ch++) frequency[ch] = 0; while (1) { ch = fgetc(txt_file); if (ch == EOF) break; if ('a' <= ch && ch <= 'z') frequency[ch-'a']++; else if ('A' <= ch && ch <= 'Z') frequency[ch-'A']++; }
use std::collections::btree_map::BTreeMap; use std::{env, process}; use std::io::{self, Read, Write}; use std::fmt::Display; use std::fs::File; fn main() { let filename = env::args().nth(1) .ok_or("Please supply a file name") .unwrap_or_else(|e| exit_err(e, 1)); let mut buf = String::new(); let mut count = BTreeMap::new(); File::open(&filename) .unwrap_or_else(|e| exit_err(e, 2)) .read_to_string(&mut buf) .unwrap_or_else(|e| exit_err(e, 3)); for c in buf.chars() { *count.entry(c).or_insert(0) += 1; } println!("Number of occurences per character"); for (ch, count) in &count { println!("{:?}: {}", ch, count); } } #[inline] fn exit_err<T>(msg: T, code: i32) -> ! where T: Display { writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr"); process::exit(code) }
Levenshtein distance
#include <stdio.h> #include <string.h> int levenshtein(const char *s, int ls, const char *t, int lt) { int a, b, c; if (!ls) return lt; if (!lt) return ls; if (s[ls - 1] == t[lt - 1]) return levenshtein(s, ls - 1, t, lt - 1); a = levenshtein(s, ls - 1, t, lt - 1); b = levenshtein(s, ls, t, lt - 1); c = levenshtein(s, ls - 1, t, lt ); if (a > b) a = b; if (a > c) a = c; return a + 1; } int main() { const char *s1 = "rosettacode"; const char *s2 = "raisethysword"; printf("distance between `%s' and `%s': %d\n", s1, s2, levenshtein(s1, strlen(s1), s2, strlen(s2))); return 0; }
fn main() { println!("{}", levenshtein_distance("kitten", "sitting")); println!("{}", levenshtein_distance("saturday", "sunday")); println!("{}", levenshtein_distance("rosettacode", "raisethysword")); } fn levenshtein_distance(word1: &str, word2: &str) -> usize { let w1 = word1.chars().collect::<Vec<_>>(); let w2 = word2.chars().collect::<Vec<_>>(); let word1_length = w1.len() + 1; let word2_length = w2.len() + 1; let mut matrix = vec![vec![0; word1_length]; word2_length]; for i in 1..word1_length { matrix[0][i] = i; } for j in 1..word2_length { matrix[j][0] = j; } for j in 1..word2_length { for i in 1..word1_length { let x: usize = if w1[i-1] == w2[j-1] { matrix[j-1][i-1] } else { 1 + std::cmp::min( std::cmp::min(matrix[j][i-1], matrix[j-1][i]) , matrix[j-1][i-1]) }; matrix[j][i] = x; } } matrix[word2_length-1][word1_length-1] }
Linear congruential generator
#include <stdio.h> int rand(); int rseed = 0; inline void srand(int x) { rseed = x; } #ifndef MS_RAND #define RAND_MAX ((1U << 31) - 1) inline int rand() { return rseed = (rseed * 1103515245 + 12345) & RAND_MAX; } #else #define RAND_MAX_32 ((1U << 31) - 1) #define RAND_MAX ((1U << 15) - 1) inline int rand() { return (rseed = (rseed * 214013 + 2531011) & RAND_MAX_32) >> 16; } #endif int main() { int i; printf("rand max is %d\n", RAND_MAX); for (i = 0; i < 100; i++) printf("%d\n", rand()); return 0; }
extern crate rand; pub use rand::{Rng, SeedableRng}; pub struct BsdLcg { state: u32, } impl Rng for BsdLcg { fn next_u32(&mut self) -> u32 { self.state = self.state.wrapping_mul(1_103_515_245).wrapping_add(12_345); self.state %= 1 << 31; self.state } } impl SeedableRng<u32> for BsdLcg { fn from_seed(seed: u32) -> Self { Self { state: seed } } fn reseed(&mut self, seed: u32) { self.state = seed; } } pub struct MsLcg { state: u32, } impl Rng for MsLcg { fn next_u32(&mut self) -> u32 { self.state = self.state.wrapping_mul(214_013).wrapping_add(2_531_011); self.state %= 1 << 31; self.state >> 16 } } impl SeedableRng<u32> for MsLcg { fn from_seed(seed: u32) -> Self { Self { state: seed } } fn reseed(&mut self, seed: u32) { self.state = seed; } } fn main() { println!("~~~ BSD ~~~"); let mut bsd = BsdLcg::from_seed(0); for _ in 0..10 { println!("{}", bsd.next_u32()); } println!("~~~ MS ~~~"); let mut ms = MsLcg::from_seed(0); for _ in 0..10 { println!("{}", ms.next_u32()); } println!("~~~ Others ~~~"); println!("{:?}", ms.gen::<[u32; 5]>()); println!("{}", ms.gen::<bool>()); println!("{}", ms.gen_ascii_chars().take(15).collect::<String>()); }
List comprehensions
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
fn pyth(n: u32) -> impl Iterator<Item = [u32; 3]> { (1..=n).flat_map(move |x| { (x..=n).flat_map(move |y| { (y..=n).filter_map(move |z| { if x.pow(2) + y.pow(2) == z.pow(2) { Some([x, y, z]) } else { None } }) }) }) }
Literals_Integer
#include <stdio.h> int main(void) { printf("%s\n", ( (727 == 0x2d7) && (727 == 01327) ) ? "true" : "false"); return 0; }
10 0b10 0x10 0o10 1_000 10_i32 10i32
Literals_String
char ch = 'z';
let char01: char = 'a'; let char02: char = '\u{25A0}'; let char03: char = '❤';
Logical operations
if(myValue == 3 && myOtherValue == 5){ myResult = true; }
fn boolean_ops(a: bool, b: bool) { println!("{} and {} -> {}", a, b, a && b); println!("{} or {} -> {}", a, b, a || b); println!("{} xor {} -> {}", a, b, a ^ b); println!("not {} -> {}\n", a, !a); } fn main() { boolean_ops(true, true); boolean_ops(true, false); boolean_ops(false, true); boolean_ops(false, false) }
Longest common prefix
#include<stdarg.h> #include<string.h> #include<stdlib.h> #include<stdio.h> char* lcp(int num,...){ va_list vaList,vaList2; int i,j,len,min; char* dest; char** strings = (char**)malloc(num*sizeof(char*)); va_start(vaList,num); va_start(vaList2,num); for(i=0;i<num;i++){ len = strlen(va_arg(vaList,char*)); strings[i] = (char*)malloc((len + 1)*sizeof(char)); strcpy(strings[i],va_arg(vaList2,char*)); if(i==0) min = len; else if(len<min) min = len; } if(min==0) return ""; for(i=0;i<min;i++){ for(j=1;j<num;j++){ if(strings[j][i]!=strings[0][i]){ if(i==0) return ""; else{ dest = (char*)malloc(i*sizeof(char)); strncpy(dest,strings[0],i-1); return dest; } } } } dest = (char*)malloc((min+1)*sizeof(char)); strncpy(dest,strings[0],min); return dest; } int main(){ printf("\nLongest common prefix : %s",lcp(3,"interspecies","interstellar","interstate")); printf("\nLongest common prefix : %s",lcp(2,"throne","throne")); printf("\nLongest common prefix : %s",lcp(2,"throne","dungeon")); printf("\nLongest common prefix : %s",lcp(3,"throne","","throne")); printf("\nLongest common prefix : %s",lcp(1,"cheese")); printf("\nLongest common prefix : %s",lcp(1,"")); printf("\nLongest common prefix : %s",lcp(0,NULL)); printf("\nLongest common prefix : %s",lcp(2,"prefix","suffix")); printf("\nLongest common prefix : %s",lcp(2,"foo","foobar")); return 0; }
fn main() { let strs: [&[&[u8]]; 7] = [ &[b"interspecies", b"interstellar", b"interstate"], &[b"throne", b"throne"], &[b"throne", b"dungeon"], &[b"cheese"], &[b""], &[b"prefix", b"suffix"], &[b"foo", b"foobar"], ]; strs.iter().for_each(|list| match lcp(list) { Some(prefix) => println!("{}", String::from_utf8_lossy(&prefix)), None => println!(), }); } fn lcp(list: &[&[u8]]) -> Option<Vec<u8>> { if list.is_empty() { return None; } let mut ret = Vec::new(); let mut i = 0; loop { let mut c = None; for word in list { if i == word.len() { return Some(ret); } match c { None => { c = Some(word[i]); } Some(letter) if letter != word[i] => return Some(ret), _ => continue, } } if let Some(letter) = c { ret.push(letter); } i += 1; } }
Longest common subsequence
#include <stdio.h> #include <stdlib.h> #define MAX(a, b) (a > b ? a : b) int lcs (char *a, int n, char *b, int m, char **s) { int i, j, k, t; int *z = calloc((n + 1) * (m + 1), sizeof (int)); int **c = calloc((n + 1), sizeof (int *)); for (i = 0; i <= n; i++) { c[i] = &z[i * (m + 1)]; } for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { if (a[i - 1] == b[j - 1]) { c[i][j] = c[i - 1][j - 1] + 1; } else { c[i][j] = MAX(c[i - 1][j], c[i][j - 1]); } } } t = c[n][m]; *s = malloc(t); for (i = n, j = m, k = t - 1; k >= 0;) { if (a[i - 1] == b[j - 1]) (*s)[k] = a[i - 1], i--, j--, k--; else if (c[i][j - 1] > c[i - 1][j]) j--; else i--; } free(c); free(z); return t; }
use std::cmp; fn lcs(string1: String, string2: String) -> (usize, String){ let total_rows = string1.len() + 1; let total_columns = string2.len() + 1; let string1_chars = string1.as_bytes(); let string2_chars = string2.as_bytes(); let mut table = vec![vec![0; total_columns]; total_rows]; for row in 1..total_rows{ for col in 1..total_columns { if string1_chars[row - 1] == string2_chars[col - 1]{ table[row][col] = table[row - 1][col - 1] + 1; } else { table[row][col] = cmp::max(table[row][col-1], table[row-1][col]); } } } let mut common_seq = Vec::new(); let mut x = total_rows - 1; let mut y = total_columns - 1; while x != 0 && y != 0 { if table[x][y] == table[x - 1][y] { x = x - 1; } else if table[x][y] == table[x][y - 1] { y = y - 1; } else { assert_eq!(string1_chars[x-1], string2_chars[y-1]); let char = string1_chars[x - 1]; common_seq.push(char); x = x - 1; y = y - 1; } } common_seq.reverse(); (table[total_rows - 1][total_columns - 1], String::from_utf8(common_seq).unwrap()) } fn main() { let res = lcs("abcdaf".to_string(), "acbcf".to_string()); assert_eq!((4 as usize, "abcf".to_string()), res); let res = lcs("thisisatest".to_string(), "testing123testing".to_string()); assert_eq!((7 as usize, "tsitest".to_string()), res); let res = lcs("AGGTAB".to_string(), "GXTXAYB".to_string()); assert_eq!((4 as usize, "GTAB".to_string()), res); }
Longest common substring
#include <stdio.h> void lcs(const char * const sa, const char * const sb, char ** const beg, char ** const end) { size_t apos, bpos; ptrdiff_t len; *beg = 0; *end = 0; len = 0; for (apos = 0; sa[apos] != 0; ++apos) { for (bpos = 0; sb[bpos] != 0; ++bpos) { if (sa[apos] == sb[bpos]) { len = 1; while (sa[apos + len] != 0 && sb[bpos + len] != 0 && sa[apos + len] == sb[bpos + len]) { len++; } } if (len > *end - *beg) { *beg = sa + apos; *end = *beg + len; len = 0; } } } } int main() { char *s1 = "thisisatest"; char *s2 = "testing123testing"; char *beg, *end, *it; lcs(s1, s2, &beg, &end); for (it = beg; it != end; it++) { putchar(*it); } printf("\n"); return 0; }
fn longest_common_substring(s1: &str, s2: &str) -> String { let s1_chars: Vec<char> = s1.chars().collect(); let s2_chars: Vec<char> = s2.chars().collect(); let mut lcs = "".to_string(); for i in 0..s1_chars.len() { for j in 0..s2_chars.len() { if s1_chars[i] == s2_chars[j] { let mut tmp_lcs = s2_chars[j].to_string(); let mut tmp_i = i + 1; let mut tmp_j = j + 1; while tmp_i < s1_chars.len() && tmp_j < s2_chars.len() && s1_chars[tmp_i] == s2_chars[tmp_j] { tmp_lcs = format!("{}{}", tmp_lcs, s1_chars[tmp_i]); tmp_i += 1; tmp_j += 1; } if tmp_lcs.len() > lcs.len() { lcs = tmp_lcs; } } } } lcs } fn main() { let s1 = "thisisatest"; let s2 = "testing123testing"; let lcs = longest_common_substring(s1, s2); println!("{}", lcs); }
Look-and-say sequence
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
Loop over multiple arrays simultaneously
#include <stdio.h> char a1[] = {'a','b','c'}; char a2[] = {'A','B','C'}; int a3[] = {1,2,3}; int main(void) { for (int i = 0; i < 3; i++) { printf("%c%c%i\n", a1[i], a2[i], a3[i]); } }
fn main() { let a1 = ["a", "b", "c"]; let a2 = ["A", "B", "C"]; let a3 = [1, 2, 3]; for ((&x, &y), &z) in a1.iter().zip(a2.iter()).zip(a3.iter()) { println!("{}{}{}", x, y, z); } }
Loops_Break
int main(){ time_t t; int a, b; srand((unsigned)time(&t)); for(;;){ a = rand() % 20; printf("%d\n", a); if(a == 10) break; b = rand() % 20; printf("%d\n", b); } return 0; }
extern crate rand; use rand::{thread_rng, Rng}; fn main() { let mut rng = thread_rng(); loop { let num = rng.gen_range(0, 20); if num == 10 { println!("{}", num); break; } println!("{}", rng.gen_range(0, 20)); } }
Loops_Continue
for(int i = 1;i <= 10; i++){ printf("%d", i); if(i % 5 == 0){ printf("\n"); continue; } printf(", "); }
fn main() { for i in 1..=10 { print!("{}", i); if i % 5 == 0 { println!(); continue; } print!(", "); } }
Loops_Do-while
int val = 0; do{ val++; printf("%d\n",val); }while(val % 6 != 0);
let mut x = 0; loop { x += 1; println!("{}", x); if x % 6 == 0 { break; } }
Loops_Downward for
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
fn main() { for i in (0..=10).rev() { println!("{}", i); } }
Loops_For
int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) putchar('*'); puts(""); }
fn main() { for i in 0..5 { for _ in 0..=i { print!("*"); } println!(); } }
Loops_For with a specified step
int i; for(i = 1; i < 10; i += 2) printf("%d\n", i);
fn main() { for i in (2..=8).step_by(2) { print!("{}", i); } println!("who do we appreciate?!"); }
Loops_Foreach
#include <stdio.h> ... const char *list[] = {"Red","Green","Blue","Black","White"}; #define LIST_SIZE (sizeof(list)/sizeof(list[0])) int ix; for(ix=0; ix<LIST_SIZE; ix++) { printf("%s\n", list[ix]); }
let collection = vec![1,2,3,4,5]; for elem in collection { println!("{}", elem); }
Loops_N plus one half
#include <stdio.h> int main() { int i; for (i = 1; i <= 10; i++) { printf("%d", i); printf(i == 10 ? "\n" : ", "); } return 0; }
fn main() { for i in 1..=10 { print!("{}{}", i, if i < 10 { ", " } else { "\n" }); } }
Loops_Nested
#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int a[10][10], i, j; srand(time(NULL)); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) a[i][j] = rand() % 20 + 1; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf(" %d", a[i][j]); if (a[i][j] == 20) goto Done; } printf("\n"); } Done: printf("\n"); return 0; }
use rand::Rng; extern crate rand; fn main() { let mut matrix = [[0u8; 10]; 10]; let mut rng = rand::thread_rng(); for row in matrix.iter_mut() { for item in row.iter_mut() { *item = rng.gen_range(0, 21); } } 'outer: for row in matrix.iter() { for &item in row.iter() { print!("{:2} ", item); if item == 20 { break 'outer } } println!(); } }
Loops_While
int i = 1024; while(i > 0) { printf("%d\n", i); i /= 2; }
fn main() { let mut n: i32 = 1024; while n > 0 { println!("{}", n); n /= 2; } }
Lucas-Lehmer test
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <gmp.h> int lucas_lehmer(unsigned long p) { mpz_t V, mp, t; unsigned long k, tlim; int res; if (p == 2) return 1; if (!(p&1)) return 0; mpz_init_set_ui(t, p); if (!mpz_probab_prime_p(t, 25)) { mpz_clear(t); return 0; } if (p < 23) { mpz_clear(t); return (p != 11); } mpz_init(mp); mpz_setbit(mp, p); mpz_sub_ui(mp, mp, 1); if (p > 3 && p % 4 == 3) { mpz_mul_ui(t, t, 2); mpz_add_ui(t, t, 1); if (mpz_probab_prime_p(t,25) && mpz_divisible_p(mp, t)) { mpz_clear(mp); mpz_clear(t); return 0; } } tlim = p/2; if (tlim > (ULONG_MAX/(2*p))) tlim = ULONG_MAX/(2*p); for (k = 1; k < tlim; k++) { unsigned long q = 2*p*k+1; if ( (q%8==1 || q%8==7) && q % 3 && q % 5 && q % 7 && mpz_divisible_ui_p(mp, q) ) { mpz_clear(mp); mpz_clear(t); return 0; } } mpz_init_set_ui(V, 4); for (k = 3; k <= p; k++) { mpz_mul(V, V, V); mpz_sub_ui(V, V, 2); if (mpz_sgn(V) < 0) mpz_add(V, V, mp); mpz_tdiv_r_2exp(t, V, p); mpz_tdiv_q_2exp(V, V, p); mpz_add(V, V, t); while (mpz_cmp(V, mp) >= 0) mpz_sub(V, V, mp); } res = !mpz_sgn(V); mpz_clear(t); mpz_clear(mp); mpz_clear(V); return res; } int main(int argc, char* argv[]) { unsigned long i, n = 43112609; if (argc >= 2) n = strtoul(argv[1], 0, 10); for (i = 1; i <= n; i++) { if (lucas_lehmer(i)) { printf("M%lu ", i); fflush(stdout); } } printf("\n"); return 0; }
extern crate rug; extern crate primal; use rug::Integer; use rug::ops::Pow; use std::thread::spawn; fn is_mersenne (p : usize) { let p = p as u32; let mut m = Integer::from(1); m = m << p; m = Integer::from(&m - 1); let mut flag1 = false; for k in 1..10_000 { let mut flag2 = false; let mut div : u32 = 2*k*p + 1; if &div >= &m {break; } for j in [3,5,7,11,13,17,19,23,29,31,37].iter() { if div % j == 0 { flag2 = true; break; } } if flag2 == true {continue;} if div % 8 != 1 && div % 8 != 7 { continue; } if m.is_divisible_u(div) { flag1 = true; break; } } if flag1 == true {return ()} let mut s = Integer::from(4); let two = Integer::from(2); for _i in 2..p { let mut sqr = s.pow(2); s = Integer::from(&Integer::from(&sqr & &m) + &Integer::from(&sqr >> p)); if &s >= &m {s = s - &m} s = Integer::from(&s - &two); } if s == 0 {println!("Mersenne : {}",p);} } fn main () { println!("Mersenne : 2"); let limit = 11_214; let mut thread_handles = vec![]; for p in primal::Primes::all().take_while(|p| *p < limit) { thread_handles.push(spawn(move || is_mersenne(p))); } for handle in thread_handles { handle.join().unwrap(); } }