name
stringlengths
2
74
C
stringlengths
7
6.19k
Rust
stringlengths
19
8.53k
Ludic numbers
#include <stdio.h> #include <stdlib.h> typedef unsigned uint; typedef struct { uint i, v; } filt_t; uint* ludic(uint min_len, uint min_val, uint *len) { uint cap, i, v, active = 1, nf = 0; filt_t *f = calloc(cap = 2, sizeof(*f)); f[1].i = 4; for (v = 1; ; ++v) { for (i = 1; i < active && --f[i].i; i++); if...
const ARRAY_MAX: usize = 25_000; const LUDIC_MAX: usize = 2100; fn ludic_numbers() -> Vec<usize> { let mut numbers = vec![1, 2]; numbers.extend((3..ARRAY_MAX).step_by(2)); for ludic_idx in 2..LUDIC_MAX { let next_ludic = numbers[ludic_idx]; ...
Luhn test of credit card numbers
#include <string.h> #include <stdio.h> int luhn(const char* cc) { const int m[] = {0,2,4,6,8,1,3,5,7,9}; int i, odd = 1, sum = 0; for (i = strlen(cc); i--; odd = !odd) { int digit = cc[i] - '0'; sum += odd ? digit : m[digit]; } return sum % 10 == 0; } int main() { const char* cc[] = { "49927398716", ...
extern crate luhn_test_of_credit_card_numbers; use luhn_test_of_credit_card_numbers::luhn_test; fn validate_isin(isin: &str) -> bool { if !isin.chars().all(|x| x.is_alphanumeric()) || isin.len() != 12 { return false; } if !isin[..2].chars().all(|x| x.is_alphabetic()) || !isin[2..12].chars(...
MD4
#include <stdlib.h> #include <string.h> #include <stdint.h> char *MD4(char *str, int len); typedef struct string{ char *c; int len; char sign; }string; static uint32_t *MD4Digest(uint32_t *w, int len); static void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD); static...
use std::fmt::Write; use std::mem; fn f(x: u32, y: u32, z: u32) -> u32 { (x & y) | (!x & z) } fn g(x: u32, y: u32, z: u32) -> u32 { (x & y) | (x & z) | (y & z) } fn h(x: u32, y: u32, z: u32) -> u32 { x ^ y ^ z } macro_rules! md4round1 { ( $a:expr, $b:expr, $c:expr, $d:expr, $i:expr,...
MD5
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> const char *string = "The quick brown fox jumped over the lazy dog's back"; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) prin...
extern crate crypto; use crypto::digest::Digest; use crypto::md5::Md5; fn main() { let mut sh = Md5::new(); sh.input_str("The quick brown fox jumped over the lazy dog's back"); println!("{}", sh.result_str()); }
Make directory path
#include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> int main (int argc, char **argv) { char *str, *s; struct stat statBuf; if (argc != 2) { fprintf (stderr, "usage: %s <path>\n", basename (argv[0])); exit (1); } ...
use std::fs; fn main() { fs::create_dir_all("./path/to/dir").expect("An Error Occured!") }
Man or boy test
#include <stdio.h> #include <stdlib.h> typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG; int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; } int eval(ARG* a) { return a->fn(a); } #define MAKE_ARG(...) (&(...
use std::cell::Cell; trait Arg { fn run(&self) -> i32; } impl Arg for i32 { fn run(&self) -> i32 { *self } } struct B<'a> { k: &'a Cell<i32>, x1: &'a Arg, x2: &'a Arg, x3: &'a Arg, x4: &'a Arg, } impl<'a> Arg for B<'a> { fn run(&self) -> i32 { self.k.set(self.k.get() - 1); ...
Mandelbrot set
#include <stdio.h> #include <math.h> int main() { int iX,iY; const int iXmax = 800; const int iYmax = 800; double Cx,Cy; const double CxMin=-2.5; const double CxMax=1.5; const double CyMin=-2.0; const double CyMax=2.0; ...
extern crate image; extern crate num_complex; use num_complex::Complex; fn main() { let max_iterations = 256u16; let img_side = 800u32; let cxmin = -2f32; let cxmax = 1f32; let cymin = -1.5f32; let cymax = 1.5f32; let scalex = (cxmax - cxmin) / img_side as f32; let scaley = (cymax - cy...
Map range
double inc = (nHasta - nDesde) / ( nTotal - 1); lista[0] = nDesde; lista[nTotal] = nHasta; for( n=1; n<nTotal; n++){ lista[n] = lista[n-1] + inc; }
use std::ops::{Add, Sub, Mul, Div}; fn map_range<T: Copy>(from_range: (T, T), to_range: (T, T), s: T) -> T where T: Add<T, Output=T> + Sub<T, Output=T> + Mul<T, Output=T> + Div<T, Output=T> { to_range.0 + (s - from_range.0) * (to_range.1 - to_range.0) / (from_range.1 - f...
Matrix chain multiplication
#include <stdio.h> #include <limits.h> #include <stdlib.h> int **m; int **s; void optimal_matrix_chain_order(int *dims, int n) { int len, i, j, k, temp, cost; n--; m = (int **)malloc(n * sizeof(int *)); for (i = 0; i < n; ++i) { m[i] = (int *)calloc(n, sizeof(int)); } s = (int **)mall...
use std::collections::HashMap; fn main() { println!("{}\n", mcm_display(vec![5, 6, 3, 1])); println!( "{}\n", mcm_display(vec![1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]) ); println!( "{}\n", mcm_display(vec![1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]) ...
Matrix multiplication
#include <stdio.h> #define MAT_ELEM(rows,cols,r,c) (r*cols+c) #ifdef __cplusplus typedef double * const __restrict MAT_OUT_t; #else typedef double * const restrict MAT_OUT_t; #endif typedef const double * const MAT_IN_t; static inline void mat_mult( const int m, const int n, const int p, M...
struct Matrix { dat: [[f32; 3]; 3] } impl Matrix { pub fn mult_m(a: Matrix, b: Matrix) -> Matrix { let mut out = Matrix { dat: [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.] ] }; for i in 0..3{ for j in 0..3 {...
Matrix transposition
#include <stdio.h> void transpose(void *dest, void *src, int src_h, int src_w) { int i, j; double (*d)[src_h] = dest, (*s)[src_w] = src; for (i = 0; i < src_h; i++) for (j = 0; j < src_w; j++) d[j][i] = s[i][j]; } int main() { int i, j; double a[3][5] = {{ 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 1, ...
struct Matrix { dat: [[i32; 3]; 3] } impl Matrix { pub fn transpose_m(a: Matrix) -> Matrix { let mut out = Matrix { dat: [[0, 0, 0], [0, 0, 0], [0, 0, 0] ] }; for i in 0..3{ for j in 0..3{ ...
Matrix-exponentiation operator
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm =...
use std::fmt; use std::ops; const WIDTH: usize = 6; #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, } impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row += ...
Maximum triangle path sum
#include <stdio.h> #include <math.h> #define max(x,y) ((x) > (y) ? (x) : (y)) int tri[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29...
use std::cmp::max; fn max_path(vector: &mut Vec<Vec<u32>>) -> u32 { while vector.len() > 1 { let last = vector.pop().unwrap(); let ante = vector.pop().unwrap(); let mut new: Vec<u32> = Vec::new(); for (i, value) in ante.iter().enumerate() { ...
Maze generation
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #define DOUBLE_SPACE 1 #if DOUBLE_SPACE # define SPC " " #else # define SPC " " #endif wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄"; typedef unsigned char byte; enum { N = 1, S = 2, W = 4, E = 8, V = 16 }; byte **cell; int...
use rand::{thread_rng, Rng, rngs::ThreadRng}; const WIDTH: usize = 16; const HEIGHT: usize = 16; #[derive(Clone, Copy)] struct Cell { col: usize, row: usize, } impl Cell { fn from(col: usize, row: usize) -> Cell { Cell {col, row} } } struct Maze { cells: [[bool; HEIGHT]; WIDTH], ...
Memory allocation
#include <stdlib.h> #define SIZEOF_MEMB (sizeof(int)) #define NMEMB 100 int main() { int *ints = malloc(SIZEOF_MEMB*NMEMB); ints = realloc(ints, sizeof(int)*(NMEMB+1)); int *int2 = calloc(NMEMB, SIZEOF_MEMB); free(ints); free(int2); return 0; }
unsafe { use std::alloc::{Layout, alloc, dealloc}; let int_layout = Layout::new::<i32>(); let ptr = alloc(int_layout); *ptr = 123; assert_eq!(*ptr, 123); dealloc(ptr, int_layout); }
Menu
#include <stdio.h> #include <stdlib.h> #include <string.h> const char *menu_select(const char *const *items, const char *prompt); int main(void) { const char *items[] = {"fee fie", "huff and puff", "mirror mirror", "tick tock", NULL}; const char *prompt = "Which is from the three pigs?"; printf("You chose %s.\n",...
fn menu_select<'a>(items: &'a [&'a str]) -> &'a str { if items.len() == 0 { return ""; } let stdin = std::io::stdin(); let mut buffer = String::new(); loop { for (i, item) in items.iter().enumerate() { println!("{}) {}", i + 1, item); } print!("Pick a nu...
Metered concurrency
#include <semaphore.h> #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> sem_t sem; int count = 3; #define getcount() count void acquire() { sem_wait(&sem); count--; } void release() { count++; sem_post(&sem); } void* work(void * id) { int i = 10; while (i--) { acquire(); pr...
use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread::{self, spawn}; use std::time::Duration; pub struct CountingSemaphore { count: AtomicUsize, backoff: Duration, } pub struct CountingSemaphoreGuard<'a> { ...
Middle three digits
#include <stdio.h> #include <stdlib.h> #include <string.h> char * mid3(int n) { static char buf[32]; int l; sprintf(buf, "%d", n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; } int main(void) { int x[] = {123, 12345, 1234567, 987654321, 10001...
fn middle_three_digits(x: i32) -> Result<String, String> { let s: String = x.abs().to_string(); let len = s.len(); if len < 3 { Err("Too short".into()) } else if len % 2 == 0 { Err("Even number of digits".into()) } else { Ok(s[len/2 - 1 .. len/2 + 2].to_owned()) } } fn p...
Miller–Rabin primality test
#ifndef _MILLER_RABIN_H_ #define _MILLER_RABIN_H #include <gmp.h> bool miller_rabin_test(mpz_t n, int j); #endif
use num::bigint::BigInt; use num::bigint::ToBigInt; fn modular_exponentiation<T: ToBigInt>(n: &T, e: &T, m: &T) -> BigInt { let n = n.to_bigint().unwrap(); let e = e.to_bigint().unwrap(); let m = m.to_bigint().unwrap(); assert!(e >= Zero::zero()); use num::traits::{Zero, One};...
Modular exponentiation
#include <gmp.h> int main() { mpz_t a, b, m, r; mpz_init_set_str(a, "2988348162058574136915891421498819466320" "163312926952423791023078876139", 0); mpz_init_set_str(b, "2351399303373464486466122544523690094744" "975233415544072992656881240319", 0); mpz_init(m); mpz_ui_pow_ui(m, 10, 40); mpz_init(r); ...
use num::bigint::BigInt; use num::bigint::ToBigInt; fn modular_exponentiation<T: ToBigInt>(n: &T, e: &T, m: &T) -> BigInt { let n = n.to_bigint().unwrap(); let e = e.to_bigint().unwrap(); let m = m.to_bigint().unwrap(); assert!(e >= Zero::zero()); use num::traits::{Zero, One}; ...
Modular inverse
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
fn mod_inv(a: isize, module: isize) -> isize { let mut mn = (module, a); let mut xy = (0, 1); while mn.1 != 0 { xy = (xy.1, xy.0 - (mn.0 / mn.1) * xy.1); mn = (mn.1, mn.0 % mn.1); } while xy.0 < 0 { xy.0 += module; } xy.0 } fn main() { println!("{}", mod_inv(42, 2017)) }
Monte Carlo methods
#include <stdio.h> #include <stdlib.h> #include <math.h> double pi(double tolerance) { double x, y, val, error; unsigned long sampled = 0, hit = 0, i; do { for (i = 1000000; i; i--, sampled++) { x = rand() / (RAND_MAX + 1.0); y = rand() / (RAND_MAX + 1.0); if (x * x + y * y < 1) hit ++; } val =...
extern crate rand; use rand::Rng; use std::f64::consts::PI; fn is_inside_circle((x, y): (f64, f64)) -> bool { x * x + y * y <= 1.0 } fn simulate<R: Rng>(rng: &mut R, samples: usize) -> f64 { let mut count = 0; for _ in 0..samples { if is_inside_circle(rng.gen()) { count += 1; ...
Monty Hall problem
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <time.h> #include <math.h> #define NumSim 1000000000 void main() { unsigned long int i,stay=0; int ChosenDoor,WinningDoor; bool door[3]={0,0,0}; srand(time(NULL)); for(i=0;i<=NumSim;i++){ WinningD...
extern crate rand; use rand::Rng; use rand::seq::SliceRandom; #[derive(Clone, Copy, PartialEq)] enum Prize {Goat , Car} const GAMES: usize = 3_000_000; fn main() { let mut switch_wins = 0; let mut rng = rand::thread_rng(); for _ in 0..GAMES { let mut doors = [Prize::Goat; 3]; *doors.c...
Morse code
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","313...
use std::process; use structopt::StructOpt; use morse_code::{Config, Opt, run}; fn main() { let opts = Opt::from_args(); let mut config = Config::new(opts).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(err) = run(&...
Mouse position
#include <stdio.h> #include <X11/Xlib.h> int main() { Display *d; Window inwin; Window inchildwin; int rootx, rooty; int childx, childy; Atom atom_type_prop; int actual_format; unsigned int mask; unsigned long n_items, bytes_after_ret; Window *props; d = XOpenDisplay(NULL); ...
use std::libc::{BOOL, HANDLE, LONG}; use std::ptr::mut_null; type HWND = HANDLE; #[deriving(Eq)] struct POINT { x: LONG, y: LONG } #[link_name = "user32"] extern "system" { fn GetCursorPos(lpPoint:&mut POINT) -> BOOL; fn GetForegroundWindow() -> HWND; fn ScreenToClient(hWnd:HWND, lpPoint:&mut P...
Move-to-front algorithm
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 100 int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); shift=q-p; strncpy(str+1,p,shift); str[0]=c; free(p); return shif...
fn main() { let examples = vec!["broood", "bananaaa", "hiphophiphop"]; for example in examples { let encoded = encode(example); let decoded = decode(&encoded); println!( "{} encodes to {:?} decodes to {}", example, encoded, decoded ); } } fn get_symbo...
Multifactorial
#include <stdio.h> #define HIGHEST_DEGREE 5 #define LARGEST_NUMBER 10 int multifact(int n, int deg){ return n <= deg ? n : n * multifact(n - deg, deg); } int multifact_i(int n, int deg){ int result = n; while (n >= deg + 1){ result *= (n - deg); n -= deg; } return result; } int main(vo...
fn multifactorial(n: i32, deg: i32) -> i32 { if n < 1 { 1 } else { n * multifactorial(n - deg, deg) } } fn main() { for i in 1..6 { for j in 1..11 { print!("{} ", multifactorial(j, i)); } println!(""); } }
Multiple distinct objects
foo *foos = malloc(n * sizeof(*foos)); for (int i = 0; i < n; i++) init_foo(&foos[i]);
use std::rc::Rc; use std::cell::RefCell; fn main() { let size = 3; let mut v: Vec<String> = vec![String::new(); size]; v[0].push('a'); println!("{:?}", v); let mut v: Vec<String> = (0..size).map(|i| i.to_string()).collect(); v[0].push('a'); println!("{:?}", v); ...
Multiplication tables
#include <stdio.h> int main(void) { int i, j, n = 12; for (j = 1; j <= n; j++) printf("%3d%c", j, j != n ? ' ' : '\n'); for (j = 0; j <= n; j++) printf(j != n ? "----" : "+\n"); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) printf(j < i ? " " : "%3d ", i * j); printf("| %d\n", i); ...
const LIMIT: i32 = 12; fn main() { for i in 1..LIMIT+1 { print!("{:3}{}", i, if LIMIT - i == 0 {'\n'} else {' '}) } for i in 0..LIMIT+1 { print!("{}", if LIMIT - i == 0 {"+\n"} else {"----"}); } for i in 1..LIMIT+1 { for j in 1..LIMIT+1 { if j < i { ...
Munchausen numbers
#include <stdio.h> #include <math.h> int main() { for (int i = 1; i < 5000; i++) { int sum = 0; for (int number = i; number > 0; number /= 10) { int digit = number % 10; sum += pow(digit, digit); } if (sum == i) { ...
fn main() { let mut solutions = Vec::new(); for num in 1..5_000 { let power_sum = num.to_string() .chars() .map(|c| { let digit = c.to_digit(10).unwrap(); (digit as f64).powi(digit as i32) as usize }) .sum::<usize>(); ...
Munching squares
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> void hue_to_rgb(double hue, double sat, unsigned char *p) { double x; int c = 255 * sat; hue /= 60; x = (1 - fabs(fmod(hue, 2) - 1)) * 255; switch((int)hue) { case 0: p[0] = c; p[1] = x; p[2] = 0; return; case 1: p[0] = x; p[1] = c; p...
extern crate image; use image::{ImageBuffer, Pixel, Rgb}; fn main() { let mut img = ImageBuffer::new(256, 256); for x in 0..256 { for y in 0..256 { let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0); img.put_pixel(x, y, pixel); } } let _ = img.save("ou...
Mutual recursion
#include <stdio.h> #include <stdlib.h> int F(const int n); int M(const int n); int F(const int n) { return (n == 0) ? 1 : n - M(F(n - 1)); } int M(const int n) { return (n == 0) ? 0 : n - F(M(n - 1)); } int main(void) { int i; for (i = 0; i < 20; i++) printf("%2d ", F(i)); printf("\n"); for (i = 0;...
fn f(n: u32) -> u32 { match n { 0 => 1, _ => n - m(f(n - 1)) } } fn m(n: u32) -> u32 { match n { 0 => 0, _ => n - f(m(n - 1)) } } fn main() { for i in (0..20).map(f) { print!("{} ", i); } println!(""); for i in (0..20).map(m) { print!("{...
N'th
#include <stdio.h> char* addSuffix(int num, char* buf, size_t len) { char *suffixes[4] = { "th", "st", "nd", "rd" }; int i; switch (num % 10) { case 1 : i = (num % 100 == 11) ? 0 : 1; break; case 2 : i = (num % 100 == 12) ? 0 : 2; break; case 3 : i =...
fn nth(num: isize) -> String { format!("{}{}", num, match (num % 10, num % 100) { (1, 11) | (2, 12) | (3, 13) => "th", (1, _) => "st", (2, _) => "nd", (3, _) => "rd", _ => "th", }) } fn main() { let ranges = [(0, 26), (250, 266), (1000, 1026)]; for &(s, e) in &ra...
N-queens problem
#include <stdio.h> #include <stdlib.h> int count = 0; void solve(int n, int col, int *hist) { if (col == n) { printf("\nNo. %d\n-----\n", ++count); for (int i = 0; i < n; i++, putchar('\n')) for (int j = 0; j < n; j++) putchar(j == hist[i] ? 'Q' : ((i + j) & 1) ? ' ' : '.'); return; } # define attack(...
const N: usize = 8; fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) { if row == N { *count += 1; for r in board.iter() { println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::<Vec<String>>().join(" ")) } println!(""); retur...
Narcissist
extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }
use std::io::{stdin, prelude::*}; fn main() { let src = include_str!("main.rs"); let mut input = String::new(); stdin() .lock() .read_to_string(&mut input) .expect("Could not read from STDIN"); println!("{}", src == input); }
Narcissistic decimal number
#include <stdio.h> #include <gmp.h> #define MAX_LEN 81 mpz_t power[10]; mpz_t dsum[MAX_LEN + 1]; int cnt[10], len; void check_perm(void) { char s[MAX_LEN + 1]; int i, c, out[10] = { 0 }; mpz_get_str(s, 10, dsum[0]); for (i = 0; s[i]; i++) { c = s[i]-'0'; if (++out[c] > cnt[c]) return; } if (i == len) g...
fn is_narcissistic(x: u32) -> bool { let digits: Vec<u32> = x .to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .collect(); digits .iter() .map(|d| d.pow(digits.len() as u32)) .sum::<u32>() == x } fn main() { let mut counter = 0; le...
Negative base numbers
#include <stdio.h> const char DIGITS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const int DIGITS_LEN = 64; void encodeNegativeBase(long n, long base, char *out) { char *ptr = out; if (base > -1 || base < -62) { out = ""; return; } if (n == 0) { ...
const DIGITS: [char;62] = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; fn main() { let nums_and_bases: [(i64,...
Nested function
#include<stdlib.h> #include<stdio.h> typedef struct{ char str[30]; }item; item* makeList(char* separator){ int counter = 0,i; item* list = (item*)malloc(3*sizeof(item)); item makeItem(){ item holder; char names[5][10] = {"first","second","third","fourth","fifth"}; sprintf(holder.str,"%d%s%s",++count...
fn make_list(sep: &str) -> String { let mut counter = 0; let mut make_item = |label| { counter += 1; format!("{}{}{}", counter, sep, label) }; format!( "{}\n{}\n{}", make_item("First"), make_item("Second"), make_item("Third") ) } fn main() { print...
Nim game
#include <stdio.h> int playerTurn(int numTokens, int take); int computerTurn(int numTokens); int main(void) { printf("Nim Game\n\n"); int Tokens = 12; while(Tokens > 0) { printf("How many tokens would you like to take?: "); int uin; scanf("%i", &uin); int nextTokens = playerTurn(Tokens, uin); ...
fn main() { let mut tokens = 12; println!("Nim game"); println!("Starting with {} tokens.", tokens); println!(""); loop { tokens = p_turn(&tokens); print_remaining(&tokens); tokens = c_turn(&tokens); print_remaining(&tokens); if tokens == 0 { ...
Non-decimal radices_Convert
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> char *to_base(int64_t num, int base) { char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[66] = {'\0'}; char *out; uint64_t n; int i, len = 0, neg = 0; if (base > 36) { fprintf(stderr, "base %d too large\n", base);...
fn format_with_radix(mut n: u32, radix: u32) -> String { assert!(2 <= radix && radix <= 36); let mut result = String::new(); loop { result.push(std::char::from_digit(n % radix, radix).unwrap()); n /= radix; if n == 0 { break; } } result.chars().rev().co...
Non-decimal radices_Input
#include <stdio.h> int main() { int num; sscanf("0123459", "%d", &num); printf("%d\n", num); sscanf("abcf123", "%x", &num); printf("%d\n", num); sscanf("7651", "%o", &num); printf("%d\n", num); return 0; }
fn main() { println!( "Parse from plain decimal: {}", "123".parse::<u32>().unwrap() ); println!( "Parse with a given radix (2-36 supported): {}", u32::from_str_radix("deadbeef", 16).unwrap() ); }
Non-decimal radices_Output
#include <stdio.h> int main() { int i; for(i=1; i <= 33; i++) printf("%6d %6x %6o\n", i, i, i); return 0; }
fn main() { println!("Binary: {:b}", 0xdeadbeefu32); println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32); println!("Octal: {:o}", 0xdeadbeefu32); println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32); println!("Decimal: {}", 0xdeadbeefu32); println!("Lowercase hexadecimal: {:x}", 0xdea...
Nth root
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0...
fn nthRoot(n: f64, A: f64) -> f64 { let p = 1e-9_f64 ; let mut x0 = A / n ; loop { let mut x1 = ( (n-1.0) * x0 + A / f64::powf(x0, n-1.0) ) / n; if (x1-x0).abs() < (x0*p).abs() { return x1 }; x0 = x1 } } fn main() { println!("{}", nthRoot(3. , 8. )); }
Null object
#include <stdio.h> int main() { char *object = 0; if (object == NULL) { puts("object is null"); } return 0; }
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&p...
Number names
#include <stdio.h> #include <string.h> const char *ones[] = { 0, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char *tens[] = { 0, "ten", "twenty", "thirty", "forty", "fi...
use std::io::{self, Write, stdout}; const SMALL: &[&str] = &[ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ]; const TENS: &[&str] = &[ "PANIC", "PANIC", "twe...
Number reversal game
void number_reversal_game() { printf("Number Reversal Game. Type a number to flip the first n numbers."); printf("Win by sorting the numbers in ascending order.\n"); printf("Anything besides numbers are ignored.\n"); printf("\t |1__2__3__4__5__6__7__8__9|\n"); int list[9] = {1,2,3,4,5,6,7,8,9}; ...
use rand::prelude::*; use std::io::stdin; fn is_sorted(seq: &[impl PartialOrd]) -> bool { if seq.len() < 2 { return true; } !seq.iter() .zip(seq[1..].iter()) .any(|(prev, foll)| prev > foll) } fn main() { println!( "Number reversal game: Given a jumbled list of...
Numerical integration
#include <stdio.h> #include <stdlib.h> #include <math.h> double int_leftrect(double from, double to, double n, double (*func)()) { double h = (to-from)/n; double sum = 0.0, x; for(x=from; x <= (to-h); x += h) sum += func(x); return h*sum; } double int_rightrect(double from, double to, double n, doub...
fn integral<F>(f: F, range: std::ops::Range<f64>, n_steps: u32) -> f64 where F: Fn(f64) -> f64 { let step_size = (range.end - range.start)/n_steps as f64; let mut integral = (f(range.start) + f(range.end))/2.; let mut pos = range.start + step_size; while pos < range.end { integral += f(pos)...
Old lady swallowed a fly
#include <stdio.h> static char const *animals[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" }; static char const *verses[] = { "I don't know why she swallowed that fly.\nPerhaps she'll die\n", "That wiggled and jiggled and tickled inside her", "H...
enum Action {Once, Every, Die} use Action::*; fn main() { let animals = [ ("horse" , Die , "She's dead, of course!") , ("donkey", Once , "It was rather wonky. To swallow a donkey.") , ("cow" , Once , "I don't know how. To swallow a cow.") , ("goat" , Once ,...
One of n lines in a file
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i ...
extern crate rand; use rand::{Rng, thread_rng}; fn one_of_n<R: Rng>(rng: &mut R, n: usize) -> usize { (1..n).fold(0, |keep, cand| { if rng.gen_weighted_bool(cand as u32 + 1) { cand } else { keep } }) } fn main() { const LINES: usize = 10; let ...
One-dimensional cellular automata
#include <stdio.h> #include <string.h> char trans[] = "___#_##_"; #define v(i) (cell[i] != '_') int evolve(char cell[], char backup[], int len) { int i, diff = 0; for (i = 0; i < len; i++) { backup[i] = trans[ v(i-1) * 4 + v(i) * 2 + v(i + 1) ]; diff += (backup[i] != cell[i]); } strcpy(cell, backup); re...
fn get_new_state(windowed: &[bool]) -> bool { match windowed { [false, true, true] | [true, true, false] => true, _ => false } } fn next_gen(cell: &mut [bool]) { let mut v = Vec::with_capacity(cell.len()); v.push(cell[0]); for i in cell.windows(3) { v.push(get_new_state(i));...
OpenGL
#include <stdlib.h> #include <GL/gl.h> #include <GL/glut.h> void paint(void) { glClearColor(0.3,0.3,0.3,0.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glShadeModel(GL_SMOOTH); glLoadIdentity(); glTranslatef(-15.0, -15.0, 0.0); glBegin(GL_TRIANGLES); glColor3f(1.0, 0.0, 0.0); glVertex2f(0.0,...
use glow::*; use glutin::event::*; use glutin::event_loop::{ControlFlow, EventLoop}; use std::os::raw::c_uint; const VERTEX: &str = "#version 410 const vec2 verts[3] = vec2[3]( vec2(0.5f, 1.0f), vec2(0.0f, 0.0f), vec2(1.0f, 0.0f) ); out vec2 vert; void main() { vert = verts[gl_VertexID]; gl_Positio...
Order two numerical lists
int list_cmp(int *a, int la, int *b, int lb) { int i, l = la; if (l > lb) l = lb; for (i = 0; i < l; i++) { if (a[i] == b[i]) continue; return (a[i] > b[i]) ? 1 : -1; } if (la == lb) return 0; return la > lb ? 1 : -1; }
vec![1, 2, 1, 3, 2] < vec![1, 2, 0, 4, 4, 0, 0, 0]
Ordered partitions
#include <stdio.h> int next_perm(int size, int * nums) { int *l, *k, tmp; for (k = nums + size - 2; k >= nums && k[0] >= k[1]; k--) {}; if (k < nums) return 0; for (l = nums + size - 1; *l <= *k; l--) {}; tmp = *k; *k = *l; *l = tmp; for (l = nums + size - 1, k++; k <...
use itertools::Itertools; type NArray = Vec<Vec<Vec<usize>>>; fn generate_partitions(args: &[usize]) -> NArray { let max = args.iter().sum(); let c = args.iter().fold(vec![], |mut acc, arg| { acc.push((1..=max).combinations(*arg).collect::<Vec<_>>()); acc }); ...
Ordered words
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #define MAXLEN 100 typedef char TWord[MAXLEN]; typedef struct Node { TWord word; struct Node *next; } Node; int is_ordered_word(const TWord word) { assert(word != NULL); int i; for (i = 0; word[i] != '\0'; i++) ...
const FILE: &'static str = include_str!("./unixdict.txt"); fn is_ordered(s: &str) -> bool { let mut prev = '\x00'; for c in s.to_lowercase().chars() { if c < prev { return false; } prev = c; } return true; } fn find_longest_ordered_words(dict: Vec<&str>) -> Vec<&st...
Palindrome dates
#include <stdbool.h> #include <stdio.h> #include <string.h> #include <time.h> bool is_palindrome(const char* str) { size_t n = strlen(str); for (size_t i = 0; i + 1 < n; ++i, --n) { if (str[i] != str[n - 1]) return false; } return true; } int main() { time_t timestamp = time(0)...
fn is_palindrome(s: &str) -> bool { s.chars().rev().eq(s.chars()) } fn main() { let mut date = chrono::Utc::today(); let mut count = 0; while count < 15 { if is_palindrome(&date.format("%Y%m%d").to_string()) { println!("{}", date.format("%F")); count += 1; } ...
Palindrome detection
#include <string.h> int palindrome(const char *s) { int i,l; l = strlen(s); for(i=0; i<l/2; i++) { if ( s[i] != s[l-i-1] ) return 0; } return 1; }
fn is_palindrome(string: &str) -> bool { let half_len = string.len() / 2; string .chars() .take(half_len) .eq(string.chars().rev().take(half_len)) } macro_rules! test { ( $( $x:tt ),* ) => { $( println!("'{}': {}", $x, is_palindrome($x)); )* }; } fn main() { test!( "", ...
Pangram checker
#include <stdio.h> int is_pangram(const char *s) { const char *alpha = "" "abcdefghjiklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char ch, wasused[26] = {0}; int total = 0; while ((ch = *s++) != '\0') { const char *p; int idx; if ((p = strchr(alpha, ch)) == NULL) continue; idx = (p - alpha) %...
#![feature(test)] extern crate test; use std::collections::HashSet; pub fn is_pangram_via_bitmask(s: &str) -> bool { let mut mask = (1 << 26) - 1; for chr in s.chars() { let val = chr as u32 & !0x20; if val <= 'Z' as u32 && val >= 'A' as u32 { mask = mask & !(1 << (val - '...
Parallel calculations
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < ...
extern crate rayon; extern crate prime_decomposition; use rayon::prelude::*; pub fn largest_min_factor(numbers: &[usize]) -> usize { numbers .par_iter() .map(|n| { prime_decomposition::factor(*n)[0] }) .max() .unwrap() } fn main() { let n...
Parametric polymorphism
#include <stdio.h> #include <stdlib.h> #define decl_tree_type(T) \ typedef struct node_##T##_t node_##T##_t, *node_##T; \ struct node_##T##_t { node_##T left, right; T value; }; \ ...
struct TreeNode<T> { value: T, left: Option<Box<TreeNode<T>>>, right: Option<Box<TreeNode<T>>>, } impl <T> TreeNode<T> { fn my_map<U,F>(&self, f: &F) -> TreeNode<U> where F: Fn(&T) -> U { TreeNode { value: f(&self.value), left: match self.left { ...
Parsing_RPN calculator algorithm
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void die(const char *msg) { fprintf(stderr, "%s", msg); abort(); } #define MAX_D 256 double stack[MAX_D]; int depth; void push(double v) { if (depth >= MAX_D) die("stack overflow\n"); stack[depth++] = v; } double pop() { if (!depth) d...
fn rpn(text: &str) -> f64 { let tokens = text.split_whitespace(); let mut stack: Vec<f64> = vec![]; println!("input operation stack"); for token in tokens { print!("{:^5} ", token); match token.parse() { Ok(num) => { stack.push(num); println!(...
Pascal's triangle
#include <stdio.h> void pascaltriangle(unsigned int n) { unsigned int c, i, j, k; for(i=0; i < n; i++) { c = 1; for(j=1; j <= 2*(n-1-i); j++) printf(" "); for(k=0; k <= i; k++) { printf("%3d ", c); c = c * (i-k)/(k+1); } printf("\n"); } } int main() { pascaltriangle(8); retu...
fn pascal_triangle(n: u64) { for i in 0..n { let mut c = 1; for _j in 1..2*(n-1-i)+1 { print!(" "); } for k in 0..i+1 { print!("{:2} ", c); c = c * (i-k)/(k+1); } println!(); } }
Password generator
#include <stdio.h> #include <stdlib.h> #include <time.h> #define DEFAULT_LENGTH 4 #define DEFAULT_COUNT 1 char* symbols[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"}; int length = DEFAULT_LENGTH; int count = DEFAULT_COUNT; unsigned seed; char exSymbo...
use rand::distributions::Alphanumeric; use rand::prelude::IteratorRandom; use rand::{thread_rng, Rng}; use std::iter; use std::process; use structopt::StructOpt; const OTHER_VALUES: &str = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"; fn generate_password(length: u8) -> String { let mut rng = thread_rng(); ...
Pell's equation
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { ...
use num_bigint::{ToBigInt, BigInt}; use num_traits::{Zero, One}; fn main() { test(61u64); test(109u64); test(181u64); test(277u64); } struct Pair { v1: BigInt, v2: BigInt, } impl Pair { pub fn make_pair(a: &BigInt, b: &BigInt) -> Pair { Pair { v1: a.clone(), ...
Percentage difference between images
#include <stdio.h> #include <stdlib.h> #include <math.h> #define RED_C 0 #define GREEN_C 1 #define BLUE_C 2 #define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ]) int main(int argc, char **argv) { image im1, im2; double totalDiff = 0.0; unsigned int x, y; if ( argc < 3 ) { fpr...
extern crate image; use image::{GenericImageView, Rgba}; fn diff_rgba3(rgba1 : Rgba<u8>, rgba2 : Rgba<u8>) -> i32 { (rgba1[0] as i32 - rgba2[0] as i32).abs() + (rgba1[1] as i32 - rgba2[1] as i32).abs() + (rgba1[2] as i32 - rgba2[2] as i32).abs() } fn main() { let img1 = image::open("Lenna100.jpg").un...
Perfect numbers
#include "stdio.h" #include "math.h" int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } ...
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { ...
Perfect shuffle
#include <stdlib.h> #include <stdio.h> #include <string.h> #define N_DECKS 7 const int kDecks[N_DECKS] = { 8, 24, 52, 100, 1020, 1024, 10000 }; int CreateDeck( int **deck, int nCards ); void InitDeck( int *deck, int nCards ); int DuplicateDeck( int **dest, const int *orig, int nCards ); int InitedDeck( int *deck, ...
extern crate itertools; fn shuffle<T>(mut deck: Vec<T>) -> Vec<T> { let index = deck.len() / 2; let right_half = deck.split_off(index); itertools::interleave(deck, right_half).collect() } fn main() { for &size in &[8, 24, 52, 100, 1020, 1024, 10_000] { let original_deck: Vec<_> = (0..size).col...
Permutations
#include <stdio.h> int main (int argc, char *argv[]) { if (argc < 2) { printf("Enter an argument. Example 1234 or dcba:\n"); return 0; } int x; for (x = 0; argv[1][x] != '\0'; x++); int f, v, m; for(f=0; f < x; f++) { for(v = x-1; v > f; v-- ) { if (argv[1][v-1] > ar...
pub fn permutations(size: usize) -> Permutations { Permutations { idxs: (0..size).collect(), swaps: vec![0; size], i: 0 } } pub struct Permutations { idxs: Vec<usize>, swaps: Vec<usize>, i: usize, } impl Iterator for Permutations { type Item = Vec<usize>; fn next(&mut self) -> Option<Self::It...
Pernicious numbers
#include <stdio.h> typedef unsigned uint; uint is_pern(uint n) { uint c = 2693408940u; while (n) c >>= 1, n &= (n - 1); return c & 1; } int main(void) { uint i, c; for (i = c = 0; c < 25; i++) if (is_pern(i)) printf("%u ", i), ++c; ...
extern crate aks_test_for_primes; use std::iter::Filter; use std::ops::RangeFrom; use aks_test_for_primes::is_prime; fn main() { for i in pernicious().take(25) { print!("{} ", i); } println!(); for i in (888_888_877u64..888_888_888).filter(is_pernicious) { print!("{} ", i); } } f...
Phrase reversals
#include <stdio.h> #include <string.h> char* reverse_section(char *s, size_t length) { if (length == 0) return s; size_t i; char temp; for (i = 0; i < length / 2 + 1; ++i) temp = s[i], s[i] = s[length - i], s[length - i] = temp; return s; } char* reverse_words_in_order(char *s, char delim) ...
fn reverse_string(string: &str) -> String { string.chars().rev().collect::<String>() } fn reverse_words(string: &str) -> String { string .split_whitespace() .map(|x| x.chars().rev().collect::<String>()) .collect::<Vec<String>>() .join(" ") } fn reverse_word_order(string: &str) ...
Pi
#include <stdio.h> #include <stdlib.h> #include <gmp.h> mpz_t tmp1, tmp2, t5, t239, pows; void actan(mpz_t res, unsigned long base, mpz_t pows) { int i, neg = 1; mpz_tdiv_q_ui(res, pows, base); mpz_set(tmp1, res); for (i = 3; ; i += 2) { mpz_tdiv_q_ui(tmp1, tmp1, base * base); mpz_tdiv_q_ui(tmp2, tmp1, i); i...
use num_bigint::BigInt; fn main() { calc_pi(); } fn calc_pi() { let mut q = BigInt::from(1); let mut r = BigInt::from(0); let mut t = BigInt::from(1); let mut k = BigInt::from(1); let mut n = BigInt::from(3); let mut l = BigInt::from(3); let mut first = true; loop { if &q *...
Pick random element
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' }; int i; time_t t; srand((unsigned)time(&t)); for(i=0;i<30;i++){ printf("%c\n", array[rand()%10]); } return 0; }
extern crate rand; use rand::Rng; fn main() { let array = [5,1,2,5,6,7,8,1,2,4,5]; let mut rng = rand::thread_rng(); println!("{}", rng.choose(&array).unwrap()); }
Pig the dice game
#include <stdio.h> #include <stdlib.h> #include <time.h> const int NUM_PLAYERS = 2; const int MAX_POINTS = 100; int randrange(int min, int max){ return (rand() % (max - min + 1)) + min; } void ResetScores(int *scores){ for(int i = 0; i < NUM_PLAYERS; i++){ scores[i] = 0; } } void Play(int ...
use rand::prelude::*; fn main() { println!("Beginning game of Pig..."); let mut players = vec![ Player::new(String::from("PLAYER (1) ONE")), Player::new(String::from("PLAYER (2) TWO")), ]; 'game: loop { for player in players.iter_mut() { if player.cont() { ...
Population count
#include <stdio.h> int main() { { unsigned long long n = 1; for (int i = 0; i < 30; i++) { printf("%d ", __builtin_popcountll(n)); n *= 3; } printf("\n"); } int od[30]; int ne = 0, no = 0; printf("evil  : "); for (int n = 0; ne+no < 60; n++) { if ((__bu...
fn main() { let mut num = 1u64; let mut vec = Vec::new(); for _ in 0..30 { vec.push(num.count_ones()); num *= 3; } println!("pop count of 3^0, 3^1 ... 3^29:\n{:?}",vec); let mut even = Vec::new(); let mut odd = Vec::new(); num = 1; while even.len() < 30 || odd.len() ...
Power set
#include <stdio.h> struct node { char *s; struct node* prev; }; void powerset(char **v, int n, struct node *up) { struct node me; if (!n) { putchar('['); while (up) { printf(" %s", up->s); up = up->prev; } puts(" ]"); } else { me.s = *v; me.prev = up; powerset(v + 1, n - 1, up); powerset(v...
use std::collections::BTreeSet; fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> { if set.is_empty() { let mut powerset = BTreeSet::new(); powerset.insert(set); return powerset; } let entry = set.iter().nth(0).unwrap().clone(); set.remove(&en...
Primality by Wilson's theorem
#include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t factorial(uint64_t n) { uint64_t product = 1; if (n < 2) { return 1; } for (; n > 0; n--) { uint64_t prev = product; product *= n; if (product < prev) { fprintf(stderr, "Overflowed\n"); ...
fn factorial_mod(mut n: u32, p: u32) -> u32 { let mut f = 1; while n != 0 && f != 0 { f = (f * n) % p; n -= 1; } f } fn is_prime(p: u32) -> bool { p > 1 && factorial_mod(p - 1, p) == p - 1 } fn main() { println!(" n | prime?\n------------"); for p in vec![2, 3, 9, 15, 29, ...
Primality by trial division
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
fn is_prime(n: u64) -> bool { match n { 0 | 1 => false, 2 => true, _even if n % 2 == 0 => false, _ => { let sqrt_limit = (n as f64).sqrt() as u64; (3..=sqrt_limit).step_by(2).find(|i| n % i == 0).is_none() } } } fn main() { for i in (1..30).fi...
Prime decomposition
#include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> typedef uint32_t pint; typedef uint64_t xint; typedef unsigned int uint; #define PRIuPINT PRIu32 #define PRIuXINT PRIu64 #define MAX_FACTORS 63 uint8_t *pbits; #define MAX_PRIME (~(pint)0) #define MAX...
use num_bigint::BigUint; use num_traits::{One, Zero}; use std::fmt::{Display, Formatter}; #[derive(Clone, Debug)] pub struct Factors { pub number: BigUint, pub result: Vec<BigUint>, } impl Factors { pub fn of(number: BigUint) -> Factors { let mut factors = Self { number: number.clone()...
Priority queue
#include <stdio.h> #include <stdlib.h> typedef struct { int priority; char *data; } node_t; typedef struct { node_t *nodes; int len; int size; } heap_t; void push (heap_t *h, int priority, char *data) { if (h->len + 1 >= h->size) { h->size = h->size ? h->size * 2 : 4; h->nodes...
use std::collections::BinaryHeap; use std::cmp::Ordering; use std::borrow::Cow; #[derive(Eq, PartialEq)] struct Item<'a> { priority: usize, task: Cow<'a, str>, } impl<'a> Item<'a> { fn new<T>(p: usize, t: T) -> Self where T: Into<Cow<'a, str>> { Item { priority: p, ...
Probabilistic choice
#include <stdio.h> #include <stdlib.h> int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0); int i; for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; } #define LEN 8 #define N 1000000 int main() { const char *names[LEN] = { "aleph", "beth", "gimel", "daleth", "he", "waw", "zayin",...
extern crate rand; use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice}; use rand::{weak_rng, Rng}; const DATA: [(&str, f64); 8] = [ ("aleph", 1.0 / 5.0), ("beth", 1.0 / 6.0), ("gimel", 1.0 / 7.0), ("daleth", 1.0 / 8.0), ("he", 1.0 / 9.0), ("waw", 1.0 / 10.0), ("z...
Program name
#include <stdio.h> int main(int argc, char **argv) { printf("Executable: %s\n", argv[0]); return 0; }
fn main() { println!("Program: {}", std::env::args().next().unwrap()); }
Program termination
#include <stdlib.h> int main(int argc, char **argv) { ... return 0; } if(problem){ exit(exit_code); }
fn main() { println!("The program is running"); return; println!("This line won't be printed"); }
Proper divisors
#include <stdio.h> #include <stdbool.h> int proper_divisors(const int n, bool print_flag) { int count = 0; for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } } if (print_flag) printf("\n"); ...
trait ProperDivisors { fn proper_divisors(&self) -> Option<Vec<u64>>; } impl ProperDivisors for u64 { fn proper_divisors(&self) -> Option<Vec<u64>> { if self.le(&1) { return None; } let mut divisors: Vec<u64> = Vec::new(); for i in 1..*self { if *self % ...
Quaternion type
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> typedef struct quaternion { double q[4]; } quaternion_t; quaternion_t *quaternion_new(void) { return malloc(sizeof(quaternion_t)); } quaternion_t *quaternion_new_set(double q1, double q2, double q3, double q4) { quate...
use std::fmt::{Display, Error, Formatter}; use std::ops::{Add, Mul, Neg}; #[derive(Clone,Copy,Debug)] struct Quaternion { a: f64, b: f64, c: f64, d: f64 } impl Quaternion { pub fn new(a: f64, b: f64, c: f64, d: f64) -> Quaternion { Quaternion { a: a, b: b, ...
Queue_Definition
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int DATA; typedef struct { DATA *buf; size_t head, tail, alloc; } queue_t, *queue; queue q_new() { queue q = malloc(sizeof(queue_t)); q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); q->head = q->tail = 0; return q; } int empt...
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), sta...
Queue_Usage
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <sys/queue.h> int main() { int i; FIFOList head; TAILQ_INIT(&head); for(i=0; i < 20; i++) { m_enqueue(i, &head); } while( m_dequeue(&i, &head) ) printf("%d\n", i); fprintf(stderr, "FIFO list %s\n", ( m_dequeu...
use std::collections::VecDeque; fn main() { let mut queue = VecDeque::new(); queue.push_back("Hello"); queue.push_back("World"); while let Some(item) = queue.pop_front() { println!("{}", item); } if queue.is_empty() { println!("Yes, it is empty!"); } }
Quickselect algorithm
#include <stdio.h> #include <string.h> int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v,...
fn partition<T: PartialOrd>(a: &mut [T], left: usize, right: usize, pivot: usize) -> usize { a.swap(pivot, right); let mut store_index = left; for i in left..right { if a[i] < a[right] { a.swap(store_index, i); store_index += 1; } } a.swap(right, store_index...
Quine
#include <stdio.h> static char sym[] = "\n\t\\\""; int main(void) { const char *code = "#include <stdio.h>%c%cstatic char sym[] = %c%cn%ct%c%c%c%c%c;%c%cint main(void) {%c%cconst char *code = %c%s%c;%c%cprintf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0...
fn main() { let x = "fn main() {\n let x = "; let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n"; print!("{}{:?}; let y = {:?}; {}", x, x, y, y) }
RIPEMD-160
#ifndef RMDsize #define RMDsize 160 #endif #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #if RMDsize == 128 #include "rmd128.h" #include "rmd128.c" #elif RMDsize == 160 #include "rmd160.h" #include "rmd160.c" #endif
use ripemd160::{Digest, Ripemd160}; fn ripemd160(text: &str) -> String { format!("{:x}", Ripemd160::digest(text.as_bytes())) } fn main() { println!("{}", ripemd160("Rosetta Code")); }
RSA code
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> int main(void) { mpz_t n, d, e, pt, ct; mpz_init(pt); mpz_init(ct); mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10); mpz_init_set_str(e, "65537", 10); mpz_init_set_str(d, "56178431878449531703084...
extern crate num; use num::bigint::BigUint; use num::integer::Integer; use num::traits::{One, Zero}; fn mod_exp(b: &BigUint, e: &BigUint, n: &BigUint) -> Result<BigUint, &'static str> { if n.is_zero() { return Err("modulus is zero"); } if b >= n { return Err("base is >= modulus");...
Random number generator (device)
#include <stdio.h> #include <stdlib.h> #define RANDOM_PATH "/dev/urandom" int main(void) { unsigned char buf[4]; unsigned long v; FILE *fin; if ((fin = fopen(RANDOM_PATH, "r")) == NULL) { fprintf(stderr, "%s: unable to open file\n", RANDOM_PATH); return...
extern crate rand; use rand::{OsRng, Rng}; fn main() { let mut rng = match OsRng::new() { Ok(v) => v, Err(e) => panic!("Failed to obtain OS RNG: {}", e) }; let rand_num: u32 = rng.gen(); println!("{}", rand_num); }
Random numbers
#include <stdlib.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif double drand() { return (rand()+1.0)/(RAND_MAX+1.0); } double random_normal() { return sqrt(-2*log(drand())) * cos(2*M_PI*drand()); } int main() { int i; double rands[1000]; for (i=0; i<1000; i++) rands[i] ...
extern crate rand; use rand::distributions::{Normal, IndependentSample}; fn main() { let mut rands = [0.0; 1000]; let normal = Normal::new(1.0, 0.5); let mut rng = rand::thread_rng(); for num in rands.iter_mut() { *num = normal.ind_sample(&mut rng); } }
Range expansion
#include <stdio.h> #include <stdlib.h> #include <ctype.h> int get_list(const char *, char **); int get_rnge(const char *, char **); void add_number(int x); int add_range(int x, int y); #define skip_space while(isspace(*s)) s++ #define get_number(x, s, e) (x = strtol(s, e, 10), *e != s) int get_list(const char *s,...
use std::str::FromStr; fn range_expand(range : &str) -> Vec<i32> { range.split(',').flat_map(|item| { match i32::from_str(item) { Ok(n) => n..n+1, _ => { let dashpos= match item.rfind("--") { Some(p) => p, ...
Range extraction
#include <stdio.h> #include <stdlib.h> size_t rprint(char *s, int *x, int len) { #define sep (a > s ? "," : "") #define ol (s ? 100 : 0) int i, j; char *a = s; for (i = j = 0; i < len; i = ++j) { for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); if (i + 1 < j) a += snprintf(s?a:s, ol, "%s%d-%d", sep...
use std::ops::Add; struct RangeFinder<'a, T: 'a> { index: usize, length: usize, arr: &'a [T], } impl<'a, T> Iterator for RangeFinder<'a, T> where T: PartialEq + Add<i8, Output=T> + Copy { type Item = (T, Option<T>); fn next(&mut self) -> Option<Self::Item> { if self.index == self.length...
Read a file line by line
#include <conio.h> #include <stdio.h> int main() { int n1, n2, n3; printf( "\n Introduzca el primer n%cmero (entero): ", 163 ); scanf( "%d", &n1 ); printf( "\n Introduzca el segundo n%cmero (entero): ", 163 ); scanf( "%d", &n2 ); printf( "\n Introduzca el tercer n%cmero (entero): ", 16...
use std::io::{BufReader,BufRead}; use std::fs::File; fn main() { let file = File::open("file.txt").unwrap(); for line in BufReader::new(file).lines() { println!("{}", line.unwrap()); } }
Read entire file
#include <stdio.h> #include <stdlib.h> int main() { char *buffer; FILE *fh = fopen("readentirefile.c", "rb"); if ( fh != NULL ) { fseek(fh, 0L, SEEK_END); long s = ftell(fh); rewind(fh); buffer = malloc(s); if ( buffer != NULL ) { fread(buffer, s, 1, fh); fclose(fh); ...
use std::fs::File; use std::io::Read; fn main() { let mut file = File::open("somefile.txt").unwrap(); let mut contents: Vec<u8> = Vec::new(); let result = file.read_to_end(&mut contents).unwrap(); println!("Read {} bytes", result); let filestr = String::from_utf8(contents).unwrap(); ...
Real constants and functions
#include <math.h> M_E; M_PI; sqrt(x); log(x); exp(x); abs(x); fabs(x); floor(x); ceil(x); pow(x,y);
use std::f64::consts::*; fn main() { let mut x = E; x += PI; x = x.sqrt(); x = x.ln(); x = x.ceil(); x = x.exp(); x = x.abs(); x = x.floor(); x = x.powf(x); assert_eq!(x, 4.0); }
Reduced row echelon form
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) {...
fn main() { let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0], vec![2.0, 3.0, -1.0, -11.0], vec![-2.0, 0.0, -3.0, 22.0]]; let mut r_mat_to_red = &mut matrix_to_reduce; let rr_mat_to_red ...
Regular expressions
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <regex.h> #include <string.h> int main() { regex_t preg; regmatch_t substmatch[1]; const char *tp = "string$"; const char *t1 = "this is a matching string"; const char *t2 = "this is not a matching string!"; const char *ss = "isty...
use regex::Regex; fn main() { let s = "I am a string"; if Regex::new("string$").unwrap().is_match(s) { println!("Ends with string."); } println!("{}", Regex::new(" a ").unwrap().replace(s, " another ")); }
Remove duplicate elements
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int ...
use std::collections::HashSet; use std::hash::Hash; fn remove_duplicate_elements_hashing<T: Hash + Eq>(elements: &mut Vec<T>) { let set: HashSet<_> = elements.drain(..).collect(); elements.extend(set.into_iter()); } fn remove_duplicate_elements_sorting<T: Ord>(elements: &mut Vec<T>) { elements.sort_unstab...
Remove lines from a file
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage:...
extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; use std::io::{BufReader,BufRead}; use std::fs::File; const USAGE: &'static str = " Usage: rosetta <start> <count> <file> "; #[derive(Debug, RustcDecodable)] struct Args { arg_start: usize, arg_count: usize, arg_file: String, } fn ma...