name stringlengths 2 74 | C stringlengths 7 6.19k | Rust stringlengths 19 8.53k |
|---|---|---|
Time a function | #include <stdio.h>
#include <time.h>
int identity(int x) { return x; }
int sum(int s)
{
int i;
for(i=0; i < 1000000; i++) s += i;
return s;
}
#ifdef CLOCK_PROCESS_CPUTIME_ID
#define CLOCKTYPE CLOCK_PROCESS_CPUTIME_ID
#else
#define CLOCKTYPE CLOCK_MONOTONIC
#endif
double time_it(int (*action)(int), int arg)
{
struct timespec tsi, tsf;
clock_gettime(CLOCKTYPE, &tsi);
action(arg);
clock_gettime(CLOCKTYPE, &tsf);
double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
return elaps_s + ((double)elaps_ns) / 1.0e9;
}
int main()
{
printf("identity (4) takes %lf s\n", time_it(identity, 4));
printf("sum (4) takes %lf s\n", time_it(sum, 4));
return 0;
}
|
use rand::Rng;
use std::time::{Instant};
fn custom_function() {
let mut i = 0;
let mut rng = rand::thread_rng();
let n1: f32 = rng.gen();
while i < ( 1000000 + 1000000 * ( n1.log10() as i32 ) ) {
i = i + 1;
}
}
fn main() {
let start = Instant::now();
custom_function();
let duration = start.elapsed();
println!("Time elapsed in the custom_function() is : {:?}", duration);
}
|
Tokenize a string | #include<string.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char *a[5];
const char *s="Hello,How,Are,You,Today";
int n=0, nn;
char *ds=strdup(s);
a[n]=strtok(ds, ",");
while(a[n] && n<4) a[++n]=strtok(NULL, ",");
for(nn=0; nn<=n; ++nn) printf("%s.", a[nn]);
putchar('\n');
free(ds);
return 0;
}
| fn main() {
let s = "Hello,How,Are,You,Today";
let tokens: Vec<&str> = s.split(",").collect();
println!("{}", tokens.join("."));
}
|
Tokenize a string with escaping | #include <stdlib.h>
#include <stdio.h>
#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'
typedef char* Str;
unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );
int main() {
char s[] = STR_DEMO;
unsigned int i, q;
Str *list = Tokenize( s, SEP, ESC, &q );
if( list != NULL ) {
printf( "\n Original string: %s\n\n", STR_DEMO );
printf( " %d tokens:\n\n", q );
for( i=0; i<q; ++i )
printf( " %4d. %s\n", i+1, list[i] );
free( list );
}
return 0;
}
unsigned int ElQ( const char *s, char sep, char esc ) {
unsigned int q, e;
const char *p;
for( e=0, q=1, p=s; *p; ++p ) {
if( *p == esc )
e = !e;
else if( *p == sep )
q += !e;
else e = 0;
}
return q;
}
Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
Str *list = NULL;
*q = ElQ( s, sep, esc );
list = malloc( *q * sizeof(Str) );
if( list != NULL ) {
unsigned int e, i;
char *p;
i = 0;
list[i++] = s;
for( e=0, p=s; *p; ++p ) {
if( *p == esc ) {
e = !e;
}
else if( *p == sep && !e ) {
list[i++] = p+1;
*p = '\0';
}
else {
e = 0;
}
}
}
return list;
}
| const SEPARATOR: char = '|';
const ESCAPE: char = '^';
const STRING: &str = "one^|uno||three^^^^|four^^^|^cuatro|";
fn tokenize(string: &str) -> Vec<String> {
let mut token = String::new();
let mut tokens: Vec<String> = Vec::new();
let mut chars = string.chars();
while let Some(ch) = chars.next() {
match ch {
SEPARATOR => {
tokens.push(token);
token = String::new();
},
ESCAPE => {
if let Some(next) = chars.next() {
token.push(next);
}
},
_ => token.push(ch),
}
}
tokens.push(token);
tokens
}
fn main() {
println!("{:#?}", tokenize(STRING));
}
|
Top rank per group | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *name, *id, *dept;
int sal;
} person;
person ppl[] = {
{"Tyler Bennett", "E10297", "D101", 32000},
{"John Rappl", "E21437", "D050", 47000},
{"George Woltman", "E00127", "D101", 53500},
{"Adam Smith", "E63535", "D202", 18000},
{"Claire Buckman", "E39876", "D202", 27800},
{"David McClellan", "E04242", "D101", 41500},
{"Rich Holcomb", "E01234", "D202", 49500},
{"Nathan Adams", "E41298", "D050", 21900},
{"Richard Potter", "E43128", "D101", 15900},
{"David Motsinger", "E27002", "D202", 19250},
{"Tim Sampair", "E03033", "D101", 27000},
{"Kim Arlich", "E10001", "D190", 57000},
{"Timothy Grove", "E16398", "D190", 29900},
};
int pcmp(const void *a, const void *b)
{
const person *aa = a, *bb = b;
int x = strcmp(aa->dept, bb->dept);
if (x) return x;
return aa->sal > bb->sal ? -1 : aa->sal < bb->sal;
}
#define N sizeof(ppl)/sizeof(person)
void top(int n)
{
int i, rank;
qsort(ppl, N, sizeof(person), pcmp);
for (i = rank = 0; i < N; i++) {
if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) {
rank = 0;
printf("\n");
}
if (rank++ < n)
printf("%s %d: %s\n", ppl[i].dept, ppl[i].sal, ppl[i].name);
}
}
int main()
{
top(2);
return 0;
}
| #[derive(Debug)]
struct Employee<S> {
id: S,
name: S,
department: S,
salary: u32,
}
impl<S> Employee<S> {
fn new(name: S, id: S, salary: u32, department: S) -> Self {
Self {
id,
name,
department,
salary,
}
}
}
#[rustfmt::skip]
fn load_data() -> Vec<Employee<&'static str>> {
vec![
Employee::new("Tyler Bennett", "E10297", 32000, "D101"),
Employee::new("John Rappl", "E21437", 47000, "D050"),
Employee::new("George Woltman", "E00127", 53500, "D101"),
Employee::new("Adam Smith", "E63535", 18000, "D202"),
Employee::new("Claire Buckman", "E39876", 27800, "D202"),
Employee::new("David McClellan", "E04242", 41500, "D101"),
Employee::new("Rich Holcomb", "E01234", 49500, "D202"),
Employee::new("Nathan Adams", "E41298", 21900, "D050"),
Employee::new("Richard Potter", "E43128", 15900, "D101"),
Employee::new("David Motsinger", "E27002", 19250, "D202"),
Employee::new("Tim Sampair", "E03033", 27000, "D101"),
Employee::new("Kim Arlich", "E10001", 57000, "D190"),
Employee::new("Timothy Grove", "E16398", 29900, "D190"),
Employee::new("Kim Tie", "E16400", 57000, "D190"),
Employee::new("Timothy Tie", "E16401", 29900, "D190"),
Employee::new("Timothy Kim", "E16401", 19900, "D190"),
]
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let n = {
println!("How many top salaries to list? ");
let mut buf = String::new();
std::io::stdin().read_line(&mut buf)?;
buf.trim().parse::<u32>()?
};
let mut employees = load_data();
employees.sort_by(|a, b| b.salary.cmp(&a.salary));
let sorted = employees
.into_iter()
.fold(std::collections::BTreeMap::new(), |mut acc, next| {
let mut bucket = acc
.entry(next.department)
.or_insert_with(|| (0, Vec::<Employee<_>>::new()));
match bucket.1.last().map(|e| e.salary) {
Some(last_salary) if last_salary == next.salary => {
if bucket.0 <= n {
bucket.1.push(next);
}
}
_ => {
if bucket.0 < n {
bucket.0 += 1;
bucket.1.push(next);
}
}
}
acc
});
for (department, (_, employees)) in sorted {
println!("{}", department);
employees
.iter()
.for_each(|employee| println!(" {:?}", employee));
}
Ok(())
}
|
Topological sort | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
| use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\n",
"dw02 ieee dw02 dware\n",
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n",
"dw04 dw04 ieee dw01 dware gtech\n",
"dw05 dw05 ieee dware\n",
"dw06 dw06 ieee dware\n",
"dw07 ieee dware\n",
"dware ieee dware\n",
"gtech ieee gtech\n",
"ramlib std ieee\n",
"std_cell_lib ieee std_cell_lib\n",
"synopsys\n",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
|
Totient function |
#include<stdio.h>
int totient(int n){
int tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);
printf("\n---------------\n");
for(n=1;n<=25;n++){
tot = totient(n);
if(n-1 == tot)
count++;
printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False");
}
printf("\nNumber of primes up to %6d =%4d\n", 25,count);
for(n = 26; n <= 100000; n++){
tot = totient(n);
if(tot == n-1)
count++;
if(n == 100 || n == 1000 || n%10000 == 0){
printf("\nNumber of primes up to %6d = %4d\n", n, count);
}
}
return 0;
}
| use num::integer::gcd;
fn main() {
println!("N\t phi(n)\t Prime");
for n in 1..26 {
let phi_n = phi(n);
println!("{}\t {}\t {:?}", n, phi_n, phi_n == n - 1);
}
[1, 100, 1000, 10000, 100000]
.windows(2)
.scan(0, |acc, tuple| {
*acc += (tuple[0]..=tuple[1]).filter(is_prime).count();
Some((tuple[1], *acc))
})
.for_each(|x| println!("Until {}: {} prime numbers", x.0, x.1));
}
fn is_prime(n: &usize) -> bool {
phi(*n) == *n - 1
}
fn phi(n: usize) -> usize {
(1..=n).filter(|&x| gcd(n, x) == 1).count()
}
|
Towers of Hanoi | #include <stdio.h>
void move(int n, int from, int via, int to)
{
if (n > 1) {
move(n - 1, from, to, via);
printf("Move disk from pole %d to pole %d\n", from, to);
move(n - 1, via, from, to);
} else {
printf("Move disk from pole %d to pole %d\n", from, to);
}
}
int main()
{
move(4, 1,2,3);
return 0;
}
| fn move_(n: i32, from: i32, to: i32, via: i32) {
if n > 0 {
move_(n - 1, from, via, to);
println!("Move disk from pole {} to pole {}", from, to);
move_(n - 1, via, to, from);
}
}
fn main() {
move_(4, 1,2,3);
}
|
Tree traversal | #include <stdlib.h>
#include <stdio.h>
typedef struct node_s
{
int value;
struct node_s* left;
struct node_s* right;
} *node;
node tree(int v, node l, node r)
{
node n = malloc(sizeof(struct node_s));
n->value = v;
n->left = l;
n->right = r;
return n;
}
void destroy_tree(node n)
{
if (n->left)
destroy_tree(n->left);
if (n->right)
destroy_tree(n->right);
free(n);
}
void preorder(node n, void (*f)(int))
{
f(n->value);
if (n->left)
preorder(n->left, f);
if (n->right)
preorder(n->right, f);
}
void inorder(node n, void (*f)(int))
{
if (n->left)
inorder(n->left, f);
f(n->value);
if (n->right)
inorder(n->right, f);
}
void postorder(node n, void (*f)(int))
{
if (n->left)
postorder(n->left, f);
if (n->right)
postorder(n->right, f);
f(n->value);
}
typedef struct qnode_s
{
struct qnode_s* next;
node value;
} *qnode;
typedef struct { qnode begin, end; } queue;
void enqueue(queue* q, node n)
{
qnode node = malloc(sizeof(struct qnode_s));
node->value = n;
node->next = 0;
if (q->end)
q->end->next = node;
else
q->begin = node;
q->end = node;
}
node dequeue(queue* q)
{
node tmp = q->begin->value;
qnode second = q->begin->next;
free(q->begin);
q->begin = second;
if (!q->begin)
q->end = 0;
return tmp;
}
int queue_empty(queue* q)
{
return !q->begin;
}
void levelorder(node n, void(*f)(int))
{
queue nodequeue = {};
enqueue(&nodequeue, n);
while (!queue_empty(&nodequeue))
{
node next = dequeue(&nodequeue);
f(next->value);
if (next->left)
enqueue(&nodequeue, next->left);
if (next->right)
enqueue(&nodequeue, next->right);
}
}
void print(int n)
{
printf("%d ", n);
}
int main()
{
node n = tree(1,
tree(2,
tree(4,
tree(7, 0, 0),
0),
tree(5, 0, 0)),
tree(3,
tree(6,
tree(8, 0, 0),
tree(9, 0, 0)),
0));
printf("preorder: ");
preorder(n, print);
printf("\n");
printf("inorder: ");
inorder(n, print);
printf("\n");
printf("postorder: ");
postorder(n, print);
printf("\n");
printf("level-order: ");
levelorder(n, print);
printf("\n");
destroy_tree(n);
return 0;
}
| #![feature(box_syntax, box_patterns)]
use std::collections::VecDeque;
#[derive(Debug)]
struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
enum TraversalMethod {
PreOrder,
InOrder,
PostOrder,
LevelOrder,
}
impl<T> TreeNode<T> {
pub fn new(arr: &[[i8; 3]]) -> TreeNode<i8> {
let l = match arr[0][1] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
let r = match arr[0][2] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
TreeNode {
value: arr[0][0],
left: l,
right: r,
}
}
pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode<T>> {
match tr {
&TraversalMethod::PreOrder => self.iterative_preorder(),
&TraversalMethod::InOrder => self.iterative_inorder(),
&TraversalMethod::PostOrder => self.iterative_postorder(),
&TraversalMethod::LevelOrder => self.iterative_levelorder(),
}
}
fn iterative_preorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
}
res
}
fn iterative_inorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
let mut p = self;
loop {
loop {
match p.right {
None => {}
Some(box ref n) => stack.push(n),
}
stack.push(p);
match p.left {
None => break,
Some(box ref n) => p = n,
}
}
p = stack.pop().unwrap();
while !stack.is_empty() && p.right.is_none() {
res.push(p);
p = stack.pop().unwrap();
}
res.push(p);
if stack.is_empty() {
break;
} else {
p = stack.pop().unwrap();
}
}
res
}
fn iterative_postorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
}
let rev_iter = res.iter().rev();
let mut rev: Vec<&TreeNode<T>> = Vec::new();
for elem in rev_iter {
rev.push(elem);
}
rev
}
fn iterative_levelorder(&self) -> Vec<&TreeNode<T>> {
let mut queue: VecDeque<&TreeNode<T>> = VecDeque::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
queue.push_back(self);
while !queue.is_empty() {
let node = queue.pop_front().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => queue.push_back(n),
}
match node.right {
None => {}
Some(box ref n) => queue.push_back(n),
}
}
res
}
}
fn main() {
let arr_tree = [[1, 2, 3],
[2, 4, 5],
[3, 6, -1],
[4, 7, -1],
[5, -1, -1],
[6, 8, 9],
[7, -1, -1],
[8, -1, -1],
[9, -1, -1]];
let root = TreeNode::<i8>::new(&arr_tree);
for method_label in [(TraversalMethod::PreOrder, "pre-order:"),
(TraversalMethod::InOrder, "in-order:"),
(TraversalMethod::PostOrder, "post-order:"),
(TraversalMethod::LevelOrder, "level-order:")]
.iter() {
print!("{}\t", method_label.1);
for n in root.traverse(&method_label.0) {
print!(" {}", n.value);
}
print!("\n");
}
}
|
Trigonometric functions | #include <math.h>
#include <stdio.h>
int main() {
double pi = 4 * atan(1);
double radians = pi / 4;
double degrees = 45.0;
double temp;
printf("%f %f\n", sin(radians), sin(degrees * pi / 180));
printf("%f %f\n", cos(radians), cos(degrees * pi / 180));
printf("%f %f\n", tan(radians), tan(degrees * pi / 180));
temp = asin(sin(radians));
printf("%f %f\n", temp, temp * 180 / pi);
temp = acos(cos(radians));
printf("%f %f\n", temp, temp * 180 / pi);
temp = atan(tan(radians));
printf("%f %f\n", temp, temp * 180 / pi);
return 0;
}
|
use std::f64::consts::PI;
fn main() {
let angle_radians: f64 = PI/4.0;
let angle_degrees: f64 = 45.0;
println!("{} {}", angle_radians.sin(), angle_degrees.to_radians().sin());
println!("{} {}", angle_radians.cos(), angle_degrees.to_radians().cos());
println!("{} {}", angle_radians.tan(), angle_degrees.to_radians().tan());
let asin = angle_radians.sin().asin();
println!("{} {}", asin, asin.to_degrees());
let acos = angle_radians.cos().acos();
println!("{} {}", acos, acos.to_degrees());
let atan = angle_radians.tan().atan();
println!("{} {}", atan, atan.to_degrees());
}
|
Truncatable primes | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PRIME 1000000
char *primes;
int n_primes;
void init_primes()
{
int j;
primes = malloc(sizeof(char) * MAX_PRIME);
memset(primes, 1, MAX_PRIME);
primes[0] = primes[1] = 0;
int i = 2;
while (i * i < MAX_PRIME) {
for (j = i * 2; j < MAX_PRIME; j += i)
primes[j] = 0;
while (++i < MAX_PRIME && !primes[i]);
}
}
int left_trunc(int n)
{
int tens = 1;
while (tens < n) tens *= 10;
while (n) {
if (!primes[n]) return 0;
tens /= 10;
if (n < tens) return 0;
n %= tens;
}
return 1;
}
int right_trunc(int n)
{
while (n) {
if (!primes[n]) return 0;
n /= 10;
}
return 1;
}
int main()
{
int n;
int max_left = 0, max_right = 0;
init_primes();
for (n = MAX_PRIME - 1; !max_left; n -= 2)
if (left_trunc(n)) max_left = n;
for (n = MAX_PRIME - 1; !max_right; n -= 2)
if (right_trunc(n)) max_right = n;
printf("Left: %d; right: %d\n", max_left, max_right);
return 0;
}
| fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p += 2;
if n % p == 0 {
return false;
}
p += 4;
}
true
}
fn is_left_truncatable(p: u32) -> bool {
let mut n = 10;
let mut q = p;
while p > n {
if !is_prime(p % n) || q == p % n {
return false;
}
q = p % n;
n *= 10;
}
true
}
fn is_right_truncatable(p: u32) -> bool {
let mut q = p / 10;
while q > 0 {
if !is_prime(q) {
return false;
}
q /= 10;
}
true
}
fn main() {
let limit = 1000000;
let mut largest_left = 0;
let mut largest_right = 0;
let mut p = limit;
while p >= 2 {
if is_prime(p) && is_left_truncatable(p) {
largest_left = p;
break;
}
p -= 1;
}
println!("Largest left truncatable prime is {}", largest_left);
p = limit;
while p >= 2 {
if is_prime(p) && is_right_truncatable(p) {
largest_right = p;
break;
}
p -= 1;
}
println!("Largest right truncatable prime is {}", largest_right);
}
|
URL decoding | #include <stdio.h>
#include <string.h>
inline int ishex(int x)
{
return (x >= '0' && x <= '9') ||
(x >= 'a' && x <= 'f') ||
(x >= 'A' && x <= 'F');
}
int decode(const char *s, char *dec)
{
char *o;
const char *end = s + strlen(s);
int c;
for (o = dec; s <= end; o++) {
c = *s++;
if (c == '+') c = ' ';
else if (c == '%' && ( !ishex(*s++) ||
!ishex(*s++) ||
!sscanf(s - 2, "%2x", &c)))
return -1;
if (dec) *o = c;
}
return o - dec;
}
int main()
{
const char *url = "http%3A%2F%2ffoo+bar%2fabcd";
char out[strlen(url) + 1];
printf("length: %d\n", decode(url, 0));
puts(decode(url, out) < 0 ? "bad string" : out);
return 0;
}
| const INPUT1: &str = "http%3A%2F%2Ffoo%20bar%2F";
const INPUT2: &str = "google.com/search?q=%60Abdu%27l-Bah%C3%A1";
fn append_frag(text: &mut String, frag: &mut String) {
if !frag.is_empty() {
let encoded = frag.chars()
.collect::<Vec<char>>()
.chunks(2)
.map(|ch| {
u8::from_str_radix(&ch.iter().collect::<String>(), 16).unwrap()
}).collect::<Vec<u8>>();
text.push_str(&std::str::from_utf8(&encoded).unwrap());
frag.clear();
}
}
fn decode(text: &str) -> String {
let mut output = String::new();
let mut encoded_ch = String::new();
let mut iter = text.chars();
while let Some(ch) = iter.next() {
if ch == '%' {
encoded_ch.push_str(&format!("{}{}", iter.next().unwrap(), iter.next().unwrap()));
} else {
append_frag(&mut output, &mut encoded_ch);
output.push(ch);
}
}
append_frag(&mut output, &mut encoded_ch);
output
}
fn main() {
println!("{}", decode(INPUT1));
println!("{}", decode(INPUT2));
}
|
UTF-8 encode and decode | #include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
typedef struct {
char mask;
char lead;
uint32_t beg;
uint32_t end;
int bits_stored;
}utf_t;
utf_t * utf[] = {
[0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 },
[1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 },
[2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 },
[3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 },
[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 },
&(utf_t){0},
};
int codepoint_len(const uint32_t cp);
int utf8_len(const char ch);
char *to_utf8(const uint32_t cp);
uint32_t to_cp(const char chr[4]);
int codepoint_len(const uint32_t cp)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((cp >= (*u)->beg) && (cp <= (*u)->end)) {
break;
}
++len;
}
if(len > 4)
exit(1);
return len;
}
int utf8_len(const char ch)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((ch & ~(*u)->mask) == (*u)->lead) {
break;
}
++len;
}
if(len > 4) {
exit(1);
}
return len;
}
char *to_utf8(const uint32_t cp)
{
static char ret[5];
const int bytes = codepoint_len(cp);
int shift = utf[0]->bits_stored * (bytes - 1);
ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;
shift -= utf[0]->bits_stored;
for(int i = 1; i < bytes; ++i) {
ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;
shift -= utf[0]->bits_stored;
}
ret[bytes] = '\0';
return ret;
}
uint32_t to_cp(const char chr[4])
{
int bytes = utf8_len(*chr);
int shift = utf[0]->bits_stored * (bytes - 1);
uint32_t codep = (*chr++ & utf[bytes]->mask) << shift;
for(int i = 1; i < bytes; ++i, ++chr) {
shift -= utf[0]->bits_stored;
codep |= ((char)*chr & utf[0]->mask) << shift;
}
return codep;
}
int main(void)
{
const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};
printf("Character Unicode UTF-8 encoding (hex)\n");
printf("----------------------------------------\n");
char *utf8;
uint32_t codepoint;
for(in = input; *in; ++in) {
utf8 = to_utf8(*in);
codepoint = to_cp(utf8);
printf("%s U+%-7.4x", utf8, codepoint);
for(int i = 0; utf8[i] && i < 4; ++i) {
printf("%hhx ", utf8[i]);
}
printf("\n");
}
return 0;
}
| fn main() {
let chars = vec!('A', 'ö', 'Ж', '€', '𝄞');
chars.iter().for_each(|c| {
let mut encoded = vec![0; c.len_utf8()];
c.encode_utf8(&mut encoded);
let decoded = String::from_utf8(encoded.to_vec()).unwrap();
let encoded_string = encoded.iter().fold(String::new(), |acc, val| format!("{}{:X}", acc, val));
println!("Character: {}, Unicode:{}, UTF-8 encoded:{}, Decoded: {}", c, c.escape_unicode(), encoded_string , decoded);
});
}
|
Unbias a random generator | #include <stdio.h>
#include <stdlib.h>
int biased(int bias)
{
int r, rand_max = RAND_MAX - (RAND_MAX % bias);
while ((r = rand()) > rand_max);
return r < rand_max / bias;
}
int unbiased(int bias)
{
int a;
while ((a = biased(bias)) == biased(bias));
return a;
}
int main()
{
int b, n = 10000, cb, cu, i;
for (b = 3; b <= 6; b++) {
for (i = cb = cu = 0; i < n; i++) {
cb += biased(b);
cu += unbiased(b);
}
printf("bias %d: %5.3f%% vs %5.3f%%\n", b,
100. * cb / n, 100. * cu / n);
}
return 0;
}
| #![feature(inclusive_range_syntax)]
extern crate rand;
use rand::Rng;
fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize {
rng.gen_weighted_bool(n) as usize
}
fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize {
let mut bit = rand_n(rng, n);
while bit == rand_n(rng, n) {
bit = rand_n(rng, n);
}
bit
}
fn main() {
const SAMPLES: usize = 100_000;
let mut rng = rand::weak_rng();
println!(" Bias rand_n unbiased");
for n in 3..=6 {
let mut count_biased = 0;
let mut count_unbiased = 0;
for _ in 0..SAMPLES {
count_biased += rand_n(&mut rng, n);
count_unbiased += unbiased(&mut rng, n);
}
let b_percentage = 100.0 * count_biased as f64 / SAMPLES as f64;
let ub_percentage = 100.0 * count_unbiased as f64 / SAMPLES as f64;
println!(
"bias {}: {:0.2}% {:0.2}%",
n, b_percentage, ub_percentage
);
}
}
|
Undefined values | #include <stdio.h>
#include <stdlib.h>
int main()
{
int junk, *junkp;
printf("junk: %d\n", junk);
junkp = malloc(sizeof *junkp);
if (junkp)
printf("*junkp: %d\n", *junkp);
return 0;
}
| use std::ptr;
let p: *const i32 = ptr::null();
assert!(p.is_null());
|
Universal Turing machine | #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
enum {
LEFT,
RIGHT,
STAY
};
typedef struct {
int state1;
int symbol1;
int symbol2;
int dir;
int state2;
} transition_t;
typedef struct tape_t tape_t;
struct tape_t {
int symbol;
tape_t *left;
tape_t *right;
};
typedef struct {
int states_len;
char **states;
int final_states_len;
int *final_states;
int symbols_len;
char *symbols;
int blank;
int state;
int tape_len;
tape_t *tape;
int transitions_len;
transition_t ***transitions;
} turing_t;
int state_index (turing_t *t, char *state) {
int i;
for (i = 0; i < t->states_len; i++) {
if (!strcmp(t->states[i], state)) {
return i;
}
}
return 0;
}
int symbol_index (turing_t *t, char symbol) {
int i;
for (i = 0; i < t->symbols_len; i++) {
if (t->symbols[i] == symbol) {
return i;
}
}
return 0;
}
void move (turing_t *t, int dir) {
tape_t *orig = t->tape;
if (dir == RIGHT) {
if (orig && orig->right) {
t->tape = orig->right;
}
else {
t->tape = calloc(1, sizeof (tape_t));
t->tape->symbol = t->blank;
if (orig) {
t->tape->left = orig;
orig->right = t->tape;
}
}
}
else if (dir == LEFT) {
if (orig && orig->left) {
t->tape = orig->left;
}
else {
t->tape = calloc(1, sizeof (tape_t));
t->tape->symbol = t->blank;
if (orig) {
t->tape->right = orig;
orig->left = t->tape;
}
}
}
}
turing_t *create (int states_len, ...) {
va_list args;
va_start(args, states_len);
turing_t *t = malloc(sizeof (turing_t));
t->states_len = states_len;
t->states = malloc(states_len * sizeof (char *));
int i;
for (i = 0; i < states_len; i++) {
t->states[i] = va_arg(args, char *);
}
t->final_states_len = va_arg(args, int);
t->final_states = malloc(t->final_states_len * sizeof (int));
for (i = 0; i < t->final_states_len; i++) {
t->final_states[i] = state_index(t, va_arg(args, char *));
}
t->symbols_len = va_arg(args, int);
t->symbols = malloc(t->symbols_len);
for (i = 0; i < t->symbols_len; i++) {
t->symbols[i] = va_arg(args, int);
}
t->blank = symbol_index(t, va_arg(args, int));
t->state = state_index(t, va_arg(args, char *));
t->tape_len = va_arg(args, int);
t->tape = NULL;
for (i = 0; i < t->tape_len; i++) {
move(t, RIGHT);
t->tape->symbol = symbol_index(t, va_arg(args, int));
}
if (!t->tape_len) {
move(t, RIGHT);
}
while (t->tape->left) {
t->tape = t->tape->left;
}
t->transitions_len = va_arg(args, int);
t->transitions = malloc(t->states_len * sizeof (transition_t **));
for (i = 0; i < t->states_len; i++) {
t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));
}
for (i = 0; i < t->transitions_len; i++) {
transition_t *tran = malloc(sizeof (transition_t));
tran->state1 = state_index(t, va_arg(args, char *));
tran->symbol1 = symbol_index(t, va_arg(args, int));
tran->symbol2 = symbol_index(t, va_arg(args, int));
tran->dir = va_arg(args, int);
tran->state2 = state_index(t, va_arg(args, char *));
t->transitions[tran->state1][tran->symbol1] = tran;
}
va_end(args);
return t;
}
void print_state (turing_t *t) {
printf("%-10s ", t->states[t->state]);
tape_t *tape = t->tape;
while (tape->left) {
tape = tape->left;
}
while (tape) {
if (tape == t->tape) {
printf("[%c]", t->symbols[tape->symbol]);
}
else {
printf(" %c ", t->symbols[tape->symbol]);
}
tape = tape->right;
}
printf("\n");
}
void run (turing_t *t) {
int i;
while (1) {
print_state(t);
for (i = 0; i < t->final_states_len; i++) {
if (t->final_states[i] == t->state) {
return;
}
}
transition_t *tran = t->transitions[t->state][t->tape->symbol];
t->tape->symbol = tran->symbol2;
move(t, tran->dir);
t->state = tran->state2;
}
}
int main () {
printf("Simple incrementer\n");
turing_t *t = create(
2, "q0", "qf",
1, "qf",
2, 'B', '1',
'B',
"q0",
3, '1', '1', '1',
2,
"q0", '1', '1', RIGHT, "q0",
"q0", 'B', '1', STAY, "qf"
);
run(t);
printf("\nThree-state busy beaver\n");
t = create(
4, "a", "b", "c", "halt",
1, "halt",
2, '0', '1',
'0',
"a",
0,
6,
"a", '0', '1', RIGHT, "b",
"a", '1', '1', LEFT, "c",
"b", '0', '1', LEFT, "a",
"b", '1', '1', RIGHT, "b",
"c", '0', '1', LEFT, "b",
"c", '1', '1', STAY, "halt"
);
run(t);
return 0;
printf("\nFive-state two-symbol probable busy beaver\n");
t = create(
6, "A", "B", "C", "D", "E", "H",
1, "H",
2, '0', '1',
'0',
"A",
0,
10,
"A", '0', '1', RIGHT, "B",
"A", '1', '1', LEFT, "C",
"B", '0', '1', RIGHT, "C",
"B", '1', '1', RIGHT, "B",
"C", '0', '1', RIGHT, "D",
"C", '1', '0', LEFT, "E",
"D", '0', '1', LEFT, "A",
"D", '1', '1', LEFT, "D",
"E", '0', '1', STAY, "H",
"E", '1', '0', LEFT, "A"
);
run(t);
}
| use std::collections::VecDeque;
use std::fmt::{Display, Formatter, Result};
fn main() {
println!("Simple incrementer");
let rules_si = vec!(
Rule::new("q0", '1', '1', Direction::Right, "q0"),
Rule::new("q0", 'B', '1', Direction::Stay, "qf")
);
let states_si = vec!("q0", "qf");
let terminating_states_si = vec!("qf");
let permissible_symbols_si = vec!('B', '1');
let mut tm_si = TM::new(states_si, "q0", terminating_states_si, permissible_symbols_si, 'B', rules_si, "111");
while !tm_si.is_done() {
println!("{}", tm_si);
tm_si.step();
}
println!("___________________");
println!("Three-state busy beaver");
let rules_bb3 = vec!(
Rule::new("a", '0', '1', Direction::Right, "b"),
Rule::new("a", '1', '1', Direction::Left, "c"),
Rule::new("b", '0', '1', Direction::Left, "a"),
Rule::new("b", '1', '1', Direction::Right, "b"),
Rule::new("c", '0', '1', Direction::Left, "b"),
Rule::new("c", '1', '1', Direction::Stay, "halt"),
);
let states_bb3 = vec!("a", "b", "c", "halt");
let terminating_states_bb3 = vec!("halt");
let permissible_symbols_bb3 = vec!('0', '1');
let mut tm_bb3 = TM::new(states_bb3 ,"a", terminating_states_bb3, permissible_symbols_bb3, '0', rules_bb3, "0");
while !tm_bb3.is_done() {
println!("{}", tm_bb3);
tm_bb3.step();
}
println!("{}", tm_bb3);
println!("___________________");
println!("Five-state busy beaver");
let rules_bb5 = vec!(
Rule::new("A", '0', '1', Direction::Right, "B"),
Rule::new("A", '1', '1', Direction::Left, "C"),
Rule::new("B", '0', '1', Direction::Right, "C"),
Rule::new("B", '1', '1', Direction::Right, "B"),
Rule::new("C", '0', '1', Direction::Right, "D"),
Rule::new("C", '1', '0', Direction::Left, "E"),
Rule::new("D", '0', '1', Direction::Left, "A"),
Rule::new("D", '1', '1', Direction::Left, "D"),
Rule::new("E", '0', '1', Direction::Stay, "H"),
Rule::new("E", '1', '0', Direction::Left, "A"),
);
let states_bb5 = vec!("A", "B", "C", "D", "E", "H");
let terminating_states_bb5 = vec!("H");
let permissible_symbols_bb5 = vec!('0', '1');
let mut tm_bb5 = TM::new(states_bb5 ,"A", terminating_states_bb5, permissible_symbols_bb5, '0', rules_bb5, "0");
let mut steps = 0;
while !tm_bb5.is_done() {
tm_bb5.step();
steps += 1;
}
println!("Steps: {}", steps);
println!("Band lenght: {}", tm_bb5.band.len());
}
struct TM<'a> {
state: &'a str,
terminating_states: Vec<&'a str>,
rules: Vec<Rule<'a>>,
band: VecDeque<char>,
head: usize,
blank: char,
}
struct Rule<'a> {
state: &'a str,
read: char,
write: char,
dir: Direction,
new_state: &'a str,
}
enum Direction{
Left,
Right,
Stay,
}
impl<'a> TM<'a> {
fn new(_states: Vec<&'a str>, initial_state: &'a str, terminating_states: Vec<&'a str>, _permissible_symbols: Vec<char>, blank: char, rules: Vec<Rule<'a>>, input: &str) -> Self {
Self { state: initial_state, terminating_states, rules, band: input.chars().collect::<VecDeque<_>>(), head: 0, blank }
}
fn is_done(&self) -> bool {
self.terminating_states.contains(&self.state)
}
fn step(&mut self) {
let field = self.band.get(self.head).unwrap();
let rule = self.rules.iter().find(|rule| rule.state == self.state && &rule.read == field).unwrap();
let field = self.band.get_mut(self.head).unwrap();
*field = rule.write;
self.state = rule.new_state;
match rule.dir {
Direction::Left => {
if self.head == 0 {
self.band.push_front(self.blank)
} else {
self.head -= 1;
}
},
Direction::Right => {
if self.head == self.band.len() - 1 {
self.band.push_back(self.blank)
}
self.head += 1;
},
Direction::Stay => {},
}
}
}
impl<'a> Display for TM<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let band = self.band.iter().enumerate().map(|(i, c)| {
if i == self.head {
format!("[{}]", c)
} else {
format!(" {} ", c)
}
}).fold(String::new(), |acc, val| acc + &val);
write!(f, "{}\t{}", self.state, band)
}
}
impl<'a> Rule<'a> {
fn new(state: &'a str, read: char, write: char, dir: Direction, new_state: &'a str) -> Self {
Self { state, read, write, dir, new_state }
}
}
|
Unix_ls | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
int cmpstr(const void *a, const void *b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
int main(void)
{
DIR *basedir;
char path[PATH_MAX];
struct dirent *entry;
char **dirnames;
int diralloc = 128;
int dirsize = 0;
if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
perror("malloc error:");
return 1;
}
if (!getcwd(path, PATH_MAX)) {
perror("getcwd error:");
return 1;
}
if (!(basedir = opendir(path))) {
perror("opendir error:");
return 1;
}
while ((entry = readdir(basedir))) {
if (dirsize >= diralloc) {
diralloc *= 2;
if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
perror("realloc error:");
return 1;
}
}
dirnames[dirsize++] = strdup(entry->d_name);
}
qsort(dirnames, dirsize, sizeof(char*), cmpstr);
int i;
for (i = 0; i < dirsize; ++i) {
if (dirnames[i][0] != '.') {
printf("%s\n", dirnames[i]);
}
}
for (i = 0; i < dirsize; ++i)
free(dirnames[i]);
free(dirnames);
closedir(basedir);
return 0;
}
| use std::{env, fmt, fs, process};
use std::io::{self, Write};
use std::path::Path;
fn main() {
let cur = env::current_dir().unwrap_or_else(|e| exit_err(e, 1));
let arg = env::args().nth(1);
print_files(arg.as_ref().map_or(cur.as_path(), |p| Path::new(p)))
.unwrap_or_else(|e| exit_err(e, 2));
}
#[inline]
fn print_files(path: &Path) -> io::Result<()> {
for x in try!(fs::read_dir(path)) {
println!("{}", try!(x).file_name().to_string_lossy());
}
Ok(())
}
#[inline]
fn exit_err<T>(msg: T, code: i32) -> ! where T: fmt::Display {
writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
process::exit(code)
}
|
User input_Text | #include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[BUFSIZ];
puts("Enter a string: ");
fgets(str, sizeof(str), stdin);
long num;
char buf[BUFSIZ];
do
{
puts("Enter 75000: ");
fgets(buf, sizeof(buf), stdin);
num = strtol(buf, NULL, 10);
} while (num != 75000);
return EXIT_SUCCESS;
}
| use std::io::{self, Write};
use std::fmt::Display;
use std::process;
fn main() {
let s = grab_input("Give me a string")
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));
println!("You entered: {}", s.trim());
let n: i32 = grab_input("Give me an integer")
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)))
.trim()
.parse()
.unwrap_or_else(|e| exit_err(&e, 2));
println!("You entered: {}", n);
}
fn grab_input(msg: &str) -> io::Result<String> {
let mut buf = String::new();
print!("{}: ", msg);
try!(io::stdout().flush());
try!(io::stdin().read_line(&mut buf));
Ok(buf)
}
fn exit_err<T: Display>(msg: T, code: i32) -> ! {
let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
process::exit(code)
}
|
Van Eck sequence | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| fn van_eck_sequence() -> impl std::iter::Iterator<Item = i32> {
let mut index = 0;
let mut last_term = 0;
let mut last_pos = std::collections::HashMap::new();
std::iter::from_fn(move || {
let result = last_term;
let mut next_term = 0;
if let Some(v) = last_pos.get_mut(&last_term) {
next_term = index - *v;
*v = index;
} else {
last_pos.insert(last_term, index);
}
last_term = next_term;
index += 1;
Some(result)
})
}
fn main() {
let mut v = van_eck_sequence().take(1000);
println!("First 10 terms of the Van Eck sequence:");
for n in v.by_ref().take(10) {
print!("{} ", n);
}
println!("\nTerms 991 to 1000 of the Van Eck sequence:");
for n in v.skip(980) {
print!("{} ", n);
}
println!();
}
|
Van der Corput sequence | #include <stdio.h>
void vc(int n, int base, int *num, int *denom)
{
int p = 0, q = 1;
while (n) {
p = p * base + (n % base);
q *= base;
n /= base;
}
*num = p;
*denom = q;
while (p) { n = p; p = q % p; q = n; }
*num /= q;
*denom /= q;
}
int main()
{
int d, n, i, b;
for (b = 2; b < 6; b++) {
printf("base %d:", b);
for (i = 0; i < 10; i++) {
vc(i, b, &n, &d);
if (n) printf(" %d/%d", n, d);
else printf(" 0");
}
printf("\n");
}
return 0;
}
|
pub fn corput(nth: usize, base: usize) -> f64 {
let mut n = nth;
let mut q: f64 = 0.0;
let mut bk: f64 = 1.0 / (base as f64);
while n > 0_usize {
q += ((n % base) as f64)*bk;
n /= base;
bk /= base as f64;
}
q
}
fn main() {
for base in 2_usize..=5_usize {
print!("Base {}:", base);
for i in 1_usize..=10_usize {
let c = corput(i, base);
print!(" {:.6}", c)
}
println!("");
}
}
|
Variables | int j;
| let var01;
let var02: u32;
let var03 = 5;
let var04 = 5u8;
let var05: i8 = 5;
let var06: u8 = 5u8;
var01 = var05;
var02 = 9u32;
|
Variadic function | #include <stdio.h>
#include <stdarg.h>
void varstrings(int count, ...)
{
va_list args;
va_start(args, count);
while (count--)
puts(va_arg(args, const char *));
va_end(args);
}
varstrings(5, "Mary", "had", "a", "little", "lamb");
|
macro_rules! print_all {
($($args:expr),*) => { $( println!("{}", $args); )* }
}
fn main() {
print_all!("Rosetta", "Code", "Is", "Awesome!");
}
|
Vector products | #include<stdio.h>
typedef struct{
float i,j,k;
}Vector;
Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13};
float dotProduct(Vector a, Vector b)
{
return a.i*b.i+a.j*b.j+a.k*b.k;
}
Vector crossProduct(Vector a,Vector b)
{
Vector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i};
return c;
}
float scalarTripleProduct(Vector a,Vector b,Vector c)
{
return dotProduct(a,crossProduct(b,c));
}
Vector vectorTripleProduct(Vector a,Vector b,Vector c)
{
return crossProduct(a,crossProduct(b,c));
}
void printVector(Vector a)
{
printf("( %f, %f, %f)",a.i,a.j,a.k);
}
int main()
{
printf("\n a = "); printVector(a);
printf("\n b = "); printVector(b);
printf("\n c = "); printVector(c);
printf("\n a . b = %f",dotProduct(a,b));
printf("\n a x b = "); printVector(crossProduct(a,b));
printf("\n a . (b x c) = %f",scalarTripleProduct(a,b,c));
printf("\n a x (b x c) = "); printVector(vectorTripleProduct(a,b,c));
return 0;
}
| #[derive(Debug)]
struct Vector {
x: f64,
y: f64,
z: f64,
}
impl Vector {
fn new(x: f64, y: f64, z: f64) -> Self {
Vector {
x: x,
y: y,
z: z,
}
}
fn dot_product(&self, other: &Vector) -> f64 {
(self.x * other.x) + (self.y * other.y) + (self.z * other.z)
}
fn cross_product(&self, other: &Vector) -> Vector {
Vector::new(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
}
fn scalar_triple_product(&self, b: &Vector, c: &Vector) -> f64 {
self.dot_product(&b.cross_product(&c))
}
fn vector_triple_product(&self, b: &Vector, c: &Vector) -> Vector {
self.cross_product(&b.cross_product(&c))
}
}
fn main(){
let a = Vector::new(3.0, 4.0, 5.0);
let b = Vector::new(4.0, 3.0, 5.0);
let c = Vector::new(-5.0, -12.0, -13.0);
println!("a . b = {}", a.dot_product(&b));
println!("a x b = {:?}", a.cross_product(&b));
println!("a . (b x c) = {}", a.scalar_triple_product(&b, &c));
println!("a x (b x c) = {:?}", a.vector_triple_product(&b, &c));
}
|
Vigenère cipher | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include <getopt.h>
#define NUMLETTERS 26
#define BUFSIZE 4096
char *get_input(void);
int main(int argc, char *argv[])
{
char const usage[] = "Usage: vinigere [-d] key";
char sign = 1;
char const plainmsg[] = "Plain text: ";
char const cryptmsg[] = "Cipher text: ";
bool encrypt = true;
int opt;
while ((opt = getopt(argc, argv, "d")) != -1) {
switch (opt) {
case 'd':
sign = -1;
encrypt = false;
break;
default:
fprintf(stderr, "Unrecogized command line argument:'-%i'\n", opt);
fprintf(stderr, "\n%s\n", usage);
return 1;
}
}
if (argc - optind != 1) {
fprintf(stderr, "%s requires one argument and one only\n", argv[0]);
fprintf(stderr, "\n%s\n", usage);
return 1;
}
char const *const restrict key = argv[optind];
size_t const keylen = strlen(key);
char shifts[keylen];
char const *restrict plaintext = NULL;
for (size_t i = 0; i < keylen; i++) {
if (!(isalpha(key[i]))) {
fprintf(stderr, "Invalid key\n");
return 2;
}
char const charcase = (isupper(key[i])) ? 'A' : 'a';
shifts[i] = (key[i] - charcase) * sign;
}
do {
fflush(stdout);
printf("%s", (encrypt) ? plainmsg : cryptmsg);
plaintext = get_input();
if (plaintext == NULL) {
fprintf(stderr, "Error getting input\n");
return 4;
}
} while (strcmp(plaintext, "") == 0);
size_t const plainlen = strlen(plaintext);
char* const restrict ciphertext = calloc(plainlen + 1, sizeof *ciphertext);
if (ciphertext == NULL) {
fprintf(stderr, "Memory error\n");
return 5;
}
for (size_t i = 0, j = 0; i < plainlen; i++) {
if (!(isalpha(plaintext[i]))) {
ciphertext[i] = plaintext[i];
continue;
}
char const charcase = (isupper(plaintext[i])) ? 'A' : 'a';
ciphertext[i] = ((plaintext[i] + shifts[j] - charcase + NUMLETTERS) % NUMLETTERS) + charcase;
j = (j+1) % keylen;
}
ciphertext[plainlen] = '\0';
printf("%s%s\n", (encrypt) ? cryptmsg : plainmsg, ciphertext);
free(ciphertext);
free((char*) plaintext);
return 0;
}
char *get_input(void) {
char *const restrict buf = malloc(BUFSIZE * sizeof (char));
if (buf == NULL) {
return NULL;
}
fgets(buf, BUFSIZE, stdin);
size_t const len = strlen(buf);
if (buf[len - 1] == '\n') buf[len - 1] = '\0';
return buf;
}
| use std::ascii::AsciiExt;
static A: u8 = 'A' as u8;
fn uppercase_and_filter(input: &str) -> Vec<u8> {
let alphabet = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let mut result = Vec::new();
for c in input.chars() {
if alphabet.iter().any(|&x| x as char == c) {
result.push(c.to_ascii_uppercase() as u8);
}
}
return result;
}
fn vigenere(key: &str, text: &str, is_encoding: bool) -> String {
let key_bytes = uppercase_and_filter(key);
let text_bytes = uppercase_and_filter(text);
let mut result_bytes = Vec::new();
for (i, c) in text_bytes.iter().enumerate() {
let c2 = if is_encoding {
(c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A
} else {
(c + 26 - key_bytes[i % key_bytes.len()]) % 26 + A
};
result_bytes.push(c2);
}
String::from_utf8(result_bytes).unwrap()
}
fn main() {
let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let key = "VIGENERECIPHER";
println!("Text: {}", text);
println!("Key: {}", key);
let encoded = vigenere(key, text, true);
println!("Code: {}", encoded);
let decoded = vigenere(key, &encoded, false);
println!("Back: {}", decoded);
}
|
Visualize a tree | #include <stdio.h>
#include <stdlib.h>
typedef struct stem_t *stem;
struct stem_t { const char *str; stem next; };
void tree(int root, stem head)
{
static const char *sdown = " |", *slast = " `", *snone = " ";
struct stem_t col = {0, 0}, *tail;
for (tail = head; tail; tail = tail->next) {
printf("%s", tail->str);
if (!tail->next) break;
}
printf("--%d\n", root);
if (root <= 1) return;
if (tail && tail->str == slast)
tail->str = snone;
if (!tail) tail = head = &col;
else tail->next = &col;
while (root) {
int r = 1 + (rand() % root);
root -= r;
col.str = root ? sdown : slast;
tree(r, head);
}
tail->next = 0;
}
int main(int c, char**v)
{
int n;
if (c < 2 || (n = atoi(v[1])) < 0) n = 8;
tree(n, 0);
return 0;
}
| extern crate rustc_serialize;
extern crate term_painter;
use rustc_serialize::json;
use std::fmt::{Debug, Display, Formatter, Result};
use term_painter::ToStyle;
use term_painter::Color::*;
type NodePtr = Option<usize>;
#[derive(Debug, PartialEq, Clone, Copy)]
enum Side {
Left,
Right,
Up,
}
#[derive(Debug, PartialEq, Clone, Copy)]
enum DisplayElement {
TrunkSpace,
SpaceLeft,
SpaceRight,
SpaceSpace,
Root,
}
impl DisplayElement {
fn string(&self) -> String {
match *self {
DisplayElement::TrunkSpace => " │ ".to_string(),
DisplayElement::SpaceRight => " ┌───".to_string(),
DisplayElement::SpaceLeft => " └───".to_string(),
DisplayElement::SpaceSpace => " ".to_string(),
DisplayElement::Root => "├──".to_string(),
}
}
}
#[derive(Debug, Clone, Copy, RustcDecodable, RustcEncodable)]
struct Node<K, V> {
key: K,
value: V,
left: NodePtr,
right: NodePtr,
up: NodePtr,
}
impl<K: Ord + Copy, V: Copy> Node<K, V> {
pub fn get_ptr(&self, side: Side) -> NodePtr {
match side {
Side::Up => self.up,
Side::Left => self.left,
_ => self.right,
}
}
}
#[derive(Debug, RustcDecodable, RustcEncodable)]
struct Tree<K, V> {
root: NodePtr,
store: Vec<Node<K, V>>,
}
impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Tree<K, V> {
pub fn get_node(&self, np: NodePtr) -> Node<K, V> {
assert!(np.is_some());
self.store[np.unwrap()]
}
pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr {
assert!(np.is_some());
self.store[np.unwrap()].get_ptr(side)
}
fn display(&self, p: NodePtr, side: Side, e: &Vec<DisplayElement>, f: &mut Formatter) {
if p.is_none() {
return;
}
let mut elems = e.clone();
let node = self.get_node(p);
let mut tail = DisplayElement::SpaceSpace;
if node.up != self.root {
if side == Side::Left && node.right.is_some() {
elems.push(DisplayElement::TrunkSpace);
} else {
elems.push(DisplayElement::SpaceSpace);
}
}
let hindex = elems.len() - 1;
self.display(node.right, Side::Right, &elems, f);
if p == self.root {
elems[hindex] = DisplayElement::Root;
tail = DisplayElement::TrunkSpace;
} else if side == Side::Right {
elems[hindex] = DisplayElement::SpaceRight;
tail = DisplayElement::TrunkSpace;
} else if side == Side::Left {
elems[hindex] = DisplayElement::SpaceLeft;
let parent = self.get_node(node.up);
if parent.up.is_some() && self.get_pointer(parent.up, Side::Right) == node.up {
elems[hindex - 1] = DisplayElement::TrunkSpace;
}
}
for e in elems.clone() {
let _ = write!(f, "{}", e.string());
}
let _ = write!(f,
"{key:>width$} ",
key = Green.bold().paint(node.key),
width = 2);
let _ = write!(f,
"{value:>width$}\n",
value = Blue.bold().paint(format!("{:.*}", 2, node.value)),
width = 4);
elems[hindex] = tail;
self.display(node.left, Side::Left, &elems, f);
}
}
impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Display for Tree<K, V> {
fn fmt(&self, f: &mut Formatter) -> Result {
if self.root.is_none() {
write!(f, "[empty]")
} else {
let mut v: Vec<DisplayElement> = Vec::new();
self.display(self.root, Side::Up, &mut v, f);
Ok(())
}
}
}
fn main() {
let encoded = r#"{"root":0,"store":[{"key":0,"value":0.45,"left":1,"right":3,
"up":null},{"key":-8,"value":-0.94,"left":7,"right":2,"up":0}, {"key":-1,
"value":0.15,"left":8,"right":null,"up":1},{"key":7, "value":-0.29,"left":4,
"right":9,"up":0},{"key":5,"value":0.80,"left":5,"right":null,"up":3},
{"key":4,"value":-0.85,"left":6,"right":null,"up":4},{"key":3,"value":-0.46,
"left":null,"right":null,"up":5},{"key":-10,"value":-0.85,"left":null,
"right":13,"up":1},{"key":-6,"value":-0.42,"left":null,"right":10,"up":2},
{"key":9,"value":0.63,"left":12,"right":null,"up":3},{"key":-3,"value":-0.83,
"left":null,"right":11,"up":8},{"key":-2,"value":0.75,"left":null,"right":null,
"up":10},{"key":8,"value":-0.48,"left":null,"right":null,"up":9},{"key":-9,
"value":0.53,"left":null,"right":null,"up":7}]}"#;
let tree: Tree<i32, f32> = json::decode(&encoded).unwrap();
println!("{}", tree);
}
|
Walk a directory_Non-recursively | #include <sys/types.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_BADOPEN,
};
int walker(const char *dir, const char *pattern)
{
struct dirent *entry;
regex_t reg;
DIR *d;
if (regcomp(®, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
if (!(d = opendir(dir)))
return WALK_BADOPEN;
while (entry = readdir(d))
if (!regexec(®, entry->d_name, 0, NULL, 0))
puts(entry->d_name);
closedir(d);
regfree(®);
return WALK_OK;
}
int main()
{
walker(".", ".\\.c$");
return 0;
}
| extern crate docopt;
extern crate regex;
extern crate rustc_serialize;
use docopt::Docopt;
use regex::Regex;
const USAGE: &'static str = "
Usage: rosetta <pattern>
Walks the directory tree starting with the current working directory and
print filenames matching <pattern>.
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_pattern: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let re = Regex::new(&args.arg_pattern).unwrap();
let paths = std::fs::read_dir(".").unwrap();
for path in paths {
let path = path.unwrap().path();
let path = path.to_str().unwrap();
if re.is_match(path) {
println!("{}", path);
}
}
}
|
Walk a directory_Recursively | #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
| #![feature(fs_walk)]
use std::fs;
use std::path::Path;
fn main() {
for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() {
let p = f.unwrap().path();
if p.extension().unwrap_or("".as_ref()) == "mp3" {
println!("{:?}", p);
}
}
}
|
Web scraping | #include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#include <sys/types.h>
#include <regex.h>
#define BUFSIZE 16384
size_t lr = 0;
size_t filterit(void *ptr, size_t size, size_t nmemb, void *stream)
{
if ( (lr + size*nmemb) > BUFSIZE ) return BUFSIZE;
memcpy(stream+lr, ptr, size*nmemb);
lr += size*nmemb;
return size*nmemb;
}
int main()
{
CURL *curlHandle;
char buffer[BUFSIZE];
regmatch_t amatch;
regex_t cregex;
curlHandle = curl_easy_init();
curl_easy_setopt(curlHandle, CURLOPT_URL, "http:
curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, filterit);
curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, buffer);
int success = curl_easy_perform(curlHandle);
curl_easy_cleanup(curlHandle);
buffer[lr] = 0;
regcomp(&cregex, " UTC", REG_NEWLINE);
regexec(&cregex, buffer, 1, &amatch, 0);
int bi = amatch.rm_so;
while ( bi-- > 0 )
if ( memcmp(&buffer[bi], "<BR>", 4) == 0 ) break;
buffer[amatch.rm_eo] = 0;
printf("%s\n", &buffer[bi+4]);
regfree(&cregex);
return 0;
}
|
use std::io::Read;
use regex::Regex;
fn main() {
let client = reqwest::blocking::Client::new();
let site = "https:
let mut res = client.get(site).send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
let re = Regex::new(r#"<td>UTC</td><td>(.*Z)</td>"#).unwrap();
let caps = re.captures(&body).unwrap();
println!("Result : {:?}", caps.get(1).unwrap().as_str());
}
|
Wieferich primes | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#define LIMIT 5000
static bool PRIMES[LIMIT];
static void prime_sieve() {
uint64_t p;
int i;
PRIMES[0] = false;
PRIMES[1] = false;
for (i = 2; i < LIMIT; i++) {
PRIMES[i] = true;
}
for (i = 4; i < LIMIT; i += 2) {
PRIMES[i] = false;
}
for (p = 3;; p += 2) {
uint64_t q = p * p;
if (q >= LIMIT) {
break;
}
if (PRIMES[p]) {
uint64_t inc = 2 * p;
for (; q < LIMIT; q += inc) {
PRIMES[q] = false;
}
}
}
}
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
uint64_t result = 1;
if (mod == 1) {
return 0;
}
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
}
return result;
}
void wieferich_primes() {
uint64_t p;
for (p = 2; p < LIMIT; ++p) {
if (PRIMES[p] && modpow(2, p - 1, p * p) == 1) {
printf("%lld\n", p);
}
}
}
int main() {
prime_sieve();
printf("Wieferich primes less than %d:\n", LIMIT);
wieferich_primes();
return 0;
}
|
fn wieferich_primes(limit: usize) -> impl std::iter::Iterator<Item = usize> {
primal::Primes::all()
.take_while(move |x| *x < limit)
.filter(|x| mod_exp::mod_exp(2, *x - 1, *x * *x) == 1)
}
fn main() {
let limit = 5000;
println!("Wieferich primes less than {}:", limit);
for p in wieferich_primes(limit) {
println!("{}", p);
}
}
|
Window creation |
#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"
int main()
{
SDL_Surface *screen;
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
atexit(SDL_Quit);
screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE );
return 0;
}
| use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
fn main() {
let event_loop = EventLoop::new();
let _win = WindowBuilder::new()
.with_title("Window")
.build(&event_loop).unwrap();
event_loop.run(move |ev, _, flow| {
match ev {
Event::WindowEvent {
event: WindowEvent::CloseRequested, ..
} => {
*flow = ControlFlow::Exit;
}
_ => {}
}
});
}
|
Word frequency | #include <stdbool.h>
#include <stdio.h>
#include <glib.h>
typedef struct word_count_tag {
const char* word;
size_t count;
} word_count;
int compare_word_count(const void* p1, const void* p2) {
const word_count* w1 = p1;
const word_count* w2 = p2;
if (w1->count > w2->count)
return -1;
if (w1->count < w2->count)
return 1;
return 0;
}
bool get_top_words(const char* filename, size_t count) {
GError* error = NULL;
GMappedFile* mapped_file = g_mapped_file_new(filename, FALSE, &error);
if (mapped_file == NULL) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return false;
}
const char* text = g_mapped_file_get_contents(mapped_file);
if (text == NULL) {
fprintf(stderr, "File %s is empty\n", filename);
g_mapped_file_unref(mapped_file);
return false;
}
gsize file_size = g_mapped_file_get_length(mapped_file);
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, g_free);
GRegex* regex = g_regex_new("\\w+", 0, 0, NULL);
GMatchInfo* match_info;
g_regex_match_full(regex, text, file_size, 0, 0, &match_info, NULL);
while (g_match_info_matches(match_info)) {
char* word = g_match_info_fetch(match_info, 0);
char* lower = g_utf8_strdown(word, -1);
g_free(word);
size_t* count = g_hash_table_lookup(ht, lower);
if (count != NULL) {
++*count;
g_free(lower);
} else {
count = g_new(size_t, 1);
*count = 1;
g_hash_table_insert(ht, lower, count);
}
g_match_info_next(match_info, NULL);
}
g_match_info_free(match_info);
g_regex_unref(regex);
g_mapped_file_unref(mapped_file);
size_t size = g_hash_table_size(ht);
word_count* words = g_new(word_count, size);
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
for (size_t i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {
words[i].word = key;
words[i].count = *(size_t*)value;
}
qsort(words, size, sizeof(word_count), compare_word_count);
if (count > size)
count = size;
printf("Top %lu words\n", count);
printf("Rank\tCount\tWord\n");
for (size_t i = 0; i < count; ++i)
printf("%lu\t%lu\t%s\n", i + 1, words[i].count, words[i].word);
g_free(words);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", argv[0]);
return EXIT_FAILURE;
}
if (!get_top_words(argv[1], 10))
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| use std::cmp::Reverse;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
extern crate regex;
use regex::Regex;
fn word_count(file: File, n: usize) {
let word_regex = Regex::new("(?i)[a-z']+").unwrap();
let mut words = HashMap::new();
for line in BufReader::new(file).lines() {
word_regex
.find_iter(&line.expect("Read error"))
.map(|m| m.as_str())
.for_each(|word| {
*words.entry(word.to_lowercase()).or_insert(0) += 1;
});
}
let mut words: Vec<_> = words.iter().collect();
words.sort_unstable_by_key(|&(word, count)| (Reverse(count), word));
for (word, count) in words.iter().take(n) {
println!("{:8} {:>8}", word, count);
}
}
fn main() {
word_count(File::open("135-0.txt").expect("File open error"), 10)
}
|
Word wrap | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
const char *string = "In olden times when wishing still helped one, there lived a king "
"whose daughters were all beautiful, but the youngest was so beautiful "
"that the sun itself, which has seen so much, was astonished whenever "
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "
"forest, and under an old lime-tree in the forest was a well, and when "
"the day was very warm, the king's child went out into the forest and "
"sat down by the side of the cool-fountain, and when she was bored she "
"took a golden ball, and threw it up on high and caught it, and this "
"ball was her favorite plaything.";
#define PENALTY_LONG 100
#define PENALTY_SHORT 1
typedef struct word_t {
const char *s;
int len;
} *word;
word make_word_list(const char *s, int *n)
{
int max_n = 0;
word words = 0;
*n = 0;
while (1) {
while (*s && isspace(*s)) s++;
if (!*s) break;
if (*n >= max_n) {
if (!(max_n *= 2)) max_n = 2;
words = realloc(words, max_n * sizeof(*words));
}
words[*n].s = s;
while (*s && !isspace(*s)) s++;
words[*n].len = s - words[*n].s;
(*n) ++;
}
return words;
}
int greedy_wrap(word words, int count, int cols, int *breaks)
{
int score = 0, line, i, j, d;
i = j = line = 0;
while (1) {
if (i == count) {
breaks[j++] = i;
break;
}
if (!line) {
line = words[i++].len;
continue;
}
if (line + words[i].len < cols) {
line += words[i++].len + 1;
continue;
}
breaks[j++] = i;
if (i < count) {
d = cols - line;
if (d > 0) score += PENALTY_SHORT * d * d;
else if (d < 0) score += PENALTY_LONG * d * d;
}
line = 0;
}
breaks[j++] = 0;
return score;
}
int balanced_wrap(word words, int count, int cols, int *breaks)
{
int *best = malloc(sizeof(int) * (count + 1));
int best_score = greedy_wrap(words, count, cols, breaks);
void test_wrap(int line_no, int start, int score) {
int line = 0, current_score = -1, d;
while (start <= count) {
if (line) line ++;
line += words[start++].len;
d = cols - line;
if (start < count || d < 0) {
if (d > 0)
current_score = score + PENALTY_SHORT * d * d;
else
current_score = score + PENALTY_LONG * d * d;
} else {
current_score = score;
}
if (current_score >= best_score) {
if (d <= 0) return;
continue;
}
best[line_no] = start;
test_wrap(line_no + 1, start, current_score);
}
if (current_score >= 0 && current_score < best_score) {
best_score = current_score;
memcpy(breaks, best, sizeof(int) * (line_no));
}
}
test_wrap(0, 0, 0);
free(best);
return best_score;
}
void show_wrap(word list, int count, int *breaks)
{
int i, j;
for (i = j = 0; i < count && breaks[i]; i++) {
while (j < breaks[i]) {
printf("%.*s", list[j].len, list[j].s);
if (j < breaks[i] - 1)
putchar(' ');
j++;
}
if (breaks[i]) putchar('\n');
}
}
int main(void)
{
int len, score, cols;
word list = make_word_list(string, &len);
int *breaks = malloc(sizeof(int) * (len + 1));
cols = 80;
score = greedy_wrap(list, len, cols, breaks);
printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
score = balanced_wrap(list, len, cols, breaks);
printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
cols = 32;
score = greedy_wrap(list, len, cols, breaks);
printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
score = balanced_wrap(list, len, cols, breaks);
printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
return 0;
}
| #[derive(Clone, Debug)]
pub struct LineComposer<I> {
words: I,
width: usize,
current: Option<String>,
}
impl<I> LineComposer<I> {
pub(crate) fn new<S>(words: I, width: usize) -> Self
where
I: Iterator<Item = S>,
S: AsRef<str>,
{
LineComposer {
words,
width,
current: None,
}
}
}
impl<I, S> Iterator for LineComposer<I>
where
I: Iterator<Item = S>,
S: AsRef<str>,
{
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let mut next = match self.words.next() {
None => return self.current.take(),
Some(value) => value,
};
let mut current = self.current.take().unwrap_or_else(String::new);
loop {
let word = next.as_ref();
if self.width <= current.len() + word.len() {
self.current = Some(String::from(word));
if !current.is_empty() {
return Some(current);
}
}
if !current.is_empty() {
current.push_str(" ")
}
current.push_str(word);
match self.words.next() {
None => return Some(current),
Some(word) => next = word,
}
}
}
}
pub trait ComposeLines: Iterator {
fn compose_lines(self, width: usize) -> LineComposer<Self>
where
Self: Sized,
Self::Item: AsRef<str>,
{
LineComposer::new(self, width)
}
}
impl<T, S> ComposeLines for T
where
T: Iterator<Item = S>,
S: AsRef<str>,
{
}
fn main() {
let text = r"
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.";
text.split_whitespace()
.compose_lines(80)
.for_each(|line| println!("{}", line));
}
|
Write entire file |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.",
freopen("sample.txt","wb",stdout));
}
| use std::fs::File;
use std::io::Write;
fn main() -> std::io::Result<()> {
let data = "Sample text.";
let mut file = File::create("filename.txt")?;
write!(file, "{}", data)?;
Ok(())
}
|
Write language name in 3D ASCII | #include <stdio.h>
const char*s = " _____\n /____/\\\n/ ___\\/\n\\ \\/__/\n \\____/";
int main(){ puts(s); return 0; }
| pub fn char_from_id(id: u8) -> char {
[' ', '#', '/', '_', 'L', '|', '\n'][id as usize]
}
const ID_BITS: u8 = 3;
pub fn decode(code: &[u8]) -> String {
let mut ret = String::new();
let mut carry = 0;
let mut carry_bits = 0;
for &b in code {
let mut bit_pos = ID_BITS - carry_bits;
let mut cur = b >> bit_pos;
let mask = (1 << bit_pos) - 1;
let id = carry | (b & mask) << carry_bits;
ret.push(char_from_id(id));
while bit_pos + ID_BITS < 8 {
ret.push(char_from_id(cur & ((1 << ID_BITS) - 1)));
cur >>= ID_BITS;
bit_pos += ID_BITS;
}
carry = cur;
carry_bits = 8 - bit_pos;
}
ret
}
fn main() {
let code = [
72, 146, 36, 0, 0, 0, 0, 0, 0, 0, 128, 196, 74, 182, 41, 1, 0, 0, 0, 0, 0, 0, 160, 196, 77, 0,
52, 1, 18, 0, 9, 144, 36, 9, 146, 36, 113, 147, 36, 9, 160, 4, 80, 130, 100, 155, 160, 41, 145,
155, 108, 74, 128, 38, 64, 19, 41, 73, 2, 160, 137, 155, 0, 84, 130, 38, 64, 19, 112, 155, 18,
160, 137, 155, 0, 160, 18, 42, 73, 18, 36, 73, 2, 128, 74, 76, 1, 0, 40, 128, 219, 38, 104, 219,
4, 0, 160, 0
];
println!("{}", decode(&code));
}
|
XML_Input | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
static void print_names(xmlNode *node)
{
xmlNode *cur_node = NULL;
for (cur_node = node; cur_node; cur_node = cur_node->next) {
if (cur_node->type == XML_ELEMENT_NODE) {
if ( strcmp(cur_node->name, "Student") == 0 ) {
xmlAttr *prop = NULL;
if ( (prop = xmlHasProp(cur_node, "Name")) != NULL ) {
printf("%s\n", prop->children->content);
}
}
}
print_names(cur_node->children);
}
}
const char *buffer =
"<Students>\n"
" <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
" <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n"
" <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n"
" <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n"
" <Pet Type=\"dog\" Name=\"Rover\" />\n"
" </Student>\n"
" <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
"</Students>\n";
int main()
{
xmlDoc *doc = NULL;
xmlNode *root = NULL;
doc = xmlReadMemory(buffer, strlen(buffer), NULL, NULL, 0);
if ( doc != NULL ) {
root = xmlDocGetRootElement(doc);
print_names(root);
xmlFreeDoc(doc);
}
xmlCleanupParser();
return 0;
}
| extern crate xml;
use xml::{name::OwnedName, reader::EventReader, reader::XmlEvent};
const DOCUMENT: &str = r#"
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
"#;
fn main() -> Result<(), xml::reader::Error> {
let parser = EventReader::new(DOCUMENT.as_bytes());
let tag_name = OwnedName::local("Student");
let attribute_name = OwnedName::local("Name");
for event in parser {
match event? {
XmlEvent::StartElement {
name,
attributes,
..
} if name == tag_name => {
if let Some(attribute) = attributes.iter().find(|&attr| attr.name == attribute_name) {
println!("{}", attribute.value);
}
}
_ => (),
}
}
Ok(())
}
|
XML_Output | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
const char *names[] = {
"April", "Tam O'Shanter", "Emily", NULL
};
const char *remarks[] = {
"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift", NULL
};
int main()
{
xmlDoc *doc = NULL;
xmlNode *root = NULL, *node;
const char **next;
int a;
doc = xmlNewDoc("1.0");
root = xmlNewNode(NULL, "CharacterRemarks");
xmlDocSetRootElement(doc, root);
for(next = names, a = 0; *next != NULL; next++, a++) {
node = xmlNewNode(NULL, "Character");
(void)xmlNewProp(node, "name", *next);
xmlAddChild(node, xmlNewText(remarks[a]));
xmlAddChild(root, node);
}
xmlElemDump(stdout, doc, root);
xmlFreeDoc(doc);
xmlCleanupParser();
return EXIT_SUCCESS;
}
| extern crate xml;
use std::collections::HashMap;
use std::str;
use xml::writer::{EmitterConfig, XmlEvent};
fn characters_to_xml(characters: HashMap<String, String>) -> String {
let mut output: Vec<u8> = Vec::new();
let mut writer = EmitterConfig::new()
.perform_indent(true)
.create_writer(&mut output);
writer
.write(XmlEvent::start_element("CharacterRemarks"))
.unwrap();
for (character, line) in &characters {
let element = XmlEvent::start_element("Character").attr("name", character);
writer.write(element).unwrap();
writer.write(XmlEvent::characters(line)).unwrap();
writer.write(XmlEvent::end_element()).unwrap();
}
writer.write(XmlEvent::end_element()).unwrap();
str::from_utf8(&output).unwrap().to_string()
}
#[cfg(test)]
mod tests {
use super::characters_to_xml;
use std::collections::HashMap;
#[test]
fn test_xml_output() {
let mut input = HashMap::new();
input.insert(
"April".to_string(),
"Bubbly: I'm > Tam and <= Emily".to_string(),
);
input.insert(
"Tam O'Shanter".to_string(),
"Burns: \"When chapman billies leave the street ...\"".to_string(),
);
input.insert("Emily".to_string(), "Short & shrift".to_string());
let output = characters_to_xml(input);
println!("{}", output);
assert!(output.contains(
"<Character name=\"Tam O'Shanter\">Burns: \"When chapman \
billies leave the street ...\"</Character>"
));
assert!(output
.contains("<Character name=\"April\">Bubbly: I'm > Tam and <= Emily</Character>"));
assert!(output.contains("<Character name=\"Emily\">Short & shrift</Character>"));
}
}
|
Yin and yang | #include <stdio.h>
void draw_yinyang(int trans, double scale)
{
printf("<use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>",
trans, trans, scale);
}
int main()
{ printf(
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<!DOCTYPE svg PUBLIC '-
" 'http:
"<svg xmlns='http:
" xmlns:xlink='http:
" width='30' height='30'>\n"
" <defs><g id='y'>\n"
" <circle cx='0' cy='0' r='200' stroke='black'\n"
" fill='white' stroke-width='1'/>\n"
" <path d='M0 -200 A 200 200 0 0 0 0 200\n"
" 100 100 0 0 0 0 0 100 100 0 0 1 0 -200\n"
" z' fill='black'/>\n"
" <circle cx='0' cy='100' r='33' fill='white'/>\n"
" <circle cx='0' cy='-100' r='33' fill='black'/>\n"
" </g></defs>\n");
draw_yinyang(20, .05);
draw_yinyang(8, .02);
printf("</svg>");
return 0;
}
| use svg::node::element::Path;
fn main() {
let doc = svg::Document::new()
.add(yin_yang(15.0, 1.0).set("transform", "translate(20,20)"))
.add(yin_yang(6.0, 1.0).set("transform", "translate(50,11)"));
svg::save("yin_yang.svg", &doc).unwrap();
}
fn yin_yang(r: f32, th: f32) -> Path {
let (cr, cw, ccw) = (",0,1,1,.1,0z", ",0,0,1,0,", ",0,0,0,0,");
let d = format!("M0,{0} a{0},{0}{cr} M0,{1} ", r + th, -r / 3.0)
+ &format!("a{0},{0}{cr} m0,{r} a{0},{0}{cr} M0,0 ", r / 6.0)
+ &format!("A{0},{0}{ccw}{r} A{r},{r}{cw}-{r} A{0},{0}{cw}0", r / 2.0);
Path::new().set("d", d).set("fill-rule", "evenodd")
}
|
Zero to the zero power | #include <stdio.h>
#include <math.h>
#include <complex.h>
int main()
{
printf("0 ^ 0 = %f\n", pow(0,0));
double complex c = cpow(0,0);
printf("0+0i ^ 0+0i = %f+%fi\n", creal(c), cimag(c));
return 0;
}
| fn main() {
println!("{}",0u32.pow(0));
}
|
Zig-zag matrix | #include <stdio.h>
#include <stdlib.h>
int main(int c, char **v)
{
int i, j, m, n, *s;
if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;
s = malloc(sizeof(int) * m * m);
for (i = n = 0; i < m * 2; i++)
for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)
s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;
for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n'))
printf("%3d", s[i]);
return 0;
}
| use std::cmp::Ordering;
use std::cmp::Ordering::{Equal, Greater, Less};
use std::iter::repeat;
#[derive(Debug, PartialEq, Eq)]
struct SortIndex {
x: usize,
y: usize,
}
impl SortIndex {
fn new(x: usize, y: usize) -> SortIndex {
SortIndex { x, y }
}
}
impl PartialOrd for SortIndex {
fn partial_cmp(&self, other: &SortIndex) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SortIndex {
fn cmp(&self, other: &SortIndex) -> Ordering {
let lower = if self.x + self.y == other.x + other.y {
if (self.x + self.y) % 2 == 0 {
self.x < other.x
} else {
self.y < other.y
}
} else {
(self.x + self.y) < (other.x + other.y)
};
if lower {
Less
} else if self == other {
Equal
} else {
Greater
}
}
}
fn zigzag(n: usize) -> Vec<Vec<usize>> {
let mut l: Vec<SortIndex> = (0..n * n).map(|i| SortIndex::new(i % n, i / n)).collect();
l.sort();
let init_vec = vec![0; n];
let mut result: Vec<Vec<usize>> = repeat(init_vec).take(n).collect();
for (i, &SortIndex { x, y }) in l.iter().enumerate() {
result[y][x] = i
}
result
}
fn main() {
println!("{:?}", zigzag(5));
}
|
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.