Dataset Viewer
Auto-converted to Parquet Duplicate
name
stringlengths
2
74
C
stringlengths
7
6.19k
Rust
stringlengths
19
8.53k
100 doors
#include <stdio.h> int main() { char is_open[100] = { 0 }; int pass, door; for (pass = 0; pass < 100; ++pass) for (door = pass; door < 100; door += pass+1) is_open[door] = !is_open[door]; for (door = 0; door < 100; ++door) printf("door #%d is %s.\n", door+1, (is_open[door]? "open" : "clos...
fn main() { let mut door_open = [false; 100]; for pass in 1..101 { let mut door = pass; while door <= 100 { door_open[door - 1] = !door_open[door - 1]; door += pass; } } for (i, &is_open) in door_open.iter().enumerate() { println!( "Doo...
100 prisoners
#include<stdbool.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #define LIBERTY false #define DEATH true typedef struct{ int cardNum; bool hasBeenOpened; }drawer; drawer *drawerSet; void initialize(int prisoners){ int i,j,card; bool unique; drawerSet = ((drawer*)malloc(prisoners * sizeof(drawer))) -...
extern crate rand; use rand::prelude::*; fn check_random_boxes(prisoner: u8, boxes: &[u8]) -> bool { let checks = { let mut b: Vec<u8> = (1u8..=100u8).collect(); b.shuffle(&mut rand::thread_rng()); b }; checks.into_iter().take(50).any(|check| boxes[check as usize - 1] == prisoner)...
15 puzzle game
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 4 #define M 4 enum Move{UP,DOWN,LEFT,RIGHT};int hR;int hC;int cc[N][M];const int nS=100;int update(enum Move m){const int dx[]={0,0,-1,1};const int dy[]={-1,1,0,0};int i=hR +dy[m];int j=hC+dx[m];if(i>= 0&&i<N&&j>=0&&j<M)...
extern crate rand; use std::collections::HashMap; use std::fmt; use rand::seq::SliceRandom; use rand::Rng; #[derive(Copy, Clone, PartialEq, Debug)] enum Cell { Card(usize), Empty, } #[derive(Eq, PartialEq, Hash, Debug)] enum Direction { Up, Down, Left, Right, } enum Action { Move(Direct...
21 game
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> #if __STDC_VERSION__ >= 199901L || _MSC_VER >= 1800 #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif #define GOAL 21 #define NUMBER_OF_PLAYERS 2 #define MIN_MOVE ...
use rand::Rng; use std::io; #[derive(Clone)] enum PlayerType { Human, Computer, } #[derive(Clone)] struct Player { name: String, wins: u32, level: u32, player_type: PlayerType, } trait Choose { fn choose(&self, game: &Game) -> u8; } impl Player { fn new(name: &str, player_type: P...
4-rings or 4-squares puzzle
#include <stdio.h> #define TRUE 1 #define FALSE 0 int a,b,c,d,e,f,g; int lo,hi,unique,show; int solutions; void bf() { for (f = lo;f <= hi; f++) if ((!unique) || ((f != a) && (f != c) && (f != d) && (f != g) && (f != e))) { b = e + f - c; if ((b >= lo) && (b...
#![feature(inclusive_range_syntax)] fn is_unique(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool { a != b && a != c && a != d && a != e && a != f && a != g && b != c && b != d && b != e && b != f && b != g && c != d && c != e && c != f && c != g && d != e && d != f && d != g && e != f && e...
9 billion names of God the integer
#include <stdio.h> #include <gmp.h> #define N 100000 mpz_t p[N + 1]; void calc(int n) { mpz_init_set_ui(p[n], 0); for (int k = 1; k <= n; k++) { int d = n - k * (3 * k - 1) / 2; if (d < 0) break; if (k&1)mpz_add(p[n], p[n], p[d]); else mpz_sub(p[n], p[n], p[d]); d -= k; if (d < 0) break; if (k&1)m...
extern crate num; use std::cmp; use num::bigint::BigUint; fn cumu(n: usize, cache: &mut Vec<Vec<BigUint>>) { for l in cache.len()..n+1 { let mut r = vec![BigUint::from(0u32)]; for x in 1..l+1 { let prev = r[r.len() - 1].clone(); r.push(prev + cache[l-x][cmp::min(x, l-x)].cl...
99 bottles of beer
const bottle = " bottle" const plural = "s" const ofbeer = " of beer" const wall = " on the wall" const sep = ", " const takedown = "Take one down and pass it around, " const u_no = "No" const l_no = "no" const more = " more bottles of beer" const store = "Go to the store and buy some more, " const dotnl = ".\n" const ...
fn main() { for n in (0..100).rev() { match n { 0 => { println!("No more bottles of beer on the wall, no more bottles of beer."); println!("Go to the store and buy some more, 99 bottles of beer on the wall."); }, 1 => { println!("1 bottle of beer on the wall, 1 bottle of beer."); println!("T...
A+B
#include <stdio.h> int main() { int a, b; scanf("%d%d", &a, &b); printf("%d\n", a + b); return 0; }
use std::io; fn main() { let mut line = String::new(); io::stdin().read_line(&mut line).expect("reading stdin"); let mut i: i64 = 0; for word in line.split_whitespace() { i += word.parse::<i64>().expect("trying to interpret your input as numbers"); } println!("{}", i); }
ABC problem
#include <stdio.h> #include <ctype.h> int can_make_words(char **b, char *word) { int i, ret = 0, c = toupper(*word); #define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; } if (!c) return 1; if (!b[0]) return 0; for (i = 0; b[i] && !ret; i++) { if (b[i][0] != c && b[i][1] != c) continue; SWAP(b[i...
use std::iter::repeat; fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool { let c = word.chars().nth(index).unwrap().to_uppercase().next().unwrap(); for i in 0..blocks.len() { if !used[i] && blocks[i].chars().any(|s| s == c) { used[i] = true; ...
AKS test for primes
#include <stdio.h> #include <stdlib.h> long long c[100]; void coef(int n) { int i, j; if (n < 0 || n > 63) abort(); for (c[i=0] = 1; i < n; c[0] = -c[0], i++) for (c[1 + (j=i)] = 1; j > 0; j--) c[j] = c[j-1] - c[j]; } int is_prime(int n) { int i; coef(n); c[0] += 1, c[i=n] -= 1; while (i-- && !(c[i] ...
fn aks_coefficients(k: usize) -> Vec<i64> { let mut coefficients = vec![0i64; k + 1]; coefficients[0] = 1; for i in 1..(k + 1) { coefficients[i] = -(1..i).fold(coefficients[0], |prev, j|{ let old = coefficients[j]; coefficients[j] = old - prev; old }); ...
Abstract type
#ifndef INTERFACE_ABS #define INTERFACE_ABS typedef struct sAbstractCls *AbsCls; typedef struct sAbstractMethods { int (*method1)(AbsCls c, int a); const char *(*method2)(AbsCls c, int b); void (*method3)(AbsCls c, double d); } *AbstractMethods, sAbsMethods; struct sAbstractCls { Abstr...
trait Shape { fn area(self) -> i32; }
Abundant odd numbers
#include <stdio.h> #include <math.h> unsigned sum_proper_divisors(const unsigned n) { unsigned sum = 1; for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j); return sum; } int main(int argc, char const *argv[]) { unsigned n, c; for (n = 1, c = 0; c < 25; n +...
fn divisors(n: u64) -> Vec<u64> { let mut divs = vec![1]; let mut divs2 = Vec::new(); for i in (2..).take_while(|x| x * x <= n).filter(|x| n % x == 0) { divs.push(i); let j = n / i; if i != j { divs2.push(j); } } divs.extend(divs2.iter().rev()); divs...
Abundant, deficient and perfect number classifications
#include<stdio.h> #define de 0 #define pe 1 #define ab 2 int main(){ int sum = 0, i, j; int try_max = 0; int count_list[3] = {1,0,0}; for(i=2; i <= 20000; i++){ try_max = i/2; sum = 1; for(j=2; j<try_max; j++){ if (i % j) continue; try_max = i/j; sum += j; if (j != try_...
fn main() { let (mut abundant, mut deficient, mut perfect) = (0u32, 1u32, 0u32); for i in 1..20_001 { if let Some(divisors) = i.proper_divisors() { let sum: u64 = divisors.iter().sum(); if sum < i { deficient += 1 } else if sum > i { ...
Accumulator factory
#include <stdio.h> #define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \ static __typeof__(n) _n=n; LOGIC; } #define LOGIC return _n+=i ACCUMULATOR(x,1.0) ACCUMULATOR(y,3) ACCUMULATOR(z,'a') #undef LOGIC int main (void) { printf ("%f\n", x(5)); printf ("%f\n", x(2.3)); printf ("%i\n...
use std::ops::Add; fn foo<Num>(n: Num) -> impl FnMut(Num) -> Num where Num: Add<Output=Num> + Copy + 'static { let mut acc = n; move |i: Num| { acc = acc + i; acc } } fn main() { let mut x = foo(1.); x(5.); foo(3.); println!("{}", x(2.3)); }
Ackermann function
#include <stdio.h> int ackermann(int m, int n) { if (!m) return n + 1; if (!n) return ackermann(m - 1, 1); return ackermann(m - 1, ackermann(m, n - 1)); } int main() { int m, n; for (m = 0; m <= 4; m++) for (n = 0; n < 6 - m; n++) printf(...
fn ack(m: isize, n: isize) -> isize { if m == 0 { n + 1 } else if n == 0 { ack(m - 1, 1) } else { ack(m - 1, ack(m, n - 1)) } } fn main() { let a = ack(3, 4); println!("{}", a); }
Active object
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include <sys/time.h> #include <pthread.h> typedef struct { double (*func)(double); struct timeval start; double v, last_v, last_t; pthread_t id; } integ_t, *integ; void update(integ x) { struct timeval tv; double t, v, (*f)(double); ...
#![feature(mpsc_select)] extern crate num; extern crate schedule_recv; use num::traits::Zero; use num::Float; use schedule_recv::periodic_ms; use std::f64::consts::PI; use std::ops::Mul; use std::sync::mpsc::{self, SendError, Sender}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; pub type Ac...
Almost prime
#include <stdio.h> int kprime(int n, int k) { int p, f = 0; for (p = 2; f < k && p*p <= n; p++) while (0 == n % p) n /= p, f++; return f + (n > 1) == k; } int main(void) { int i, c, k; for (k = 1; k <= 5; k++) { printf("k = %d:", k); for (i = 2, c = 0; c < 10; i++) if (kprime(i, k)) { printf("...
fn is_kprime(n: u32, k: u32) -> bool { let mut primes = 0; let mut f = 2; let mut rem = n; while primes < k && rem > 1{ while (rem % f) == 0 && rem > 1{ rem /= f; primes += 1; } f += 1; } rem == 1 && primes == k } struct KPrimeGen { k: u32, ...
Amb
typedef const char * amb_t; amb_t amb(size_t argc, ...) { amb_t *choices; va_list ap; int i; if(argc) { choices = malloc(argc*sizeof(amb_t)); va_start(ap, argc); i = 0; do { choices[i] = va_arg(ap, amb_t); } while(++i < argc); va_end(ap); i = 0; do { TRY(choices[i]); } while...
use std::ops::Add; struct Amb<'a> { list: Vec<Vec<&'a str>>, } fn main() { let amb = Amb { list: vec![ vec!["the", "that", "a"], vec!["frog", "elephant", "thing"], vec!["walked", "treaded", "grows"], vec!["slowly", "quickly"], ], }; match a...
Amicable pairs
#include <stdio.h> #include <stdlib.h> typedef unsigned int uint; int main(int argc, char **argv) { uint top = atoi(argv[1]); uint *divsum = malloc((top + 1) * sizeof(*divsum)); uint pows[32] = {1, 0}; for (uint i = 0; i <= top; i++) divsum[i] = 1; for (uint p = 2; p+p <= top; p++) { if (divsum[...
fn sum_of_divisors(val: u32) -> u32 { (1..val/2+1).filter(|n| val % n == 0) .fold(0, |sum, n| sum + n) } fn main() { let iter = (1..20_000).map(|i| (i, sum_of_divisors(i))) .filter(|&(i, div_sum)| i > div_sum); for (i, sum1) in iter { if sum_of_divisors(su...
Anagrams
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> char *sortedWord(const char *word, char *wbuf) { char *p1, *p2, *endwrd; char t; int swaps; strcpy(wbuf, word); endwrd = wbuf+strlen(wbuf); do { swaps = 0; p1 = wbuf; p2 = endwrd-1; ...
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead,BufReader}; use std::borrow::ToOwned; extern crate unicode_segmentation; use unicode_segmentation::{UnicodeSegmentation}; fn main () { let file = BufReader::new(File::open("unixdict.txt").unwrap()); let mut map = HashMap::new(); for l...
Anagrams_Deranged anagrams
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h> const char *freq = "zqxjkvbpygfwmucldrhsnioate"; int char_to_idx[128]; struct word { const char *w; struct word *next; }; union node { union node *down[10]; struct word...
use std::cmp::Ordering; use std::collections::HashMap; use std::fs::File; use std::io; use std::io::BufReader; use std::io::BufRead; use std::usize::MAX; pub fn get_words() -> Result<Vec<String>, io::Error> { let mut words = vec!(); let f = File::open("data/unixdict.txt")?; let reader = BufRead...
Angle difference between two bearings
#include<stdlib.h> #include<stdio.h> #include<math.h> void processFile(char* name){ int i,records; double diff,b1,b2; FILE* fp = fopen(name,"r"); fscanf(fp,"%d\n",&records); for(i=0;i<records;i++){ fscanf(fp,"%lf%lf",&b1,&b2); diff = fmod(b2-b1,360.0); printf("\nDifference between b2(%lf) and b1(%l...
pub fn angle_difference(bearing1: f64, bearing2: f64) -> f64 { let diff = (bearing2 - bearing1) % 360.0; if diff < -180.0 { 360.0 + diff } else if diff > 180.0 { -360.0 + diff } else { diff } } #[cfg(test)] mod tests { use super::*; #[test] fn test_angle_diffe...
Animate a pendulum
#include <stdlib.h> #include <math.h> #include <GL/glut.h> #include <GL/gl.h> #include <sys/time.h> #define length 5 #define g 9.8 double alpha, accl, omega = 0, E; struct timeval tv; double elappsed() { struct timeval now; gettimeofday(&now, 0); int ret = (now.tv_sec - tv.tv_sec) * 1000000 + now.tv_usec - tv.tv...
use piston_window::{clear, ellipse, line_from_to, PistonWindow, WindowSettings}; const PI: f64 = std::f64::consts::PI; const WIDTH: u32 = 640; const HEIGHT: u32 = 480; const ANCHOR_X: f64 = WIDTH as f64 / 2. - 12.; const ANCHOR_Y: f64 = HEIGHT as f64 / 4.; const ANCHOR_ELLIPSE: [f64; 4] = [ANCHOR_X - 3., ANCHOR_Y - ...
Animation
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r =...
#[cfg(feature = "gtk")] mod graphical { extern crate gtk; use self::gtk::traits::*; use self::gtk::{Inhibit, Window, WindowType}; use std::ops::Not; use std::sync::{Arc, RwLock}; pub fn create_window() { gtk::init().expect("Failed to initialize GTK"); let window = Window::new(...
Anonymous recursion
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib yo...
fn fib(n: i64) -> Option<i64> { fn actual_fib(n: i64) -> i64 { if n < 2 { n } else { actual_fib(n - 1) + actual_fib(n - 2) } } if n < 0 { None } else { Some(actual_fib(n)) } } fn main() { println!("Fib(-1) = {:?}", fib(-1)); ...
Anti-primes
#include <stdio.h> int countDivisors(int n) { int i, count; if (n < 2) return 1; count = 2; for (i = 2; i <= n/2; ++i) { if (n%i == 0) ++count; } return count; } int main() { int n, d, maxDiv = 0, count = 0; printf("The first 20 anti-primes are:\n"); for (n = 1; count < 20...
fn count_divisors(n: u64) -> usize { if n < 2 { return 1; } 2 + (2..=(n / 2)).filter(|i| n % i == 0).count() } fn main() { println!("The first 20 anti-primes are:"); (1..) .scan(0, |max, n| { let d = count_divisors(n); Some(if d > *max { *max ...
Append a record to the end of a text file
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:...
use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Result; use std::io::Write; use std::path::Path; #[derive(Eq, PartialEq, Debug)] pub struct PasswordRecord { pub account: String, pub password: String, pub uid: u64, pub gid:...
Apply a callback to an array
#ifndef CALLBACK_H #define CALLBACK_H void map(int* array, int len, void(*callback)(int,int)); #endif
fn echo(n: &i32) { println!("{}", n); } fn main() { let a: [i32; 5]; a = [1, 2, 3, 4, 5]; let _: Vec<_> = a.into_iter().map(echo).collect(); }
Apply a digital filter (direct form II transposed)
#include<stdlib.h> #include<string.h> #include<stdio.h> #define MAX_LEN 1000 typedef struct{ float* values; int size; }vector; vector extractVector(char* str){ vector coeff; int i=0,count = 1; char* token; while(str[i]!=00){ if(str[i++]==' ') count++; } coeff.values = (float*)malloc(count*sizeof(flo...
use std::cmp::Ordering; struct IIRFilter<'f>(&'f [f32], &'f [f32]); impl<'f> IIRFilter<'f> { pub fn with_coefficients(a: &'f [f32], b: &'f [f32]) -> IIRFilter<'f> { IIRFilter(a, b) } pub fn apply<I: Iterator<Item = &'f f32> + 'f>( &self, samples: I, ) -> impl Iterator<Ite...
Approximate equality
#include <math.h> #include <stdbool.h> #include <stdio.h> bool approxEquals(double value, double other, double epsilon) { return fabs(value - other) < epsilon; } void test(double a, double b) { double epsilon = 1e-18; printf("%f, %f => %d\n", a, b, approxEquals(a, b, epsilon)); } int main() { test(10...
fn isclose(a: f64, b: f64, epsilon: f64) -> bool { (a - b).abs() <= a.abs().max(b.abs()) * epsilon } fn main() { fn sqrt(x: f64) -> f64 { x.sqrt() } macro_rules! test { ($a: expr, $b: expr) => { let operator = if isclose($a, $b, 1.0e-9) { '≈' } else { '≉' }; println!("{:...
Arbitrary-precision integers (included)
#include <gmp.h> #include <stdio.h> #include <string.h> int main() { mpz_t a; mpz_init_set_ui(a, 5); mpz_pow_ui(a, a, 1 << 18); int len = mpz_sizeinbase(a, 10); printf("GMP says size is: %d\n", len); char *s = mpz_get_str(0, 10, a); printf("size really is %d\n", len = strlen(s)); printf("Digits: %.20s...%...
extern crate num; use num::bigint::BigUint; use num::FromPrimitive; use num::pow::pow; fn main() { let big = BigUint::from_u8(5).unwrap(); let answer_as_string = format!("{}", pow(big,pow(4,pow(3,2)))); let first_twenty: String = answer_as_string.chars().take(20).collect(); let last_twenty_...
Archimedean spiral
#include <jambo.h> Main Set break a=1.5, b=1.5, r=0, origen x=200, origen y=105 total = 0, Let ( total := Mul(20, M_PI) ) Cls Loop for ( t=0, var 't' Is less equal to 'total', Let (t := Add (t, 0.005)) ) #( r = a + b * t ) Set 'origen x, origen y', # ( 200 + (2*r*sin(t)) ) » 'origen x', #(...
#[macro_use(px)] extern crate bmp; use bmp::{Image, Pixel}; use std::f64; fn main() { let width = 600u32; let half_width = (width / 2) as i32; let mut img = Image::new(width, width); let draw_color = px!(255, 128, 128); let a = 1.0_f64; let b = 9.0_f64; let max_angle = 5.0_f64 ...
Arithmetic-geometric mean
#include<math.h> #include<stdio.h> #include<stdlib.h> double agm( double a, double g ) { double iota = 1.0E-16; double a1, g1; if( a*g < 0.0 ) { printf( "arithmetic-geometric mean undefined when x*y<0\n" ); exit(1); } while( fabs(a-g)>iota ) { a1 = (a + g) / 2.0; g1 = sq...
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result)...
Arithmetic_Complex
#include <complex.h> #include <stdio.h> void cprint(double complex c) { printf("%f%+fI", creal(c), cimag(c)); } void complex_operations() { double complex a = 1.0 + 1.0I; double complex b = 3.14159 + 1.2I; double complex c; printf("\na="); cprint(a); printf("\nb="); cprint(b); c = a + b; printf("...
extern crate num; use num::complex::Complex; fn main() { let a = Complex {re:-4.0, im: 5.0}; let b = Complex::new(1.0, 1.0); println!(" a = {}", a); println!(" b = {}", b); println!(" a + b = {}", a + b); println!(" a * b = {}", a * b); println!(" 1 / a = {}", a.inv()); ...
Arithmetic_Integer
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a, b; if (argc < 3) exit(1); b = atoi(argv[--argc]); if (b == 0) exit(2); a = atoi(argv[--argc]); printf("a+b = %d\n", a+b); printf("a-b = %d\n", a-b); printf("a*b = %d\n", a*b); printf("a/b = %d\n", a/b); printf("a%%b =...
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let a = args[1].parse::<i32>().unwrap(); let b = args[2].parse::<i32>().unwrap(); println!("sum: {}", a + b); println!("difference: {}", a - b); println!("product: {}", a * b); println!("integer...
Arithmetic_Rational
#include <stdio.h> #include <stdlib.h> #define FMT "%lld" typedef long long int fr_int_t; typedef struct { fr_int_t num, den; } frac; fr_int_t gcd(fr_int_t m, fr_int_t n) { fr_int_t t; while (n) { t = n; n = m % n; m = t; } return m; } frac frac_new(fr_int_t num, fr_int_t den) { frac a; if (!den) { printf("div...
use std::cmp::Ordering; use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg}; fn gcd(a: i64, b: i64) -> i64 { match b { 0 => a, _ => gcd(b, a % b), } } fn lcm(a: i64, b: i64) -> i64 { a / gcd(a, b) * b } #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord)...
Array concatenation
#include <stdlib.h> #include <stdio.h> #include <string.h> #define ARRAY_CONCAT(TYPE, A, An, B, Bn) \ (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE)); void *array_concat(const void *a, size_t an, const void *b, size_t bn, size_t s) { char *p = malloc(s * (an...
fn main() { let a_vec = vec![1, 2, 3, 4, 5]; let b_vec = vec![6; 5]; let c_vec = concatenate_arrays(&a_vec, &b_vec); println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec); } fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> { let mut concat = x.to_vec(); concat.extend_from_slice(y); ...
Array length
#include <stdio.h> int main() { const char *fruit[2] = { "apples", "oranges" }; int length = sizeof(fruit) / sizeof(fruit[0]); printf("%d\n", length); return 0; }
fn main() { let array = ["foo", "bar", "baz", "biff"]; println!("the array has {} elements", array.len()); }
Arrays
char foo() { char array[5] = {3,6,9,12,15}; return array[2]; }
let a = [1, 2, 3]; let mut m = [1, 2, 3]; let zeroes = [0; 200];
Assertions
#include <assert.h> int main(){ int a; assert(a == 42); return 0; }
let x = 42; assert!(x == 42); assert_eq!(x, 42);
Atomic updates
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <time.h> #include <pthread.h> #define N_BUCKETS 15 pthread_mutex_t bucket_mutex[N_BUCKETS]; int buckets[N_BUCKETS]; pthread_t equalizer; pthread_t randomizer; void transfer_value(int from, int to, int howmuch) { bool swapped ...
extern crate rand; use std::sync::{Arc, Mutex}; use std::thread; use std::cmp; use std::time::Duration; use rand::Rng; use rand::distributions::{IndependentSample, Range}; trait Buckets { fn equalize<R:Rng>(&mut self, rng: &mut R); fn randomize<R:Rng>(&mut self, rng: &mut R); fn print_state(&self); } im...
Attractive numbers
#include <stdio.h> #define TRUE 1 #define FALSE 0 #define MAX 120 typedef int bool; bool is_prime(int n) { int d = 5; if (n < 2) return FALSE; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; while (d *d <= n) { if (!(n % d)) return FALSE; d += 2; if (!(n % d)) re...
use primal::Primes; const MAX: u64 = 120; fn extract_prime_factor(num: u64) -> Option<(u64, u64)> { let mut i = 0; if primal::is_prime(num) { None } else { loop { let prime = Primes::all().nth(i).unwrap() as u64; if num % prime == 0 { return Some((...
Average loop length
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, ...
extern crate rand; use rand::{ThreadRng, thread_rng}; use rand::distributions::{IndependentSample, Range}; use std::collections::HashSet; use std::env; use std::process; fn help() { println!("usage: average_loop_length <max_N> <trials>"); } fn main() { let args: Vec<String> = env::args().collect(); let m...
Averages_Arithmetic mean
#include <stdio.h> double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; } int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%g"...
fn sum(arr: &[f64]) -> f64 { arr.iter().fold(0.0, |p,&q| p + q) } fn mean(arr: &[f64]) -> f64 { sum(arr) / arr.len() as f64 } fn main() { let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0]; println!("mean of {:?}: {:?}", v, mean(v)); let w = &[]; println!("mean of {:?}: {:?}", w, mean(w));...
Averages_Mean angle
#include<math.h> #include<stdio.h> double meanAngle (double *angles, int size) { double y_part = 0, x_part = 0; int i; for (i = 0; i < size; i++) { x_part += cos (angles[i] * M_PI / 180); y_part += sin (angles[i] * M_PI / 180); } return atan2 (y_part / size, x_part / size) * 180 / M_PI; }...
use std::f64; fn mean_angle(angles: &[f64]) -> f64 { let length: f64 = angles.len() as f64; let cos_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().cos()) / length; let sin_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().sin()) / length; (sin_mean).atan2(cos_mean)....
Averages_Mean time of day
#include<stdlib.h> #include<math.h> #include<stdio.h> typedef struct { int hour, minute, second; } digitime; double timeToDegrees (digitime time) { return (360 * time.hour / 24.0 + 360 * time.minute / (24 * 60.0) + 360 * time.second / (24 * 3600.0)); } digitime timeFromDegrees (double angle) { digiti...
use std::f64::consts::PI; #[derive(Debug, PartialEq, Eq)] struct Time { h: u8, m: u8, s: u8, } impl Time { fn from_radians(mut rads: f64) -> Time { rads %= 2.0 * PI; if rads < 0.0 { rads += 2.0 * PI } Time { h: (rads * 12.0 / PI) as u8, ...
Averages_Median
#include <stdio.h> #include <stdlib.h> typedef struct floatList { float *list; int size; } *FloatList; int floatcmp( const void *a, const void *b) { if (*(const float *)a < *(const float *)b) return -1; else return *(const float *)a > *(const float *)b; } float median( FloatList fl ) { qsort( f...
fn median(mut xs: Vec<f64>) -> f64 { xs.sort_by(|x,y| x.partial_cmp(y).unwrap() ); let n = xs.len(); if n % 2 == 0 { (xs[n/2] + xs[n/2 - 1]) / 2.0 } else { xs[n/2] } } fn main() { let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.]; println!("{:?}", median(nums)) }
Averages_Mode
#include <stdio.h> #include <stdlib.h> typedef struct { double v; int c; } vcount; int cmp_dbl(const void *a, const void *b) { double x = *(const double*)a - *(const double*)b; return x < 0 ? -1 : x > 0; } int vc_cmp(const void *a, const void *b) { return ((const vcount*)b)->c - ((const vcount*)a)->c; } int get_...
use std::collections::HashMap; fn main() { let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]); let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]); println!("Mode of vec1 is: {:?}", mode_vec1); println!("Mode of vec2 is: {:?}", mode_vec2); assert!( mode_vec1 == [6], "Error in mode calculation...
Averages_Pythagorean means
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char* argv[]) { int i, count=0; double f, sum=0.0, prod=1.0, resum=0.0; for (i=1; i<argc; ++i) { f = atof(argv[i]); count++; sum += f; prod *= f; resum += (1.0/f); } printf("Arithmetic mean = %f\n",sum/count...
fn main() { let mut sum = 0.0; let mut prod = 1; let mut recsum = 0.0; for i in 1..11{ sum += i as f32; prod *= i; recsum += 1.0/(i as f32); } let avg = sum/10.0; let gmean = (prod as f32).powf(0.1); let hmean = 10.0/recsum; println!("Average: {}, Geometric m...
Averages_Root mean square
#include <stdio.h> #include <math.h> double rms(double *v, int n) { int i; double sum = 0.0; for(i = 0; i < n; i++) sum += v[i] * v[i]; return sqrt(sum / n); } int main(void) { double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}; printf("%f\n", rms(v, sizeof(v)/sizeof(double))); return 0; }
fn root_mean_square(vec: Vec<i32>) -> f32 { let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2)); return ((sum_squares as f32)/(vec.len() as f32)).sqrt(); } fn main() { let vec = (1..11).collect(); println!("The root mean square is: {}", root_mean_square(vec)); }
Averages_Simple moving average
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> typedef struct sma_obj { double sma; double sum; int period; double *values; int lv; } sma_obj_t; typedef union sma_result { sma_obj_t *handle; double sma; double *values; } sma_result_t; enum Action { SMA_NEW, SMA_FREE, SMA_VALUES, SMA_ADD, ...
struct SimpleMovingAverage { period: usize, numbers: Vec<usize> } impl SimpleMovingAverage { fn new(p: usize) -> SimpleMovingAverage { SimpleMovingAverage { period: p, numbers: Vec::new() } } fn add_number(&mut self, number: usize) -> f64 { self.numb...
Babbage problem
#include <stdio.h> #include <stdlib.h> #include <limits.h> int main() { int current = 0, square; while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) { current++; } if (square>+INT_MAX) printf("Condition not satisfied before INT_MAX reached."); else ...
fn main() { let mut current = 0; while (current * current) % 1_000_000 != 269_696 { current += 1; } println!( "The smallest number whose square ends in 269696 is {}", current ); }
Balanced brackets
#include<stdio.h> #include<stdlib.h> #include<string.h> int isBal(const char*s,int l){ signed c=0; while(l--) if(s[l]==']') ++c; else if(s[l]=='[') if(--c<0) break; return !c; } void shuffle(char*s,int h){ int x,t,i=h; while(i--){ t=s[x=rand()%h]; s[x]=s[i]; s[i]=t; } } void genSeq(char*...
extern crate rand; trait Balanced { fn is_balanced(&self) -> bool; } impl<'a> Balanced for str { fn is_balanced(&self) -> bool { let mut count = 0; for bracket in self.chars() { let change = match bracket { '[' => 1, ']' => -1, ...
Balanced ternary
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char...
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {...
Barnsley fern
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<time.h> void barnsleyFern(int windowWidth, unsigned long iter){ double x0=0,y0=0,x1,y1; int diceThrow; time_t t; srand((unsigned)time(&t)); while(iter>0){ diceThrow = rand()%100; if(diceThrow==0){ x1 = 0; y1 = 0.16*y0; } el...
extern crate rand; extern crate raster; use rand::Rng; fn main() { let max_iterations = 200_000u32; let height = 640i32; let width = 640i32; let mut rng = rand::thread_rng(); let mut image = raster::Image::blank(width, height); raster::editor::fill(&mut image, raster::Color::white()).unwrap()...
Base64 decode data
#include <stdio.h> #include <stdlib.h> typedef unsigned char ubyte; const ubyte BASE64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int findIndex(const ubyte val) { if ('A' <= val && val <= 'Z') { return val - 'A'; } if ('a' <= val && val <= 'z') { return val - '...
use std::str; const INPUT: &str = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"; const UPPERCASE_OFFSET: i8 = -65; const LOWERCASE_OFFSET: i8 = 26 - 97; const NUM_OFFSET: i8 = 52 - 48; fn main() { println!("Input: {}", INPUT); let resul...
Bell numbers
#include <stdio.h> #include <stdlib.h> size_t bellIndex(int row, int col) { return row * (row - 1) / 2 + col; } int getBell(int *bellTri, int row, int col) { size_t index = bellIndex(row, col); return bellTri[index]; } void setBell(int *bellTri, int row, int col, int value) { size_t index = bellInde...
use num::BigUint; fn main() { let bt = bell_triangle(51); for i in 1..=15 { println!("{}: {}", i, bt[i][0]); } println!("50: {}", bt[50][0]) } fn bell_triangle(n: usize) -> Vec<Vec<BigUint>> { let mut tri: Vec<Vec<BigUint>> = Vec::with_capacity(n); for i in 0..n { le...
Bernoulli numbers
#include <stdlib.h> #include <gmp.h> #define mpq_for(buf, op, n)\ do {\ size_t i;\ for (i = 0; i < (n); ++i)\ mpq_##op(buf[i]);\ } while (0) void bernoulli(mpq_t rop, unsigned int n) { unsigned int m, j; mpq_t *a = malloc(sizeof(mpq_t) * (n + 1)); mpq_for(a, init, n + 1...
#![feature(test)] extern crate num; extern crate test; use num::bigint::{BigInt, ToBigInt}; use num::rational::{BigRational}; use std::cmp::max; use std::env; use std::ops::{Mul, Sub}; use std::process; struct Bn { value: BigRational, index: i32 } struct Context { bigone_const: BigInt, a: Vec<Bi...
Best shuffle
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <limits.h> #define DEBUG void best_shuffle(const char* txt, char* result) { const size_t len = strlen(txt); if (len == 0) return; #ifdef DEBUG assert(len == strlen(result)); #endif size_t counts...
extern crate permutohedron; extern crate rand; use std::cmp::{min, Ordering}; use std::env; use rand::{thread_rng, Rng}; use std::str; const WORDS: &'static [&'static str] = &["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"]; #[derive(Eq)] struct Solution { original: String, shuffled: String, score:...
Bin given limits
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { ...
fn make_bins(limits: &Vec<usize>, data: &Vec<usize>) -> Vec<Vec<usize>> { let mut bins: Vec<Vec<usize>> = Vec::with_capacity(limits.len() + 1); for _ in 0..=limits.len() {bins.push(Vec::new());} limits.iter().enumerate().for_each(|(idx, limit)| { data.iter().for_each(|elem| { if id...
Binary digits
#define _CRT_SECURE_NO_WARNINGS #define _CRT_NONSTDC_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> char* bin2str(unsigned value, char* buffer) { const unsigned N_DIGITS = sizeof(unsigned) * 8; unsigned mask = 1 << (N_DIGITS - 1); char* ptr = buffer; f...
fn main() { for i in 0..8 { println!("{:b}", i) } }
Binary search
#include <stdio.h> int bsearch (int *a, int n, int x) { int i = 0, j = n - 1; while (i <= j) { int k = i + ((j - i) / 2); if (a[k] == x) { return k; } else if (a[k] < x) { i = k + 1; } else { j = k - 1; } } retu...
fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> { let mut lower = 0 as usize; let mut upper = v.len() - 1; while upper >= lower { let mid = (upper + lower) / 2; if v[mid] == searchvalue { return Some(searchvalue); } else if searchvalue < v[mid] { ...
Binary strings
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct str_t { size_t len, alloc; unsigned char *s; } bstr_t, *bstr; #define str_len(s) ((s)->len) bstr str_new(size_t len) { bstr s = malloc(sizeof(bstr_t)); if (len < 8) len = 8; s->alloc = len; s->s = malloc(len); s->len = 0; return s; } v...
use std::str; fn main() { let string = String::from("Hello world!"); println!("{}", string); assert_eq!(string, "Hello world!", "Incorrect string text"); let mut assigned_str = String::new(); assert_eq!(assigned_str, "", "Incorrect string creation"); assigned_str += "Text has been as...
Bitcoin_address validation
#include <stdio.h> #include <string.h> #include <openssl/sha.h> const char *coin_err; #define bail(s) { coin_err = s; return 0; } int unbase58(const char *s, unsigned char *out) { static const char *tmpl = "123456789" "ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz"; int i, j, c; const char *p; memset(...
extern crate crypto; use crypto::digest::Digest; use crypto::sha2::Sha256; const DIGITS58: [char; 58] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'...
Bitmap
#ifndef _IMGLIB_0 #define _IMGLIB_0 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <string.h> #include <math.h> #include <sys/queue.h> typedef unsigned char color_component; typedef color_component pixel[3]; typedef struct { unsigned int width; unsigned int height; pixel * buf; } i...
#[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Rgb { pub r: u8, pub g: u8, pub b: u8, } impl Rgb { pub fn new(r: u8, g: u8, b: u8) -> Self { Rgb { r, g, b } } pub const BLACK: Rgb = Rgb { r: 0, g: 0, b: 0 }; pub const RED: Rgb = Rgb { r: 255, g: 0, b: 0 }; pub const GR...
Bitmap_Bresenham's line algorithm
void line(int x0, int y0, int x1, int y1) { int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1; int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1; int err = (dx>dy ? dx : -dy)/2, e2; for(;;){ setPixel(x0,y0); if (x0==x1 && y0==y1) break; e2 = err; if (e2 >-dx) { err -= dy; x0 += sx; } if (e2 < dy) { err += ...
struct Point { x: i32, y: i32 } fn main() { let mut points: Vec<Point> = Vec::new(); points.append(&mut get_coordinates(1, 20, 20, 28)); points.append(&mut get_coordinates(20, 28, 69, 0)); draw_line(points, 70, 30); } fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<Point> { l...
Bitmap_Flood fill
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #define MAXSIZE 2048 #define BYTE unsigned char static int width, height; static BYTE bitmap[MAXSIZE][MAXSIZE]; static BYTE oldColor; static BYTE newColor; void floodFill(int i, int j) { if ( 0 <= i && i < height && 0 <= j && j < ...
use std::fs::File; use std::io::{BufReader, BufRead, Write}; fn read_image(filename: String) -> Vec<Vec<(u8,u8,u8)>> { let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let mut lines = reader.lines(); let _ = lines.next().unwrap(); let _ = lines.next().unwrap(); ...
Bitmap_Read a PPM file
image get_ppm(FILE *pf);
parser.rs: use super::{Color, ImageFormat}; use std::str::from_utf8; use std::str::FromStr; pub fn parse_version(input: &[u8]) -> nom::IResult<&[u8], ImageFormat> { use nom::branch::alt; use nom::bytes::complete::tag; use nom::character::complete::line_ending; use nom::combinator::map; use nom::seq...
Bitmap_Write a PPM file
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0]...
use std::path::Path; use std::io::Write; use std::fs::File; pub struct RGB { r: u8, g: u8, b: u8, } pub struct PPM { height: u32, width: u32, data: Vec<u8>, } impl PPM { pub fn new(height: u32, width: u32) -> PPM { let size = 3 * height * width; let buffer = vec![0; size a...
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
6