name stringlengths 2 74 | C stringlengths 7 6.19k | Rust stringlengths 19 8.53k |
|---|---|---|
Fork | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <err.h>
int main()
{
pid_t pid;
if (!(pid = fork())) {
usleep(10000);
printf("\tchild process: done\n");
} else if (pid < 0) {
err(1, "fork error");
} else {
printf("waiting for child %d...\n", (int)pid);
printf("c... | use nix::unistd::{fork, ForkResult};
use std::process::id;
fn main() {
match fork() {
Ok(ForkResult::Parent { child, .. }) => {
println!(
"This is the original process(pid: {}). New child has pid: {}",
id(),
child
);
}
... |
Formatted numeric output | #include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 0;
}
| fn main() {
let x = 7.125;
println!("{:9}", x);
println!("{:09}", x);
println!("{:9}", -x);
println!("{:09}", -x);
}
|
Forward difference | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
unsigned int i, j;
double* y;
if (order >= len) return 0;
y = malloc(sizeof(double) * len);
if (!order) {
memcpy(y, x, sizeof(double) * len);
return y;
}
for (j = 0; j < orde... | fn forward_difference(input_seq: Vec<i32>, order: u32) -> Vec<i32> {
match order {
0 => input_seq,
1 => {
let input_seq_iter = input_seq.into_iter();
let clone_of_input_seq_iter = input_seq_iter.clone();
input_seq_iter.zip(clone_of_input_seq_iter.skip(1)).map(|(cu... |
Four bit adder | #include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
... |
fn half_adder(a: usize, b: usize) -> (usize, usize) {
return (a ^ b, a & b);
}
fn full_adder(a: usize, b: usize, c_in: usize) -> (usize, usize) {
let (s0, c0) = half_adder(a, b);
let (s1, c1) = half_adder(s0, c_in);
return (s1, c0 | c1);
}
fn four_bit_adder (
a: (usize, usize, usize, usiz... |
Function composition | #include <stdlib.h>
typedef struct double_to_double {
double (*fn)(struct double_to_double *, double);
} double_to_double;
#define CALL(f, x) f->fn(f, x)
typedef struct compose_functor {
double (*fn)(struct compose_functor *, double);
double_to_double *f;
double_to_double *g;
} compose_functor;
double co... | fn compose<'a,F,G,T,U,V>(f: F, g: G) -> Box<Fn(T) -> V + 'a>
where F: Fn(U) -> V + 'a,
G: Fn(T) -> U + 'a,
{
Box::new(move |x| f(g(x)))
}
|
Fusc sequence | #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
... | fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> {
let mut sequence = vec![0, 1];
let mut n = 0;
std::iter::from_fn(move || {
if n > 1 {
sequence.push(match n % 2 {
0 => sequence[n / 2],
_ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2],
... |
Gaussian elimination | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))
void swap_row(double *a, double *b, int r1, int r2, int n)
{
double tmp, *p1, *p2;
int i;
if (r1 == r2) return;
for (i = 0; i < n; i++) {
p1 = mat_elem(a, r1, i, n);
p2 = mat_elem(a, r2, i, n);
tmp... |
const SIZE: usize = 6;
pub fn eliminate(mut system: [[f32; SIZE+1]; SIZE]) -> Option<Vec<f32>> {
for i in 0..SIZE-1 {
for j in i..SIZE-1 {
if system[i][i] == 0f32 {
continue;
} else {
let factor = system[j +... |
General FizzBuzz | #include <stdio.h>
#include <stdlib.h>
struct replace_info {
int n;
char *text;
};
int compare(const void *a, const void *b)
{
struct replace_info *x = (struct replace_info *) a;
struct replace_info *y = (struct replace_info *) b;
return x->n - y->n;
}
void generic_fizz_buzz(int max, struct repla... | use std::io;
use std::io::BufRead;
fn parse_entry(l: &str) -> (i32, String) {
let params: Vec<&str> = l.split(' ').collect();
let divisor = params[0].parse::<i32>().unwrap();
let word = params[1].to_string();
(divisor, word)
}
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().... |
Generate lower case ASCII alphabet | #include <stdlib.h>
#define N 26
int main() {
unsigned char lower[N];
for (size_t i = 0; i < N; i++) {
lower[i] = i + 'a';
}
return EXIT_SUCCESS;
}
| fn main() {
let ascii_iter = (0..26)
.map(|x| (x + b'a') as char);
println!("{:?}", ascii_iter.collect::<Vec<char>>());
}
|
Generator_Exponential | #include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <libco.h>
struct gen64 {
cothread_t giver;
cothread_t taker;
int64_t given;
void (*free)(struct gen64 *);
void *garbage;
};
inline void
yield64(struct gen64 *gen, int64_t value)
{
gen->given = value;
co_switch(gen->taker);
}
inl... | use std::cmp::Ordering;
use std::iter::Peekable;
fn powers(m: u32) -> impl Iterator<Item = u64> {
(0u64..).map(move |x| x.pow(m))
}
fn noncubic_squares() -> impl Iterator<Item = u64> {
NoncubicSquares {
squares: powers(2).peekable(),
cubes: powers(3).peekable(),
}
}
struct NoncubicSquares... |
Generic swap | void swap(void *va, void *vb, size_t s)
{
char t, *a = (char*)va, *b = (char*)vb;
while(s--)
t = a[s], a[s] = b[s], b[s] = t;
}
| fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
std::mem::swap(var1, var2)
}
|
Get system command output | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) return 1;
FILE *fd;
fd = popen(argv[1], "r");
if (!fd) return 1;
char buffer[256];
size_t chread;
size_t comalloc = 256;
size_t comlen = 0;
char *comout = malloc(... | use std::process::Command;
use std::io::{Write, self};
fn main() {
let output = Command::new("/bin/cat")
.arg("/etc/fstab")
.output()
.expect("failed to execute process");
io::stdout().write(&output.stdout);
}
|
Globally replace text in several files | #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <string.h>
char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
ptrdiff_t i;
char *start = bu... |
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Write;
fn main() {
let out_fd = OpenOptions::new()
.write(true)
.create(true)
.open("resources/output.txt");
let write_line = |line: &str| match ... |
Greatest common divisor | int
gcd_iter(int u, int v) {
if (u < 0) u = -u;
if (v < 0) v = -v;
if (v) while ((u %= v) && (v %= u));
return (u + v);
}
| extern crate num;
use num::integer::gcd;
|
Greatest element of a list | #include <assert.h>
float max(unsigned int count, float values[]) {
assert(count > 0);
size_t idx;
float themax = values[0];
for(idx = 1; idx < count; ++idx) {
themax = values[idx] > themax ? values[idx] : themax;
}
return themax;
}
| fn main() {
let nums = [1,2,39,34,20];
println!("{:?}", nums.iter().max());
println!("{}", nums.iter().max().unwrap());
}
|
Greatest subsequential sum | #include "stdio.h"
typedef struct Range {
int start, end, sum;
} Range;
Range maxSubseq(const int sequence[], const int len) {
int maxSum = 0, thisSum = 0, i = 0;
int start = 0, end = -1, j;
for (j = 0; j < len; j++) {
thisSum += sequence[j];
if (thisSum < 0) {
i = j + 1;
... | fn main() {
let nums = [1,2,39,34,20, -20, -16, 35, 0];
let mut max = 0;
let mut boundaries = 0..0;
for length in 0..nums.len() {
for start in 0..nums.len()-length {
let sum = (&nums[start..start+length]).iter()
.fold(0, |sum, elem| sum+elem);
if sum > m... |
Guess the number | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(void)
{
int n;
int g;
char c;
srand(time(NULL));
n = 1 + (rand() % 10);
puts("I'm thinking of a number between 1 and 10.");
puts("Try to guess it:");
while (1) {
if (scanf("%d", &g) != 1) {
scanf("%c", &c)... | extern crate rand;
fn main() {
println!("Type in an integer between 1 and 10 and press enter.");
let n = rand::random::<u32>() % 10 + 1;
loop {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let option: Result<u32,_> = line.trim().parse();
mat... |
Guess the number_With feedback | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define lower_limit 0
#define upper_limit 100
int main(){
int number, guess;
srand( time( 0 ) );
number = lower_limit + rand() % (upper_limit - lower_limit + 1);
printf( "Guess the number between %d and %d: ", lower_limit, upper_limit );
while( sca... | use rand::Rng;
use std::cmp::Ordering;
use std::io;
const LOWEST: u32 = 1;
const HIGHEST: u32 = 100;
fn main() {
let secret_number = rand::thread_rng().gen_range(1..101);
println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);
loop {
println!("Please input your... |
Guess the number_With feedback (player) | #include <stdio.h>
int main(){
int bounds[ 2 ] = {1, 100};
char input[ 2 ] = " ";
int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );
do{
switch( input[ 0 ] ){
case 'H':
bounds[ 1 ] = choice;
break;
... | use std::io::stdin;
const MIN: isize = 1;
const MAX: isize = 100;
fn main() {
loop {
let mut min = MIN;
let mut max = MAX;
let mut num_guesses = 1;
println!("Please think of a number between {} and {}", min, max);
loop {
let guess = (min + max) / 2;
... |
HTTP | #include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
int
main(void)
{
CURL *curl;
char buffer[CURL_ERROR_SIZE];
if ((curl = curl_easy_init()) != NULL) {
curl_easy_setopt(curl, CURLOPT_URL, "http:
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
... |
extern crate hyper;
use std::io::Read;
use hyper::client::Client;
fn main() {
let client = Client::new();
let mut resp = client.get("http:
let mut body = String::new();
resp.read_to_string(&mut body).unwrap();
println!("{}", body);
}
|
HTTPS | #include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
CURL *curl;
char buffer[CURL_ERROR_SIZE];
int main(void) {
if ((curl = curl_easy_init()) != NULL) {
curl_easy_setopt(curl, CURLOPT_URL, "https:
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_ERRO... | extern crate reqwest;
fn main() {
let response = match reqwest::blocking::get("https:
Ok(response) => response,
Err(e) => panic!("error encountered while making request: {:?}", e),
};
println!("{}", response.text().unwrap());
}
|
Hailstone sequence | #include <stdio.h>
#include <stdlib.h>
int hailstone(int n, int *arry)
{
int hs = 1;
while (n!=1) {
hs++;
if (arry) *arry++ = n;
n = (n&1) ? (3*n+1) : (n/2);
}
if (arry) *arry++ = n;
return hs;
}
int main()
{
int j, hmax = 0;
int jatmax, n;
int *arry;
for ... | fn hailstone(start : u32) -> Vec<u32> {
let mut res = Vec::new();
let mut next = start;
res.push(start);
while next != 1 {
next = if next % 2 == 0 { next/2 } else { 3*next+1 };
res.push(next);
}
res
}
fn main() {
let test_num = 27;
let test_hailseq = hailstone(test_... |
Halt and catch fire | int main(){int a=0, b=0, c=a/b;}
| fn main(){panic!("");}
|
Hamming numbers | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ham;
size_t alloc = 0, n = 1;
ham *q = 0;
void qpush(ham h)
{
int i, j;
if (alloc <= n) {
alloc = alloc ? alloc * 2 : 16;
q = realloc(q, sizeof(ham) * alloc);
}
for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j);
q[i] = h;
}
ham qpop(... | extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u... |
Handle a signal | #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
... | #[cfg(unix)]
fn main() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use libc::{sighandler_t, SIGINT};
let duration = Duration::from_secs(1) / 2;
static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);
unsafe {
... |
Happy numbers | #include <stdio.h>
#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};
int happy(int n)
{
int sum = 0, x, nn;
if (n < CACHE) {
if (buf[n]) return 2 - buf[n];
buf[n] = h_no;
}
for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;
x = happy(sum);
if (n < CACHE) b... | #![feature(core)]
fn sumsqd(mut n: i32) -> i32 {
let mut sq = 0;
while n > 0 {
let d = n % 10;
sq += d*d;
n /= 10
}
sq
}
use std::num::Int;
fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T {
let mut t = a;
let mut h = f(a);
while t != h {
t = f(t);
h = f(... |
Harshad or Niven series | #include <stdio.h>
static int digsum(int n)
{
int sum = 0;
do { sum += n % 10; } while (n /= 10);
return sum;
}
int main(void)
{
int n, done, found;
for (n = 1, done = found = 0; !done; ++n) {
if (n % digsum(n) == 0) {
if (found++ < 20) printf("%d ", n);
if (n > 10... | fn is_harshad (n : u32) -> bool {
let sum_digits = n.to_string()
.chars()
.map(|c| c.to_digit(10).unwrap())
.fold(0, |a, b| a+b);
n % sum_digits == 0
}
fn main() {
for i in (1u32..).filter(|num| is_harshad(*num)).take(20) {
println!(... |
Hash from two arrays | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KeyType const char *
#define ValType int
#define HASH_SIZE 4096
unsigned strhashkey( const char * key, int max)
{
unsigned h=0;
unsigned hl, hr;
while(*key) {
h += *key;
hl= 0x5C5 ^ (h&0xfff00000 )>>18;
hr =(h&0x... | use std::collections::HashMap;
fn main() {
let keys = ["a", "b", "c"];
let values = [1, 2, 3];
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
println!("{:?}", hash);
}
|
Haversine formula | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define R 6371
#define TO_RAD (3.1415926536 / 180)
double dist(double th1, double ph1, double th2, double ph2)
{
double dx, dy, dz;
ph1 -= ph2;
ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;
dz = sin(th1) - sin(th2);
dx = cos(ph1) * cos(th1) - cos(th2);
dy ... | struct Point {
lat: f64,
lon: f64,
}
fn haversine(origin: Point, destination: Point) -> f64 {
const R: f64 = 6372.8;
let lat1 = origin.lat.to_radians();
let lat2 = destination.lat.to_radians();
let d_lat = lat2 - lat1;
let d_lon = (destination.lon - origin.lon).to_radians();
let a = (... |
Hello world_Graphical | #include <gtk/gtk.h>
int main (int argc, char **argv) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Goodbye, World");
g_signal_connect (G_OBJECT (window), "delete-event", gtk_main_quit, NULL);
gtk_widget_show_all (wi... |
extern crate gtk;
use gtk::traits::*;
use gtk::{Window, WindowType, WindowPosition};
use gtk::signal::Inhibit;
fn main() {
gtk::init().unwrap();
let window = Window::new(WindowType::Toplevel).unwrap();
window.set_title("Goodbye, World!");
window.set_border_width(10);
window.set_window_position(Wi... |
Hello world_Newline omission | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
(void) printf("Goodbye, World!");
return EXIT_SUCCESS;
}
| fn main () {
print!("Goodbye, World!");
}
|
Hello world_Standard error | #include <stdio.h>
int main()
{
fprintf(stderr, "Goodbye, ");
fputs("World!\n", stderr);
return 0;
}
| fn main() {
eprintln!("Hello, {}!", "world");
}
|
Hello world_Text | const hello = "Hello world!\n"
print(hello)
| fn main() {
print!("Hello world!");
}
|
Hello world_Web server | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Bye-b... | use std::net::{Shutdown, TcpListener};
use std::thread;
use std::io::Write;
const RESPONSE: &'static [u8] = b"HTTP/1.1 200 OK\r
Content-Type: text/html; charset=UTF-8\r\n\r
<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>
<style>body { background-color: #111 }
h1 { font-size:4cm; text-align: center; colo... |
Heronian triangles | #include<stdlib.h>
#include<stdio.h>
#include<math.h>
typedef struct{
int a,b,c;
int perimeter;
double area;
}triangle;
typedef struct elem{
triangle t;
struct elem* next;
}cell;
typedef cell* list;
void addAndOrderList(list *a,triangle t){
list iter,temp;
int flag = 0;
if(*a==NULL){
*a = (list)malloc(s... | use num_integer::Integer;
use std::{f64, usize};
const MAXSIZE: usize = 200;
#[derive(Debug)]
struct HerionanTriangle {
a: usize,
b: usize,
c: usize,
area: usize,
perimeter: usize,
}
fn get_area(a: &usize, b: &usize, c: &usize) -> f64 {
let s = (a + b + c) as f64 / 2.;
(s * (s - *a as f64... |
Higher-order functions | void myFuncSimple( void (*funcParameter)(void) )
{
(*funcParameter)();
funcParameter();
}
| fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 {
f(10)
}
fn square(n: u64) -> u64 {
n*n
}
fn main() {
println!("{}", execute_with_10(|n| n*n ));
println!("{}", execute_with_10(square));
}
|
Hilbert curve | #include <stdio.h>
#define N 32
#define K 3
#define MAX N * K
typedef struct { int x; int y; } point;
void rot(int n, point *p, int rx, int ry) {
int t;
if (!ry) {
if (rx == 1) {
p->x = n - 1 - p->x;
p->y = n - 1 - p->y;
}
t = p->x;
p->x = p->y;
... |
use svg::node::element::path::Data;
use svg::node::element::Path;
struct HilbertCurve {
current_x: f64,
current_y: f64,
current_angle: i32,
line_length: f64,
}
impl HilbertCurve {
fn new(x: f64, y: f64, length: f64, angle: i32) -> HilbertCurve {
HilbertCurve {
current_x: x,
... |
Hofstadter Figure-Figure sequences | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef struct {
size_t len, alloc;
xint *buf;
} xarray;
xarray rs, ss;
void setsize(xarray *a, size_t size)
{
size_t n = a->alloc;
if (!n) n = 1;
while (n < size) n <<= 1;
if (a->alloc < n) {
a->buf = realloc(a->buf, sizeof(xint) * n... | use std::collections::HashMap;
struct Hffs {
sequence_r: HashMap<usize, usize>,
sequence_s: HashMap<usize, usize>,
}
impl Hffs {
fn new() -> Hffs {
Hffs {
sequence_r: HashMap::new(),
sequence_s: HashMap::new(),
}
}
fn ffr(&mut self, n: usize) -> usize {
... |
Hofstadter-Conway $10,000 sequence | #include <stdio.h>
#include <stdlib.h>
int a_list[1<<20 + 1];
int doSqnc( int m)
{
int max_df = 0;
int p2_max = 2;
int v, n;
int k1 = 2;
int lg2 = 1;
double amax = 0;
a_list[0] = -50000;
a_list[1] = a_list[2] = 1;
v = a_list[2];
for (n=3; n <= m; n++) {
v = a_list[n] ... | struct HofstadterConway {
current: usize,
sequence: Vec<usize>,
}
impl HofstadterConway {
fn new() -> HofstadterConway {
HofstadterConway {
current: 0,
sequence: vec![1, 1],
}
}
}
impl Default for HofstadterConway {
fn default() -> Self {
Self::... |
Holidays related to Easter | #include <stdio.h>
typedef int year_t, month_t, week_t, day_t;
typedef struct{
year_t year;
month_t month; day_t month_day; day_t week_day; } date_t;
const char *mon_fmt[] = {0, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
const char *wee... | use std::ops::Add;
use chrono::{prelude::*, Duration};
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_wrap)]
fn get_easter_day(year: u32) -> chrono::NaiveDate {
let k = (f64::from(year) / 100.).floor();
let d = (19 * (year % 19)
+ ((15 - ((13.... |
Horizontal sundial calculations | #include <stdio.h>
#include <math.h>
#define PICKVALUE(TXT, VM) do { \
printf("%s: ", TXT); \
scanf("%lf", &VM); \
} while(0);
#if !defined(M_PI)
#define M_PI 3.14159265358979323846
#endif
#define DR(X) ((X)*M_PI/180.0)
#define RD(X) ((X)*180.0/M_PI)
int main()
{
double lat, slat, lng, ref;
int... | use std::io;
struct SundialCalculation {
hour_angle: f64,
hour_line_angle: f64,
}
fn get_input(prompt: &str) -> Result<f64, Box<dyn std::error::Error>> {
println!("{}", prompt);
let mut input = String::new();
let stdin = io::stdin();
stdin.read_line(&mut input)?;
Ok(input.trim().parse::<f64... |
Horner's rule for polynomial evaluation | #include <stdio.h>
double horner(double *coeffs, int s, double x)
{
int i;
double res = 0.0;
for(i=s-1; i >= 0; i--)
{
res = res * x + coeffs[i];
}
return res;
}
int main()
{
double coeffs[] = { -19.0, 7.0, -4.0, 6.0 };
printf("%5.1f\n", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0));
... | fn horner(v: &[f64], x: f64) -> f64 {
v.iter().rev().fold(0.0, |acc, coeff| acc*x + coeff)
}
fn main() {
let v = [-19., 7., -4., 6.];
println!("result: {}", horner(&v, 3.0));
}
|
Host introspection | #include <stdio.h>
#include <stddef.h>
#include <limits.h>
int main() {
int one = 1;
printf("word size = %d bits\n", (int)(CHAR_BIT * sizeof(size_t)));
if (*(char *)&one)
printf("little endian\n");
else
printf("big endian\n");
return 0;
}
| #[derive(Copy, Clone, Debug)]
enum Endianness {
Big, Little,
}
impl Endianness {
fn target() -> Self {
#[cfg(target_endian = "big")]
{
Endianness::Big
}
#[cfg(not(target_endian = "big"))]
{
Endianness::Little
}
}
}
fn main() {
pri... |
Hostname | #include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <unistd.h>
int main(void)
{
char name[_POSIX_HOST_NAME_MAX + 1];
return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
| fn main() {
match hostname::get_hostname() {
Some(host) => println!("hostname: {}", host),
None => eprintln!("Could not get hostname!"),
}
}
|
Huffman coding | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BYTES 256
struct huffcode {
int nbits;
int code;
};
typedef struct huffcode huffcode_t;
struct huffheap {
int *h;
int n, s, cs;
long *f;
};
typedef struct huffheap heap_t;
static heap_t *_heap_create(int s, long *f)
{
heap_t *h;
h = m... | use std::collections::BTreeMap;
use std::collections::binary_heap::BinaryHeap;
#[derive(Debug, Eq, PartialEq)]
enum NodeKind {
Internal(Box<Node>, Box<Node>),
Leaf(char),
}
#[derive(Debug, Eq, PartialEq)]
struct Node {
frequency: usize,
kind: NodeKind,
}
impl Ord for Node {
fn cmp(&self, rhs: &Se... |
IBAN | #include <alloca.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define V(cc, exp) if (!strncmp(iban, cc, 2)) return len == exp
int valid_cc(const char *iban, int len)
{
V("AL", 28); V("AD", 24); V("AT", 20); V("AZ", 28); V("BE", 16); V("BH", 22); V("BA", 20); V("BR", 29);
V... | fn main() {
for iban in [
"",
"x",
"QQ82",
"QQ82W",
"GB82 TEST 1234 5698 7654 322",
"gb82 WEST 1234 5698 7654 32",
"GB82 WEST 1234 5698 7654 32",
"GB82 TEST 1234 5698 7654 32",
"GB81 WEST 1234 5698 7654 32",
"SA03 8000 0000 6080 1016 75... |
ISBN13 check digit | #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
... | fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
l... |
Identity matrix | #include <stdlib.h>
#include <stdio.h>
int main(int argc, char** argv) {
if (argc < 2) {
printf("usage: identitymatrix <number of rows>\n");
exit(EXIT_FAILURE);
}
int rowsize = atoi(argv[1]);
if (rowsize < 0) {
printf("Dimensions of matrix cannot be negative\n");
exit(EXIT_FAILURE);
... | extern crate num;
struct Matrix<T> {
data: Vec<T>,
size: usize,
}
impl<T> Matrix<T>
where
T: num::Num + Clone + Copy,
{
fn new(size: usize) -> Self {
Self {
data: vec![T::zero(); size * size],
size: size,
}
}
fn get(&mut self, x: usize, y: usize) -> T {
... |
Increment a numerical string | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * incr(char *s)
{
int i, begin, tail, len;
int neg = (*s == '-');
char tgt = neg ? '0' : '9';
if (!strcmp(s, "-1")) {
s[0] = '0', s[1] = '\0';
return s;
}
len = strlen(s);
begin = (*s == '-' || *s == '+') ? 1 : 0;
for (tail = len - 1; ... | fn next_string(input: &str) -> String {
(input.parse::<i64>().unwrap() + 1).to_string()
}
fn main() {
let s = "-1";
let s2 = next_string(s);
println!("{:?}", s2);
}
|
Infinity | #include <math.h>
#include <stdio.h>
double inf(void) {
return HUGE_VAL;
}
int main() {
printf("%g\n", inf());
return 0;
}
| fn main() {
let inf = f32::INFINITY;
println!("{}", inf);
}
|
Inheritance_Multiple | typedef struct{
double focalLength;
double resolution;
double memory;
}Camera;
typedef struct{
double balance;
double batteryLevel;
char** contacts;
}Phone;
typedef struct{
Camera cameraSample;
Phone phoneSample;
}CameraPhone;
| trait Camera {}
trait MobilePhone {}
trait CameraPhone: Camera + MobilePhone {}
|
Input loop | #include <stdlib.h>
#include <stdio.h>
char *get_line(FILE* fp)
{
int len = 0, got = 0, c;
char *buf = 0;
while ((c = fgetc(fp)) != EOF) {
if (got + 1 >= len) {
len *= 2;
if (len < 4) len = 4;
buf = realloc(buf, len);
}
buf[got++] = c;
if (c == '\n') break;
}
if (c == EOF && !got) return 0;
bu... | use std::io::{self, BufReader, Read, BufRead};
use std::fs::File;
fn main() {
print_by_line(io::stdin())
.expect("Could not read from stdin");
File::open("/etc/fstab")
.and_then(print_by_line)
.expect("Could not read from file");
}
fn print_by_line<T: Read>(reader: T) -> io::Result<(... |
Integer comparison | #include <stdio.h>
int main()
{
int a, b;
scanf("%d %d", &a, &b);
if (a < b)
printf("%d is less than %d\n", a, b);
if (a == b)
printf("%d is equal to %d\n", a, b);
if (a > b)
printf("%d is greater than %d\n", a, b);
return 0;
}
| use std::io::{self, BufRead};
fn main() {
let mut reader = io::stdin();
let mut buffer = String::new();
let mut lines = reader.lock().lines().take(2);
let nums: Vec<i32>= lines.map(|string|
string.unwrap().trim().parse().unwrap()
).collect();
let a: i32 = nums[0];
let b: i32 = n... |
Integer overflow | #include <stdio.h>
int main (int argc, char *argv[])
{
printf("Signed 32-bit:\n");
printf("%d\n", -(-2147483647-1));
printf("%d\n", 2000000000 + 2000000000);
printf("%d\n", -2147483647 - 2147483647);
printf("%d\n", 46341 * 46341);
printf("%d\n", (-2147483647-1) / -1);
printf("Signed 64-bit:\n");
printf... |
let i32_1 : i32 = -(-2_147_483_647 - 1);
let i32_2 : i32 = 2_000_000_000 + 2_000_000_000;
let i32_3 : i32 = -2_147_483_647 - 2_147_483_647;
let i32_4 : i32 = 46341 * 46341;
let i32_5 : i32 = (-2_147_483_647 - 1) / -1;
let i64_1 : i64 = -(-9_223_372_036_854_775_807 - 1);
let i64_2 ... |
Integer sequence | #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
| fn main() {
for i in 0.. {
println!("{}", i);
}
}
|
Inverted index | #include <stdio.h>
#include <stdlib.h>
char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./";
int chr_idx[256] = {0};
char idx_chr[256] = {0};
#define FNAME 0
typedef struct trie_t *trie, trie_t;
struct trie_t {
trie next[sizeof(chr_legal)];
int eow;
};
trie trie_new() { return calloc(sizeof(trie_t... |
use std::{
borrow::Borrow,
collections::{BTreeMap, BTreeSet},
};
#[derive(Debug, Default)]
pub struct InvertedIndex<T> {
indexed: BTreeMap<String, BTreeSet<usize>>,
sources: Vec<T>,
}
impl<T> InvertedIndex<T> {
pub fn add<I, V>(&mut self, source: T, tokens: I)
where
I: IntoIterator<I... |
Isqrt (integer square root) of X | #include <stdint.h>
#include <stdio.h>
int64_t isqrt(int64_t x) {
int64_t q = 1, r = 0;
while (q <= x) {
q <<= 2;
}
while (q > 1) {
int64_t t;
q >>= 2;
t = x - r - q;
r >>= 1;
if (t >= 0) {
x = t;
r += q;
}
}
return... | use num::BigUint;
use num::CheckedSub;
use num_traits::{One, Zero};
fn isqrt(number: &BigUint) -> BigUint {
let mut q: BigUint = One::one();
while q <= *number {
q <<= &2;
}
let mut z = number.clone();
let mut result: BigUint = Zero::zero();
while q > One::one() {
q >>= &2;
... |
Iterated digits squaring | #include <stdio.h>
typedef unsigned long long ull;
int is89(int x)
{
while (1) {
int s = 0;
do s += (x%10)*(x%10); while ((x /= 10));
if (s == 89) return 1;
if (s == 1) return 0;
x = s;
}
}
int main(void)
{
ull sums[32*81 + 1] = {1, 0};
for (int n = 1; ; n++) {
for (int i = n*81; i; i--) {
fo... | fn digit_square_sum(mut num: usize) -> usize {
let mut sum = 0;
while num != 0 {
sum += (num % 10).pow(2);
num /= 10;
}
sum
}
fn last_in_chain(num: usize) -> usize {
match num {
1 | 89 => num,
_ => last_in_chain(digit_square_sum(num)),
}
}
fn main() {
let co... |
JSON | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yajl/yajl_tree.h>
#include <yajl/yajl_gen.h>
static void print_callback (void *ctx, const char *str, size_t len)
{
FILE *f = (FILE *) ctx;
fwrite (str, 1, len, f);
}
static void check_status (yajl_gen_status status)
{
if (status != yajl_gen_st... | use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
|
Jensen's Device | #include <stdio.h>
int i;
double sum(int *i, int lo, int hi, double (*term)()) {
double temp = 0;
for (*i = lo; *i <= hi; (*i)++)
temp += term();
return temp;
}
double term_func() { return 1.0 / i; }
int main () {
printf("%f\n", sum(&i, 1, 100, term_func));
return 0;
}
| use std::f32;
fn harmonic_sum<F>(lo: usize, hi: usize, term: F) -> f32
where
F: Fn(f32) -> f32,
{
(lo..hi + 1).fold(0.0, |acc, item| acc + term(item as f32))
}
fn main() {
println!("{}", harmonic_sum(1, 100, |i| 1.0 / i));
}
|
Jewels and stones | #include <stdio.h>
#include <string.h>
int count_jewels(const char *s, const char *j) {
int count = 0;
for ( ; *s; ++s) if (strchr(j, *s)) ++count;
return count;
}
int main() {
printf("%d\n", count_jewels("aAAbbbb", "aA"));
printf("%d\n", count_jewels("ZZ", "z"));
return 0;
}
| fn count_jewels(stones: &str, jewels: &str) -> u8 {
let mut count: u8 = 0;
for cur_char in stones.chars() {
if jewels.contains(cur_char) {
count += 1;
}
}
count
}
fn main() {
println!("{}", count_jewels("aAAbbbb", "aA"));
println!("{}", count_jewels("ZZ", "z"));
}
|
JortSort | #include <stdio.h>
#include <stdlib.h>
int number_of_digits(int x){
int NumberOfDigits;
for(NumberOfDigits=0;x!=0;NumberOfDigits++){
x=x/10;
}
return NumberOfDigits;
}
int* convert_array(char array[], int NumberOfElements)
{
int *convertedArray=malloc(NumberOfElements*sizeof(int));
... | use std::cmp::{Ord, Eq};
fn jort_sort<T: Ord + Eq + Clone>(array: Vec<T>) -> bool {
let mut sorted_array = array.to_vec();
sorted_array.sort();
for i in 0..array.len() {
if array[i] != sorted_array[i] {
return false;
}
}
return true;
}
|
Josephus problem | #include <stdio.h>
int jos(int n, int k, int m) {
int a;
for (a = m + 1; a <= n; a++)
m = (m + k) % a;
return m;
}
typedef unsigned long long xint;
xint jos_large(xint n, xint k, xint m) {
if (k <= 1) return n - m - 1;
xint a = m;
while (a < n) {
xint q = (a - m + k - 2) / (k - 1);
if (a + q > n) q =... | const N: usize = 41;
const K: usize = 3;
const M: usize = 3;
const POSITION: usize = 5;
fn main() {
let mut prisoners: Vec<usize> = Vec::new();
let mut executed: Vec<usize> = Vec::new();
for pos in 0..N {
prisoners.push(pos);
}
let mut to_kill: usize = 0;
let mut len: usize = prisoners... |
Julia set | #include<graphics.h>
#include<stdlib.h>
#include<math.h>
typedef struct{
double x,y;
}complex;
complex add(complex a,complex b){
complex c;
c.x = a.x + b.x;
c.y = a.y + b.y;
return c;
}
complex sqr(complex a){
complex c;
c.x = a.x*a.x - a.y*a.y;
c.y = 2*a.x*a.y;
return c;
}
double mod(complex a){
return s... | extern crate image;
use image::{ImageBuffer, Pixel, Rgb};
fn main() {
let width = 8000;
let height = 6000;
let mut img = ImageBuffer::new(width as u32, height as u32);
let cx = -0.9;
let cy = 0.27015;
let iterations = 110;
for x in 0..width {
for y in 0..height {
... |
Kernighans large earthquake problem | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
char *lw, *lt;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Unable to open file\n");
exit(1);
}
printf("Those earthquakes with... | fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::io::{BufRead, BufReader};
for line in BufReader::new(std::fs::OpenOptions::new().read(true).open("data.txt")?).lines() {
let line = line?;
let magnitude = line
.split_whitespace()
.nth(2)
.and_th... |
Knapsack problem_0-1 | #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
} item_t;
item_t items[] = {
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"gluc... | use std::cmp;
struct Item {
name: &'static str,
weight: usize,
value: usize
}
fn knapsack01_dyn(items: &[Item], max_weight: usize) -> Vec<&Item> {
let mut best_value = vec![vec![0; max_weight + 1]; items.len() + 1];
for (i, it) in items.iter().enumerate() {
for w in 1 .. max_weight + 1 {
... |
Knapsack problem_Continuous | #include <stdio.h>
#include <stdlib.h>
struct item { double w, v; const char *name; } items[] = {
{ 3.8, 36, "beef" },
{ 5.4, 43, "pork" },
{ 3.6, 90, "ham" },
{ 2.4, 45, "greaves" },
{ 4.0, 30, "flitch" },
{ 2.5, 56, "brawn" },
{ 3.7, 67, "welt" },
{ 3.0, 95, "salami" },
{ 5.9, 98, "sausage" },
};
int item_... | fn main() {
let items: [(&str, f32, u8); 9] = [
("beef", 3.8, 36),
("pork", 5.4, 43),
("ham", 3.6, 90),
("greaves", 2.4, 45),
("flitch", 4.0, 30),
("brawn", 2.5, 56),
("welt", 3.7, 67),
("salami", 3.0, 95),
("sausage", 5.9, 98),
];
let ... |
Knight's tour | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef unsigned char cell;
int dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 };
int dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 };
void init_board(int w, int h, cell **a, cell **b)
{
int i, j, k, x, y, p = w + 4, q = h + 4;
a[0] = (cell*)(a + q);
... | use std::fmt;
const SIZE: usize = 8;
const MOVES: [(i32, i32); 8] = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
];
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn mov(&self, &(dx, dy): &(... |
Knuth shuffle | #include <stdlib.h>
#include <string.h>
int rrand(int m)
{
return (int)((double)m * ( rand() / (RAND_MAX+1.0) ));
}
#define BYTE(X) ((unsigned char *)(X))
void shuffle(void *obj, size_t nmemb, size_t size)
{
void *temp = malloc(size);
size_t n = nmemb;
while ( n > 1 ) {
size_t k = rrand(n--);
memcpy(... | use rand::Rng;
extern crate rand;
fn knuth_shuffle<T>(v: &mut [T]) {
let mut rng = rand::thread_rng();
let l = v.len();
for n in 0..l {
let i = rng.gen_range(0, l - n);
v.swap(i, l - n - 1);
}
}
fn main() {
let mut v: Vec<_> = (0..10).collect();
println!("before: {:?}", v);
... |
Kronecker product | #include<stdlib.h>
#include<stdio.h>
int main(){
char input[100],output[100];
int i,j,k,l,rowA,colA,rowB,colB,rowC,colC,startRow,startCol;
double **matrixA,**matrixB,**matrixC;
printf("Enter full path of input file : ");
fscanf(stdin,"%s",input);
printf("Enter full path of output file : ");
fscanf(stdin,"... | fn main() {
let mut a = vec![vec![1., 2.], vec![3., 4.]];
let mut b = vec![vec![0., 5.], vec![6., 7.]];
let mut a_ref = &mut a;
let a_rref = &mut a_ref;
let mut b_ref = &mut b;
let b_rref = &mut b_ref;
let ab = kronecker_product(a_rref, b_rref);
println!("Kronecker product of\n");
... |
Langton's ant | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int w = 0, h = 0;
unsigned char *pix;
void refresh(int x, int y)
{
int i, j, k;
printf("\033[H");
for (i = k = 0; i < h; putchar('\n'), i++)
for (j = 0; j < w; j++, k++)
putchar(pix[k] ? '#' : ' ');
}
void walk()
{
int dx = 0, dy... | struct Ant {
x: usize,
y: usize,
dir: Direction
}
#[derive(Clone,Copy)]
enum Direction {
North,
East,
South,
West
}
use Direction::*;
impl Ant {
fn mv(&mut self, vec: &mut Vec<Vec<u8>>) {
let pointer = &mut vec[self.y][self.x];
match *pointer {
0 =... |
Largest int from concatenated ints | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int catcmp(const void *a, const void *b)
{
char ab[32], ba[32];
sprintf(ab, "%d%d", *(int*)a, *(int*)b);
sprintf(ba, "%d%d", *(int*)b, *(int*)a);
return strcmp(ba, ab);
}
void maxcat(int *a, int len)
{
int i;
qsort(a, len, sizeof(int), catcmp);
for (i ... | fn maxcat(a: &mut [u32]) {
a.sort_by(|x, y| {
let xy = format!("{}{}", x, y);
let yx = format!("{}{}", y, x);
xy.cmp(&yx).reverse()
});
for x in a {
print!("{}", x);
}
println!();
}
fn main() {
maxcat(&mut [1, 34, 3, 98, 9, 76, 45, 4]);
maxcat(&mut [54, 546,... |
Last Friday of each month | #include <stdio.h>
#include <stdlib.h>
int main(int c, char *v[])
{
int days[] = {31,29,31,30,31,30,31,31,30,31,30,31};
int m, y, w;
if (c < 2 || (y = atoi(v[1])) <= 1700) return 1;
days[1] -= (y % 4) || (!(y % 100) && (y % 400));
w = y * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 6;
for(m = 0; m < 1... | use std::env::args;
use time::{Date, Duration};
fn main() {
let year = args().nth(1).unwrap().parse::<i32>().unwrap();
(1..=12)
.map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1))
.filter_map(|date| date.ok())
.for_each(|date| {
let days_back =
... |
Last letter-first letter | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
typedef struct {
uint16_t index;
char last_char, first_char;
} Ref;
Ref* longest_path_refs;
size_t longest_path_refs_len;
Ref* refs;
size_t refs_len;
size_t n_solutions;
const char** longest_path;
size_t longest_path_len;
v... |
fn first_char(string: &str) -> char {
string.chars().next().unwrap()
}
fn first_and_last_char(string: &str) -> (char, char) {
(
first_char(string),
first_char(string.rmatches(|_: char| true).next().unwrap()),
)
}
struct Pokemon {
name: &'static str,
first: char,
last: cha... |
Leap year | #include <stdio.h>
int is_leap_year(unsigned year)
{
return !(year & (year % 100 ? 3 : 15));
}
int main(void)
{
const unsigned test_case[] = {
1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100
};
const unsigned n = sizeof test_case / sizeof test_case[0];
for (unsigned i = 0; i != n; ++... | fn is_leap(year: i32) -> bool {
let factor = |x| year % x == 0;
factor(4) && (!factor(100) || factor(400))
}
|
Least common multiple | #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
| use std::cmp::{max, min};
fn gcd(a: usize, b: usize) -> usize {
match ((a, b), (a & 1, b & 1)) {
((x, y), _) if x == y => y,
((0, x), _) | ((x, 0), _) => x,
((x, y), (0, 1)) | ((y, x), (1, 0)) => gcd(x >> 1, y),
((x, y), (0, 0)) => gcd(x >> 1, y >> 1) << 1,
((x, y), (1, 1)) ... |
Leonardo numbers | #include<stdio.h>
void leonardo(int a,int b,int step,int num){
int i,temp;
printf("First 25 Leonardo numbers : \n");
for(i=1;i<=num;i++){
if(i==1)
printf(" %d",a);
else if(i==2)
printf(" %d",b);
else{
printf(" %d",a+b+step);
temp = a;
a = b;
b = temp+b+step;
}
}
}
int main()
{
int... | fn leonardo(mut n0: u32, mut n1: u32, add: u32) -> impl std::iter::Iterator<Item = u32> {
std::iter::from_fn(move || {
let n = n0;
n0 = n1;
n1 += n + add;
Some(n)
})
}
fn main() {
println!("First 25 Leonardo numbers:");
for i in leonardo(1, 1, 1).take(25) {
print... |
Letter frequency |
int frequency[26];
int ch;
FILE* txt_file = fopen ("a_text_file.txt", "rt");
for (ch = 0; ch < 26; ch++)
frequency[ch] = 0;
while (1) {
ch = fgetc(txt_file);
if (ch == EOF) break;
if ('a' <= ch && ch <= 'z')
frequency[ch-'a']++;
else if ('A' <= ch && ch <= 'Z')
freq... | use std::collections::btree_map::BTreeMap;
use std::{env, process};
use std::io::{self, Read, Write};
use std::fmt::Display;
use std::fs::File;
fn main() {
let filename = env::args().nth(1)
.ok_or("Please supply a file name")
.unwrap_or_else(|e| exit_err(e, 1));
let mut buf = String::new();
... |
Levenshtein distance | #include <stdio.h>
#include <string.h>
int levenshtein(const char *s, int ls, const char *t, int lt)
{
int a, b, c;
if (!ls) return lt;
if (!lt) return ls;
if (s[ls - 1] == t[lt - 1])
return levenshtein(s, ls - 1, t, lt - 1);
a = le... | fn main() {
println!("{}", levenshtein_distance("kitten", "sitting"));
println!("{}", levenshtein_distance("saturday", "sunday"));
println!("{}", levenshtein_distance("rosettacode", "raisethysword"));
}
fn levenshtein_distance(word1: &str, word2: &str) -> usize {
let w1 = word1.chars().collect::<Vec<_... |
Linear congruential generator | #include <stdio.h>
int rand();
int rseed = 0;
inline void srand(int x)
{
rseed = x;
}
#ifndef MS_RAND
#define RAND_MAX ((1U << 31) - 1)
inline int rand()
{
return rseed = (rseed * 1103515245 + 12345) & RAND_MAX;
}
#else
#define RAND_MAX_32 ((1U << 31) - 1)
#define RAND_MAX ((1U << 15) - 1)
inline int rand()
... | extern crate rand;
pub use rand::{Rng, SeedableRng};
pub struct BsdLcg {
state: u32,
}
impl Rng for BsdLcg {
fn next_u32(&mut self) -> u32 {
self.state = self.state.wrapping_mul(1_103_515_245).wrapping_add(12_345);
self.state %= 1 << 31;
self.state
}
}
impl Se... |
List comprehensions | for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
| fn pyth(n: u32) -> impl Iterator<Item = [u32; 3]> {
(1..=n).flat_map(move |x| {
(x..=n).flat_map(move |y| {
(y..=n).filter_map(move |z| {
if x.pow(2) + y.pow(2) == z.pow(2) {
Some([x, y, z])
} else {
None
}
... |
Literals_Integer | #include <stdio.h>
int main(void)
{
printf("%s\n",
( (727 == 0x2d7) &&
(727 == 01327) ) ? "true" : "false");
return 0;
}
| 10
0b10
0x10
0o10
1_000
10_i32
10i32
|
Literals_String | char ch = 'z';
| let char01: char = 'a';
let char02: char = '\u{25A0}';
let char03: char = '❤';
|
Logical operations | if(myValue == 3 && myOtherValue == 5){
myResult = true;
}
| fn boolean_ops(a: bool, b: bool) {
println!("{} and {} -> {}", a, b, a && b);
println!("{} or {} -> {}", a, b, a || b);
println!("{} xor {} -> {}", a, b, a ^ b);
println!("not {} -> {}\n", a, !a);
}
fn main() {
boolean_ops(true, true);
boolean_ops(true, false);
boolean_ops(false, true);
... |
Longest common prefix | #include<stdarg.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
char* lcp(int num,...){
va_list vaList,vaList2;
int i,j,len,min;
char* dest;
char** strings = (char**)malloc(num*sizeof(char*));
va_start(vaList,num);
va_start(vaList2,num);
for(i=0;i<num;i++){
len = strlen(va_arg(vaList,char*));
... | fn main() {
let strs: [&[&[u8]]; 7] = [
&[b"interspecies", b"interstellar", b"interstate"],
&[b"throne", b"throne"],
&[b"throne", b"dungeon"],
&[b"cheese"],
&[b""],
&[b"prefix", b"suffix"],
&[b"foo", b"foobar"],
];
strs.iter().for_each(|list| match lcp... |
Longest common subsequence | #include <stdio.h>
#include <stdlib.h>
#define MAX(a, b) (a > b ? a : b)
int lcs (char *a, int n, char *b, int m, char **s) {
int i, j, k, t;
int *z = calloc((n + 1) * (m + 1), sizeof (int));
int **c = calloc((n + 1), sizeof (int *));
for (i = 0; i <= n; i++) {
c[i] = &z[i * (m + 1)];
}
... | use std::cmp;
fn lcs(string1: String, string2: String) -> (usize, String){
let total_rows = string1.len() + 1;
let total_columns = string2.len() + 1;
let string1_chars = string1.as_bytes();
let string2_chars = string2.as_bytes();
let mut table = vec![vec![0; total_columns]; total_rows];
... |
Longest common substring | #include <stdio.h>
void lcs(const char * const sa, const char * const sb, char ** const beg, char ** const end) {
size_t apos, bpos;
ptrdiff_t len;
*beg = 0;
*end = 0;
len = 0;
for (apos = 0; sa[apos] != 0; ++apos) {
for (bpos = 0; sb[bpos] != 0; ++bpos) {
if (sa[apos] == ... | fn longest_common_substring(s1: &str, s2: &str) -> String {
let s1_chars: Vec<char> = s1.chars().collect();
let s2_chars: Vec<char> = s2.chars().collect();
let mut lcs = "".to_string();
for i in 0..s1_chars.len() {
for j in 0..s2_chars.len() {
if s1_chars[i] == s2_chars[j] {
... |
Look-and-say sequence | #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt,... | fn next_sequence(in_seq: &[i8]) -> Vec<i8> {
assert!(!in_seq.is_empty());
let mut result = Vec::new();
let mut current_number = in_seq[0];
let mut current_runlength = 1;
for i in &in_seq[1..] {
if current_number == *i {
current_runlength += 1;
} else {
resul... |
Loop over multiple arrays simultaneously | #include <stdio.h>
char a1[] = {'a','b','c'};
char a2[] = {'A','B','C'};
int a3[] = {1,2,3};
int main(void) {
for (int i = 0; i < 3; i++) {
printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}
}
| fn main() {
let a1 = ["a", "b", "c"];
let a2 = ["A", "B", "C"];
let a3 = [1, 2, 3];
for ((&x, &y), &z) in a1.iter().zip(a2.iter()).zip(a3.iter()) {
println!("{}{}{}", x, y, z);
}
}
|
Loops_Break | int main(){
time_t t;
int a, b;
srand((unsigned)time(&t));
for(;;){
a = rand() % 20;
printf("%d\n", a);
if(a == 10)
break;
b = rand() % 20;
printf("%d\n", b);
}
return 0;
}
|
extern crate rand;
use rand::{thread_rng, Rng};
fn main() {
let mut rng = thread_rng();
loop {
let num = rng.gen_range(0, 20);
if num == 10 {
println!("{}", num);
break;
}
println!("{}", rng.gen_range(0, 20));
}
}
|
Loops_Continue | for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
| fn main() {
for i in 1..=10 {
print!("{}", i);
if i % 5 == 0 {
println!();
continue;
}
print!(", ");
}
}
|
Loops_Do-while | int val = 0;
do{
val++;
printf("%d\n",val);
}while(val % 6 != 0);
| let mut x = 0;
loop {
x += 1;
println!("{}", x);
if x % 6 == 0 { break; }
}
|
Loops_Downward for | int i;
for(i = 10; i >= 0; --i)
printf("%d\n",i);
| fn main() {
for i in (0..=10).rev() {
println!("{}", i);
}
}
|
Loops_For | int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
putchar('*');
puts("");
}
| fn main() {
for i in 0..5 {
for _ in 0..=i {
print!("*");
}
println!();
}
}
|
Loops_For with a specified step | int i;
for(i = 1; i < 10; i += 2)
printf("%d\n", i);
| fn main() {
for i in (2..=8).step_by(2) {
print!("{}", i);
}
println!("who do we appreciate?!");
}
|
Loops_Foreach | #include <stdio.h>
...
const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))
int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
printf("%s\n", list[ix]);
}
| let collection = vec![1,2,3,4,5];
for elem in collection {
println!("{}", elem);
}
|
Loops_N plus one half | #include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++) {
printf("%d", i);
printf(i == 10 ? "\n" : ", ");
}
return 0;
}
| fn main() {
for i in 1..=10 {
print!("{}{}", i, if i < 10 { ", " } else { "\n" });
}
}
|
Loops_Nested | #include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(" %d", a[i][j... | use rand::Rng;
extern crate rand;
fn main() {
let mut matrix = [[0u8; 10]; 10];
let mut rng = rand::thread_rng();
for row in matrix.iter_mut() {
for item in row.iter_mut() {
*item = rng.gen_range(0, 21);
}
}
'outer: for row in matrix.iter() {
for &item in row.... |
Loops_While | int i = 1024;
while(i > 0) {
printf("%d\n", i);
i /= 2;
}
| fn main() {
let mut n: i32 = 1024;
while n > 0 {
println!("{}", n);
n /= 2;
}
}
|
Lucas-Lehmer test | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <gmp.h>
int lucas_lehmer(unsigned long p)
{
mpz_t V, mp, t;
unsigned long k, tlim;
int res;
if (p == 2) return 1;
if (!(p&1)) return 0;
mpz_init_set_ui(t, p);
if (!mpz_probab_prime_p(t, 25))
{ mpz_clear(t); return 0; }
if (p < ... | extern crate rug;
extern crate primal;
use rug::Integer;
use rug::ops::Pow;
use std::thread::spawn;
fn is_mersenne (p : usize) {
let p = p as u32;
let mut m = Integer::from(1);
m = m << p;
m = Integer::from(&m - 1);
let mut flag1 = false;
for k in 1..10_000 {
let mut flag2 = false;
... |
Subsets and Splits
SQL Console for aandvalenzuela/test
Displays the highest values of 'C' and 'Rust' for each distinct name, highlighting the maximum levels of these two features per name.
SQL Console for aandvalenzuela/test
Retrieves distinct names along with the highest values for 'C' and 'Rust' if both are present for each name, providing a comparison of these metrics.
SQL Console for aandvalenzuela/test
The query retrieves names from the validation dataset where both the C and Rust columns are not null, providing a basic filter for entries with complete data on these languages.