{"name":"24 game","C":"#include \n#include \n#include \n#include \n#include \n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '\/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom \/= t;\n\t\tres->num \/= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr\/n\/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); \n\t\tif (msg) {\n\t\t\t\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24. Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d\/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good. Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}\n","Rust":"use std::io::{self,BufRead};\nextern crate rand;\nuse rand::Rng;\n\nfn op_type(x: char) -> i32{\n match x {\n '-' | '+' => return 1,\n '\/' | '*' => return 2,\n '(' | ')' => return -1,\n _ => return 0,\n }\n}\n\nfn to_rpn(input: &mut String){\n\n let mut rpn_string : String = String::new();\n let mut rpn_stack : String = String::new();\n let mut last_token = '#';\n for token in input.chars(){\n if token.is_digit(10) {\n rpn_string.push(token);\n }\n else if op_type(token) == 0 {\n continue;\n }\n else if op_type(token) > op_type(last_token) || token == '(' {\n rpn_stack.push(token);\n last_token=token;\n }\n else {\n while let Some(top) = rpn_stack.pop() {\n if top=='(' {\n break;\n }\n rpn_string.push(top);\n }\n if token != ')'{\n rpn_stack.push(token);\n }\n }\n }\n while let Some(top) = rpn_stack.pop() {\n rpn_string.push(top);\n }\n\n println!(\"you formula results in {}\", rpn_string);\n\n *input=rpn_string;\n}\n\nfn calculate(input: &String, list : &mut [u32;4]) -> f32{\n let mut stack : Vec = Vec::new();\n let mut accumulator : f32 = 0.0;\n\n for token in input.chars(){\n if token.is_digit(10) {\n let test = token.to_digit(10).unwrap() as u32;\n match list.iter().position(|&x| x == test){\n Some(idx) => list[idx]=10 ,\n _ => println!(\" invalid digit: {} \",test),\n }\n stack.push(accumulator);\n accumulator = test as f32;\n }else{\n let a = stack.pop().unwrap();\n accumulator = match token {\n '-' => a-accumulator,\n '+' => a+accumulator,\n '\/' => a\/accumulator,\n '*' => a*accumulator,\n _ => {accumulator},\n };\n }\n }\n println!(\"you formula results in {}\",accumulator);\n accumulator\n}\n\nfn main() {\n\n let mut rng = rand::thread_rng();\n let mut list :[u32;4]=[rng.gen::()%10,rng.gen::()%10,rng.gen::()%10,rng.gen::()%10];\n\n println!(\"form 24 with using + - \/ * {:?}\",list);\n \n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n \n to_rpn(&mut input);\n let result = calculate(&input, &mut list);\n\n if list.iter().any(|&list| list !=10){\n println!(\"and you used all numbers\");\n match result {\n 24.0 => println!(\"you won\"),\n _ => println!(\"but your formulla doesn't result in 24\"),\n }\n }else{\n println!(\"you didn't use all the numbers\");\n }\n\n}\n"} {"name":"Abbreviations, easy","C":"#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \"\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \"\n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \"\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \"\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n char* cmd;\n size_t length;\n size_t min_len;\n struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n size_t olen = strlen(str);\n return olen >= command->min_len && olen <= command->length\n && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n for (size_t i = 0; i < n; ++i)\n str[i] = toupper((unsigned char)str[i]);\n return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n size_t len = 0;\n while (len < n && isupper((unsigned char)str[len]))\n ++len;\n return len;\n}\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n size_t size = 0;\n size_t capacity = 16;\n char** words = xmalloc(capacity * sizeof(char*));\n size_t len = strlen(str);\n for (size_t begin = 0; begin < len; ) {\n size_t i = begin;\n for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n begin = i;\n for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n size_t word_len = i - begin;\n if (word_len == 0)\n break;\n char* word = xmalloc(word_len + 1);\n memcpy(word, str + begin, word_len);\n word[word_len] = 0;\n begin += word_len;\n if (capacity == size) {\n capacity *= 2;\n words = xrealloc(words, capacity * sizeof(char*));\n }\n words[size++] = word;\n }\n *count = size;\n return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n command_t* cmd = NULL;\n size_t count = 0;\n char** words = split_into_words(table, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n command_t* new_cmd = xmalloc(sizeof(command_t));\n size_t word_len = strlen(word);\n new_cmd->length = word_len;\n new_cmd->min_len = get_min_length(word, word_len);\n new_cmd->cmd = uppercase(word, word_len);\n new_cmd->next = cmd;\n cmd = new_cmd;\n }\n free(words);\n return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n while (cmd != NULL) {\n command_t* next = cmd->next;\n free(cmd->cmd);\n free(cmd);\n cmd = next;\n }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n if (command_match(cmd, word))\n return cmd;\n }\n return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n printf(\" input: %s\\n\", input);\n printf(\"output:\");\n size_t count = 0;\n char** words = split_into_words(input, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n uppercase(word, strlen(word));\n const command_t* cmd_ptr = find_command(commands, word);\n printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n free(word);\n }\n free(words);\n printf(\"\\n\");\n}\n\nint main() {\n command_t* commands = make_command_list(command_table);\n const char* input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n test(commands, input);\n free_command_list(commands);\n return 0;\n}\n","Rust":"use std::collections::HashMap;\n\nfn main() {\n let commands = \"\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \\\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \\\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \\\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \\\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \\\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \\\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up \\\n \";\n let split = commands.split_ascii_whitespace();\n let count_hashtable: HashMap<&str, usize> = split.map(|word| {\n (word, word.chars().take_while(|c| c.is_ascii_uppercase()).count())\n }).collect();\n\n let line = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n let mut words_vec: Vec = vec![];\n for word in line.split_ascii_whitespace() {\n let split = commands.split_ascii_whitespace();\n let abbr = split.filter(|x| {\n x.to_ascii_lowercase().starts_with(&word.to_ascii_lowercase()) &&\n word.len() >= *count_hashtable.get(x).unwrap()\n }).next();\n words_vec.push(match abbr {\n Some(word) => word.to_ascii_uppercase(),\n None => String::from(\"*error*\"),\n });\n }\n let corrected_line = words_vec.join(\" \");\n println!(\"{}\", corrected_line);\n}\n"} {"name":"Abbreviations, simple","C":"#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \"\n \"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \"\n \"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n \"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \"\n \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \"\n \"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \"\n \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n \"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\";\n\ntypedef struct command_tag {\n char* cmd;\n size_t length;\n size_t min_len;\n struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n size_t olen = strlen(str);\n return olen >= command->min_len && olen <= command->length\n && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n for (size_t i = 0; i < n; ++i)\n str[i] = toupper((unsigned char)str[i]);\n return str;\n}\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n size_t size = 0;\n size_t capacity = 16;\n char** words = xmalloc(capacity * sizeof(char*));\n size_t len = strlen(str);\n for (size_t begin = 0; begin < len; ) {\n size_t i = begin;\n for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n begin = i;\n for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n size_t word_len = i - begin;\n if (word_len == 0)\n break;\n char* word = xmalloc(word_len + 1);\n memcpy(word, str + begin, word_len);\n word[word_len] = 0;\n begin += word_len;\n if (capacity == size) {\n capacity *= 2;\n words = xrealloc(words, capacity * sizeof(char*));\n }\n words[size++] = word;\n }\n *count = size;\n return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n command_t* cmd = NULL;\n size_t count = 0;\n char** words = split_into_words(table, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n command_t* new_cmd = xmalloc(sizeof(command_t));\n size_t word_len = strlen(word);\n new_cmd->length = word_len;\n new_cmd->min_len = word_len;\n new_cmd->cmd = uppercase(word, word_len);\n if (i + 1 < count) {\n char* eptr = 0;\n unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n if (min_len > 0 && *eptr == 0) {\n free(words[i + 1]);\n new_cmd->min_len = min_len;\n ++i;\n }\n }\n new_cmd->next = cmd;\n cmd = new_cmd;\n }\n free(words);\n return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n while (cmd != NULL) {\n command_t* next = cmd->next;\n free(cmd->cmd);\n free(cmd);\n cmd = next;\n }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n if (command_match(cmd, word))\n return cmd;\n }\n return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n printf(\" input: %s\\n\", input);\n printf(\"output:\");\n size_t count = 0;\n char** words = split_into_words(input, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n uppercase(word, strlen(word));\n const command_t* cmd_ptr = find_command(commands, word);\n printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n free(word);\n }\n free(words);\n printf(\"\\n\");\n}\n\nint main() {\n command_t* commands = make_command_list(command_table);\n const char* input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n test(commands, input);\n free_command_list(commands);\n return 0;\n}\n","Rust":"use std::collections::HashMap;\n\n\n\n\n\n\n\n\n\nfn main() {\n let command_table_string =\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input_command 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\";\n\n \n \n \n let mut iter = command_table_string.split_whitespace().peekable();\n\n let mut command_table = HashMap::new();\n\n \n \n \n \n \n \n \n \n while let Some(command_string) = iter.next() {\n let command_string_length = command_string.len() as i32;\n\n let min_letter_match = match iter.peek() {\n Some(potential_number) => match potential_number.parse::() {\n Ok(number) => {\n iter.next();\n number\n }\n Err(_) => command_string_length,\n },\n None => break,\n };\n\n \n \n for i in min_letter_match..=command_string_length {\n let cmd_list = command_table.entry(i).or_insert_with(Vec::new);\n cmd_list.push(command_string.to_uppercase());\n }\n }\n\n const ERROR_TEXT: &str = \"*error*\";\n\n let test_input_text = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n\n let mut output_text = String::new();\n\n let mut iter = test_input_text.split_whitespace().peekable();\n\n \n \n \n \n \n while let Some(input_command) = iter.next() {\n let input_command_length = input_command.len() as i32;\n\n let command_list = match command_table.get(&input_command_length) {\n Some(list) => list,\n None => {\n output_text.push_str(ERROR_TEXT);\n continue;\n }\n };\n\n let input_command_caps = input_command.to_uppercase();\n let matched_commands: Vec<&String> = command_list\n .iter()\n .filter(|command| command.starts_with(&input_command_caps))\n .collect();\n\n \n assert!(\n matched_commands.len() < 2,\n \"Strange.. {:?}\",\n matched_commands\n );\n\n match matched_commands.first() {\n Some(cmd) => output_text.push_str(cmd),\n None => output_text.push_str(ERROR_TEXT),\n }\n\n if iter.peek().is_some() {\n output_text.push(' ');\n }\n }\n\n println!(\"Input was: {}\", test_input_text);\n println!(\"Output is: {}\", output_text);\n\n let correct_output = \"RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\";\n assert_eq!(output_text, correct_output)\n}\n"} {"name":"Additive primes","C":"#include \n#include \n#include \n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n result[2] = true;\n result[3] = true;\n int prime[N];\n prime[0] = 3;\n int end = 1;\n for (int n = 5; n < N; n += 2)\n {\n bool n_is_prime = true;\n for (int i = 0; i < end; ++i)\n {\n const int PRIME = prime[i];\n if (n % PRIME == 0)\n {\n n_is_prime = false;\n break;\n }\n if (PRIME * PRIME > n)\n {\n break;\n }\n }\n if (n_is_prime)\n {\n prime[end++] = n;\n result[n] = true;\n }\n }\n}\n\nint sumOfDecimalDigits( int n )\n{\n int sum = 0;\n while (n > 0)\n {\n sum += n % 10;\n n \/= 10;\n }\n return sum;\n}\n\nint main( void )\n{\n const int N = 500;\n\n printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n bool is_prime[N];\n memset( is_prime, 0, sizeof(is_prime) );\n memoizeIsPrime( is_prime, N );\n\n printf( \" 2\" );\n int count = 1;\n for (int i = 3; i < N; i += 2)\n {\n if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n {\n printf( \"%4d\", i );\n ++count;\n if ((count % 10) == 0)\n {\n printf( \"\\n\" );\n }\n }\n }\n printf( \"\\nThose were %d additive primes.\\n\", count );\n return 0;\n}\n","Rust":"fn main() {\n let limit = 500;\n let column_w = limit.to_string().len() + 1;\n let mut pms = Vec::with_capacity(limit \/ 2 - limit \/ 3 \/ 2 - limit \/ 5 \/ 3 \/ 2 + 1);\n let mut count = 0;\n for u in (2..3).chain((3..limit).step_by(2)) {\n if pms.iter().take_while(|&&p| p * p <= u).all(|&p| u % p != 0) {\n pms.push(u);\n let dgs = std::iter::successors(Some(u), |&n| (n > 9).then(|| n \/ 10)).map(|n| n % 10);\n if pms.binary_search(&dgs.sum()).is_ok() {\n print!(\"{}{u:column_w$}\", if count % 10 == 0 { \"\\n\" } else { \"\" });\n count += 1;\n }\n }\n }\n println!(\"\\n---\\nFound {count} additive primes less than {limit}\");\n}\n"} {"name":"Alternade words","C":"#include \n#include \n#include \n#include \n\n#define WORD_BUF_SIZE 30\n#define MIN_WORD_SIZE 6\n\n\nvoid fail(void) {\n fprintf(stderr, \"%s\\n\", strerror(errno));\n exit(42);\n}\n\n\nstruct trie_node {\n char ch, final;\n struct trie_node *parent, *sibling, *root, *child; \n};\n\nstruct trie_node *alloc_node() {\n struct trie_node *t = calloc(1, sizeof(struct trie_node));\n if (t == NULL) fail();\n return t;\n}\n\nstruct trie_node *make_sibling(struct trie_node *node) {\n struct trie_node *t = alloc_node();\n node->sibling = t;\n t->ch = node->ch;\n t->parent = node->parent;\n t->root = node->root;\n return t;\n}\n\nstruct trie_node *make_child(struct trie_node *node, char ch) {\n struct trie_node *t = alloc_node();\n t->parent = node;\n t->ch = ch;\n t->root = node->root;\n node->child = t;\n return t;\n}\n\n\nstruct trie_node *add_word(struct trie_node *root, const char *word) {\n struct trie_node *cur = root;\n for (; *word; word++) {\n while (cur->child == NULL || cur->child->ch != *word) {\n if (cur->child == NULL) {\n \n make_child(cur, *word);\n } else {\n \n if (cur->sibling == NULL) make_sibling(cur);\n cur = cur->sibling;\n }\n }\n \n \n cur = cur->child;\n }\n cur->final = 1; \n return cur;\n}\n\n\nstruct trie_node *find_word(struct trie_node *root, const char *word) {\n struct trie_node *cur = root;\n for (; *word && cur; word++) {\n while (cur != NULL && cur->child != NULL && cur->child->ch != *word) {\n cur = cur->sibling;\n }\n if (cur == NULL) return NULL; \n cur = cur->child;\n }\n if (cur && cur->final) return cur;\n else return NULL;\n}\n\n\nvoid scan_trie(struct trie_node *node, void callback(struct trie_node *)) {\n if (node == NULL) return;\n if (node->final) callback(node);\n scan_trie(node->child, callback);\n scan_trie(node->sibling, callback);\n}\n\n\nchar *get_word(struct trie_node *node, char *buffer) {\n char t, *ch = buffer, *s = buffer;\n for (; node != NULL; node=node->parent) *ch++ = node->ch;\n for (ch-=2; ch >= s; ch--, s++) *ch ^= *s ^= *ch ^= *s;\n return buffer;\n}\n\n\nvoid check_alternade(struct trie_node *node) {\n static char word[WORD_BUF_SIZE], even[WORD_BUF_SIZE], odd[WORD_BUF_SIZE];\n char *p_even = even, *p_odd = odd;\n int i;\n \n \n if (strlen(get_word(node, word)) < MIN_WORD_SIZE) return;\n \n \n for (i=0; word[i]; i++) {\n if (i & 1) *p_odd++ = word[i];\n else *p_even++ = word[i];\n }\n *p_odd = *p_even = '\\0';\n \n \n if (find_word(node->root, even) && find_word(node->root, odd)) {\n printf(\"%-20s%-10s%-10s\\n\", word, even, odd);\n }\n}\n \nint main(void) {\n struct trie_node *root = alloc_node();\n root->root = root;\n char word[WORD_BUF_SIZE], *nl;\n \n \n while (!feof(stdin)) {\n fgets(word, WORD_BUF_SIZE, stdin);\n if (nl = strchr(word, '\\n')) *nl = '\\0'; \n add_word(root, word);\n }\n \n \n scan_trie(root, check_alternade);\n return 0;\n}\n","Rust":"use std::collections::BTreeSet;\nuse std::fs::File;\nuse std::io::{self, BufRead};\n\nfn load_dictionary(filename: &str) -> std::io::Result> {\n let file = File::open(filename)?;\n let mut dict = BTreeSet::new();\n for line in io::BufReader::new(file).lines() {\n dict.insert(line?);\n }\n Ok(dict)\n}\n\nfn main() {\n match load_dictionary(\"unixdict.txt\") {\n Ok(dictionary) => {\n for word in &dictionary {\n if word.len() < 6 {\n continue;\n }\n let mut odd_word = String::new();\n let mut even_word = String::new();\n for (i, c) in word.chars().enumerate() {\n if (i & 1) == 0 {\n odd_word.push(c);\n } else {\n even_word.push(c);\n }\n }\n if dictionary.contains(&odd_word) && dictionary.contains(&even_word) {\n println!(\"{:<10}{:<6}{}\", word, odd_word, even_word);\n }\n }\n }\n Err(error) => eprintln!(\"{}\", error),\n }\n}\n"} {"name":"Arithmetic numbers","C":"#include \n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n unsigned int* psum) {\n unsigned int divisor_count = 1;\n unsigned int divisor_sum = 1;\n unsigned int power = 2;\n for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n ++divisor_count;\n divisor_sum += power;\n }\n for (unsigned int p = 3; p * p <= n; p += 2) {\n unsigned int count = 1, sum = 1;\n for (power = p; n % p == 0; power *= p, n \/= p) {\n ++count;\n sum += power;\n }\n divisor_count *= count;\n divisor_sum *= sum;\n }\n if (n > 1) {\n divisor_count *= 2;\n divisor_sum *= n + 1;\n }\n *pcount = divisor_count;\n *psum = divisor_sum;\n}\n\nint main() {\n unsigned int arithmetic_count = 0;\n unsigned int composite_count = 0;\n\n for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n unsigned int divisor_count;\n unsigned int divisor_sum;\n divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n if (divisor_sum % divisor_count != 0)\n continue;\n ++arithmetic_count;\n if (divisor_count > 2)\n ++composite_count;\n if (arithmetic_count <= 100) {\n printf(\"%3u \", n);\n if (arithmetic_count % 10 == 0)\n printf(\"\\n\");\n }\n if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n arithmetic_count == 100000 || arithmetic_count == 1000000) {\n printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n composite_count);\n }\n }\n return 0;\n}\n","Rust":"fn divisor_count_and_sum(mut n: u32) -> (u32, u32) {\n let mut divisor_count = 1;\n let mut divisor_sum = 1;\n let mut power = 2;\n while (n & 1) == 0 {\n divisor_count += 1;\n divisor_sum += power;\n power <<= 1;\n n >>= 1;\n }\n let mut p = 3;\n while p * p <= n {\n let mut count = 1;\n let mut sum = 1;\n power = p;\n while n % p == 0 {\n count += 1;\n sum += power;\n power *= p;\n n \/= p;\n }\n divisor_count *= count;\n divisor_sum *= sum;\n p += 2;\n }\n if n > 1 {\n divisor_count *= 2;\n divisor_sum *= n + 1;\n }\n (divisor_count, divisor_sum)\n}\n\nfn main() {\n let mut arithmetic_count = 0;\n let mut composite_count = 0;\n let mut n = 1;\n while arithmetic_count <= 1000000 {\n let (divisor_count, divisor_sum) = divisor_count_and_sum(n);\n if divisor_sum % divisor_count != 0 {\n n += 1;\n continue;\n }\n arithmetic_count += 1;\n if divisor_count > 2 {\n composite_count += 1;\n }\n if arithmetic_count <= 100 {\n print!(\"{:3} \", n);\n if arithmetic_count % 10 == 0 {\n println!();\n }\n }\n if arithmetic_count == 1000\n || arithmetic_count == 10000\n || arithmetic_count == 100000\n || arithmetic_count == 1000000\n {\n println!(\"\\n{}th arithmetic number is {}\", arithmetic_count, n);\n println!(\n \"Number of composite arithmetic numbers <= {}: {}\",\n n, composite_count\n );\n }\n n += 1;\n }\n}\n"} {"name":"Benford's law","C":"#include \n#include \n#include \n\nfloat *benford_distribution(void)\n{\n static float prob[9];\n for (int i = 1; i < 10; i++)\n prob[i - 1] = log10f(1 + 1.0 \/ i);\n\n return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n FILE *input = fopen(fn, \"r\");\n if (!input)\n {\n perror(\"Can't open file\");\n exit(EXIT_FAILURE);\n }\n\n int tally[9] = { 0 };\n char c;\n int total = 0;\n while ((c = getc(input)) != EOF)\n {\n \n while (c < '1' || c > '9')\n c = getc(input);\n\n tally[c - '1']++;\n total++;\n\n \n while ((c = getc(input)) != '\\n' && c != EOF)\n ;\n }\n fclose(input);\n \n static float freq[9];\n for (int i = 0; i < 9; i++)\n freq[i] = tally[i] \/ (float) total;\n\n return freq;\n}\n\nint main(int argc, char **argv)\n{\n if (argc != 2)\n {\n printf(\"Usage: benford \\n\");\n return EXIT_FAILURE;\n }\n\n float *actual = get_actual_distribution(argv[1]);\n float *expected = benford_distribution(); \n\n puts(\"digit\\tactual\\texpected\");\n for (int i = 0; i < 9; i++)\n printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n return EXIT_SUCCESS;\n}\n","Rust":"extern crate num_traits;\nextern crate num;\n\nuse num::bigint::{BigInt, ToBigInt};\nuse num_traits::{Zero, One};\nuse std::collections::HashMap;\n\n\nfn fib(n: usize) -> Vec {\n let mut result = Vec::with_capacity(n);\n let mut a = BigInt::zero();\n let mut b = BigInt::one();\n\n result.push(b.clone());\n\n for i in 1..n {\n let t = b.clone();\n b = a+b;\n a = t;\n result.push(b.clone());\n }\n\n result\n}\n\n\nfn first_digit(x: &BigInt) -> u8 {\n let zero = BigInt::zero();\n assert!(x > &zero);\n\n let s = x.to_str_radix(10);\n\n \n *&s[..1].parse::().unwrap()\n}\n\nfn main() {\n const N: usize = 1000;\n let mut counter: HashMap = HashMap::new();\n for x in fib(N) {\n let d = first_digit(&x);\n *counter.entry(d).or_insert(0) += 1;\n }\n\n println!(\"{:>13} {:>10}\", \"real\", \"predicted\");\n for y in 1..10 {\n println!(\"{}: {:10.3} v. {:10.3}\", y, *counter.get(&y).unwrap_or(&0) as f32 \/ N as f32,\n (1.0 + 1.0 \/ (y as f32)).log10());\n }\n\n}\n"} {"name":"Bioinformatics_Sequence mutation","C":"#include\n#include\n#include\n\ntypedef struct genome{\n char base;\n struct genome *next;\n}genome;\n\ntypedef struct{\n char mutation;\n int position;\n}genomeChange;\n\ntypedef struct{\n int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n int len = 1;\n\n while(num>10){\n num \/= 10;\n len++;\n }\n return len;\n}\n\nvoid generateStrand(){\n\n int baseChoice = rand()%4, i;\n genome *strandIterator, *newStrand;\n\n baseData.adenineCount = 0;\n baseData.thymineCount = 0;\n baseData.cytosineCount = 0;\n baseData.guanineCount = 0;\n \n strand = (genome*)malloc(sizeof(genome));\n strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n strand->next = NULL;\n\n strandIterator = strand;\n\n for(i=1;ibase = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n newStrand->next = NULL;\n\n strandIterator->next = newStrand;\n strandIterator = newStrand;\n }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n \n genomeChange mutationCommand;\n\n mutationCommand.mutation = mutationChoice=swapWeight && mutationChoicebase);\n strandIterator = strandIterator->next;\n }\n len += lineLength;\n }\n\n while(strandIterator!=NULL){\n printf(\"%c\",strandIterator->base);\n strandIterator = strandIterator->next;\n }\n\n printf(\"\\n\\nBase Counts\\n-----------\");\n\n printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n int i,j,width,baseChoice;\n genomeChange newMutation;\n genome *strandIterator, *strandFollower, *newStrand;\n\n for(i=0;inext;\n }\n \n if(newMutation.mutation=='S'){\n if(strandIterator->base=='A'){\n strandIterator->base='T';\n printf(\"\\nSwapping A at position\u00a0:\u00a0%*d with T\",width,newMutation.position);\n }\n else if(strandIterator->base=='A'){\n strandIterator->base='T';\n printf(\"\\nSwapping A at position\u00a0:\u00a0%*d with T\",width,newMutation.position);\n }\n else if(strandIterator->base=='C'){\n strandIterator->base='G';\n printf(\"\\nSwapping C at position\u00a0:\u00a0%*d with G\",width,newMutation.position);\n }\n else{\n strandIterator->base='C';\n printf(\"\\nSwapping G at position\u00a0:\u00a0%*d with C\",width,newMutation.position);\n }\n }\n\n else if(newMutation.mutation=='I'){\n baseChoice = rand()%4;\n\n newStrand = (genome*)malloc(sizeof(genome));\n newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n printf(\"\\nInserting %c at position\u00a0:\u00a0%*d\",newStrand->base,width,newMutation.position);\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n newStrand->next = strandIterator;\n strandFollower->next = newStrand;\n genomeLength++;\n }\n\n else{\n strandFollower->next = strandIterator->next;\n strandIterator->next = NULL;\n printf(\"\\nDeleting %c at position\u00a0:\u00a0%*d\",strandIterator->base,width,newMutation.position);\n free(strandIterator);\n genomeLength--;\n }\n }\n}\n\nint main(int argc,char* argv[])\n{\n int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n if(argc==1||argc>6){\n printf(\"Usage\u00a0: %s \\n\",argv[0]);\n return 0;\n }\n\n switch(argc){\n case 2: genomeLength = atoi(argv[1]);\n break;\n case 3: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n break;\n case 4: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n break; \n case 5: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n insertWeight = atoi(argv[4]);\n break; \n case 6: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n insertWeight = atoi(argv[4]);\n deleteWeight = atoi(argv[5]);\n break; \n };\n\n srand(time(NULL));\n generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n printGenome();\n mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n return 0;\n}\n","Rust":"use rand::prelude::*;\nuse std::collections::HashMap;\nuse std::fmt::{Display, Formatter, Error};\n\npub struct Seq<'a> {\n alphabet: Vec<&'a str>,\n distr: rand::distributions::Uniform,\n pos_distr: rand::distributions::Uniform,\n seq: Vec<&'a str>,\n}\n\nimpl Display for Seq<'_> {\n fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {\n\n let pretty: String = self.seq\n .iter()\n .enumerate()\n .map(|(i, nt)| if (i + 1) % 60 == 0 { format!(\"{}\\n\", nt) } else { nt.to_string() })\n .collect();\n \n let counts_hm = self.seq\n .iter()\n .fold(HashMap::<&str, usize>::new(), |mut m, nt| {\n *m.entry(nt).or_default() += 1;\n m\n });\n\n let mut counts_vec: Vec<(&str, usize)> = counts_hm.into_iter().collect();\n counts_vec.sort_by(|a, b| a.0.cmp(&b.0));\n let counts_string = counts_vec\n .iter()\n .fold(String::new(), |mut counts_string, (nt, count)| {\n counts_string += &format!(\"{} = {}\\n\", nt, count);\n counts_string\n });\n\n write!(f, \"Seq:\\n{}\\n\\nLength: {}\\n\\nCounts:\\n{}\", pretty, self.seq.len(), counts_string)\n }\n}\n\nimpl Seq<'_> {\n pub fn new(alphabet: Vec<&str>, len: usize) -> Seq {\n let distr = rand::distributions::Uniform::new_inclusive(0, alphabet.len() - 1);\n let pos_distr = rand::distributions::Uniform::new_inclusive(0, len - 1);\n\n let seq: Vec<&str> = (0..len)\n .map(|_| {\n alphabet[thread_rng().sample(distr)]\n })\n .collect();\n Seq { alphabet, distr, pos_distr, seq }\n }\n\n pub fn insert(&mut self) {\n let pos = thread_rng().sample(self.pos_distr);\n let nt = self.alphabet[thread_rng().sample(self.distr)];\n println!(\"Inserting {} at position {}\", nt, pos);\n self.seq.insert(pos, nt);\n }\n\n pub fn delete(&mut self) {\n let pos = thread_rng().sample(self.pos_distr);\n println!(\"Deleting {} at position {}\", self.seq[pos], pos);\n self.seq.remove(pos);\n }\n\n pub fn swap(&mut self) {\n let pos = thread_rng().sample(self.pos_distr);\n let cur_nt = self.seq[pos];\n let new_nt = self.alphabet[thread_rng().sample(self.distr)];\n println!(\"Replacing {} at position {} with {}\", cur_nt, pos, new_nt);\n self.seq[pos] = new_nt;\n }\n}\n\nfn main() {\n\n let mut seq = Seq::new(vec![\"A\", \"C\", \"T\", \"G\"], 200);\n println!(\"Initial sequnce:\\n{}\", seq);\n\n let mut_distr = rand::distributions::Uniform::new_inclusive(0, 2);\n\n for _ in 0..10 {\n let mutation = thread_rng().sample(mut_distr);\n\n if mutation == 0 {\n seq.insert()\n } else if mutation == 1 {\n seq.delete()\n } else {\n seq.swap()\n }\n }\n\n println!(\"\\nMutated sequence:\\n{}\", seq);\n}\n"} {"name":"Bioinformatics_base count","C":"#include\n#include\n#include\n\ntypedef struct genome{\n char* strand;\n int length;\n struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n int len = 1;\n\n while(num>10){\n num = num\/10;\n len++;\n }\n\n return len;\n}\n\nvoid buildGenome(char str[100]){\n int len = strlen(str),i;\n genome *genomeIterator, *newGenome; \n\n totalLength += len;\n\n for(i=0;istrand = (char*)malloc(len*sizeof(char));\n strcpy(genomeData->strand,str);\n genomeData->length = len;\n\n genomeData->next = NULL;\n }\n\n else{\n genomeIterator = genomeData;\n\n while(genomeIterator->next!=NULL)\n genomeIterator = genomeIterator->next;\n\n newGenome = (genome*)malloc(sizeof(genome));\n\n newGenome->strand = (char*)malloc(len*sizeof(char));\n strcpy(newGenome->strand,str);\n newGenome->length = len;\n\n newGenome->next = NULL;\n genomeIterator->next = newGenome;\n }\n}\n\nvoid printGenome(){\n genome* genomeIterator = genomeData;\n\n int width = numDigits(totalLength), len = 0;\n\n printf(\"Sequence:\\n\");\n\n while(genomeIterator!=NULL){\n printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n len += genomeIterator->length;\n\n genomeIterator = genomeIterator->next;\n }\n\n printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n char str[100];\n int counter = 0, len;\n \n if(argc!=2){\n printf(\"Usage\u00a0: %s \\n\",argv[0]);\n return 0;\n }\n\n FILE *fp = fopen(argv[1],\"r\");\n\n while(fscanf(fp,\"%s\",str)!=EOF)\n buildGenome(str);\n fclose(fp);\n\n printGenome();\n\n return 0;\n}\n","Rust":"use std::collections::HashMap;\n\nfn main() {\n let dna = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\\\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\\\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\\\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\\\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\\\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\\\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\\\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\\\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\\\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\n let mut base_count = HashMap::new();\n let mut total_count = 0;\n print!(\"Sequence:\");\n for base in dna.chars() {\n if total_count % 50 == 0 {\n print!(\"\\n{:3}: \", total_count);\n }\n print!(\"{}\", base);\n total_count += 1;\n let count = base_count.entry(base).or_insert(0); \n *count += 1;\n }\n println!(\"\\n\");\n println!(\"Base count:\");\n println!(\"-----------\");\n\n let mut base_count: Vec<_> = base_count.iter().collect(); \n base_count.sort_by_key(|bc| bc.0); \n for (base, count) in base_count.iter() {\n println!(\" {}: {:3}\", base, count);\n }\n println!();\n println!(\"Total: {}\", total_count);\n}\n"} {"name":"Bitmap_Histogram","C":"typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n","Rust":"extern crate image;\nuse image::{DynamicImage, GenericImageView, ImageBuffer, Rgba};\n\n\nconst ALPHA: usize = 3;\n\n\n\nconst fn luminance(rgba: Rgba) -> u16 {\n let Rgba([r, g, b, _a]) = rgba;\n 55 * r as u16 + 183 * g as u16 + 19 * b as u16\n}\n\n\n\nfn get_median(total: usize, histogram: &[usize]) -> u16 {\n let mut sum = 0;\n for (index, &count) in histogram.iter().enumerate() {\n sum += count;\n if sum >= total \/ 2 {\n return index as u16;\n }\n }\n\n u16::MAX\n}\n\n\nfn compute_histogram(img: &DynamicImage) -> Vec {\n let mut histogram = vec![0; 1 << u16::BITS];\n\n img.pixels()\n .map(|(_x, _y, pixel)| luminance(pixel))\n .for_each(|luminance| histogram[luminance as usize] += 1);\n\n histogram\n}\n\n\nconst fn black_white(is_white: bool, alpha: u8) -> [u8; 4] {\n if is_white {\n [255, 255, 255, alpha]\n } else {\n [0, 0, 0, alpha]\n }\n}\n\n\n\nfn convert_to_monochrome(img: &DynamicImage) -> ImageBuffer, Vec> {\n let histogram = compute_histogram(img);\n\n let (width, height) = img.dimensions();\n let pixel_count = (width * height) as usize;\n let median = get_median(pixel_count, &histogram);\n\n let pixel_buffer = img.pixels()\n .flat_map(|(_x, _y, pixel)| black_white(luminance(pixel) > median, pixel[ALPHA]))\n .collect();\n\n ImageBuffer::from_vec(width, height, pixel_buffer).unwrap_or_else(|| unreachable!())\n}\n\nfn main() {\n let img = image::open(\"lena.jpg\").expect(\"could not load image file\");\n let img = convert_to_monochrome(&img);\n img.save(\"lena-mono.png\").expect(\"could not save result image\");\n}\n"} {"name":"Boolean values","C":"int a = 0;\nint b = 1;\nint c;\nstring str1 = \"initialized string\";\nstring str2; \n\nif (a) {puts(\"first test a is false\");} \nif (b) {puts(\"second test b is true\");} \nif (c) {puts(\"third test b is false\");} \nif (!defined(c)) {puts(\"fourth test is true\");} \nif (str1) {puts(\"fifth test str1 is true\");} \nif (str2) {puts(\"sixth test str2 is false\");} \n","Rust":"fn main() {\n \n \n \n\n let true_value = true;\n if true_value {\n println!(\"foo is {}.\", true_value);\n }\n\n let false_value = false;\n if !false_value {\n println!(\"bar is {}.\", false_value);\n }\n}\n"} {"name":"CSV to HTML translation","C":"#include \n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!<\/angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"\\n
\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"<\/td><\/tr>\\n
\"); break;\n\t\tcase ',': printf(\"<\/td>\"); break;\n\t\tcase '<': printf(\"<\"); break;\n\t\tcase '>': printf(\">\"); break;\n\t\tcase '&': printf(\"&\"); break;\n\t\tdefault: putchar(*s);\n\t\t}\n\t}\n\tputs(\"<\/td><\/tr>\\n<\/table>\");\n\n\treturn 0;\n}\n","Rust":"static INPUT : &'static str =\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!<\/angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n\nfn main() {\n print!(\"\\n
\");\n for c in INPUT.chars() {\n match c {\n '\\n' => print!(\"<\/td><\/tr>\\n
\"),\n ',' => print!(\"<\/td>\"),\n '<' => print!(\"<\"),\n '>' => print!(\">\"),\n '&' => print!(\"&\"),\n _ => print!(\"{}\", c)\n }\n }\n println!(\"<\/td><\/tr>\\n<\/table>\");\n}\n"} {"name":"Call a foreign-language function","C":"\n\n\n\n#include \n\nvoid sayHello(char* name){\n printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n return num * 2;\n}\n","Rust":"extern crate libc;\n\n\nextern {\n fn add_input(in1: libc::c_int, in2: libc::c_int) -> libc::c_int;\n}\n\nfn main() {\n let (in1, in2) = (5, 4);\n let output = unsafe {\n add_input(in1, in2) };\n assert!( (output == (in1 + in2) ),\"Error in sum calculation\") ;\n}\n"} {"name":"Call a function","C":"\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n} \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n int arg1;\n int arg2;\n char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv(); \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n","Rust":"fn main() {\n \n fn no_args() {}\n \n no_args();\n\n \n \n fn adds_one(num: i32) -> i32 {\n \n num + 1\n }\n adds_one(1);\n\n \n \n \n fn prints_argument(maybe: Option) {\n match maybe {\n Some(num) => println!(\"{}\", num),\n None => println!(\"No value given\"),\n };\n }\n prints_argument(Some(3));\n prints_argument(None);\n\n \n fn prints_argument_into(maybe: I)\n where I: Into>\n {\n match maybe.into() {\n Some(num) => println!(\"{}\", num),\n None => println!(\"No value given\"),\n };\n }\n prints_argument_into(3);\n prints_argument_into(None);\n\n \n \n\n \n\n \n\n \n adds_one(1) + adds_one(5); \n\n \n let two = adds_one(1);\n\n \n \n\n \n\n \n \n \n\n let mut v = vec![1, 2, 3, 4, 5, 6];\n\n \n fn add_one_to_first_element(vector: &mut Vec) {\n vector[0] += 1;\n }\n add_one_to_first_element(&mut v);\n \n fn print_first_element(vector: &Vec) {\n println!(\"{}\", vector[0]);\n }\n print_first_element(&v);\n\n \n fn consume_vector(vector: Vec) {\n \n }\n consume_vector(v);\n \n \n\n \n \n fn average(x: f64, y: f64) -> f64 {\n (x + y) \/ 2.0\n }\n let average_with_four = |y| average(4.0, y);\n average_with_four(2.0);\n\n\n}\n"} {"name":"Carmichael 3 strong pseudoprimes","C":"#include \n\n\n#define mod(n,m) ((((n)\u00a0% (m)) + (m))\u00a0% (m))\n\nint is_prime(unsigned int n)\n{\n if (n <= 3) {\n return n > 1;\n }\n else if (!(n % 2) || !(n % 3)) {\n return 0;\n }\n else {\n unsigned int i;\n for (i = 5; i*i <= n; i += 6)\n if (!(n % i) || !(n % (i + 2)))\n return 0;\n return 1;\n }\n}\n\nvoid carmichael3(int p1)\n{\n if (!is_prime(p1)) return;\n\n int h3, d, p2, p3;\n for (h3 = 1; h3 < p1; ++h3) {\n for (d = 1; d < h3 + p1; ++d) {\n if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n p2 = 1 + ((p1 - 1) * (h3 + p1)\/d);\n if (!is_prime(p2)) continue;\n p3 = 1 + (p1 * p2 \/ h3);\n if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n printf(\"%d %d %d\\n\", p1, p2, p3);\n }\n }\n }\n}\n\nint main(void)\n{\n int p1;\n for (p1 = 2; p1 < 62; ++p1)\n carmichael3(p1);\n return 0;\n}\n","Rust":"fn is_prime(n: i64) -> bool {\n if n > 1 {\n (2..((n \/ 2) + 1)).all(|x| n % x != 0)\n } else {\n false\n }\n}\n\n\nfn modulo(n: i64, m: i64) -> i64 {\n ((n % m) + m) % m\n}\n\nfn carmichael(p1: i64) -> Vec<(i64, i64, i64)> {\n let mut results = Vec::new();\n if !is_prime(p1) {\n return results;\n }\n\n for h3 in 2..p1 {\n for d in 1..(h3 + p1) {\n if (h3 + p1) * (p1 - 1) % d != 0 || modulo(-p1 * p1, h3) != d % h3 {\n continue;\n }\n\n let p2 = 1 + ((p1 - 1) * (h3 + p1) \/ d);\n if !is_prime(p2) {\n continue;\n }\n\n let p3 = 1 + (p1 * p2 \/ h3);\n if !is_prime(p3) || ((p2 * p3) % (p1 - 1) != 1) {\n continue;\n }\n\n results.push((p1, p2, p3));\n }\n }\n\n results\n}\n\nfn main() {\n (1..62)\n .filter(|&x| is_prime(x))\n .map(carmichael)\n .filter(|x| !x.is_empty())\n .flat_map(|x| x)\n .inspect(|x| println!(\"{:?}\", x))\n .count(); \n}\n"} {"name":"Case-sensitivity of identifiers","C":"#include \n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n return 0;\n}\n","Rust":"fn main() {\n let dog = \"Benjamin\";\n let Dog = \"Samba\";\n let DOG = \"Bernie\";\n println!(\"The three dogs are named {}, {} and {}.\", dog, Dog, DOG);\n}\n"} {"name":"Change e letters to i in words","C":"#include \n#include \n#include \n#include \n\n#define MAX_WORD_SIZE 128\n#define MIN_WORD_LENGTH 6\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nint string_compare(const void* p1, const void* p2) {\n const char* const* s1 = p1;\n const char* const* s2 = p2;\n return strcmp(*s1, *s2);\n}\n\nchar* string_copy(const char* str) {\n size_t len = strlen(str);\n char* str2 = xmalloc(len + 1);\n memcpy(str2, str, len + 1);\n return str2;\n}\n\nchar** load_dictionary(const char* filename, size_t* psize) {\n FILE* in = fopen(filename, \"r\");\n if (!in) {\n perror(filename);\n return NULL;\n }\n size_t size = 0, capacity = 1024;\n char** dictionary = xmalloc(sizeof(char*) * capacity);\n char line[MAX_WORD_SIZE];\n while (fgets(line, sizeof(line), in)) {\n size_t len = strlen(line);\n if (len > MIN_WORD_LENGTH) {\n line[len - 1] = '\\0'; \n char* str = string_copy(line);\n if (size == capacity) {\n capacity <<= 1;\n dictionary = xrealloc(dictionary, sizeof(char*) * capacity);\n }\n dictionary[size++] = str;\n }\n }\n fclose(in);\n qsort(dictionary, size, sizeof(char*), string_compare);\n *psize = size;\n return dictionary;\n}\n\nvoid free_dictionary(char** dictionary, size_t size) {\n for (size_t i = 0; i < size; ++i)\n free(dictionary[i]);\n free(dictionary);\n}\n\nbool find_word(char** dictionary, size_t size, const char* word) {\n return bsearch(&word, dictionary, size, sizeof(char*), string_compare) !=\n NULL;\n}\n\nint main(int argc, char** argv) {\n const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n size_t size = 0;\n char** dictionary = load_dictionary(filename, &size);\n if (dictionary == NULL)\n return EXIT_FAILURE;\n int count = 0;\n for (size_t i = 0; i < size; ++i) {\n const char* word1 = dictionary[i];\n if (strchr(word1, 'e') != NULL) {\n char* word2 = string_copy(word1);\n for (char* p = word2; *p; ++p) {\n if (*p == 'e')\n *p = 'i';\n }\n if (find_word(dictionary, size, word2))\n printf(\"%2d.\u00a0%-10s -> %s\\n\", ++count, word1, word2);\n free(word2);\n }\n }\n free_dictionary(dictionary, size);\n return EXIT_SUCCESS;\n}\n","Rust":"use std::collections::BTreeSet;\nuse std::fs::File;\nuse std::io::{self, BufRead};\n\nfn load_dictionary(filename: &str, min_length: usize) -> std::io::Result> {\n let file = File::open(filename)?;\n let mut dict = BTreeSet::new();\n for line in io::BufReader::new(file).lines() {\n let word = line?;\n if word.len() >= min_length {\n dict.insert(word);\n }\n }\n Ok(dict)\n}\n\nfn main() {\n match load_dictionary(\"unixdict.txt\", 6) {\n Ok(dictionary) => {\n let mut count = 0;\n for word in dictionary.iter().filter(|x| x.contains(\"e\")) {\n let word2 = word.replace(\"e\", \"i\");\n if dictionary.contains(&word2) {\n count += 1;\n println!(\"{:2}. {:<9} -> {}\", count, word, word2);\n }\n }\n }\n Err(error) => eprintln!(\"{}\", error),\n }\n}\n"} {"name":"Check input device is a terminal","C":"#include \t\n#include \t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n","Rust":"\n\nextern crate libc;\n\nfn main() {\n let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0;\n if istty {\n println!(\"stdout is tty\");\n } else {\n println!(\"stdout is not tty\");\n }\n}\n"} {"name":"Colour bars_Display","C":"#include\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK); \n\tclrscr();\n\t\n\tfor(colour=0;colour {\n if input.virtual_keycode == Some(VirtualKeyCode::Escape) {\n *flow = ControlFlow::Exit;\n }\n }\n Event::RedrawRequested(_) | Event::WindowEvent {\n event: WindowEvent::Focused(true), ..\n } => {\n image_buffer.render().unwrap();\n }\n _ => {}\n }\n });\n}\n"} {"name":"Conjugate transpose","C":"\n\n#include\n#include\n#include\n\ntypedef struct\n{\n int rows, cols;\n complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n int i, j;\n matrix b;\n\n b.rows = a.cols;\n b.cols = a.rows;\n\n b.z = malloc (b.rows * sizeof (complex *));\n\n for (i = 0; i < b.rows; i++)\n {\n b.z[i] = malloc (b.cols * sizeof (complex));\n for (j = 0; j < b.cols; j++)\n {\n b.z[i][j] = conj (a.z[j][i]);\n }\n }\n\n return b;\n}\n\nint\nisHermitian (matrix a)\n{\n int i, j;\n matrix b = transpose (a);\n\n if (b.rows == a.rows && b.cols == a.cols)\n {\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if (b.z[i][j] != a.z[i][j])\n return 0;\n }\n }\n }\n\n else\n return 0;\n\n return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n matrix c;\n int i, j;\n\n if (a.cols == b.rows)\n {\n c.rows = a.rows;\n c.cols = b.cols;\n\n c.z = malloc (c.rows * (sizeof (complex *)));\n\n for (i = 0; i < c.rows; i++)\n {\n c.z[i] = malloc (c.cols * sizeof (complex));\n c.z[i][j] = 0 + 0 * I;\n for (j = 0; j < b.cols; j++)\n {\n c.z[i][j] += a.z[i][j] * b.z[j][i];\n }\n }\n\n }\n\n return c;\n}\n\nint\nisNormal (matrix a)\n{\n int i, j;\n matrix a_ah, ah_a;\n\n if (a.rows != a.cols)\n return 0;\n\n a_ah = multiply (a, transpose (a));\n ah_a = multiply (transpose (a), a);\n\n for (i = 0; i < a.rows; i++)\n {\n for (j = 0; j < a.cols; j++)\n {\n if (a_ah.z[i][j] != ah_a.z[i][j])\n return 0;\n }\n }\n\n return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n matrix b;\n int i, j;\n if (isNormal (a) == 1)\n {\n b = multiply (a, transpose(a));\n\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n return 0;\n }\n }\n return 1;\n }\n return 0;\n}\n\n\nint\nmain ()\n{\n complex z = 3 + 4 * I;\n matrix a, aT;\n int i, j;\n printf (\"Enter rows and columns\u00a0:\");\n scanf (\"%d%d\", &a.rows, &a.cols);\n\n a.z = malloc (a.rows * sizeof (complex *));\n printf (\"Randomly Generated Complex Matrix A is\u00a0: \");\n for (i = 0; i < a.rows; i++)\n {\n printf (\"\\n\");\n a.z[i] = malloc (a.cols * sizeof (complex));\n for (j = 0; j < a.cols; j++)\n {\n a.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n }\n }\n\n aT = transpose (a);\n\n printf (\"\\n\\nTranspose of Complex Matrix A is\u00a0: \");\n for (i = 0; i < aT.rows; i++)\n {\n printf (\"\\n\");\n aT.z[i] = malloc (aT.cols * sizeof (complex));\n for (j = 0; j < aT.cols; j++)\n {\n aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n }\n }\n\n printf (\"\\n\\nComplex Matrix A %s hermitian\",\n isHermitian (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s unitary\",\n isUnitary (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s normal\",\n isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n return 0;\n}\n","Rust":"extern crate num; \n\nuse num::complex::Complex;\nuse std::ops::Mul;\nuse std::fmt;\n\n\n#[derive(Debug, PartialEq)]\nstruct Matrix {\n grid: [[Complex; 2]; 2], \n}\n\n\nimpl Matrix { \n fn conjugate_transpose(&self) -> Matrix {\n Matrix {grid: [[self.grid[0][0].conj(), self.grid[1][0].conj()],\n [self.grid[0][1].conj(), self.grid[1][1].conj()]]}\n }\n}\n\nimpl Mul for Matrix { \n type Output = Matrix;\n\n fn mul(self, other: Matrix) -> Matrix {\n Matrix {grid: [[self.grid[0][0]*other.grid[0][0] + self.grid[0][1]*other.grid[1][0],\n self.grid[0][0]*other.grid[0][1] + self.grid[0][1]*other.grid[1][1]],\n [self.grid[1][0]*other.grid[0][0] + self.grid[1][1]*other.grid[1][0],\n self.grid[1][0]*other.grid[1][0] + self.grid[1][1]*other.grid[1][1]]]}\n }\n}\n\nimpl Copy for Matrix {} \nimpl Clone for Matrix {\n fn clone(&self) -> Matrix {\n *self\n }\n}\n\nimpl fmt::Display for Matrix { \n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"({}, {})\\n({}, {})\", self.grid[0][0], self.grid[0][1], self.grid[1][0], self.grid[1][1])\n }\n}\n\nfn main() {\n let a = Matrix {grid: [[Complex::new(3.0, 0.0), Complex::new(2.0, 1.0)],\n [Complex::new(2.0, -1.0), Complex::new(1.0, 0.0)]]};\n\n let b = Matrix {grid: [[Complex::new(0.5, 0.5), Complex::new(0.5, -0.5)],\n [Complex::new(0.5, -0.5), Complex::new(0.5, 0.5)]]};\n\n test_type(a);\n test_type(b);\n}\n\nfn test_type(mat: Matrix) {\n let identity = Matrix {grid: [[Complex::new(1.0, 0.0), Complex::new(0.0, 0.0)],\n [Complex::new(0.0, 0.0), Complex::new(1.0, 0.0)]]};\n let mat_conj = mat.conjugate_transpose();\n\n println!(\"Matrix: \\n{}\\nConjugate transpose: \\n{}\", mat, mat_conj);\n\n if mat == mat_conj {\n println!(\"Hermitian?: TRUE\");\n } else {\n println!(\"Hermitian?: FALSE\");\n }\n\n if mat*mat_conj == mat_conj*mat {\n println!(\"Normal?: TRUE\");\n } else {\n println!(\"Normal?: FALSE\");\n }\n\n if mat*mat_conj == identity {\n println!(\"Unitary?: TRUE\");\n } else {\n println!(\"Unitary?: FALSE\");\n }\n}\n"} {"name":"Copy a string","C":"#include \t\n#include \t\n#include \n\nint\nmain()\n{\n\tsize_t len;\n\tchar src[] = \"Hello\";\n\tchar dst1[80], dst2[80];\n\tchar *dst3, *ref;\n\n\t\n\tstrcpy(dst1, src);\n\n\t\n\tlen = strlen(src);\n\tif (len >= sizeof dst2) {\n\t\tfputs(\"The buffer is too small!\\n\", stderr);\n\t\texit(1);\n\t}\n\tmemcpy(dst2, src, len + 1);\n\n\t\n\tdst3 = strdup(src);\n\tif (dst3 == NULL) {\n\t\t\n\t\tperror(\"strdup\");\n\t\texit(1);\n\t}\n\n\t\n\tref = src;\n\n\t\n\tmemset(src, '-', 5);\n\n\tprintf(\" src: %s\\n\", src); \n\tprintf(\"dst1: %s\\n\", dst1); \n\tprintf(\"dst2: %s\\n\", dst2); \n\tprintf(\"dst3: %s\\n\", dst3); \n\tprintf(\" ref: %s\\n\", ref); \n\n\t\n\tfree(dst3);\n\n\treturn 0;\n}\n","Rust":"fn main() {\n let s1 = \"A String\";\n let mut s2 = s1;\n\n s2 = \"Another String\";\n\n println!(\"s1 = {}, s2 = {}\", s1, s2);\n}\n"} {"name":"Count occurrences of a substring","C":"#include \n#include \n\nint match(const char *s, const char *p, int overlap)\n{\n int c = 0, l = strlen(p);\n\n while (*s != '\\0') {\n if (strncmp(s++, p, l)) continue;\n if (!overlap) s += l - 1;\n c++;\n }\n return c;\n}\n\nint main()\n{\n printf(\"%d\\n\", match(\"the three truths\", \"th\", 0));\n printf(\"overlap:%d\\n\", match(\"abababababa\", \"aba\", 1));\n printf(\"not: %d\\n\", match(\"abababababa\", \"aba\", 0));\n return 0;\n}\n","Rust":"fn main() {\n println!(\"{}\",\"the three truths\".matches(\"th\").count());\n println!(\"{}\",\"ababababab\".matches(\"abab\").count());\n}\n"} {"name":"Create an object at a given address","C":"#include \n\nint main()\n{\n int intspace;\n int *address;\n\n address = &intspace; \n *address = 65535;\n printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n \n *((char*)address) = 0x00;\n *((char*)address+1) = 0x00;\n *((char*)address+2) = 0xff;\n *((char*)address+3) = 0xff; \n \n printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n return 0;\n}\n","Rust":"use std::{mem,ptr};\n\nfn main() {\n let mut data: i32;\n\n \n \n unsafe {data = mem::uninitialized()}\n\n \n let address = &mut data as *mut _;\n\n unsafe {ptr::write(address, 5)}\n println!(\"{0:p}: {0}\", &data);\n\n unsafe {ptr::write(address, 6)}\n println!(\"{0:p}: {0}\", &data);\n\n}\n"} {"name":"Dice game probabilities","C":"#include \n#include \n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n ulong result = 1;\n for (uint i = 1; i <= y; i++)\n result *= x;\n return result;\n}\n\nuint min(const uint x, const uint y) {\n return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n if (n_dice == 0) {\n counts[s]++;\n return;\n }\n\n for (uint i = 1; i < n_sides + 1; i++)\n throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n const uint n_sides2, const uint n_dice2) {\n const uint len1 = (n_sides1 + 1) * n_dice1;\n uint C1[len1];\n for (uint i = 0; i < len1; i++)\n C1[i] = 0;\n throw_die(n_sides1, n_dice1, 0, C1);\n\n const uint len2 = (n_sides2 + 1) * n_dice2;\n uint C2[len2];\n for (uint j = 0; j < len2; j++)\n C2[j] = 0;\n throw_die(n_sides2, n_dice2, 0, C2);\n\n const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n double tot = 0;\n for (uint i = 0; i < len1; i++)\n for (uint j = 0; j < min(i, len2); j++)\n tot += (double)C1[i] * C2[j] \/ p12;\n return tot;\n}\n\nint main() {\n printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n return 0;\n}\n","Rust":"\n\nfn get_totals(dice: usize, faces: usize) -> Vec {\n let mut result = vec![1.0; faces + 1];\n for d in 2..=dice {\n let mut tmp = vec![0.0; d * faces + 1];\n for i in d - 1..result.len() {\n for j in 1..=faces {\n tmp[i + j] += result[i];\n }\n }\n result = tmp;\n }\n result\n}\n\nfn probability(dice1: usize, faces1: usize, dice2: usize, faces2: usize) -> f64 {\n let totals1 = get_totals(dice1, faces1);\n let totals2 = get_totals(dice2, faces2);\n let mut wins = 0.0;\n let mut total = 0.0;\n for i in dice1..totals1.len() {\n for j in dice2..totals2.len() {\n let n = totals1[i] * totals2[j];\n total += n;\n if j < i {\n wins += n;\n }\n }\n }\n wins \/ total\n}\n\nfn main() {\n println!(\"{}\", probability(9, 4, 6, 6));\n println!(\"{}\", probability(5, 10, 6, 7));\n}\n"} {"name":"Dining philosophers","C":"#include \n#include \n#include \n#include \n#include \n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n","Rust":"use std::thread;\nuse std::sync::{Mutex, Arc};\n\nstruct Philosopher {\n name: String,\n left: usize,\n right: usize,\n}\n\nimpl Philosopher {\n fn new(name: &str, left: usize, right: usize) -> Philosopher {\n Philosopher {\n name: name.to_string(),\n left: left,\n right: right,\n }\n }\n\n fn eat(&self, table: &Table) {\n let _left = table.forks[self.left].lock().unwrap();\n let _right = table.forks[self.right].lock().unwrap();\n\n println!(\"{} is eating.\", self.name);\n\n thread::sleep_ms(1000);\n\n println!(\"{} is done eating.\", self.name);\n }\n}\n\nstruct Table {\n forks: Vec>,\n}\n\nfn main() {\n let table = Arc::new(Table { forks: vec![\n Mutex::new(()),\n Mutex::new(()),\n Mutex::new(()),\n Mutex::new(()),\n Mutex::new(()),\n ]});\n\n let philosophers = vec![\n Philosopher::new(\"Baruch Spinoza\", 0, 1),\n Philosopher::new(\"Gilles Deleuze\", 1, 2),\n Philosopher::new(\"Karl Marx\", 2, 3),\n Philosopher::new(\"Friedrich Nietzsche\", 3, 4),\n Philosopher::new(\"Michel Foucault\", 0, 4),\n ];\n\n let handles: Vec<_> = philosophers.into_iter().map(|p| {\n let table = table.clone();\n\n thread::spawn(move || {\n p.eat(&table);\n })\n }).collect();\n\n for h in handles {\n h.join().unwrap();\n }\n}\n"} {"name":"Disarium numbers","C":"#include \n#include \n#include \n\nint power (int base, int exponent) {\n int result = 1;\n for (int i = 1; i <= exponent; i++) {\n result *= base;\n }\n return result;\n}\n\nint is_disarium (int num) {\n int n = num;\n int sum = 0;\n int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n while (n > 0) {\n sum += power(n % 10, len);\n n \/= 10;\n len--;\n }\n\n return num == sum;\n}\n\nint main() {\n int count = 0;\n int i = 0;\n while (count < 19) {\n if (is_disarium(i)) {\n printf(\"%d \", i);\n count++;\n }\n i++;\n }\n printf(\"%s\\n\", \"\\n\");\n}\n","Rust":"fn power(n: i32, exp: i32) -> i32 {\n let mut result = 1;\n for _i in 0..exp {\n result *= n;\n }\n return result;\n}\n\nfn is_disarium(num: i32) -> bool {\n let mut n = num;\n let mut sum = 0;\n let mut i = 1;\n let len = num.to_string().len();\n while n > 0 {\n sum += power(n % 10, len as i32 - i + 1);\n n \/= 10;\n i += 1\n }\n return sum == num;\n}\n\n\nfn main() {\n let mut i = 0;\n let mut count = 0;\n while count <= 18 {\n if is_disarium(i) {\n print!(\"{} \", i);\n count += 1;\n }\n i += 1;\n }\n println!(\"{}\", \" \")\n}\n"} {"name":"Draw a pixel","C":"#include\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n","Rust":"extern crate piston_window;\nextern crate image;\n\nuse piston_window::*;\n\nfn main() {\n let (width, height) = (320, 240);\n \n let mut window: PistonWindow =\n WindowSettings::new(\"Red Pixel\", [width, height])\n .exit_on_esc(true).build().unwrap();\n\n \n \n let mut canvas = image::ImageBuffer::new(width, height);\n canvas.put_pixel(100, 100, image::Rgba([0xff, 0, 0, 0xff]));\n\n \n let texture: G2dTexture = Texture::from_image(\n &mut window.factory,\n &canvas,\n &TextureSettings::new()\n ).unwrap();\n\n \n while let Some(event) = window.next() {\n window.draw_2d(&event, |context, graphics| {\n clear([1.0; 4], graphics);\n image(&texture,\n context.transform,\n graphics);\n });\n }\n}\n"} {"name":"Draw a sphere","C":"#include \n#include \n#include \n#include \n#include \n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n v[0] \/= len; v[1] \/= len; v[2] \/= len;\n}\n\ndouble dot(double *x, double *y)\n{\n double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n int i, j, intensity;\n double b;\n double vec[3], x, y;\n for (i = floor(-R); i <= ceil(R); i++) {\n x = i + .5;\n for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n y = j \/ 2. + .5;\n if (x * x + y * y <= R * R) {\n vec[0] = x;\n vec[1] = y;\n vec[2] = sqrt(R * R - x * x - y * y);\n normalize(vec);\n b = pow(dot(light, vec), k) + ambient;\n intensity = (1 - b) * (sizeof(shades) - 1);\n if (intensity < 0) intensity = 0;\n if (intensity >= sizeof(shades) - 1)\n intensity = sizeof(shades) - 2;\n putchar(shades[intensity]);\n } else\n putchar(' ');\n }\n putchar('\\n');\n }\n}\n\n\nint main()\n{\n normalize(light);\n draw_sphere(20, 4, .1);\n draw_sphere(10, 2, .4);\n\n return 0;\n}\n","Rust":"\n\n\nuse image::{GrayImage, Luma};\n\ntype Vector = [f64; 3];\n\nfn normalize(v: &mut Vector) {\n let inv_len = 1.0\/dot_product(v, v).sqrt();\n v[0] *= inv_len;\n v[1] *= inv_len;\n v[2] *= inv_len;\n}\n\nfn dot_product(v1: &Vector, v2: &Vector) -> f64 {\n v1.iter().zip(v2.iter()).map(|(x, y)| *x * *y).sum()\n}\n\nfn draw_sphere(radius: u32, k: f64, ambient: f64, dir: &Vector) -> GrayImage {\n let width = radius * 4;\n let height = radius * 3;\n let mut image = GrayImage::new(width, height);\n let mut vec = [0.0; 3];\n let diameter = radius * 2;\n let r = radius as f64;\n let xoffset = (width - diameter)\/2;\n let yoffset = (height - diameter)\/2;\n for i in 0..diameter {\n let x = i as f64 - r;\n for j in 0..diameter {\n let y = j as f64 - r;\n let z = r * r - x * x - y * y;\n if z >= 0.0 {\n vec[0] = x;\n vec[1] = y;\n vec[2] = z.sqrt();\n normalize(&mut vec);\n let mut s = dot_product(&dir, &vec);\n if s < 0.0 {\n s = 0.0;\n }\n let mut lum = 255.0 * (s.powf(k) + ambient)\/(1.0 + ambient);\n if lum < 0.0 {\n lum = 0.0;\n } else if lum > 255.0 {\n lum = 255.0;\n }\n image.put_pixel(i + xoffset, j + yoffset, Luma([lum as u8]));\n }\n }\n }\n image\n}\n\nfn main() {\n let mut dir = [-30.0, -30.0, 50.0];\n normalize(&mut dir);\n match draw_sphere(200, 1.5, 0.2, &dir).save(\"sphere.png\") {\n Ok(()) => {}\n Err(error) => eprintln!(\"{}\", error),\n }\n}\n"} {"name":"Enforced immutability","C":"#define PI 3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n","Rust":"let x = 3;\nx += 2;\n"} {"name":"Entropy_Narcissist","C":"#include \n#include \n#include \n#include \n#include \n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i>(iter: I) -> f32 {\n let mut histogram = [0u64; 256];\n let mut len = 0u64;\n\n for b in iter {\n histogram[b as usize] += 1;\n len += 1;\n }\n \n histogram\n .iter()\n .cloned()\n .filter(|&h| h > 0)\n .map(|h| h as f32 \/ len as f32)\n .map(|ratio| -ratio * ratio.log2())\n .sum()\n}\n\nfn main() {\n let name = std::env::args().nth(0).expect(\"Could not get program name.\");\n let file = BufReader::new(File::open(name).expect(\"Could not read file.\"));\n println!(\"Entropy is {}.\", entropy(file.bytes().flatten()));\n}\n"} {"name":"Exceptions","C":"#include \n \nenum { MY_EXCEPTION = 1 }; \n \njmp_buf env;\n \nvoid foo()\n{\n longjmp(env, MY_EXCEPTION); \n}\n \nvoid call_foo()\n{\n switch (setjmp(env)) {\n case 0: \n foo();\n break;\n case MY_EXCEPTION: \n \n break;\n default:\n \n \n \n \n }\n}\n","Rust":"\n\nuse std::io::{Error, ErrorKind};\n\n\n\n\nfn valid_function() -> Result {\n Ok(100)\n}\n\nfn errored_function() -> Result {\n Err(Error::new(ErrorKind::Other, \"Something wrong happened.\"))\n}\n\n\nfn panicking_function() {\n panic!(\"Unrecoverable state reached\");\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_valid_function() {\n let result = match valid_function() {\n Ok(number) => number,\n Err(_) => panic!(\"This is not going to happen\"),\n };\n assert_eq!(result, 100);\n }\n\n #[test]\n fn test_errored_function() {\n let result = match errored_function() {\n Ok(_) => panic!(\"This is not going to happen\"),\n Err(e) => {\n assert_eq!(e.to_string(), \"Something wrong happened.\");\n 0\n }\n };\n assert_eq!(result, 0);\n }\n\n #[test]\n #[should_panic]\n fn test_panicking_function() {\n panicking_function();\n }\n}\n"} {"name":"Extensible prime generator","C":"#include \n#include \n#include \n#include \n\n#define CHUNK_BYTES (32 << 8)\n#define CHUNK_SIZE (CHUNK_BYTES << 6)\n\nint field[CHUNK_BYTES];\n#define GET(x) (field[(x)>>6] & 1<<((x)>>1&31))\n#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))\n\ntypedef unsigned uint;\ntypedef struct {\n uint *e;\n uint cap, len;\n} uarray;\nuarray primes, offset;\n\nvoid push(uarray *a, uint n)\n{\n if (a->len >= a->cap) {\n if (!(a->cap *= 2)) a->cap = 16;\n a->e = realloc(a->e, sizeof(uint) * a->cap);\n }\n a->e[a->len++] = n;\n}\n\nuint low;\nvoid init(void)\n{\n uint p, q;\n\n unsigned char f[1<<16];\n memset(f, 0, sizeof(f));\n push(&primes, 2);\n push(&offset, 0);\n for (p = 3; p < 1<<16; p += 2) {\n if (f[p]) continue;\n for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;\n push(&primes, p);\n push(&offset, q);\n }\n low = 1<<16;\n}\n\nvoid sieve(void)\n{\n uint i, p, q, hi, ptop;\n if (!low) init();\n\n memset(field, 0, sizeof(field));\n\n hi = low + CHUNK_SIZE;\n ptop = sqrt(hi) * 2 + 1;\n\n for (i = 1; (p = primes.e[i]*2) < ptop; i++) {\n for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)\n SET(q);\n offset.e[i] = q + low;\n }\n\n for (p = 1; p < CHUNK_SIZE; p += 2)\n if (!GET(p)) push(&primes, low + p);\n\n low = hi;\n}\n\nint main(void)\n{\n uint i, p, c;\n\n while (primes.len < 20) sieve();\n printf(\"First 20:\");\n for (i = 0; i < 20; i++)\n printf(\" %u\", primes.e[i]);\n putchar('\\n');\n\n while (primes.e[primes.len-1] < 150) sieve();\n printf(\"Between 100 and 150:\");\n for (i = 0; i < primes.len; i++) {\n if ((p = primes.e[i]) >= 100 && p < 150)\n printf(\" %u\", primes.e[i]);\n }\n putchar('\\n');\n\n while (primes.e[primes.len-1] < 8000) sieve();\n for (i = c = 0; i < primes.len; i++)\n if ((p = primes.e[i]) >= 7700 && p < 8000) c++;\n printf(\"%u primes between 7700 and 8000\\n\", c);\n\n for (c = 10; c <= 100000000; c *= 10) {\n while (primes.len < c) sieve();\n printf(\"%uth prime: %u\\n\", c, primes.e[c-1]);\n }\n\n return 0;\n}\n","Rust":"mod pagesieve;\n\nuse pagesieve::{count_primes_paged, primes_paged};\n\nfn main() {\n println!(\"First 20 primes:\\n {:?}\",\n primes_paged().take(20).collect::>());\n println!(\"Primes between 100 and 150:\\n {:?}\",\n primes_paged().skip_while(|&x| x < 100)\n .take_while(|&x| x < 150)\n .collect::>());\n let diff = count_primes_paged(8000) - count_primes_paged(7700);\n println!(\"There are {} primes between 7,700 and 8,000\", diff);\n \n println!(\"The 10,000th prime is {}\", primes_paged().nth(10_000 - 1).unwrap());\n}\n"} {"name":"Extra primes","C":"#include \n#include \n#include \n\nunsigned int next_prime_digit_number(unsigned int n) {\n if (n == 0)\n return 2;\n switch (n % 10) {\n case 2:\n return n + 1;\n case 3:\n case 5:\n return n + 2;\n default:\n return 2 + next_prime_digit_number(n\/10) * 10;\n }\n}\n\nbool is_prime(unsigned int n) {\n if (n < 2)\n return false;\n if ((n & 1) == 0)\n return n == 2;\n if (n % 3 == 0)\n return n == 3;\n if (n % 5 == 0)\n return n == 5;\n static const unsigned int wheel[] = { 4,2,4,2,4,6,2,6 };\n unsigned int p = 7;\n for (;;) {\n for (int w = 0; w < sizeof(wheel)\/sizeof(wheel[0]); ++w) {\n if (p * p > n)\n return true;\n if (n % p == 0)\n return false;\n p += wheel[w];\n }\n }\n}\n\nunsigned int digit_sum(unsigned int n) {\n unsigned int sum = 0;\n for (; n > 0; n \/= 10)\n sum += n % 10;\n return sum;\n}\n\nint main() {\n setlocale(LC_ALL, \"\");\n const unsigned int limit1 = 10000;\n const unsigned int limit2 = 1000000000;\n const int last = 10;\n unsigned int p = 0, n = 0;\n unsigned int extra_primes[last];\n printf(\"Extra primes under\u00a0%'u:\\n\", limit1);\n while ((p = next_prime_digit_number(p)) < limit2) {\n if (is_prime(digit_sum(p)) && is_prime(p)) {\n ++n;\n if (p < limit1)\n printf(\"%2u:\u00a0%'u\\n\", n, p);\n extra_primes[n % last] = p;\n }\n }\n printf(\"\\nLast %d extra primes under\u00a0%'u:\\n\", last, limit2);\n for (int i = last - 1; i >= 0; --i)\n printf(\"%'u:\u00a0%'u\\n\", n-i, extra_primes[(n-i) % last]);\n return 0;\n}\n","Rust":"\n\n\nfn is_prime(n: u64) -> bool {\n primal::is_prime(n)\n}\n\nfn next_prime_digit_number(n: u64) -> u64 {\n if n == 0 {\n return 2;\n }\n match n % 10 {\n 2 => n + 1,\n 3 | 5 => n + 2,\n _ => 2 + next_prime_digit_number(n \/ 10) * 10,\n }\n}\n\nfn digit_sum(mut n: u64) -> u64 {\n let mut sum = 0;\n while n > 0 {\n sum += n % 10;\n n \/= 10;\n }\n return sum;\n}\n\nfn main() {\n let limit1 = 10000;\n let limit2 = 1000000000;\n let last = 10;\n let mut p = 0;\n let mut n = 0;\n let mut extra_primes = vec![0; last];\n println!(\"Extra primes under {}:\", limit1);\n loop {\n p = next_prime_digit_number(p);\n if p >= limit2 {\n break;\n }\n if is_prime(digit_sum(p)) && is_prime(p) {\n n += 1;\n if p < limit1 {\n println!(\"{:2}: {}\", n, p);\n }\n extra_primes[n % last] = p;\n }\n }\n println!(\"\\nLast {} extra primes under {}:\", last, limit2);\n let mut i = last;\n while i > 0 {\n i -= 1;\n println!(\"{}: {}\", n - i, extra_primes[(n - i) % last]);\n }\n}\n"} {"name":"Extract file extension","C":"#include \n#include \n#include \n#include \n\n\nchar* file_ext(const char *string)\n{\n assert(string != NULL);\n char *ext = strrchr(string, '.');\n\n if (ext == NULL)\n return (char*) string + strlen(string);\n\n for (char *iter = ext + 1; *iter != '\\0'; iter++) {\n if (!isalnum((unsigned char)*iter))\n return (char*) string + strlen(string);\n }\n\n return ext;\n}\n\nint main(void)\n{\n const char *testcases[][2] = {\n {\"http:\n {\"CharacterModel.3DS\", \".3DS\"},\n {\".desktop\", \".desktop\"},\n {\"document\", \"\"},\n {\"document.txt_backup\", \"\"},\n {\"\/etc\/pam.d\/login\", \"\"}\n };\n\n int exitcode = 0;\n for (size_t i = 0; i < sizeof(testcases) \/ sizeof(testcases[0]); i++) {\n const char *ext = file_ext(testcases[i][0]);\n if (strcmp(ext, testcases[i][1]) != 0) {\n fprintf(stderr, \"expected '%s' for '%s', got '%s'\\n\",\n testcases[i][1], testcases[i][0], ext);\n exitcode = 1;\n }\n }\n return exitcode;\n}\n","Rust":"use std::path::Path;\n\nfn main() {\n let filenames = &[\n \"http:\n \"CharacterModel.3DS\",\n \".desktop\",\n \"document\",\n \"document.txt_backup\",\n \"\/etc\/pam.d\/login\",\n ];\n\n for filename in filenames {\n println!(\n \"{:34} | {:8} | {:?}\",\n filename,\n extension(filename),\n Path::new(filename).extension()\n );\n }\n}\n\nfn extension(filename: &str) -> &str {\n filename\n .rfind('.')\n .map(|idx| &filename[idx..])\n .filter(|ext| ext.chars().skip(1).all(|c| c.is_ascii_alphanumeric()))\n .unwrap_or(\"\")\n}\n"} {"name":"Extreme floating point values","C":"#include \n\nint main()\n{\n double inf = 1\/0.0;\n double minus_inf = -1\/0.0;\n double minus_zero = -1\/ inf ;\n double nan = 0.0\/0.0;\n\n printf(\"positive infinity: %f\\n\",inf);\n printf(\"negative infinity: %f\\n\",minus_inf);\n printf(\"negative zero: %f\\n\",minus_zero);\n printf(\"not a number: %f\\n\",nan);\n\n \n\n printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n printf(\"1.0\/-0.0 = %f\\n\",1.0\/minus_zero);\n printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n \n\n printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n return 0;\n}\n","Rust":"fn main() {\n let inf: f64 = 1. \/ 0.; \n let minus_inf: f64 = -1. \/ 0.; \n let minus_zero: f64 = -1. \/ inf; \n let nan: f64 = 0. \/ 0.; \n \n println!(\"positive infinity: {:+}\", inf);\n println!(\"negative infinity: {:+}\", minus_inf);\n println!(\"negative zero: {:+?}\", minus_zero);\n println!(\"not a number: {:+}\", nan);\n println!();\n println!(\"+inf + 2.0 = {:+}\", inf + 2.);\n println!(\"+inf - 10.0 = {:+}\", inf - 10.);\n println!(\"+inf + -inf = {:+}\", inf + minus_inf);\n println!(\"0.0 * inf = {:+}\", 0. * inf);\n println!(\"1.0 \/ -0.0 = {:+}\", 1. \/ -0.);\n println!(\"NaN + 1.0 = {:+}\", nan + 1.);\n println!(\"NaN + NaN = {:+}\", nan + nan);\n println!();\n println!(\"NaN == NaN = {}\", nan == nan);\n println!(\"0.0 == -0.0 = {}\", 0. == -0.);\n}\n"} {"name":"FASTA format","C":"#include \n#include \n#include \n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n","Rust":"use std::env;\nuse std::io::{BufReader, Lines};\nuse std::io::prelude::*;\nuse std::fs::File;\n\nfn main() {\n let args: Vec = env::args().collect();\n let f = File::open(&args[1]).unwrap();\n for line in FastaIter::new(f) {\n println!(\"{}\", line);\n }\n}\n\nstruct FastaIter {\n buffer_lines: Lines>,\n current_name: Option,\n current_sequence: String\n}\n\nimpl FastaIter {\n fn new(file: T) -> FastaIter {\n FastaIter { buffer_lines: BufReader::new(file).lines(),\n current_name: None,\n current_sequence: String::new() }\n }\n}\n\nimpl Iterator for FastaIter {\n type Item = String;\n\n fn next(&mut self) -> Option {\n while let Some(l) = self.buffer_lines.next() {\n let line = l.unwrap();\n if line.starts_with(\">\") {\n if self.current_name.is_some() { \n let mut res = String::new();\n res.push_str(self.current_name.as_ref().unwrap());\n res.push_str(\": \");\n res.push_str(&self.current_sequence);\n self.current_name = Some(String::from(&line[1..]));\n self.current_sequence.clear();\n return Some(res);\n } else {\n self.current_name = Some(String::from(&line[1..]));\n self.current_sequence.clear();\n }\n continue;\n }\n self.current_sequence.push_str(line.trim());\n }\n if self.current_name.is_some() {\n let mut res = String::new();\n res.push_str(self.current_name.as_ref().unwrap());\n res.push_str(\": \");\n res.push_str(&self.current_sequence);\n self.current_name = None;\n self.current_sequence.clear();\n self.current_sequence.shrink_to_fit();\n return Some(res);\n }\n None\n }\n}\n"} {"name":"Fibonacci word","C":"#include \n#include \n#include \n#include \n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\"\u00a0%-20s\", \"Entropy\");\n\tprintf(\"\u00a0%-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones \/ total * log2((double) ones \/ total);\n\tresult -= (double) zeros \/ total * log2((double) zeros \/ total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\"\u00a0%-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\"\u00a0%-40s\", word);\n\t} else {\n\t\tprintf(\"\u00a0%-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n","Rust":"struct Fib {\n curr: T,\n next: T,\n}\n\nimpl Fib {\n fn new(curr: T, next: T) -> Self {\n Fib { curr: curr, next: next, }\n }\n}\n\nimpl Iterator for Fib {\n type Item = String;\n fn next(&mut self) -> Option {\n let ret = self.curr.clone();\n self.curr = self.next.clone();\n self.next = format!(\"{}{}\", ret, self.next);\n Some(ret)\n }\n}\n\nfn get_entropy(s: &[u8]) -> f64 {\n let mut entropy = 0.0;\n let mut histogram = [0.0; 256];\n \n for i in 0..s.len() {\n histogram.get_mut(s[i] as usize).map(|v| *v += 1.0);\n }\n\n for i in 0..256 {\n if histogram[i] > 0.0 {\n let ratio = histogram[i] \/ s.len() as f64;\n entropy -= ratio * ratio.log2();\n }\n }\n entropy\n}\n\nfn main() {\n let f = Fib::new(\"1\".to_string(), \"0\".to_string());\n println!(\"{:10} {:10} {:10} {:60}\", \"N\", \"Length\", \"Entropy\", \"Word\");\n for (i, s) in f.take(37).enumerate() {\n let word = if s.len() > 60 {\"Too long\"} else {&*s};\n println!(\"{:10} {:10} {:.10} {:60}\", i + 1, s.len(), get_entropy(&s.bytes().collect::>()), word);\n }\n}\n"} {"name":"File extension is in extensions list","C":"\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef _Bool\n#include \n#else\n#define bool int\n#define true 1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n char* fileExtension = fileExtensions;\n\n if ( *fileName )\n {\n while ( *fileExtension )\n {\n int fileNameLength = strlen(fileName);\n int extensionLength = strlen(fileExtension);\n if ( fileNameLength >= extensionLength )\n {\n char* a = fileName + fileNameLength - extensionLength;\n char* b = fileExtension;\n while ( *a && toupper(*a++) == toupper(*b++) )\n ;\n if ( !*a )\n return true;\n }\n fileExtension += extensionLength + 1;\n }\n }\n return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n while( *extensions )\n {\n printf(\"%s\\n\", extensions);\n extensions += strlen(extensions) + 1;\n }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n bool result = checkFileExtension(fileName,extension);\n bool returnValue = result == expectedResult;\n printf(\"%20s result:\u00a0%-5s expected:\u00a0%-5s test %s\\n\", \n fileName,\n result ? \"true\" : \"false\",\n expectedResult ? \"true\" : \"false\", \n returnValue ? \"passed\" : \"failed\" );\n return returnValue;\n}\n\nint main(void)\n{\n static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n setlocale(LC_ALL,\"\");\n\n printExtensions(extensions);\n printf(\"\\n\");\n\n if ( test(\"MyData.a##\", extensions,true )\n && test(\"MyData.tar.Gz\", extensions,true )\n && test(\"MyData.gzip\", extensions,false)\n && test(\"MyData.7z.backup\", extensions,false)\n && test(\"MyData...\", extensions,false)\n && test(\"MyData\", extensions,false)\n && test(\"MyData_v1.0.tar.bz2\",extensions,true )\n && test(\"MyData_v1.0.bz2\", extensions,false) \n && test(\"filename\", extensions,false)\n )\n printf(\"\\n%s\\n\", \"All tests passed.\");\n else\n printf(\"\\n%s\\n\", \"Last test failed.\");\n\n printf(\"\\n%s\\n\", \"press enter\");\n getchar();\n return 0;\n}\n","Rust":"fn main() {\n let exts = [\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"];\n let filenames = [\n \"MyData.a##\",\n \"MyData.tar.Gz\",\n \"MyData.gzip\",\n \"MyData.7z.backup\",\n \"MyData...\",\n \"MyData\",\n \"MyData_v1.0.tar.bz2\",\n \"MyData_v1.0.bz2\",\n ];\n\n println!(\"extenstions: {:?}\\n\", exts);\n\n for filename in filenames.iter() {\n let check = exts.iter().any(|ext| {\n filename\n .to_lowercase()\n .ends_with(&format!(\".{}\", ext.to_lowercase()))\n });\n println!(\"{:20} {}\", filename, check);\n }\n}\n"} {"name":"Find prime n such that reversed n is also prime","C":"#include \n#include \n\nbool is_prime(unsigned int n) {\n if (n < 2)\n return false;\n if (n % 2 == 0)\n return n == 2;\n if (n % 3 == 0)\n return n == 3;\n for (unsigned int p = 5; p * p <= n; p += 4) {\n if (n % p == 0)\n return false;\n p += 2;\n if (n % p == 0)\n return false;\n }\n return true;\n}\n\nunsigned int reverse(unsigned int n) {\n unsigned int rev = 0;\n for (; n > 0; n \/= 10)\n rev = rev * 10 + n % 10;\n return rev;\n}\n\nint main() {\n unsigned int count = 0;\n for (unsigned int n = 1; n < 500; ++n) {\n if (is_prime(n) && is_prime(reverse(n)))\n printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n }\n printf(\"\\nCount = %u\\n\", count);\n return 0;\n}\n","Rust":"use prime_tools ;\n\nfn myreverse( n : u32 ) -> u32 {\n let forward : String = n.to_string( ) ;\n let numberstring = &forward[..] ;\n let mut reversed : String = String::new( ) ;\n for c in numberstring.chars( ).rev( ) {\n reversed.push( c ) ;\n }\n *&reversed[..].parse::( ).unwrap( )\n}\n\nfn main() {\n let mut reversible_primes : Vec = Vec::new( ) ;\n for num in 2..=500 {\n if prime_tools::is_u32_prime( num ) && prime_tools::is_u32_prime( \n myreverse( num )) {\n reversible_primes.push( num ) ;\n }\n }\n println!(\"{:?}\" , reversible_primes ) ;\n}\n"} {"name":"Find prime numbers of the form n_n_n+2","C":"#include \n#include \n#include \n\nbool isPrime(int n) {\n int d;\n if (n < 2) return false;\n if (!(n%2)) return n == 2;\n if (!(n%3)) return n == 3;\n d = 5;\n while (d*d <= n) {\n if (!(n%d)) return false;\n d += 2;\n if (!(n%d)) return false;\n d += 4;\n }\n return true;\n}\n\nint main() {\n int n, p;\n const int limit = 200;\n setlocale(LC_ALL, \"\");\n for (n = 1; n < limit; ++n) {\n p = n*n*n + 2;\n if (isPrime(p)) {\n printf(\"n = %3d => n\u00b3 + 2 =\u00a0%'9d\\n\", n, p);\n }\n }\n return 0;\n}\n","Rust":"\n\nuse primes::is_prime;\n\nfn main() {\n\n let mut count = 0;\n let begin = 0;\n let end = 200;\n\n println!(\"Find prime numbers of the form\");\n println!(\" n => n\u00b3 + 2 \");\n\n for n in begin+1..end-1 {\n let m = n*n*n+2;\n if is_prime(m) {\n println!(\"{:4} => {}\", n, m);\n count += 1;\n }\n }\n\n println!(\"Found {} such prime numbers where {} < n < {}.\", count,begin,end);\n}\n"} {"name":"First 9 prime Fibonacci number","C":"#include \n#include \n#include \n\nbool isPrime(uint64_t n) {\n if (n < 2) return false;\n if (!(n%2)) return n == 2;\n if (!(n%3)) return n == 3;\n uint64_t d = 5;\n while (d*d <= n) {\n if (!(n%d)) return false;\n d += 2;\n if (!(n%d)) return false;\n d += 4;\n }\n return true;\n}\n\nint main() {\n uint64_t f1 = 1, f2 = 1, f3;\n int count = 0, limit = 12; \n printf(\"The first %d prime Fibonacci numbers are:\\n\", limit);\n while (count < limit) {\n f3 = f1 + f2;\n if (isPrime(f3)) {\n printf(\"%ld \", f3);\n count++;\n }\n f1 = f2;\n f2 = f3;\n }\n printf(\"\\n\");\n return 0;\n}\n","Rust":"\n\n\n\nuse rug::{Assign, Integer};\n\nfn fibonacci() -> impl std::iter::Iterator {\n let mut f0 = Integer::from(0);\n let mut f1 = Integer::from(1);\n std::iter::from_fn(move || {\n let result = Integer::from(&f0);\n let f = Integer::from(&f0 + &f1);\n f0.assign(&f1);\n f1.assign(&f);\n Some(result)\n })\n}\n\nfn prime_fibonacci() -> impl std::iter::Iterator {\n use rug::integer::IsPrime;\n let mut primes = primal::Primes::all().skip(2);\n let mut fib = fibonacci();\n let mut n = 0;\n std::iter::from_fn(move || loop {\n if n > 4 {\n let p = primes.next().unwrap();\n while p > n {\n fib.next();\n n += 1;\n }\n }\n n += 1;\n if let Some(f) = fib.next() {\n if f.is_probably_prime(30) != IsPrime::No {\n return Some((n - 1, f));\n }\n }\n })\n}\n\nfn to_string(num: &Integer) -> String {\n let str = num.to_string();\n let len = str.len();\n if len > 40 {\n let mut result = String::from(&str[..20]);\n result.push_str(\"...\");\n result.push_str(&str[len - 20..]);\n result.push_str(\" (\");\n result.push_str(&len.to_string());\n result.push_str(\" digits)\");\n return result;\n }\n str\n}\n\nfn main() {\n use std::time::Instant;\n let now = Instant::now();\n for (i, (n, f)) in prime_fibonacci().take(26).enumerate() {\n println!(\"{}: F({}) = {}\", i + 1, n, to_string(&f));\n }\n let time = now.elapsed();\n println!(\"elapsed time: {} milliseconds\", time.as_millis());\n}\n"} {"name":"Flipping bits game","C":"#include \n#include \n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n","Rust":"\nextern crate rand;\n\n\nuse std::fmt;\n\nuse std::io::prelude::*;\n\nuse rand::Rng;\n\n\nstruct Board {\n \n cells: Vec,\n \n size: usize,\n}\n\n\nimpl Board {\n \n \n \n \n \n \n \n \n \n fn new(size: usize) -> Board {\n \n if size > 0 {\n Board {\n cells: vec![false; size * size],\n size,\n }\n } else {\n Board::new(1)\n }\n }\n\n \n \n \n \n \n \n \n \n fn fliprow(&mut self, row: usize) -> bool {\n \n if row > self.size {\n return false;\n }\n \n let start = row * self.size;\n \n for i in start..start + self.size {\n self.cells[i] = !self.cells[i];\n }\n true\n }\n\n \n \n \n \n \n \n \n \n fn flipcol(&mut self, col: usize) -> bool {\n \n if col > self.size {\n return false;\n }\n \n for i in 0..self.size {\n self.cells[col + i * self.size] = !self.cells[col + i * self.size];\n }\n true\n }\n\n \n \n \n \n \n \n \n \n fn random(rng: &mut R, size: usize) -> Board {\n \n if size == 0 {\n return Board::random(rng, 1);\n }\n\n \n let cells = (0..size * size)\n .map(|_| rng.gen::())\n .collect::>();\n \n Board { cells, size }\n }\n}\n\nimpl PartialEq for Board {\n fn eq(&self, rhs: &Board) -> bool {\n self.cells == rhs.cells\n }\n}\n\n\nimpl fmt::Display for Board {\n \n \n \n \n \n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n \n let width = (self.size - 1).to_string().len();\n \n write!(f, \"{space: >0$}\", width, space = \" \")?;\n \n for i in 0..self.size {\n write!(f, \" {offset:>0$}\", width, offset = i)?;\n }\n \n writeln!(f)?;\n \n for row in 0..self.size {\n \n write!(f, \"{row:>0$}\", width, row = row)?;\n \n for col in 0..self.size {\n \n let p = self.cells[row * self.size + col] as usize;\n \n write!(f, \" {col:>0$}\", width, col = p)?;\n }\n \n writeln!(f)?;\n }\n \n Ok(())\n }\n}\n\nfn main() {\n let mut rng = rand::thread_rng();\n\n \n let size: usize = 3;\n \n let target: Board = Board::random(&mut rng, size);\n \n let mut board: Board = Board::new(size);\n \n let mut moves: u32 = 0;\n \n 'mainloop: loop {\n \n let mut input: String;\n \n println!(\"Target:\\n{}\\nBoard:\\n{}\", &target, &board);\n \n 'userinput: loop {\n \n print!(\"\\nFlip? [q|[r|c]#] \");\n \n match std::io::stdout().flush() {\n Ok(_) => {}\n Err(e) => {\n println!(\"Error: cannot flush stdout: {}\", e);\n break 'mainloop;\n }\n };\n \n input = String::new();\n \n match std::io::stdin().read_line(&mut input) {\n Ok(_) => {\n input = input.trim().to_string();\n \n let rc: char = match input.chars().next() {\n Some(c) => c,\n None => {\n println!(\"Error: No input\");\n continue 'userinput;\n }\n };\n \n if rc != 'r' && rc != 'c' && rc != 'q' {\n println!(\"Error: '{}': Must use 'r'ow or 'c'olumn or 'q'uit\", rc);\n continue 'userinput;\n }\n \n if rc == 'q' {\n println!(\"Thanks for playing!\");\n break 'mainloop;\n }\n \n let n: usize = match input[1..].to_string().parse() {\n Ok(x) => {\n \n if x < size {\n x\n } else {\n println!(\n \"Error: Must specify a row or column within size({})\",\n size\n );\n continue 'userinput;\n }\n }\n Err(_) => {\n println!(\n \"Error: '{}': Unable to parse row or column number\",\n input[1..].to_string()\n );\n continue 'userinput;\n }\n };\n \n match rc {\n 'r' => board.fliprow(n),\n 'c' => board.flipcol(n),\n _ => {\n \n \n panic!(\"How did you end up here?\");\n }\n };\n \n moves += 1;\n println!(\"Moves taken: {}\", moves);\n break 'userinput;\n }\n Err(e) => {\n println!(\"Error reading input: {}\", e);\n break 'mainloop;\n }\n }\n } \n if board == target {\n println!(\"You win!\");\n break;\n }\n } \n}\n"} {"name":"Fractal tree","C":"#include \n#ifdef WITH_CAIRO\n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n#include \n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE 800 \n#define SCALE 5 \n#define BRANCHES 14 \n#define ROTATION_SCALE 0.75 \n#define INITIAL_LENGTH 50 \n \ndouble rand_fl(){\n return (double)rand() \/ (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n double directionx, double directiony, double size,\n double rotation, int depth) {\n#ifdef WITH_CAIRO\n cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t surface->w, surface->h,\n\t\t\t\t\t\t\t surface->pitch );\n cairo_t *ct = cairo_create(surf);\n\n cairo_set_line_width(ct, 1);\n cairo_set_source_rgba(ct, 0,0,0,1);\n cairo_move_to(ct, (int)offsetx, (int)offsety);\n cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n cairo_stroke(ct);\n#else\n sge_AALine(surface,\n (int)offsetx, (int)offsety,\n (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n if (depth > 0){\n \n draw_tree(surface,\n offsetx + directionx * size,\n offsety + directiony * size,\n directionx * cos(rotation) + directiony * sin(rotation),\n directionx * -sin(rotation) + directiony * cos(rotation),\n size * rand_fl() \/ SCALE + size * (SCALE - 1) \/ SCALE,\n rotation * ROTATION_SCALE,\n depth - 1);\n \n \n draw_tree(surface,\n offsetx + directionx * size,\n offsety + directiony * size,\n directionx * cos(-rotation) + directiony * sin(-rotation),\n directionx * -sin(-rotation) + directiony * cos(-rotation),\n size * rand_fl() \/ SCALE + size * (SCALE - 1) \/ SCALE,\n rotation * ROTATION_SCALE,\n depth - 1);\n }\n}\n \nvoid render(SDL_Surface * surface){\n SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n draw_tree(surface,\n surface->w \/ 2.0,\n surface->h - 10.0,\n 0.0, -1.0,\n INITIAL_LENGTH,\n PI \/ 8,\n BRANCHES);\n SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n SDL_Surface * screen;\n SDL_Event evt;\n \n SDL_Init(SDL_INIT_VIDEO);\n \n srand((unsigned)time(NULL));\n \n screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n render(screen);\n while(1){\n if (SDL_PollEvent(&evt)){\n if(evt.type == SDL_QUIT) break;\n }\n SDL_Delay(1);\n }\n SDL_Quit();\n return 0;\n}\n","Rust":"\n\n\n\n\n\nextern crate piston;\nextern crate graphics;\nextern crate opengl_graphics;\nextern crate glutin_window;\n\nuse piston::window::WindowSettings;\nuse piston::event_loop::{Events, EventSettings};\nuse piston::input::RenderEvent;\nuse glutin_window::GlutinWindow as Window;\nuse opengl_graphics::{GlGraphics, OpenGL};\nuse graphics::{clear, line, Context};\n\nconst ANG: f64 = 20.0;\nconst COLOR: [f32; 4] = [1.0, 0.0, 0.5, 1.0];\nconst LINE_THICKNESS: f64 = 5.0;\nconst DEPTH: u32 = 11;\n\nfn main() {\n let mut window: Window = WindowSettings::new(\"Fractal Tree\", [1024, 768])\n .opengl(OpenGL::V3_2)\n .exit_on_esc(true)\n .build()\n .unwrap();\n let mut gl = GlGraphics::new(OpenGL::V3_2);\n\n let mut events = Events::new(EventSettings::new());\n while let Some(e) = events.next(&mut window) {\n if let Some(args) = e.render_args() {\n gl.draw(args.viewport(), |c, g| {\n clear([1.0, 1.0, 1.0, 1.0], g);\n draw_fractal_tree(512.0, 700.0, 0.0, DEPTH, c, g);\n });\n }\n }\n}\n\nfn draw_fractal_tree(x1: f64, y1: f64, angle: f64, depth: u32, c: Context, g: &mut GlGraphics) {\n let x2 = x1 + angle.to_radians().sin() * depth as f64 * 10.0;\n let y2 = y1 - angle.to_radians().cos() * depth as f64 * 10.0;\n line(\n COLOR,\n LINE_THICKNESS * depth as f64 * 0.2,\n [x1, y1, x2, y2],\n c.transform,\n g,\n );\n if depth > 0 {\n draw_fractal_tree(x2, y2, angle - ANG, depth - 1, c, g);\n draw_fractal_tree(x2, y2, angle + ANG, depth - 1, c, g);\n }\n}\n"} {"name":"Gray code","C":"int gray_encode(int n) {\n return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n int p = n;\n while (n >>= 1) p ^= n;\n return p;\n}\n","Rust":"fn gray_encode(integer: u64) -> u64 {\n (integer >> 1) ^ integer\n}\n\nfn gray_decode(integer: u64) -> u64 {\n match integer {\n 0 => 0,\n _ => integer ^ gray_decode(integer >> 1)\n }\n}\n\nfn main() {\n for i in 0..32 {\n println!(\"{:2} {:0>5b} {:0>5b} {:2}\", i, i, gray_encode(i),\n gray_decode(i));\n }\n\n}\n"} {"name":"Hello world_Line printer","C":"#include \n\nint main()\n{\n FILE *lp;\n lp = fopen(\"\/dev\/lp0\",\"w\");\n fprintf(lp,\"Hello world!\\n\");\n fclose(lp);\n return 0;\n}\n","Rust":"use std::fs::OpenOptions;\nuse std::io::Write;\n\nfn main() {\n let file = OpenOptions::new().write(true).open(\"\/dev\/lp0\").unwrap();\n file.write(b\"Hello, World!\").unwrap();\n}\n"} {"name":"Hickerson series of almost integers","C":"#include \n#include \n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n","Rust":"use decimal::d128;\nuse factorial::Factorial;\n\nfn hickerson(n: u64) -> d128 {\n d128::from(n.factorial()) \/ (d128!(2) * (d128!(2).ln().pow(d128::from(n + 1))))\n}\n\n\nfn main() {\n for i in 1..18 {\n let h = hickerson(i);\n let string = h.to_string();\n let dec_part = string.split('.').nth(1).unwrap();\n if dec_part.starts_with('0') || dec_part.starts_with('9') {\n println!(\"{} is an almost integer.\", h);\n } else {\n println!(\"{} is not an almost integer.\", h);\n }\n }\n}\n"} {"name":"Hofstadter Q sequence","C":"#include \n#include \n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n","Rust":"fn hofq(q: &mut Vec, x : u32) -> u32 {\n let cur_len=q.len()-1;\n let i=x as usize;\n if i>cur_len {\n \n q.reserve(i+1);\n for j in (cur_len+1)..(i+1) {\n let qj=(q[j-q[j-1] as usize]+q[j-q[j-2] as usize]) as u32;\n q.push(qj);\n }\n }\n q[i]\n}\n\nfn main() {\n let mut q_memo: Vec=vec![0,1,1];\n let mut q=|i| {hofq(&mut q_memo, i)};\n for i in 1..11 {\n println!(\"Q({})={}\", i, q(i));\n }\n println!(\"Q(1000)={}\", q(1000));\n let q100001=q(100_000); \n println!(\"Q(100000)={}\", q100000);\n let nless=(1..100_000).fold(0,|s,i|{if q(i+1)\n\n\n#include \"myutil.h\"\n","Rust":"mod test;\n\nfn main() {\n test::some_function();\n}\n"} {"name":"Kahan summation","C":"#include \n#include \n\nfloat epsilon() {\n float eps = 1.0f;\n while (1.0f + eps != 1.0f) eps \/= 2.0f;\n return eps;\n}\n\nfloat kahanSum(float *nums, int count) {\n float sum = 0.0f;\n float c = 0.0f;\n float t, y;\n int i;\n for (i = 0; i < count; ++i) {\n y = nums[i] - c;\n t = sum + y;\n c = (t - sum) - y;\n sum = t;\n }\n return sum;\n}\n\nint main() {\n float a = 1.0f;\n float b = epsilon();\n float c = -b;\n float fa[3];\n\n fa[0] = a;\n fa[1] = b;\n fa[2] = c;\n\n printf(\"Epsilon = %0.12f\\n\", b);\n printf(\"(a + b) + c = %0.12f\\n\", (a + b) + c);\n printf(\"Kahan sum = %0.12f\\n\", kahanSum(fa, 3));\n\n return 0;\n}\n","Rust":"extern crate num;\nextern crate permutohedron;\n\nuse num::Float;\nuse permutohedron::Heap;\nuse std::f32;\n\nfn find_max(lst: &[f32]) -> Option {\n if lst.is_empty() {\n return None;\n }\n let max = lst.iter().fold(f32::NEG_INFINITY, |a, &b| Float::max(a, b));\n Some(max)\n}\n\nfn with_bits(val: f32, digits: usize) -> f32 {\n let num = format!(\"{:.*}\", digits, val);\n num.parse::().unwrap()\n}\n\nfn kahan_sum(lst: &[f32]) -> Option {\n let mut sum = 0.0f32;\n let mut c = 0.0f32;\n for i in lst {\n let y = *i - c;\n let t = sum + y;\n c = (t - sum) - y;\n sum = t;\n }\n Some(with_bits(sum, 1))\n}\n\nfn all_sums(vec: &mut [f32]) -> Vec {\n let mut res = Vec::new();\n let mut perms = Heap::new(vec);\n loop {\n let v = perms.next();\n match v {\n Some(v) => {\n let mut sum = 0.0f32;\n for e in &v {\n sum += with_bits(*e, 1);\n }\n res.push(with_bits(sum, 1));\n }\n None => break,\n }\n }\n res\n}\n\n#[allow(clippy::approx_constant)]\nfn main() {\n let v = vec![10_000f32, 3.14159, 2.71828];\n let sums = all_sums(&mut v.clone());\n let res = kahan_sum(&v).unwrap();\n let max = find_max(&sums[..]).unwrap();\n println!(\"max: {} res: {}\", max, res);\n}\n"} {"name":"Keyboard input_Obtain a Y or N response","C":"#include \n#include \n#include \n#include \n#include \n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y\/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n","Rust":"\n\nextern crate ncurses;\nuse ncurses::*;\n\nfn main() {\n initscr();\n loop {\n printw(\"Yes or no? \");\n refresh();\n\n match getch() as u8 as char {\n 'Y'|'y' => {printw(\"You said yes!\");},\n 'N'|'n' => {printw(\"You said no!\");},\n _ => {printw(\"Try again!\\n\"); continue;},\n }\n break\n }\n refresh();\n endwin();\n}\n"} {"name":"Knuth's algorithm S","C":"#include \n#include \n#include \n#include \n\nstruct s_env {\n unsigned int n, i;\n size_t size;\n void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n s_env->i = 0;\n s_env->n = n;\n s_env->size = size;\n s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n s_env->i++;\n if (s_env->i <= s_env->n)\n sample_set_i(s_env, s_env->i - 1, item);\n else if ((rand() % s_env->i) < s_env->n)\n sample_set_i(s_env, rand() % s_env->n, item);\n return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n int i;\n struct s_env s_env;\n s_of_n_init(&s_env, sizeof(items_set[0]), n);\n for (i = 0; i < num_items; i++) {\n s_of_n(&s_env, (void *) &items_set[i]);\n }\n return (int *)s_env.sample;\n}\n\nint main()\n{\n unsigned int i, j;\n unsigned int n = 3;\n unsigned int num_items = 10;\n unsigned int *frequencies;\n int *items_set;\n srand(time(NULL));\n items_set = malloc(num_items * sizeof(int));\n frequencies = malloc(num_items * sizeof(int));\n for (i = 0; i < num_items; i++) {\n items_set[i] = i;\n frequencies[i] = 0;\n }\n for (i = 0; i < 100000; i++) {\n int *res = test(n, items_set, num_items);\n for (j = 0; j < n; j++) {\n frequencies[res[j]]++;\n }\n\tfree(res);\n }\n for (i = 0; i < num_items; i++) {\n printf(\" %d\", frequencies[i]);\n }\n puts(\"\");\n return 0;\n}\n","Rust":"use rand::{Rng,weak_rng};\n\nstruct SofN {\n rng: R,\n sample: Vec,\n i: usize,\n n: usize,\n}\n\nimpl SofN {\n fn new(rng: R, n: usize) -> Self {\n SofN{rng, sample: Vec::new(), i: 0, n}\n }\n\n fn add(&mut self, item: T) {\n self.i += 1;\n if self.i <= self.n {\n self.sample.push(item);\n } else if self.rng.gen_range(0, self.i) < self.n {\n self.sample[self.rng.gen_range(0, self.n)] = item;\n }\n }\n\n fn sample(&self) -> &Vec {\n &self.sample\n }\n}\n\n\npub fn main() {\n const MAX: usize = 10;\n let mut bin: [i32; MAX] = Default::default();\n for _ in 0..100000 {\n let mut s_of_n = SofN::new(weak_rng(), 3);\n \n for i in 0..MAX { s_of_n.add(i); }\n\n for s in s_of_n.sample() {\n bin[*s] += 1;\n }\n }\n \n for (i, x) in bin.iter().enumerate() {\n println!(\"frequency of {}: {}\", i, x);\n }\n}\n"} {"name":"Kronecker product based fractals","C":"#include\n#include\n#include\n\ntypedef struct{\n int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n if(power==0)\n return 1;\n else\n return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n FILE* fp = fopen(inputFile,\"r\");\n \n int i,j,k,l;\n unsigned long prod;\n int** matrix;\n cell *coreList,*tempList,*resultList;\n \n fscanf(fp,\"%d%d\",&ROW,&COL);\n \n matrix = (int**)malloc(ROW*sizeof(int*));\n \n for(i=0;i {\n col_count: usize,\n row_count: usize,\n items: Vec,\n}\n\nimpl Mat {\n pub fn from_vec(items: Vec, col_count: usize, row_count: usize) -> Self {\n assert_eq!(items.len(), col_count * row_count, \"mismatching dimensions\");\n\n Self {\n col_count,\n row_count,\n items,\n }\n }\n\n pub fn row_count(&self) -> usize {\n self.row_count\n }\n\n pub fn col_count(&self) -> usize {\n self.col_count\n }\n\n pub fn iter(&self) -> impl Iterator {\n self.items.iter()\n }\n\n pub fn row_iter(&self, row: usize) -> impl Iterator {\n assert!(row < self.row_count, \"index out of bounds\");\n let start = row * self.col_count;\n self.items[start..start + self.col_count].iter()\n }\n\n pub fn col_iter(&self, col: usize) -> impl Iterator {\n assert!(col < self.col_count, \"index out of bounds\");\n self.items.iter().skip(col).step_by(self.col_count)\n }\n}\n\nimpl Display for Mat {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n \n let mut len = 0usize;\n let mut buf = String::new();\n for item in (0..self.row_count).flat_map(|row| self.row_iter(row)) {\n buf.clear();\n write!(buf, \"{}\", item)?;\n len = std::cmp::max(len, buf.chars().count());\n }\n\n \n\n len += 1; \n let width = len * self.col_count + 1;\n writeln!(f, \"\u250c{:width$}\u2510\", \"\", width = width)?;\n\n for row in (0..self.row_count).map(|row| self.row_iter(row)) {\n write!(f, \"\u2502\")?;\n\n for item in row {\n write!(f, \"{:>width$}\", item, width = len)?;\n }\n\n writeln!(f, \" \u2502\")?;\n }\n\n write!(f, \"\u2514{:width$}\u2518\", \"\", width = width)\n }\n}\n\n\n\n\nimpl Mat {\n pub fn write_ppm(\n &self,\n f: &mut dyn std::io::Write,\n rgb: impl Fn(&T) -> (u8, u8, u8),\n ) -> std::io::Result<()> {\n let bytes = self\n .iter()\n .map(rgb)\n .flat_map(|(r, g, b)| {\n use std::iter::once;\n once(r).chain(once(g)).chain(once(b))\n })\n .collect::>();\n\n write!(f, \"P6\\n{} {}\\n255\\n\", self.col_count, self.row_count)?;\n f.write_all(&bytes)\n }\n}\n\nmod kronecker {\n\n use super::Mat;\n use std::ops::Mul;\n\n \n\n pub fn product(a: &Mat, b: &Mat) -> Mat<>::Output>\n where\n T: Clone + Mul,\n U: Clone,\n {\n let row_count = a.row_count() * b.row_count();\n let col_count = a.col_count() * b.col_count();\n let mut items = Vec::with_capacity(row_count * col_count);\n\n for i in 0..a.row_count() {\n for k in 0..b.row_count() {\n for a_x in a.row_iter(i) {\n for b_x in b.row_iter(k) {\n items.push(a_x.clone() * b_x.clone());\n }\n }\n }\n }\n\n Mat::from_vec(items, col_count, row_count)\n }\n\n pub fn power(m: &Mat, n: u32) -> Mat\n where\n T: Clone + Mul,\n {\n match n {\n 0 => m.clone(),\n _ => (1..n).fold(product(&m, &m), |result, _| product(&result, &m)),\n }\n }\n}\n\n\n\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]\nstruct Char(char);\n\nimpl Char {\n fn space() -> Self {\n Char(' ')\n }\n\n fn is_space(&self) -> bool {\n self.0 == ' '\n }\n}\n\nimpl Display for Char {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n Display::fmt(&self.0, f)\n }\n}\n\nimpl Mul for Char {\n type Output = Self;\n\n #[allow(clippy::suspicious_arithmetic_impl)]\n fn mul(self, rhs: Self) -> Self {\n if self.is_space() || rhs.is_space() {\n Char(' ')\n } else {\n self\n }\n }\n}\n\nfn main() -> std::io::Result<()> {\n\n \n\n #[rustfmt::skip]\n let vicsek = Mat::::from_vec(vec![\n 0, 1, 0,\n 1, 1, 1,\n 0, 1, 0,\n ], 3, 3);\n\n println!(\"{}\", vicsek);\n println!(\"{}\", kronecker::power(&vicsek, 3));\n\n \n \n \n let s = Char::space();\n let b = Char('\\u{2588}');\n\n #[rustfmt::skip]\n let sierpienski = Mat::from_vec(vec![\n b, b, b,\n b, s, b,\n b, b, b,\n ], 3, 3);\n\n println!(\"{}\", sierpienski);\n println!(\"{}\", kronecker::power(&sierpienski, 3));\n\n #[rustfmt::skip]\n let matrix = Mat::from_vec(vec![\n s, s, b, s, s,\n s, b, b, b, s,\n b, s, b, s, b,\n s, s, b, s, s,\n s, b, s, b, s,\n ], 5, 5,);\n\n println!(\"{}\", kronecker::power(&matrix, 1));\n\n \n kronecker::power(&matrix, 4).write_ppm(\n &mut std::fs::OpenOptions::new()\n .write(true)\n .create(true)\n .truncate(true)\n .open(\"kronecker_power.ppm\")?,\n |&item| {\n if item.is_space() {\n (0, 0, 32)\n } else {\n (192, 192, 0)\n }\n },\n )\n}\n"} {"name":"LU decomposition","C":"#include \n#include \n#include \n\n#define foreach(a, b, c) for (int a = b; a < c; a++)\n#define for_i foreach(i, 0, n)\n#define for_j foreach(j, 0, n)\n#define for_k foreach(k, 0, n)\n#define for_ij for_i for_j\n#define for_ijk for_ij for_k\n#define _dim int n\n#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }\n#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }\n\ntypedef double **mat;\n\n#define _zero(a) mat_zero(a, n)\nvoid mat_zero(mat x, int n) { for_ij x[i][j] = 0; }\n\n#define _new(a) a = mat_new(n)\nmat mat_new(_dim)\n{\n\tmat x = malloc(sizeof(double*) * n);\n\tx[0] = malloc(sizeof(double) * n * n);\n\n\tfor_i x[i] = x[0] + n * i;\n\t_zero(x);\n\n\treturn x;\n}\n\n#define _copy(a) mat_copy(a, n)\nmat mat_copy(void *s, _dim)\n{\n\tmat x = mat_new(n);\n\tfor_ij x[i][j] = ((double (*)[n])s)[i][j];\n\treturn x;\n}\n\n#define _del(x) mat_del(x)\nvoid mat_del(mat x) { free(x[0]); free(x); }\n\n#define _QUOT(x) #x\n#define QUOTE(x) _QUOT(x)\n#define _show(a) printf(QUOTE(a)\" =\");mat_show(a, 0, n)\nvoid mat_show(mat x, char *fmt, _dim)\n{\n\tif (!fmt) fmt = \"%8.4g\";\n\tfor_i {\n\t\tprintf(i ? \" \" : \" [ \");\n\t\tfor_j {\n\t\t\tprintf(fmt, x[i][j]);\n\t\t\tprintf(j < n - 1 ? \" \" : i == n - 1 ? \" ]\\n\" : \"\\n\");\n\t\t}\n\t}\n}\n\n#define _mul(a, b) mat_mul(a, b, n)\nmat mat_mul(mat a, mat b, _dim)\n{\n\tmat c = _new(c);\n\tfor_ijk c[i][j] += a[i][k] * b[k][j];\n\treturn c;\n}\n\n#define _pivot(a, b) mat_pivot(a, b, n)\nvoid mat_pivot(mat a, mat p, _dim)\n{\n\tfor_ij { p[i][j] = (i == j); }\n\tfor_i {\n\t\tint max_j = i;\n\t\tforeach(j, i, n)\n\t\t\tif (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;\n\n\t\tif (max_j != i)\n\t\t\tfor_k { _swap(p[i][k], p[max_j][k]); }\n\t}\n}\n\n#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)\nvoid mat_LU(mat A, mat L, mat U, mat P, _dim)\n{\n\t_zero(L); _zero(U);\n\t_pivot(A, P);\n\n\tmat Aprime = _mul(P, A);\n\n\tfor_i { L[i][i] = 1; }\n\tfor_ij {\n\t\tdouble s;\n\t\tif (j <= i) {\n\t\t\t_sum_k(0, j, L[j][k] * U[k][i], s)\n\t\t\tU[j][i] = Aprime[j][i] - s;\n\t\t}\n\t\tif (j >= i) {\n\t\t\t_sum_k(0, i, L[j][k] * U[k][i], s);\n\t\t\tL[j][i] = (Aprime[j][i] - s) \/ U[i][i];\n\t\t}\n\t}\n\n\t_del(Aprime);\n}\n\ndouble A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};\ndouble A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};\n\nint main()\n{\n\tint n = 3;\n\tmat A, L, P, U;\n\n\t_new(L); _new(P); _new(U);\n\tA = _copy(A3);\n\t_LU(A, L, U, P);\n\t_show(A); _show(L); _show(U); _show(P);\n\t_del(A); _del(L); _del(U); _del(P);\n\n\tprintf(\"\\n\");\n\n\tn = 4;\n\n\t_new(L); _new(P); _new(U);\n\tA = _copy(A4);\n\t_LU(A, L, U, P);\n\t_show(A); _show(L); _show(U); _show(P);\n\t_del(A); _del(L); _del(U); _del(P);\n\n\treturn 0;\n}\n","Rust":"#![allow(non_snake_case)]\nuse ndarray::{Array, Axis, Array2, arr2, Zip, NdFloat, s};\n\nfn main() {\n println!(\"Example 1:\");\n let A: Array2 = arr2(&[\n [1.0, 3.0, 5.0],\n [2.0, 4.0, 7.0],\n [1.0, 1.0, 0.0],\n ]);\n println!(\"A \\n {}\", A);\n let (L, U, P) = lu_decomp(A);\n println!(\"L \\n {}\", L);\n println!(\"U \\n {}\", U);\n println!(\"P \\n {}\", P);\n\n println!(\"\\nExample 2:\");\n let A: Array2 = arr2(&[\n [11.0, 9.0, 24.0, 2.0],\n [1.0, 5.0, 2.0, 6.0],\n [3.0, 17.0, 18.0, 1.0],\n [2.0, 5.0, 7.0, 1.0],\n ]);\n println!(\"A \\n {}\", A);\n let (L, U, P) = lu_decomp(A);\n println!(\"L \\n {}\", L);\n println!(\"U \\n {}\", U);\n println!(\"P \\n {}\", P);\n}\n\nfn pivot(A: &Array2) -> Array2\nwhere T: NdFloat {\n let matrix_dimension = A.rows();\n let mut P: Array2 = Array::eye(matrix_dimension);\n for (i, column) in A.axis_iter(Axis(1)).enumerate() {\n \n let mut max_pos = i;\n for j in i..matrix_dimension {\n if column[max_pos].abs() < column[j].abs() {\n max_pos = j;\n }\n }\n \n if max_pos != i {\n swap_rows(&mut P, i, max_pos);\n }\n }\n P\n}\n\nfn swap_rows(A: &mut Array2, idx_row1: usize, idx_row2: usize)\nwhere T: NdFloat {\n \n \n let (.., mut matrix_rest) = A.view_mut().split_at(Axis(0), idx_row1);\n let (row0, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), 1);\n let (_matrix_helper, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), idx_row2 - idx_row1 - 1);\n let (row1, ..) = matrix_rest.view_mut().split_at(Axis(0), 1);\n Zip::from(row0).and(row1).apply(std::mem::swap);\n}\n\nfn lu_decomp(A: Array2) -> (Array2, Array2, Array2)\nwhere T: NdFloat {\n\n let matrix_dimension = A.rows();\n assert_eq!(matrix_dimension, A.cols(), \"Tried LU decomposition with a non-square matrix.\");\n let P = pivot(&A);\n let pivotized_A = P.dot(&A);\n\n let mut L: Array2 = Array::eye(matrix_dimension);\n let mut U: Array2 = Array::zeros((matrix_dimension, matrix_dimension));\n for idx_col in 0..matrix_dimension {\n \n for idx_row in 0..idx_col+1 {\n U[[idx_row, idx_col]] = pivotized_A[[idx_row, idx_col]] -\n U.slice(s![0..idx_row,idx_col]).dot(&L.slice(s![idx_row,0..idx_row]));\n }\n \n for idx_row in idx_col+1..matrix_dimension {\n L[[idx_row, idx_col]] = (pivotized_A[[idx_row, idx_col]] -\n U.slice(s![0..idx_col,idx_col]).dot(&L.slice(s![idx_row,0..idx_col]))) \/\n U[[idx_col, idx_col]];\n }\n }\n (L, U, P)\n}\n"} {"name":"LZW compression","C":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n x[0] = item_size;\n x[1] = n_item;\n return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n size_t *x = (size_t*)m - 2;\n x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n if (new_n > x[1])\n memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n x[1] = new_n;\n return x + 2;\n}\n\ninline void _clear(void *m)\n{\n size_t *x = (size_t*)m - 2;\n memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m) { free((size_t*)(m) - 2); m = 0; }\n#define _len(m) *((size_t*)m - 1)\n#define _setsize(m, n) m = mem_extend(m, n)\n#define _extend(m) m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n ushort prev, back;\n byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n int len = _len(in), bits = 9, next_shift = 512;\n ushort code, c, nc, next_code = M_NEW;\n lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n if (max_bits > 15) max_bits = 15;\n if (max_bits < 9 ) max_bits = 12;\n\n byte *out = _new(ushort, 4);\n int out_len = 0, o_bits = 0;\n uint32_t tmp = 0;\n\n inline void write_bits(ushort x) {\n tmp = (tmp << bits) | x;\n o_bits += bits;\n if (_len(out) <= out_len) _extend(out);\n while (o_bits >= 8) {\n o_bits -= 8;\n out[out_len++] = tmp >> o_bits;\n tmp &= (1 << o_bits) - 1;\n }\n }\n\n \n for (code = *(in++); --len; ) {\n c = *(in++);\n if ((nc = d[code].next[c]))\n code = nc;\n else {\n write_bits(code);\n nc = d[code].next[c] = next_code++;\n code = c;\n }\n\n \n if (next_code == next_shift) {\n \n if (++bits > max_bits) {\n \n write_bits(M_CLR);\n\n bits = 9;\n next_shift = 512;\n next_code = M_NEW;\n _clear(d);\n } else \n _setsize(d, next_shift *= 2);\n }\n }\n\n write_bits(code);\n write_bits(M_EOD);\n if (tmp) write_bits(tmp);\n\n _del(d);\n\n _setsize(out, out_len);\n return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n byte *out = _new(byte, 4);\n int out_len = 0;\n\n inline void write_out(byte c)\n {\n while (out_len >= _len(out)) _extend(out);\n out[out_len++] = c;\n }\n\n lzw_dec_t *d = _new(lzw_dec_t, 512);\n int len, j, next_shift = 512, bits = 9, n_bits = 0;\n ushort code, c, t, next_code = M_NEW;\n\n uint32_t tmp = 0;\n inline void get_code() {\n while(n_bits < bits) {\n if (len > 0) {\n len --;\n tmp = (tmp << 8) | *(in++);\n n_bits += 8;\n } else {\n tmp = tmp << (bits - n_bits);\n n_bits = bits;\n }\n }\n n_bits -= bits;\n code = tmp >> n_bits;\n tmp &= (1 << n_bits) - 1;\n }\n\n inline void clear_table() {\n _clear(d);\n for (j = 0; j < 256; j++) d[j].c = j;\n next_code = M_NEW;\n next_shift = 512;\n bits = 9;\n };\n\n clear_table(); \n for (len = _len(in); len;) {\n get_code();\n if (code == M_EOD) break;\n if (code == M_CLR) {\n clear_table();\n continue;\n }\n\n if (code >= next_code) {\n fprintf(stderr, \"Bad sequence\\n\");\n _del(out);\n goto bail;\n }\n\n d[next_code].prev = c = code;\n while (c > 255) {\n t = d[c].prev; d[t].back = c; c = t;\n }\n\n d[next_code - 1].c = c;\n\n while (d[c].back) {\n write_out(d[c].c);\n t = d[c].back; d[c].back = 0; c = t;\n }\n write_out(d[c].c);\n\n if (++next_code >= next_shift) {\n if (++bits > 16) {\n \n fprintf(stderr, \"Too many bits\\n\");\n _del(out);\n goto bail;\n }\n _setsize(d, next_shift *= 2);\n }\n }\n\n \n if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n _setsize(out, out_len);\nbail: _del(d);\n return out;\n}\n\nint main()\n{\n int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n if (fd == -1) {\n fprintf(stderr, \"Can't read file\\n\");\n return 1;\n };\n\n struct stat st;\n fstat(fd, &st);\n\n byte *in = _new(char, st.st_size);\n read(fd, in, st.st_size);\n _setsize(in, st.st_size);\n close(fd);\n\n printf(\"input size: %d\\n\", _len(in));\n\n byte *enc = lzw_encode(in, 9);\n printf(\"encoded size: %d\\n\", _len(enc));\n\n byte *dec = lzw_decode(enc);\n printf(\"decoded size: %d\\n\", _len(dec));\n\n for (i = 0; i < _len(dec); i++)\n if (dec[i] != in[i]) {\n printf(\"bad decode at %d\\n\", i);\n break;\n }\n\n if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n _del(in);\n _del(enc);\n _del(dec);\n\n return 0;\n}\n","Rust":"use std::collections::HashMap;\n\nfn compress(data: &[u8]) -> Vec {\n \n let mut dictionary: HashMap, u32> = (0u32..=255)\n .map(|i| (vec![i as u8], i))\n .collect();\n\n let mut w = Vec::new();\n let mut compressed = Vec::new();\n\n for &b in data {\n let mut wc = w.clone();\n wc.push(b);\n\n if dictionary.contains_key(&wc) {\n w = wc;\n } else {\n \n compressed.push(dictionary[&w]);\n\n \n dictionary.insert(wc, dictionary.len() as u32);\n w.clear();\n w.push(b);\n }\n }\n\n \n if !w.is_empty() {\n compressed.push(dictionary[&w]);\n }\n\n compressed\n}\n\nfn decompress(mut data: &[u32]) -> Vec {\n \n let mut dictionary: HashMap::> = (0u32..=255)\n .map(|i| (i, vec![i as u8]))\n .collect();\n\n let mut w = dictionary[&data[0]].clone();\n data = &data[1..];\n let mut decompressed = w.clone();\n\n for &k in data {\n let entry = if dictionary.contains_key(&k) {\n dictionary[&k].clone()\n } else if k == dictionary.len() as u32 {\n let mut entry = w.clone();\n entry.push(w[0]);\n entry\n } else {\n panic!(\"Invalid dictionary!\");\n };\n\n decompressed.extend_from_slice(&entry);\n\n \n w.push(entry[0]);\n dictionary.insert(dictionary.len() as u32, w);\n\n w = entry;\n }\n\n decompressed\n}\n\nfn main() {\n let compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\".as_bytes());\n println!(\"{:?}\", compressed);\n\n let decompressed = decompress(&compressed);\n let decompressed = String::from_utf8(decompressed).unwrap();\n println!(\"{}\", decompressed);\n}\n"} {"name":"Longest string challenge","C":"#include \n#include \n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n","Rust":"use std::cmp::Ordering;\nuse std::io::BufRead;\n\n\n\nfn compare(a: &str, b: &str) -> Ordering {\n let mut a = a.chars();\n let mut b = b.chars();\n loop {\n match (a.next(), b.next()) {\n (None, None) => return Ordering::Equal,\n (Some(_), None) => return Ordering::Greater,\n (None, Some(_)) => return Ordering::Less,\n (Some(_), Some(_)) => {}\n }\n }\n}\n\n\nfn longest>(input: I) -> String {\n let mut longest = String::new();\n let mut output = String::new();\n\n for line in input {\n match compare(&line, &longest) {\n \n Ordering::Greater => {\n output.clear();\n output.push_str(&line);\n longest = line;\n }\n \n Ordering::Equal => {\n output.push('\\n');\n output.push_str(&line);\n }\n \n Ordering::Less => {}\n }\n }\n\n output\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let lines = stdin.lock().lines().map(|l| l.expect(\"Failed to read.\"));\n \n println!(\"{}\", longest(lines))\n}\n"} {"name":"MAC vendor lookup","C":"#include \n#include \n#include \n#include \n\n\/* Length of http:\n#define FIXED_LENGTH 16\n\nstruct MemoryStruct {\n char *memory;\n size_t size;\n};\n \nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)\n{\n size_t realsize = size * nmemb;\n struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n mem->memory = realloc(mem->memory, mem->size + realsize + 1);\n \n memcpy(&(mem->memory[mem->size]), contents, realsize);\n mem->size += realsize;\n mem->memory[mem->size] = 0;\n \n return realsize;\n}\n\nvoid checkResponse(char* str){\n\tchar ref[] = \"Vendor not found\";\n\tint len = strlen(str),flag = 1,i;\n\t\n\tif(len<16)\n\t\tfputs(str,stdout);\n\telse{\n\t\tfor(i=0;i\",argV[0]);\n\t\telse{\n\t\t\tCURL *curl;\n\t\t\tint len = strlen(argV[1]);\n\t\t\tchar* str = (char*)malloc((FIXED_LENGTH + len)*sizeof(char));\n\t\t\tstruct MemoryStruct chunk;\n\t\t\tCURLcode res;\n \n\t\t\tchunk.memory = malloc(1);\n\t\t\tchunk.size = 0; \n \n if ((curl = curl_easy_init()) != NULL) {\n\t\t\t\tsprintf(str,\"http:\n\n curl_easy_setopt(curl, CURLOPT_URL, str);\n\t\t\t\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);\n\t\t\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);\n\t\t\t\t\n\t\t\t\tfree(str);\n\t\t\t\t\n\t\t\t\tres = curl_easy_perform(curl);\n\t\t\t\t\n if (res == CURLE_OK) {\n\t\t\t\tcheckResponse(chunk.memory);\n return EXIT_SUCCESS;\n }\n\t\t\t\t\n curl_easy_cleanup(curl);\n\t\t\t}\n\t\t}\n \n return EXIT_FAILURE;\n}\n","Rust":"extern crate reqwest;\n\nuse std::{thread, time};\n\nfn get_vendor(mac: &str) -> Option {\n let mut url = String::from(\"http:\n url.push_str(mac);\n let url_ref = &url;\n match reqwest::get(url_ref) {\n Ok(mut res) => match res.text() {\n Ok(text) => {\n if text.contains(\"Not Found\") {\n Some(\"N\/A\".to_string())\n } else {\n Some(text)\n }\n }\n Err(e) => {\n println!(\"{:?}\", e);\n None\n }\n },\n Err(e) => {\n println!(\"{:?}\", e);\n None\n }\n }\n}\n\nfn main() {\n let duration = time::Duration::from_millis(1000);\n match get_vendor(\"88:53:2E:67:07:BE\") {\n None => println!(\"Error!\"),\n Some(text) => println!(\"{}\", text),\n }\n thread::sleep(duration);\n match get_vendor(\"FC:FB:FB:01:FA:21\") {\n None => println!(\"Error!\"),\n Some(text) => println!(\"{}\", text),\n }\n thread::sleep(duration);\n match get_vendor(\"FC-A1-3E\") {\n None => println!(\"Error!\"),\n Some(text) => println!(\"{}\", text),\n }\n thread::sleep(duration);\n match get_vendor(\"abcdefg\") {\n None => println!(\"Error!\"),\n Some(text) => println!(\"{}\", text),\n }\n}\n"} {"name":"Mad Libs","C":"#include \n#include \n#include \n\n#define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)\n\n\ntypedef struct {\n char *data;\n size_t alloc;\n size_t length;\n} dstr;\n\ninline int dstr_space(dstr *s, size_t grow_amount)\n{\n return s->length + grow_amount < s->alloc;\n}\n\nint dstr_grow(dstr *s)\n{\n s->alloc *= 2;\n char *attempt = realloc(s->data, s->alloc);\n\n if (!attempt) return 0;\n else s->data = attempt;\n\n return 1;\n}\n\ndstr* dstr_init(const size_t to_allocate)\n{\n dstr *s = malloc(sizeof(dstr));\n if (!s) goto failure;\n\n s->length = 0;\n s->alloc = to_allocate;\n s->data = malloc(s->alloc);\n\n if (!s->data) goto failure;\n\n return s;\n\nfailure:\n if (s->data) free(s->data);\n if (s) free(s);\n return NULL;\n}\n\nvoid dstr_delete(dstr *s)\n{\n if (s->data) free(s->data);\n if (s) free(s);\n}\n\ndstr* readinput(FILE *fd)\n{\n static const size_t buffer_size = 4096;\n char buffer[buffer_size];\n\n dstr *s = dstr_init(buffer_size);\n if (!s) goto failure;\n\n while (fgets(buffer, buffer_size, fd)) {\n while (!dstr_space(s, buffer_size))\n if (!dstr_grow(s)) goto failure;\n\n strncpy(s->data + s->length, buffer, buffer_size);\n s->length += strlen(buffer);\n }\n\n return s;\n\nfailure:\n dstr_delete(s);\n return NULL;\n}\n\nvoid dstr_replace_all(dstr *story, const char *replace, const char *insert)\n{\n const size_t replace_l = strlen(replace);\n const size_t insert_l = strlen(insert);\n char *start = story->data;\n\n while ((start = strstr(start, replace))) {\n if (!dstr_space(story, insert_l - replace_l))\n if (!dstr_grow(story)) err(\"Failed to allocate memory\");\n\n if (insert_l != replace_l) {\n memmove(start + insert_l, start + replace_l, story->length -\n (start + replace_l - story->data));\n\n \n story->length += insert_l - replace_l;\n story->data[story->length] = 0;\n }\n\n memmove(start, insert, insert_l);\n }\n}\n\nvoid madlibs(dstr *story)\n{\n static const size_t buffer_size = 128;\n char insert[buffer_size];\n char replace[buffer_size];\n\n char *start,\n *end = story->data;\n\n while (start = strchr(end, '<')) {\n if (!(end = strchr(start, '>'))) err(\"Malformed brackets in input\");\n\n \n strncpy(replace, start, end - start + 1);\n replace[end - start + 1] = '\\0';\n\n printf(\"Enter value for field %s: \", replace);\n\n fgets(insert, buffer_size, stdin);\n const size_t il = strlen(insert) - 1;\n if (insert[il] == '\\n')\n insert[il] = '\\0';\n\n dstr_replace_all(story, replace, insert);\n }\n printf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n if (argc < 2) return 0;\n\n FILE *fd = fopen(argv[1], \"r\");\n if (!fd) err(\"Could not open file: '%s\\n\", argv[1]);\n\n dstr *story = readinput(fd); fclose(fd);\n if (!story) err(\"Failed to allocate memory\");\n\n madlibs(story);\n printf(\"%s\\n\", story->data);\n dstr_delete(story);\n return 0;\n}\n","Rust":"extern crate regex;\n\nuse regex::Regex;\nuse std::collections::HashMap;\nuse std::io;\n\nfn main() {\n let mut input_line = String::new();\n let mut template = String::new();\n\n println!(\"Please enter a multi-line story template with to replace, terminated by a blank line.\\n\");\n loop {\n io::stdin()\n .read_line(&mut input_line)\n .expect(\"The read line failed.\");\n if input_line.trim().is_empty() {\n break;\n }\n template.push_str(&input_line);\n input_line.clear();\n }\n\n let re = Regex::new(r\"<[^>]+>\").unwrap();\n let mut parts: HashMap<_, _> = re\n .captures_iter(&template)\n .map(|x| (x.get(0).unwrap().as_str().to_string(), \"\".to_string()))\n .collect();\n if parts.is_empty() {\n println!(\"No to replace.\\n\");\n } else {\n for (k, v) in parts.iter_mut() {\n println!(\"Please provide a replacement for {}: \", k);\n io::stdin()\n .read_line(&mut input_line)\n .expect(\"The read line failed.\");\n *v = input_line.trim().to_string();\n println!();\n template = template.replace(k, v);\n input_line.clear();\n }\n }\n println!(\"Resulting story:\\n\\n{}\", template);\n}\n"} {"name":"Magic 8-ball","C":"#include \n#include \n#include \n\nint main() {\n char *question = NULL;\n size_t len = 0;\n ssize_t read;\n const char* answers[20] = {\n \"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n \"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n \"Most likely\", \"Outlook good\", \"Signs point to yes\", \"Yes\",\n \"Reply hazy, try again\", \"Ask again later\",\n \"Better not tell you now\", \"Cannot predict now\",\n \"Concentrate and ask again\", \"Don't bet on it\",\n \"My reply is no\", \"My sources say no\", \"Outlook not so good\",\n \"Very doubtful\"\n };\n srand(time(NULL));\n printf(\"Please enter your question or a blank line to quit.\\n\");\n while (1) {\n printf(\"\\n?\u00a0: \");\n read = getline(&question, &len, stdin);\n if (read < 2) break;\n printf(\"\\n%s\\n\", answers[rand() % 20]);\n }\n if (question) free(question);\n return 0;\n}\n","Rust":"extern crate rand;\n\nuse rand::prelude::*;\nuse std::io;\n\nfn main() {\n let answers = [\n \"It is certain\",\n \"It is decidedly so\",\n \"Without a doubt\",\n \"Yes, definitely\",\n \"You may rely on it\",\n \"As I see it, yes\",\n \"Most likely\",\n \"Outlook good\",\n \"Signs point to yes\",\n \"Yes\",\n \"Reply hazy, try again\",\n \"Ask again later\",\n \"Better not tell you now\",\n \"Cannot predict now\",\n \"Concentrate and ask again\",\n \"Don't bet on it\",\n \"My reply is no\",\n \"My sources say no\",\n \"Outlook not so good\",\n \"Very doubtful\",\n ];\n let mut rng = rand::thread_rng();\n let mut input_line = String::new();\n\n println!(\"Please enter your question or a blank line to quit.\\n\");\n loop {\n io::stdin()\n .read_line(&mut input_line)\n .expect(\"The read line failed.\");\n if input_line.trim() == \"\" {\n break;\n }\n println!(\"{}\\n\", answers.choose(&mut rng).unwrap());\n input_line.clear();\n }\n}\n"} {"name":"Magic squares of odd order","C":"#include \n#include \n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)\/2*n);\n \n\treturn 0;\n}\n","Rust":"fn main() {\n let n = 9;\n let mut square = vec![vec![0; n]; n];\n for (i, row) in square.iter_mut().enumerate() {\n for (j, e) in row.iter_mut().enumerate() {\n *e = n * (((i + 1) + (j + 1) - 1 + (n >> 1)) % n) + (((i + 1) + (2 * (j + 1)) - 2) % n) + 1;\n print!(\"{:3} \", e);\n }\n println!(\"\");\n }\n let sum = n * (((n * n) + 1) \/ 2);\n println!(\"The sum of the square is {}.\", sum);\n}\n"} {"name":"Matrix digital rain","C":"\n#include \n#include \n#include \n#include \n#include \n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n \n srand(time(NULL));\n\n \n char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n int total_chars = sizeof(chars);\n\n \n initscr();\n noecho();\n curs_set(FALSE);\n\n start_color();\n init_pair(1, COLOR_GREEN, COLOR_BLACK);\n attron(COLOR_PAIR(1));\n\n int max_x = 0, max_y = 0;\n\n getmaxyx(stdscr, max_y, max_x);\n\n \n\n \n int columns_row[max_x];\n\n \n int columns_active[max_x];\n\n int i;\n\n \n for (i = 0; i < max_x; i++)\n {\n columns_row[i] = -1;\n columns_active[i] = 0;\n }\n\n while (1)\n {\n for (i = 0; i < max_x; i++)\n {\n if (columns_row[i] == -1)\n {\n \n columns_row[i] = get_rand_in_range(0, max_y);\n columns_active[i] = get_rand_in_range(0, 1);\n }\n }\n\n \n for (i = 0; i < max_x; i++)\n {\n if (columns_active[i] == 1)\n {\n \n int char_index = get_rand_in_range(0, total_chars);\n mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n }\n else\n {\n \n mvprintw(columns_row[i], i, \" \");\n }\n\n columns_row[i]++;\n\n \n if (columns_row[i] >= max_y)\n {\n columns_row[i] = -1;\n }\n\n \n if (get_rand_in_range(0, 1000) == 0)\n {\n columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n }\n }\n\n usleep(ROW_DELAY);\n refresh();\n }\n\n endwin();\n return 0;\n}\n","Rust":"#![warn(clippy::pedantic)] \n\nuse rand::prelude::{ThreadRng, SliceRandom};\nuse rand::{thread_rng, Rng};\nuse termion::{color::Rgb};\nuse termion::input::TermRead;\nuse termion::raw::IntoRawMode;\nuse std::sync::mpsc::{channel, TryRecvError};\nuse std::thread;\nuse std::{io::{Write, stdout, stdin}, iter::repeat, time::Duration};\n\n\n\n\nconst CHARS: [char; 322] = [\n 'M', '\u0407', '\u0409', '\u040a', '\u040b', '\u040c', '\u040d', '\u040e', '\u040f', '\u0411', '\u0413', '\u0414', '\u0416', '\u0418', '\u0419', '\u041b', '\u041f', '\u0424', '\u0426', '\u0427', '\u0428', '\u0429', '\u042a',\n '\u042b', '\u042d', '\u042e', '\u042f', '\u0432', '\u0434', '\u0436', '\u0437', '\u0438', '\u0439', '\u043a', '\u043b', '\u043c', '\u043d', '\u043f', '\u0442', '\u0444', '\u0446', '\u0447', '\u0448', '\u0449', '\u044a', '\u044b',\n '\u044c', '\u044d', '\u044e', '\u044f', '\u0450', '\u0451', '\u0452', '\u0453', '\u0454', '\u0457', '\u0459', '\u045a', '\u045b', '\u045c', '\u045d', '\u045e', '\u045f', '\u0462', '\u0463', '\u0467', '\u046e', '\u0471', '\u0472',\n '\u0473', '\u048b', '\u048c', '\u048d', '\u048e', '\u048f', '\u0490', '\u0491', '\u0492', '\u0493', '\u0494', '\u0495', '\u0496', '\u0497', '\u0498', '\u0499', '\u049a', '\u049b', '\u049d', '\u049f', '\u04a1', '\u04a2', '\u04a3',\n '\u04a4', '\u04a5', '\u04a9', '\u04aa', '\u04ab', '\u04ac', '\u04ad', '\u04b0', '\u04b1', '\u04b2', '\u04b3', '\u04b5', '\u04b7', '\u04b9', '\u04ba', '\u04bf', '\u04c1', '\u04c2', '\u04c3', '\u04c4', '\u04c6', '\u04c7', '\u04c8',\n '\u04ca', '\u04cb', '\u04cc', '\u04ce', '\u04d0', '\u04d1', '\u04d2', '\u04d3', '\u04d4', '\u04d5', '\u04d6', '\u04d7', '\u04d8', '\u04d9', '\u04da', '\u04db', '\u04dc', '\u04dd', '\u04de', '\u04df', '\u04e1', '\u04e2', '\u04e3',\n '\u04e4', '\u04e5', '\u04e6', '\u04e7', '\u04e8', '\u04e9', '\u04ea', '\u04eb', '\u04ec', '\u04ed', '\u04ee', '\u04ef', '\u04f0', '\u04f1', '\u04f2', '\u04f3', '\u04f4', '\u04f5', '\u04f6', '\u04f7', '\u04f8', '\u04f9', '\u04fa',\n '\u04fd', '\u04ff', '\u0500', '\u050d', '\u050f', '\u0510', '\u0511', '\u0513', '\u051a', '\u051f', '\u0526', '\u0527', '\u03e4', '\u03e5', '\u03eb', '\u03ed', '\uff69', '\uff6a', '\uff6b', '\uff6c', '\uff6d', '\uff6e', '\uff6f',\n '\uff70', '\uff71', '\uff72', '\uff73', '\uff74', '\uff75', '\uff76', '\uff77', '\uff78', '\uff79', '\uff7a', '\uff7b', '\uff7c', '\uff7d', '\uff7e', '\uff7f', '\uff80', '\uff81', '\uff82', '\uff83', '\uff84', '\uff85', '\uff86',\n '\uff87', '\uff88', '\uff89', '\uff8a', '\uff8b', '\uff8c', '\uff8d', '\uff8e', '\uff8f', '\uff90', '\uff91', '\uff92', '\uff93', '\uff94', '\uff95', '\uff96', '\uff97', '\uff98', '\uff99', '\uff9a', '\uff9b', '\uff9c', '\uff9d',\n '\u2c81', '\u2c82', '\u2c83', '\u2c84', '\u0393', '\u0394', '\u0398', '\u039b', '\u039e', '\u03a0', '\u0400', '\u0401', '\u0402', '\u0403', '\u0404', '\u2c89', '\u2c8a', '\u2c8b', '\u2c8c', '\u2c8d', '\u2c8f', '\u2c91', '\u2c93',\n '\u2c95', '\u2c97', '\u2c99', '\u2c9b', '\u2c9c', '\u2c9d', '\u2ca1', '\u2ca7', '\u2ca9', '\u2cab', '\u2cad', '\u2caf', '\u2cc1', '\u2cc8', '\u2cc9', '\u2ccb', '\u2ce4', '\u2ce5', '\u2ce6', '\u2ce8', '\u2ce9', '\u2200', '\u2201',\n '\u2202', '\u2203', '\u2204', '\u2205', '\u2206', '\u2207', '\u2208', '\u2209', '\u220a', '\u220b', '\u220c', '\u220d', '\u220e', '\u220f', '\u2210', '\u2211', '\u2213', '\u2107', '\u210f', '\u2125', '\u2132', '\u2137', '\u2a6b',\n '\u2a00', '\u2a05', '\u2a06', '\u2a09', '\u2a0d', '\u2a0e', '\u2a0f', '\u2a10', '\u2a11', '\u2a12', '\u2a13', '\u2a14', '\u2a15', '\u2a16', '\u2a17', '\u2a18', '\u2a19', '\u2a1a', '\u2a1b', '\u2a1c', '\u2a1d', '\u2a3f', '\u2a6a',\n ];\n\n\nfn color(brightness: u8) -> Rgb {\n let v = f32::from(brightness) \/ 255.0;\n let r = v.powi(7);\n let g = v.powi(1);\n let b = v.powi(4);\n \n #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]\n Rgb ((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8)\n}\n\n\n#[derive(Clone, Copy)]\nstruct Symbol {\n char: char,\n brightness: u8,\n}\n\n\nimpl Default for Symbol {\n fn default() -> Self {\n Self { char: ' ', brightness: 0 }\n }\n}\n\nimpl Symbol {\n \n fn print(self, out: &mut W) {\n write!(out, \"{}{}\", termion::color::Fg(color(self.brightness)), self.char).unwrap();\n }\n\n \n fn darken(&mut self) {\n self.brightness = self.brightness.saturating_sub(10);\n }\n\n \n fn set(&mut self, char: char) {\n self.char = char;\n self.brightness = 255;\n }\n}\n\n\n#[derive(Clone)]\nstruct Column {\n symbols: Vec,\n}\n\nimpl Column {\n \n fn new(height: usize) -> Self {\n Self {\n symbols: vec![Symbol::default(); height],\n }\n }\n\n \n fn print_symbol(&self, out: &mut W, row: usize) {\n self.symbols[row].print(out);\n }\n\n \n fn darken(&mut self) {\n self.symbols.iter_mut().for_each(Symbol::darken);\n }\n\n fn set(&mut self, row: usize, char: char) {\n self.symbols[row].set(char);\n }\n}\n\n\nstruct Droplet {\n \n \n row: isize,\n col: usize,\n}\n\nimpl Droplet {\n \n fn new_random(rng: &mut ThreadRng, width: usize, height: usize) -> Self {\n \n #[allow(clippy::cast_possible_wrap)]\n Self {\n row: -(rng.gen_range(0..height) as isize),\n col: rng.gen_range(0..width),\n }\n }\n\n \n \n fn update(&mut self, width: usize, height: usize) {\n self.row += 1;\n \n #[allow(clippy::cast_possible_wrap)]\n if self.row >= height as isize {\n let mut rng = thread_rng();\n self.col = rng.gen_range(0..width);\n self.row = 0;\n }\n }\n}\n\n\nstruct Screen {\n width: usize,\n height: usize,\n columns: Vec,\n droplets: Vec,\n}\n\nimpl Screen {\n\n \n fn new(width: usize, height: usize) -> Self {\n let mut rng = thread_rng();\n Self {\n width,\n height,\n columns: repeat(Column::new(height)).take(width).collect(),\n droplets: (0..width).map(|_| Droplet::new_random(&mut rng, width, height)).collect(),\n }\n }\n\n \n fn print(&self, out: &mut W) {\n for row in 0..self.height {\n for column in &self.columns {\n column.print_symbol(out, row);\n }\n write!(out, \"\\r\\n\").unwrap();\n }\n }\n\n \n fn update_droplets(&mut self) {\n let mut rng = thread_rng();\n for droplet in &mut self.droplets {\n droplet.update(self.width, self.height);\n if let Ok(row) = droplet.row.try_into() {\n let ch = CHARS.choose(&mut rng).copied().unwrap_or(' ');\n self.columns[droplet.col].set(row, ch);\n }\n }\n }\n\n \n fn darken(&mut self) {\n self.columns.iter_mut().for_each(Column::darken);\n }\n\n}\n\nfn main() {\n \n let (width, height) = termion::terminal_size().unwrap();\n let mut screen = Screen::new(width as usize, height as usize - 1);\n\n \n let (tx, rx) = channel();\n \n \n thread::spawn(move || {\n stdin().keys().next();\n \n tx.send(()).expect(\"Could not send signal on channel.\");\n });\n\n \n let mut stdout = stdout().into_raw_mode().unwrap();\n\n \n write!(stdout, \"{}{}\", termion::clear::All, termion::cursor::Hide).unwrap();\n\n \n while rx.try_recv() == Err(TryRecvError::Empty) {\n \n write!(stdout, \"{}{}\", termion::cursor::Goto(1, 1), termion::color::Bg(termion::color::Rgb(0, 0, 0))).unwrap();\n\n \n screen.print(&mut stdout);\n screen.darken();\n screen.update_droplets();\n \n stdout.flush().unwrap();\n\n \n std::thread::sleep(Duration::from_millis(50));\n }\n\n \n write!(stdout, \"{}\", termion::style::Reset).unwrap();\n write!(stdout, \"{}\", termion::clear::All).unwrap();\n write!(stdout, \"{}\", termion::cursor::Goto(1, 1)).unwrap();\n write!(stdout, \"{}\", termion::cursor::Show).unwrap();\n}\n"} {"name":"Optional parameters","C":"#include \n#include \n#include \n#include \n#include \n\ntypedef const char * String;\ntypedef struct sTable {\n String * *rows;\n int n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n CompareFctn compare;\n int column;\n int reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n String *rA = *(String *const *)aa;\n String *rB = *(String *const *)bb;\n int sortCol = sortSpec.column;\n\n String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n va_list vl;\n const char *p;\n int c;\n sortSpec.compare = &strcmp;\n sortSpec.column = 0;\n sortSpec.reversed = 0;\n\n va_start(vl, argSpec);\n if (argSpec)\n for (p=argSpec; *p; p++) {\n switch (*p) {\n case 'o':\n sortSpec.compare = va_arg(vl,CompareFctn);\n break;\n case 'c':\n c = va_arg(vl,int);\n if ( 0<=c && cn_cols)\n sortSpec.column = c;\n break;\n case 'r':\n sortSpec.reversed = (0!=va_arg(vl,int));\n break;\n }\n }\n va_end(vl);\n qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n int row, col;\n\n for (row=0; rown_rows; row++) {\n fprintf(fout, \" \");\n for(col=0; coln_cols; col++) {\n fprintf(fout, colFmts[col], tbl->rows[row][col]);\n }\n fprintf(fout, \"\\n\");\n }\n fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n const char *p1 = s1; \n const char *p2 = s2;\n const char *mrk1, *mrk2;\n while ((tolower(*p1) == tolower(*p2)) && *p1) {\n p1++; p2++;\n }\n if (isdigit(*p1) && isdigit(*p2)) {\n long v1, v2;\n if ((*p1 == '0') ||(*p2 == '0')) {\n while (p1 > s1) {\n p1--; p2--;\n if (*p1 != '0') break;\n }\n if (!isdigit(*p1)) {\n p1++; p2++;\n }\n }\n mrk1 = p1; mrk2 = p2;\n v1 = 0;\n while(isdigit(*p1)) {\n v1 = 10*v1+ord(*p1);\n p1++;\n }\n v2 = 0;\n while(isdigit(*p2)) {\n v2 = 10*v2+ord(*p2);\n p2++;\n }\n if (v1 == v2) \n return(p2-mrk2)-(p1-mrk1);\n return v1 - v2;\n }\n if (tolower(*p1) != tolower(*p2))\n return (tolower(*p1) - tolower(*p2));\n for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n return (*p1 -*p2);\n}\n\nint main()\n{\n const char *colFmts[] = {\"\u00a0%-5.5s\",\"\u00a0%-5.5s\",\"\u00a0%-9.9s\"};\n String r1[] = { \"a101\", \"red\", \"Java\" };\n String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n String r3[] = { \"ab9\", \"blue\", \"Fortran\" };\n String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n String r8[] = { \"ab1\", \"orng\", \"Scheme\" };\n\n String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n struct sTable table;\n table.rows = rows;\n table.n_rows = 8;\n table.n_cols = 3;\n\n sortTable(&table, \"\");\n printf(\"sort on col 0, ascending\\n\");\n printTable(&table, stdout, colFmts);\n\n sortTable(&table, \"ro\", 1, &cmprStrgs);\n printf(\"sort on col 0, reverse.special\\n\");\n printTable(&table, stdout, colFmts);\n\n sortTable(&table, \"c\", 1);\n printf(\"sort on col 1, ascending\\n\");\n printTable(&table, stdout, colFmts);\n\n sortTable(&table, \"cr\", 2, 1);\n printf(\"sort on col 2, reverse\\n\");\n printTable(&table, stdout, colFmts);\n return 0;\n}\n","Rust":"use std::cmp::Ordering;\n\nstruct Table {\n rows: Vec>,\n ordering_function: fn(&str, &str) -> Ordering,\n ordering_column: usize,\n reverse: bool,\n}\n\nimpl Table {\n fn new(rows: Vec>) -> Table {\n Table {\n rows: rows,\n ordering_column: 0,\n reverse: false,\n ordering_function: |str1, str2| str1.cmp(str2),\n }\n }\n}\n\nimpl Table {\n fn with_ordering_column(&mut self, ordering_column: usize) -> &mut Table {\n self.ordering_column = ordering_column;\n self\n }\n\n fn with_reverse(&mut self, reverse: bool) -> &mut Table {\n self.reverse = reverse;\n self\n }\n\n fn with_ordering_fun(&mut self, compare: fn(&str, &str) -> Ordering) -> &mut Table {\n self.ordering_function = compare;\n self\n }\n\n fn sort(&mut self) {\n let fun = &mut self.ordering_function;\n let idx = self.ordering_column;\n if self.reverse {\n self.rows\n .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]).reverse());\n } else {\n self.rows\n .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]));\n }\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::Table;\n\n fn generate_test_table() -> Table {\n Table::new(vec![\n vec![\"0\".to_string(), \"fff\".to_string()],\n vec![\"2\".to_string(), \"aab\".to_string()],\n vec![\"1\".to_string(), \"ccc\".to_string()],\n ])\n }\n\n #[test]\n fn test_simple_sort() {\n let mut table = generate_test_table();\n table.sort();\n assert_eq!(\n table.rows,\n vec![\n vec![\"0\".to_string(), \"fff\".to_string()],\n vec![\"1\".to_string(), \"ccc\".to_string()],\n vec![\"2\".to_string(), \"aab\".to_string()],\n ],\n )\n }\n\n #[test]\n fn test_ordering_column() {\n let mut table = generate_test_table();\n table.with_ordering_column(1).sort();\n assert_eq!(\n table.rows,\n vec![\n vec![\"2\".to_string(), \"aab\".to_string()],\n vec![\"1\".to_string(), \"ccc\".to_string()],\n vec![\"0\".to_string(), \"fff\".to_string()],\n ],\n )\n }\n\n #[test]\n fn test_with_reverse() {\n let mut table = generate_test_table();\n table.with_reverse(true).sort();\n assert_eq!(\n table.rows,\n vec![\n vec![\"2\".to_string(), \"aab\".to_string()],\n vec![\"1\".to_string(), \"ccc\".to_string()],\n vec![\"0\".to_string(), \"fff\".to_string()],\n ],\n )\n }\n\n #[test]\n fn test_custom_ordering_fun() {\n let mut table = generate_test_table();\n \n \n table.with_ordering_fun(|x, y| x.cmp(y).reverse()).sort();\n assert_eq!(\n table.rows,\n vec![\n vec![\"2\".to_string(), \"aab\".to_string()],\n vec![\"1\".to_string(), \"ccc\".to_string()],\n vec![\"0\".to_string(), \"fff\".to_string()],\n ],\n )\n }\n\n #[test]\n fn test_everything_together() {\n let mut table = generate_test_table();\n \n \n table\n .with_ordering_fun(|x, y| x.cmp(y).reverse())\n .with_reverse(true)\n .with_ordering_column(1)\n .sort();\n assert_eq!(\n table.rows,\n vec![\n vec![\"2\".to_string(), \"aab\".to_string()],\n vec![\"1\".to_string(), \"ccc\".to_string()],\n vec![\"0\".to_string(), \"fff\".to_string()],\n ],\n )\n }\n}\n"} {"name":"Peano curve","C":"\n\n#include \n#include \n\nvoid Peano(int x, int y, int lg, int i1, int i2) {\n\n\tif (lg == 1) {\n\t\tlineto(3*x,3*y);\n\t\treturn;\n\t}\n\t\n\tlg = lg\/3;\n\tPeano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2);\n\tPeano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2);\n\tPeano(x+lg, y+lg, lg, i1, 1-i2);\n\tPeano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2);\n\tPeano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2);\n\tPeano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2);\n\tPeano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2);\n\tPeano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2);\n\tPeano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2);\n}\n\nint main(void) {\n\n\tinitwindow(1000,1000,\"Peano, Peano\");\n\n\tPeano(0, 0, 1000, 0, 0); \n\t\n\tgetch();\n\tcleardevice();\n\t\n\treturn 0;\n}\n","Rust":"\n\n\nuse svg::node::element::path::Data;\nuse svg::node::element::Path;\n\nstruct PeanoCurve {\n current_x: f64,\n current_y: f64,\n current_angle: i32,\n line_length: f64,\n}\n\nimpl PeanoCurve {\n fn new(x: f64, y: f64, length: f64, angle: i32) -> PeanoCurve {\n PeanoCurve {\n current_x: x,\n current_y: y,\n current_angle: angle,\n line_length: length,\n }\n }\n fn rewrite(order: usize) -> String {\n let mut str = String::from(\"L\");\n for _ in 0..order {\n let mut tmp = String::new();\n for ch in str.chars() {\n match ch {\n 'L' => tmp.push_str(\"LFRFL-F-RFLFR+F+LFRFL\"),\n 'R' => tmp.push_str(\"RFLFR+F+LFRFL-F-RFLFR\"),\n _ => tmp.push(ch),\n }\n }\n str = tmp;\n }\n str\n }\n fn execute(&mut self, order: usize) -> Path {\n let mut data = Data::new().move_to((self.current_x, self.current_y));\n for ch in PeanoCurve::rewrite(order).chars() {\n match ch {\n 'F' => data = self.draw_line(data),\n '+' => self.turn(90),\n '-' => self.turn(-90),\n _ => {}\n }\n }\n Path::new()\n .set(\"fill\", \"none\")\n .set(\"stroke\", \"black\")\n .set(\"stroke-width\", \"1\")\n .set(\"d\", data)\n }\n fn draw_line(&mut self, data: Data) -> Data {\n let theta = (self.current_angle as f64).to_radians();\n self.current_x += self.line_length * theta.cos();\n self.current_y += self.line_length * theta.sin();\n data.line_to((self.current_x, self.current_y))\n }\n fn turn(&mut self, angle: i32) {\n self.current_angle = (self.current_angle + angle) % 360;\n }\n fn save(file: &str, size: usize, order: usize) -> std::io::Result<()> {\n use svg::node::element::Rectangle;\n let rect = Rectangle::new()\n .set(\"width\", \"100%\")\n .set(\"height\", \"100%\")\n .set(\"fill\", \"white\");\n let mut p = PeanoCurve::new(8.0, 8.0, 8.0, 90);\n let document = svg::Document::new()\n .set(\"width\", size)\n .set(\"height\", size)\n .add(rect)\n .add(p.execute(order));\n svg::save(file, &document)\n }\n}\n\nfn main() {\n PeanoCurve::save(\"peano_curve.svg\", 656, 4).unwrap();\n}\n"} {"name":"Permutation test","C":"#include \n\nint data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97,\n 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n if (!remain) return (accu > treat) ? 1 : 0;\n\n return pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n int treat = 0, i;\n int le, gt;\n double total = 1;\n for (i = 0; i < 9; i++) treat += data[i];\n for (i = 19; i > 10; i--) total *= i;\n for (i = 9; i > 0; i--) total \/= i;\n\n gt = pick(19, 9, 0, treat);\n le = total - gt;\n\n printf(\"<=\u00a0: %f%% %d\\n >\u00a0: %f%% %d\\n\",\n 100 * le \/ total, le, 100 * gt \/ total, gt);\n return 0;\n}\n","Rust":"fn main() {\n let treatment = vec![85, 88, 75, 66, 25, 29, 83, 39, 97];\n let control = vec![68, 41, 10, 49, 16, 65, 32, 92, 28, 98];\n\n let mut data_set = control.clone();\n data_set.extend_from_slice(&treatment);\n\n let greater = combinations(treatment.iter().sum(), treatment.len() as i64, &data_set) as f64;\n let lesser = combinations(control.iter().sum(), control.len() as i64, &data_set) as f64;\n let total = binomial(data_set.len() as i64, treatment.len() as i64) as f64;\n\n println!(\"<=\u00a0: {}%\", (lesser \/ total * 100.0));\n println!(\" >\u00a0: {}%\", (greater \/ total * 100.0));\n}\n\nfn factorial(x: i64) -> i64 {\n let mut product = 1;\n for a in 1..(x + 1) {\n product *= a;\n }\n product\n}\n\nfn binomial(n: i64, k: i64) -> i64 {\n let numerator = factorial(n);\n let denominator = factorial(k) * factorial(n - k);\n numerator \/ denominator\n}\n\nfn combinations(total: i64, number: i64, data: &[i64]) -> i64 {\n if total < 0 {\n return binomial(data.len() as i64, number);\n }\n\n if number == 0 {\n return 0;\n }\n\n if number > data.len() as i64 {\n return 0;\n }\n\n if number == data.len() as i64 {\n if total < data.iter().sum() {\n return 1;\n } else {\n return 0;\n }\n }\n\n let tail = &data[1..];\n combinations(total - data[0], number - 1, &tail) + combinations(total, number, &tail)\n}\n"} {"name":"Pythagoras tree","C":"#include\n#include\n#include\n#include\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y - b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y - b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x + ( b.x - a.x - (a.y - b.y) ) \/ 2;\n\te.y = d.y - ( b.x - a.x + a.y - b.y ) \/ 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length\u00a0: \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations\u00a0: \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side\/2 - side\/2;\n\ta.y = 4*side;\n\tb.x = 6*side\/2 + side\/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree\u00a0?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n","Rust":"\n\nuse svg::node::element::{Group, Polygon};\n\nfn main() {\n let mut doc = svg::Document::new().set(\"stroke\", \"white\");\n let mut base: Vec<[(f64, f64); 2]> = vec![[(-200.0, 0.0), (200.0, 0.0)]];\n for lvl in 0..12u8 {\n let rg = |step| lvl.wrapping_mul(step).wrapping_add(80 - step * 2);\n let mut group = Group::new().set(\"fill\", format!(\"#{:02X}{:02X}18\", rg(20), rg(30))); \n let mut next_base = Vec::new();\n for [a, b] in base {\n let v = (b.0 - a.0, b.1 - a.1);\n let c = (a.0 + v.1, a.1 - v.0);\n let d = (c.0 + v.0, c.1 + v.1);\n let e = (c.0 + 0.5 * (v.0 + v.1), c.1 + 0.5 * (v.1 - v.0));\n group = group.add(Polygon::new().set(\"points\", vec![a, c, e, d, c, d, b]));\n next_base.extend([[c, e], [e, d]]);\n }\n base = next_base;\n doc = doc.add(group);\n }\n let (x0, y0) = (base.iter()).fold((0.0, 0.0), |(x0, y0), [(x, y), _]| (x.min(x0), y.min(y0)));\n let file = \"pythagoras_tree.svg\";\n match svg::save(file, &doc.set(\"viewBox\", (x0, y0, -x0 * 2.0, -y0))) {\n Ok(_) => println!(\"{file} file written successfully!\"),\n Err(e) => println!(\"failed to write {file}: {e}\"),\n }\n}\n"} {"name":"Pythagorean triples","C":"#include \n#include \n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n ulong t;\n while (n) { t = n; n = m % n; m = t; }\n return m;\n}\n \nint main()\n{\n ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n xint aa, bb, cc;\n\n for (a = 1; a <= max_p \/ 3; a++) {\n aa = (xint)a * a;\n printf(\"a = %lu\\r\", a); \n fflush(stdout);\n\n \n for (b = a + 1; b < max_p\/2; b++) {\n bb = (xint)b * b;\n for (c = b + 1; c < max_p\/2; c++) {\n cc = (xint)c * c;\n if (aa + bb < cc) break;\n if (a + b + c > max_p) break;\n\n if (aa + bb == cc) {\n pytha++;\n if (gcd(a, b) == 1) prim++;\n }\n }\n }\n }\n \n printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n max_p, pytha, prim);\n\n return 0;\n}\n","Rust":"use std::thread;\n\nfn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 {\n let mut primitive_count = 0;\n for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], \n [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c],\n [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() {\n let l = triangle[0] + triangle[1] + triangle[2];\n if l > d { continue; }\n primitive_count += 1 + f1(triangle[0], triangle[1], triangle[2], d);\n }\n primitive_count\n}\n\nfn f2 (a : u64, b : u64, c : u64, d : u64) -> u64 {\n let mut triplet_count = 0;\n for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], \n [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c],\n [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() {\n let l = triangle[0] + triangle[1] + triangle[2];\n if l > d { continue; }\n triplet_count += (d\/l) + f2(triangle[0], triangle[1], triangle[2], d);\n }\n triplet_count\n}\n\nfn main () {\n let new_th_1 = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || {\n let mut i = 100;\n while i <= 100_000_000_000 {\n println!(\" Primitive triples below {}\u00a0: {}\", i, f1(3, 4, 5, i) + 1);\n i *= 10;\n }\n }).unwrap();\n\n let new_th_2 =thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || {\n let mut i = 100;\n while i <= 100_000_000_000 {\n println!(\" Triples below {}\u00a0: {}\", i, f2(3, 4, 5, i) + i\/12);\n i *= 10;\n }\n }).unwrap();\n\n new_th_1.join().unwrap();\n new_th_2.join().unwrap();\n}\n"} {"name":"Range consolidation","C":"#include \n#include \n\ntypedef struct range_tag {\n double low;\n double high;\n} range_t;\n\nvoid normalize_range(range_t* range) {\n if (range->high < range->low) {\n double tmp = range->low;\n range->low = range->high;\n range->high = tmp;\n }\n}\n\nint range_compare(const void* p1, const void* p2) {\n const range_t* r1 = p1;\n const range_t* r2 = p2;\n if (r1->low < r2->low)\n return -1;\n if (r1->low > r2->low)\n return 1;\n if (r1->high < r2->high)\n return -1;\n if (r1->high > r2->high)\n return 1;\n return 0;\n}\n\nvoid normalize_ranges(range_t* ranges, size_t count) {\n for (size_t i = 0; i < count; ++i)\n normalize_range(&ranges[i]);\n qsort(ranges, count, sizeof(range_t), range_compare);\n}\n\n\n\nsize_t consolidate_ranges(range_t* ranges, size_t count) {\n normalize_ranges(ranges, count);\n size_t out_index = 0;\n for (size_t i = 0; i < count; ) {\n size_t j = i;\n while (++j < count && ranges[j].low <= ranges[i].high) {\n if (ranges[i].high < ranges[j].high)\n ranges[i].high = ranges[j].high;\n }\n ranges[out_index++] = ranges[i];\n i = j;\n }\n return out_index;\n}\n\nvoid print_range(const range_t* range) {\n printf(\"[%g, %g]\", range->low, range->high);\n}\n\nvoid print_ranges(const range_t* ranges, size_t count) {\n if (count == 0)\n return;\n print_range(&ranges[0]);\n for (size_t i = 1; i < count; ++i) {\n printf(\", \");\n print_range(&ranges[i]);\n }\n}\n\nvoid test_consolidate_ranges(range_t* ranges, size_t count) {\n print_ranges(ranges, count);\n printf(\" -> \");\n count = consolidate_ranges(ranges, count);\n print_ranges(ranges, count);\n printf(\"\\n\");\n}\n\n#define LENGTHOF(a) sizeof(a)\/sizeof(a[0])\n\nint main() {\n range_t test1[] = { {1.1, 2.2} };\n range_t test2[] = { {6.1, 7.2}, {7.2, 8.3} };\n range_t test3[] = { {4, 3}, {2, 1} };\n range_t test4[] = { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} };\n range_t test5[] = { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} };\n test_consolidate_ranges(test1, LENGTHOF(test1));\n test_consolidate_ranges(test2, LENGTHOF(test2));\n test_consolidate_ranges(test3, LENGTHOF(test3));\n test_consolidate_ranges(test4, LENGTHOF(test4));\n test_consolidate_ranges(test5, LENGTHOF(test5));\n return 0;\n}\n","Rust":"use std::fmt::{Display, Formatter};\n\n\n\n\n\n#[derive(Clone, Debug, PartialEq, PartialOrd)]\npub struct ClosedRange {\n start: Idx,\n end: Idx,\n}\n\nimpl ClosedRange {\n pub fn start(&self) -> &Idx {\n &self.start\n }\n\n pub fn end(&self) -> &Idx {\n &self.end\n }\n}\n\nimpl ClosedRange {\n pub fn new(start: Idx, end: Idx) -> Self {\n if start <= end {\n Self { start, end }\n } else {\n Self {\n end: start,\n start: end,\n }\n }\n }\n}\n\n\nimpl From<(Idx, Idx)> for ClosedRange {\n fn from((start, end): (Idx, Idx)) -> Self {\n Self::new(start, end)\n }\n}\n\n\nimpl Display for ClosedRange {\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n write!(f, \"[{}, {}]\", self.start, self.end)\n }\n}\n\nfn consolidate(a: &ClosedRange, b: &ClosedRange) -> Option>\nwhere\n Idx: PartialOrd + Clone,\n{\n if a.start() <= b.start() {\n if b.end() <= a.end() {\n Some(a.clone())\n } else if a.end() < b.start() {\n None\n } else {\n Some(ClosedRange::new(a.start().clone(), b.end().clone()))\n }\n } else {\n consolidate(b, a)\n }\n}\n\nfn consolidate_all(mut ranges: Vec>) -> Vec>\nwhere\n Idx: PartialOrd + Clone,\n{\n \n ranges.sort_by(|a, b| a.partial_cmp(b).unwrap());\n let mut ranges = ranges.into_iter();\n let mut result = Vec::new();\n\n if let Some(current) = ranges.next() {\n let leftover = ranges.fold(current, |mut acc, next| {\n match consolidate(&acc, &next) {\n Some(merger) => {\n acc = merger;\n }\n\n None => {\n result.push(acc);\n acc = next;\n }\n }\n\n acc\n });\n\n result.push(leftover);\n }\n\n result\n}\n\n#[cfg(test)]\nmod tests {\n use super::{consolidate_all, ClosedRange};\n use std::fmt::{Display, Formatter};\n\n struct IteratorToDisplay(F);\n\n impl Display for IteratorToDisplay\n where\n F: Fn() -> I,\n I: Iterator,\n I::Item: Display,\n {\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n let mut items = self.0();\n\n if let Some(item) = items.next() {\n write!(f, \"{}\", item)?;\n for item in items {\n write!(f, \", {}\", item)?;\n }\n }\n\n Ok(())\n }\n }\n\n macro_rules! parameterized {\n ($($name:ident: $value:expr,)*) => {\n $(\n #[test]\n fn $name() {\n let (input, expected) = $value;\n let expected: Vec<_> = expected.into_iter().map(ClosedRange::from).collect();\n let output = consolidate_all(input.into_iter().map(ClosedRange::from).collect());\n println!(\"{}: {}\", stringify!($name), IteratorToDisplay(|| output.iter()));\n assert_eq!(expected, output);\n }\n )*\n }\n }\n\n parameterized! {\n single: (vec![(1.1, 2.2)], vec![(1.1, 2.2)]),\n touching: (vec![(6.1, 7.2), (7.2, 8.3)], vec![(6.1, 8.3)]),\n disjoint: (vec![(4, 3), (2, 1)], vec![(1, 2), (3, 4)]),\n overlap: (vec![(4.0, 3.0), (2.0, 1.0), (-1.0, -2.0), (3.9, 10.0)], vec![(-2.0, -1.0), (1.0, 2.0), (3.0, 10.0)]),\n integer: (vec![(1, 3), (-6, -1), (-4, -5), (8, 2), (-6, -6)], vec![(-6, -1), (1, 8)]),\n }\n}\n\nfn main() {\n \n consolidate_all(Vec::>::new());\n\n println!(\"Run: cargo test -- --nocapture\");\n}\n"} {"name":"Ray-casting algorithm","C":"#include \n#include \n#include \n\ntypedef struct { double x, y; } vec;\ntypedef struct { int n; vec* v; } polygon_t, *polygon;\n\n#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}\n#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }\nBIN_V(sub, a.x - b.x, a.y - b.y);\nBIN_V(add, a.x + b.x, a.y + b.y);\nBIN_S(dot, a.x * b.x + a.y * b.y);\nBIN_S(cross, a.x * b.y - a.y * b.x);\n\n\nvec vmadd(vec a, double s, vec b)\n{\n\tvec c;\n\tc.x = a.x + s * b.x;\n\tc.y = a.y + s * b.y;\n\treturn c;\n}\n\n\nint intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)\n{\n\tvec dx = vsub(x1, x0), dy = vsub(y1, y0);\n\tdouble d = vcross(dy, dx), a;\n\tif (!d) return 0; \n\n\ta = (vcross(x0, dx) - vcross(y0, dx)) \/ d;\n\tif (sect)\n\t\t*sect = vmadd(y0, a, dy);\n\n\tif (a < -tol || a > 1 + tol) return -1;\n\tif (a < tol || a > 1 - tol) return 0;\n\n\ta = (vcross(x0, dy) - vcross(y0, dy)) \/ d;\n\tif (a < 0 || a > 1) return -1;\n\n\treturn 1;\n}\n\n\ndouble dist(vec x, vec y0, vec y1, double tol)\n{\n\tvec dy = vsub(y1, y0);\n\tvec x1, s;\n\tint r;\n\n\tx1.x = x.x + dy.y; x1.y = x.y - dy.x;\n\tr = intersect(x, x1, y0, y1, tol, &s);\n\tif (r == -1) return HUGE_VAL;\n\ts = vsub(s, x);\n\treturn sqrt(vdot(s, s));\n}\n\n#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)\n\nint inside(vec v, polygon p, double tol)\n{\n\t\n\tint i, k, crosses, intersectResult;\n\tvec *pv;\n\tdouble min_x, max_x, min_y, max_y;\n\n\tfor (i = 0; i < p->n; i++) {\n\t\tk = (i + 1) % p->n;\n\t\tmin_x = dist(v, p->v[i], p->v[k], tol);\n\t\tif (min_x < tol) return 0;\n\t}\n\n\tmin_x = max_x = p->v[0].x;\n\tmin_y = max_y = p->v[1].y;\n\n\t\n\tfor_v(i, pv, p) {\n\t\tif (pv->x > max_x) max_x = pv->x;\n\t\tif (pv->x < min_x) min_x = pv->x;\n\t\tif (pv->y > max_y) max_y = pv->y;\n\t\tif (pv->y < min_y) min_y = pv->y;\n\t}\n\tif (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)\n\t\treturn -1;\n\n\tmax_x -= min_x; max_x *= 2;\n\tmax_y -= min_y; max_y *= 2;\n\tmax_x += max_y;\n\n\tvec e;\n\twhile (1) {\n\t\tcrosses = 0;\n\t\t\n\t\te.x = v.x + (1 + rand() \/ (RAND_MAX + 1.)) * max_x;\n\t\te.y = v.y + (1 + rand() \/ (RAND_MAX + 1.)) * max_x;\n\n\t\tfor (i = 0; i < p->n; i++) {\n\t\t\tk = (i + 1) % p->n;\n\t\t\tintersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);\n\n\t\t\t\n\t\t\tif (!intersectResult) break;\n\n\t\t\tif (intersectResult == 1) crosses++;\n\t\t}\n\t\tif (i == p->n) break;\n\t}\n\treturn (crosses & 1) ? 1 : -1;\n}\n\nint main()\n{\n\tvec vsq[] = {\t{0,0}, {10,0}, {10,10}, {0,10},\n\t\t\t{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};\n\n\tpolygon_t sq = { 4, vsq }, \n\t\tsq_hole = { 8, vsq }; \n\n\tvec c = { 10, 5 }; \n\tvec d = { 5, 5 };\n\n\tprintf(\"%d\\n\", inside(c, &sq, 1e-10));\n\tprintf(\"%d\\n\", inside(c, &sq_hole, 1e-10));\n\n\tprintf(\"%d\\n\", inside(d, &sq, 1e-10));\t\n\tprintf(\"%d\\n\", inside(d, &sq_hole, 1e-10)); \n\n\treturn 0;\n}\n","Rust":"use std::f64;\n\nconst _EPS: f64 = 0.00001;\nconst _MIN: f64 = f64::MIN_POSITIVE;\nconst _MAX: f64 = f64::MAX;\n\n#[derive(Clone)]\nstruct Point {\n x: f64,\n y: f64,\n}\n\n#[derive(Clone)]\nstruct Edge {\n pt1: Point,\n pt2: Point,\n}\n\nimpl Edge {\n fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge {\n Edge {\n pt1: Point { x: pt1.0, y: pt1.1 },\n pt2: Point { x: pt2.0, y: pt2.1 },\n }\n }\n}\n\nstruct Polygon {\n edges: Vec, \n}\n\nfn pt_in_polygon(pt: &Point, poly: &Polygon) -> bool {\n let count = poly.edges\n .iter()\n .filter(|edge| ray_intersect_seg(pt, edge))\n .count();\n\n count % 2 == 1\n}\n\nfn ray_intersect_seg(p: &Point, edge: &Edge) -> bool {\n let mut pt = p.clone();\n let (mut a, mut b): (&Point, &Point) = (&edge.pt1, &edge.pt2);\n if a.y > b.y {\n std::mem::swap(&mut a, &mut b);\n }\n if pt.y == a.y || pt.y == b.y {\n pt.y += _EPS;\n }\n\n if (pt.y > b.y || pt.y < a.y) || pt.x > a.x.max(b.x) {\n false\n } else if pt.x < a.x.min(b.x) {\n true\n } else {\n let m_red = if (a.x - b.x).abs() > _MIN {\n (b.y - a.y) \/ (b.x - a.x)\n } else {\n _MAX\n };\n let m_blue = if (a.x - pt.x).abs() > _MIN {\n (pt.y - a.y) \/ (pt.x - a.x)\n } else {\n _MAX\n };\n m_blue >= m_red\n }\n}\n\nfn main() {\n let p = |x, y| Point { x, y };\n let testpoints = [p(5.0, 5.0), p(5.0, 8.0), p(-10.0, 5.0), p(0.0, 5.0), p(10.0, 5.0), p(8.0, 5.0), p(10.0, 10.0)];\n let poly_square = Polygon {\n edges: vec![\n Edge::new((0.0, 0.0), (10.0, 0.0)),\n Edge::new((10.0, 0.0), (10.0, 10.0)),\n Edge::new((10.0, 10.0), (0.0, 10.0)),\n Edge::new((0.0, 10.0), (0.0, 0.0)),\n ],\n };\n let poly_square_hole = Polygon {\n edges: vec![\n Edge::new((0.0, 0.0), (10.0, 0.0)),\n Edge::new((10.0, 0.0), (10.0, 10.0)),\n Edge::new((10.0, 10.0), (0.0, 10.0)),\n Edge::new((0.0, 10.0), (0.0, 0.0)),\n Edge::new((2.5, 2.5), (7.5, 2.5)),\n Edge::new((7.5, 2.5), (7.5, 7.5)),\n Edge::new((7.5, 7.5), (2.5, 7.5)),\n Edge::new((2.5, 7.5), (2.5, 2.5)),\n ],\n };\n let poly_strange = Polygon {\n edges: vec![\n Edge::new((0.0, 0.0), (2.5, 2.5)),\n Edge::new((2.5, 2.5), (0.0, 10.0)),\n Edge::new((0.0, 10.0), (2.5, 7.5)),\n Edge::new((2.5, 7.5), (7.5, 7.5)),\n Edge::new((7.5, 7.5), (10.0, 10.0)),\n Edge::new((10.0, 10.0), (10.0, 0.0)),\n Edge::new((10.0, 0.0), (2.5, 2.5)),\n ],\n };\n let poly_hexagon = Polygon {\n edges: vec![\n Edge::new((3.0, 0.0), (7.0, 0.0)),\n Edge::new((7.0, 0.0), (10.0, 5.0)),\n Edge::new((10.0, 5.0), (7.0, 10.0)),\n Edge::new((7.0, 10.0), (3.0, 10.0)),\n Edge::new((3.0, 10.0), (0.0, 5.0)),\n Edge::new((0.0, 5.0), (3.0, 0.0)),\n ],\n };\n print!(\"\\nSquare\u00a0:\");\n for pt in &testpoints {\n print!(\" {:?}\", pt_in_polygon(pt, &poly_square));\n }\n print!(\"\\nSquare with hole:\");\n for pt in &testpoints {\n print!(\" {:?}\", pt_in_polygon(pt, &poly_square_hole));\n }\n print!(\"\\nStrange polygon\u00a0:\");\n for pt in &testpoints {\n print!(\" {:?}\", pt_in_polygon(pt, &poly_strange));\n }\n print!(\"\\nHexagon\u00a0:\");\n for pt in &testpoints {\n print!(\" {:?}\", pt_in_polygon(pt, &poly_hexagon));\n }\n println!();\n}\n"} {"name":"Read a configuration file","C":"#include \n#include \n#include \n#include \n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong\u00a0:-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n","Rust":"use std::fs::File;\nuse std::io::BufRead;\nuse std::io::BufReader;\nuse std::iter::FromIterator;\nuse std::path::Path;\n\nfn main() {\n let path = String::from(\"file.conf\");\n let cfg = config_from_file(path);\n println!(\"{:?}\", cfg);\n}\n\nfn config_from_file(path: String) -> Config {\n let path = Path::new(&path);\n let file = File::open(path).expect(\"File not found or cannot be opened\");\n let content = BufReader::new(&file);\n let mut cfg = Config::new();\n\n for line in content.lines() {\n let line = line.expect(\"Could not read the line\");\n \n let line = line.trim();\n\n \n if line.starts_with(\"#\") || line.starts_with(\";\") || line.is_empty() {\n continue;\n }\n\n \n let tokens = Vec::from_iter(line.split_whitespace()); \n let name = tokens.first().unwrap();\n let tokens = tokens.get(1..).unwrap();\n\n \n let tokens = tokens.iter().filter(|t| !t.starts_with(\"=\"));\n \n let tokens = tokens.take_while(|t| !t.starts_with(\"#\") && !t.starts_with(\";\"));\n \n \n let mut parameters = String::new();\n tokens.for_each(|t| { parameters.push_str(t); parameters.push(' '); });\n \n let parameters = parameters.split(',').map(|s| s.trim());\n \n let parameters: Vec = parameters.map(|s| s.to_string()).collect();\n \n \n match name.to_lowercase().as_str() {\n \"fullname\" => cfg.full_name = parameters.get(0).cloned(),\n \"favouritefruit\" => cfg.favourite_fruit = parameters.get(0).cloned(),\n \"needspeeling\" => cfg.needs_peeling = true,\n \"seedsremoved\" => cfg.seeds_removed = true,\n \"otherfamily\" => cfg.other_family = Some(parameters),\n _ => (),\n }\n }\n\n cfg\n}\n\n#[derive(Clone, Debug)]\nstruct Config {\n full_name: Option,\n favourite_fruit: Option,\n needs_peeling: bool,\n seeds_removed: bool,\n other_family: Option>,\n}\n\nimpl Config {\n fn new() -> Config {\n Config {\n full_name: None,\n favourite_fruit: None,\n needs_peeling: false,\n seeds_removed: false,\n other_family: None,\n }\n }\n}\n"} {"name":"Read a specific line from a file","C":"#include \n#include \n#include \n#include \n#include \n#include \n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n","Rust":"use std::fs::File;\nuse std::io::BufRead;\nuse std::io::BufReader;\nuse std::io::Error;\nuse std::path::Path;\n \nfn main() {\n let path = Path::new(\"file.txt\");\n let line_num = 7usize;\n let line = get_line_at(&path, line_num - 1);\n println!(\"{}\", line.unwrap());\n}\n \nfn get_line_at(path: &Path, line_num: usize) -> Result {\n let file = File::open(path).expect(\"File not found or cannot be opened\");\n let content = BufReader::new(&file);\n let mut lines = content.lines();\n lines.nth(line_num).expect(\"No line found at that position\")\n}\n"} {"name":"Rep-string","C":"#include \n#include \n\nint repstr(char *str)\n{\n if (!str) return 0;\n\n size_t sl = strlen(str) \/ 2;\n while (sl > 0) {\n if (strstr(str, str + sl) == str)\n return sl;\n --sl;\n }\n\n return 0;\n}\n\nint main(void)\n{\n char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n size_t strslen = sizeof(strs) \/ sizeof(strs[0]);\n size_t i;\n for (i = 0; i < strslen; ++i) {\n int n = repstr(strs[i]);\n if (n)\n printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n else\n printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n }\n\n return 0;\n}\n","Rust":"fn main() {\n let strings = vec![\n String::from(\"1001110011\"),\n String::from(\"1110111011\"),\n String::from(\"0010010010\"),\n String::from(\"1010101010\"),\n String::from(\"1111111111\"),\n String::from(\"0100101101\"),\n String::from(\"0100100\"),\n String::from(\"101\"),\n String::from(\"11\"),\n String::from(\"00\"),\n String::from(\"1\"),\n ];\n for string in strings {\n match rep_string(&string) {\n Some(rep_string) => println!(\n \"Longuest rep-string for '{}' is '{}' ({} chars)\",\n string,\n rep_string,\n rep_string.len(),\n ),\n None => println!(\"No rep-string found for '{}'\", string),\n };\n }\n}\n\nfn rep_string(string: &str) -> Option<&str> {\n let index = string.len() \/ 2;\n\n for split_index in (1..=index).rev() {\n let mut is_rep_string = true;\n let (first, last) = string.split_at(split_index);\n\n let inter = last.chars().collect::>();\n let mut iter = inter.chunks_exact(split_index);\n for chunk in iter.by_ref() {\n if first != chunk.iter().collect::() {\n is_rep_string = false;\n break;\n }\n }\n let rmnd = iter.remainder().iter().collect::();\n\n \n if !first.starts_with(rmnd.as_str()) {\n is_rep_string = false;\n }\n\n if is_rep_string {\n return Some(first);\n }\n }\n None\n}\n\n#[cfg(test)]\nmod tests {\n use super::rep_string;\n use std::collections::HashMap;\n\n #[test]\n fn test_rep_string() {\n let mut results = HashMap::new();\n results.insert(String::from(\"1001110011\"), Some(\"10011\"));\n results.insert(String::from(\"1110111011\"), Some(\"1110\"));\n results.insert(String::from(\"0010010010\"), Some(\"001\"));\n results.insert(String::from(\"1010101010\"), Some(\"1010\"));\n results.insert(String::from(\"1111111111\"), Some(\"11111\"));\n results.insert(String::from(\"0100101101\"), None);\n results.insert(String::from(\"0100100\"), Some(\"010\"));\n results.insert(String::from(\"101\"), None);\n results.insert(String::from(\"11\"), Some(\"1\"));\n results.insert(String::from(\"00\"), Some(\"0\"));\n results.insert(String::from(\"1\"), None);\n\n for (input, expected) in results {\n assert_eq!(expected, rep_string(&input));\n }\n }\n}\n"} {"name":"Return multiple values","C":"#include\n\ntypedef struct{\n\tint integer;\n\tfloat decimal;\n\tchar letter;\n\tchar string[100];\n\tdouble bigDecimal;\n}Composite;\n\nComposite example()\n{\n\tComposite C = {1, 2.3, 'a', \"Hello World\", 45.678};\n\treturn C;\n}\n\n\nint main()\n{\n\tComposite C = example();\n\n\tprintf(\"Values from a function returning a structure\u00a0: { %d, %f, %c, %s, %f}\\n\", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);\n\n\treturn 0;\n}\n","Rust":"fn multi_hello() -> (&'static str, i32) {\n (\"Hello\",42)\n}\n\nfn main() {\n let (str,num)=multi_hello();\n println!(\"{},{}\",str,num);\n}\n"} {"name":"Rock-paper-scissors","C":"#include \n#include \n#define LEN 3 \n\n\nint rand_idx(double *p, int n)\n{\n\tdouble s = rand() \/ (RAND_MAX + 1.0);\n\tint i;\n\tfor (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);\n\treturn i;\n}\n\nint main()\n{\n\tint user_action, my_action;\n\tint user_rec[] = {0, 0, 0};\n\tconst char *names[] = { \"Rock\", \"Paper\", \"Scissors\" };\n\tchar str[2];\n\tconst char *winner[] = { \"We tied.\", \"Meself winned.\", \"You win.\" };\n\tdouble p[LEN] = { 1.\/3, 1.\/3, 1.\/3 };\n \n\twhile (1) {\n\t\tmy_action = rand_idx(p,LEN);\n \n\t\tprintf(\"\\nYour choice [1-3]:\\n\"\n\t\t\t\" 1. Rock\\n 2. Paper\\n 3. Scissors\\n> \");\n \n\t\t\n\t\tif (!scanf(\"%d\", &user_action)) {\n\t\t\tscanf(\"%1s\", str);\n\t\t\tif (*str == 'q') {\n\t\t\t\tprintf(\"Your choices [rock\u00a0: %d , paper\u00a0: %d , scissors %d] \",user_rec[0],user_rec[1], user_rec[2]); \n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tuser_action --;\n\t\tif (user_action > 2 || user_action < 0) {\n\t\t\tprintf(\"invalid choice; again\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tprintf(\"You chose %s; I chose %s. %s\\n\",\n\t\t\tnames[user_action], names[my_action],\n\t\t\twinner[(my_action - user_action + 3) % 3]);\n \n\t\tuser_rec[user_action]++;\n\t}\n}\n","Rust":"extern crate rand;\n#[macro_use]\nextern crate rand_derive;\n\nuse std::io;\nuse rand::Rng;\nuse Choice::*;\n\n#[derive(PartialEq, Clone, Copy, Rand, Debug)]\nenum Choice {\n Rock,\n Paper,\n Scissors,\n}\n\nfn beats(c1: Choice, c2: Choice) -> bool {\n (c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) || (c1 == Paper && c2 == Rock)\n}\n\nfn ai_move(rng: &mut R, v: [usize; 3]) -> Choice {\n \n let rand = rng.gen_range(0, v[0] + v[1] + v[2]);\n if rand < v[0] {\n Paper\n } else if rand < v[0] + v[1] {\n Scissors\n } else {\n Rock\n }\n}\n\nfn main() {\n let mut rng = rand::thread_rng();\n\n println!(\"Rock, paper, scissors!\");\n let mut ai_choice: Choice = rng.gen();\n let mut ucf = [0, 0, 0]; \n let mut score = [0, 0];\n\n loop {\n println!(\"Please input your move: 'r', 'p' or 's'. Type 'q' to quit\");\n\n let mut input = String::new();\n io::stdin()\n .read_line(&mut input)\n .expect(\"failed to read line\");\n let u_choice = match input.to_lowercase().trim() {\n s if s.starts_with('r') => {\n ucf[0] += 1;\n Rock\n }\n s if s.starts_with('p') => {\n ucf[1] += 1;\n Paper\n }\n s if s.starts_with('s') => {\n ucf[2] += 1;\n Scissors\n }\n s if s.starts_with('q') => break,\n _ => {\n println!(\"Please enter a correct choice!\");\n continue;\n }\n };\n println!(\"You chose {:?}, I chose {:?}.\", u_choice, ai_choice);\n if beats(u_choice, ai_choice) {\n score[0] += 1;\n println!(\"You win!\");\n } else if u_choice == ai_choice {\n println!(\"It's a tie!\");\n } else {\n score[1] += 1;\n println!(\"I win!\");\n }\n println!(\"-Score: You {}, Me {}\", score[0], score[1]);\n\n \n \n ai_choice = ai_move(&mut rng, ucf);\n }\n println!(\"Thank you for the game!\");\n}\n"} {"name":"Sierpinski arrowhead curve","C":"\n#include \n#include \n#include \n\n\ntypedef struct cursor_tag {\n double x;\n double y;\n int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n double theta = (M_PI * cursor->angle)\/180.0;\n cursor->x += length * cos(theta);\n cursor->y += length * sin(theta);\n fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n if (order == 0) {\n draw_line(out, cursor, length);\n } else {\n curve(out, order - 1, length\/2, cursor, -angle);\n turn(cursor, angle);\n curve(out, order - 1, length\/2, cursor, angle);\n turn(cursor, angle);\n curve(out, order - 1, length\/2, cursor, -angle);\n }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n const double margin = 20.0;\n const double side = size - 2.0 * margin;\n cursor_t cursor;\n cursor.angle = 0;\n cursor.x = margin;\n cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n if ((order & 1) != 0)\n turn(&cursor, -60);\n fprintf(out, \"\\n\");\n fprintf(out, \"\\n<\/svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n const char* filename = \"sierpinski_arrowhead.svg\";\n if (argc == 2)\n filename = argv[1];\n FILE* out = fopen(filename, \"w\");\n if (!out) {\n perror(filename);\n return EXIT_FAILURE;\n }\n write_sierpinski_arrowhead(out, 600, 8);\n fclose(out);\n return EXIT_SUCCESS;\n}\n","Rust":"\n\n\nconst SQRT3_2: f64 = 0.86602540378444;\n\nuse svg::node::element::path::Data;\n\nstruct Cursor {\n x: f64,\n y: f64,\n angle: i32,\n}\n\nimpl Cursor {\n fn new(x: f64, y: f64) -> Cursor {\n Cursor {\n x: x,\n y: y,\n angle: 0,\n }\n }\n fn turn(&mut self, angle: i32) {\n self.angle = (self.angle + angle) % 360;\n }\n fn draw_line(&mut self, data: Data, length: f64) -> Data {\n let theta = (self.angle as f64).to_radians();\n self.x += length * theta.cos();\n self.y += length * theta.sin();\n data.line_to((self.x, self.y))\n }\n}\n\nfn curve(mut data: Data, order: usize, length: f64, cursor: &mut Cursor, angle: i32) -> Data {\n if order == 0 {\n return cursor.draw_line(data, length);\n }\n data = curve(data, order - 1, length \/ 2.0, cursor, -angle);\n cursor.turn(angle);\n data = curve(data, order - 1, length \/ 2.0, cursor, angle);\n cursor.turn(angle);\n curve(data, order - 1, length \/ 2.0, cursor, -angle)\n}\n\nfn write_sierpinski_arrowhead(file: &str, size: usize, order: usize) -> std::io::Result<()> {\n use svg::node::element::Path;\n use svg::node::element::Rectangle;\n\n let margin = 20.0;\n let side = (size as f64) - 2.0 * margin;\n let y = 0.5 * (size as f64) + 0.5 * SQRT3_2 * side;\n let x = margin;\n let mut cursor = Cursor::new(x, y);\n if (order & 1) != 0 {\n cursor.turn(-60);\n }\n let mut data = Data::new().move_to((x, y));\n data = curve(data, order, side, &mut cursor, 60);\n let rect = Rectangle::new()\n .set(\"width\", \"100%\")\n .set(\"height\", \"100%\")\n .set(\"fill\", \"white\");\n let mut document = svg::Document::new()\n .set(\"width\", size)\n .set(\"height\", size)\n .add(rect);\n let path = Path::new()\n .set(\"fill\", \"none\")\n .set(\"stroke\", \"black\")\n .set(\"stroke-width\", \"1\")\n .set(\"d\", data);\n document = document.add(path);\n svg::save(file, &document)\n}\n\nfn main() {\n write_sierpinski_arrowhead(\"sierpinski_arrowhead.svg\", 600, 8).unwrap();\n}\n"} {"name":"Snake","C":"\n\n\n\n\n\n\n\n\nchar nonblocking_getch();\nvoid positional_putch(int x, int y, char ch);\nvoid millisecond_sleep(int n);\nvoid init_screen();\nvoid update_screen();\nvoid close_screen();\n\n\n\n#ifdef __linux__\n#define _POSIX_C_SOURCE 200809L\n#include \n#include \nchar nonblocking_getch() { return getch(); }\nvoid positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }\nvoid millisecond_sleep(int n) { \n\tstruct timespec t = { 0, n * 1000000 };\n\tnanosleep(&t, 0);\n\t\n}\nvoid update_screen() { refresh(); }\nvoid init_screen() {\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\tnodelay(stdscr, TRUE);\n}\nvoid close_screen() { endwin(); }\n#endif\n\n\n#ifdef _WIN32\n#error \"not implemented\"\n#endif\n\n\n#include \n#include \n\n#define w 80\n#define h 40\n\nint board[w * h];\nint head;\nenum Dir { N, E, S, W } dir;\nint quit;\n\nenum State { SPACE=0, FOOD=1, BORDER=2 };\n\n\n\nvoid age() {\n int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tif(board[i] < 0)\n\t\t\t++board[i];\n}\n\n\nvoid plant() {\n\tint r;\n\tdo\n\t\tr = rand() % (w * h);\n\twhile(board[r] != SPACE);\n\tboard[r] = FOOD;\n}\n\n\nvoid start(void) {\n int i;\n\tfor(i = 0; i < w; ++i)\n\t\tboard[i] = board[i + (h - 1) * w] = BORDER;\n\tfor(i = 0; i < h; ++i)\n\t\tboard[i * w] = board[i * w + w - 1] = BORDER;\n\thead = w * (h - 1 - h % 2) \/ 2; \n\tboard[head] = -5;\n\tdir = N;\n\tquit = 0;\n\tsrand(time(0));\n\tplant();\n}\n\nvoid step() {\n\tint len = board[head];\n\tswitch(dir) {\n\t\tcase N: head -= w; break;\n\t\tcase S: head += w; break;\n\t\tcase W: --head; break;\n\t\tcase E: ++head; break;\n\t}\n\tswitch(board[head]) {\n\t\tcase SPACE:\n\t\t\tboard[head] = len - 1; \n\t\t\tage();\n\t\t\tbreak;\n\t\tcase FOOD:\n\t\t\tboard[head] = len - 1;\n\t\t\tplant();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tquit = 1;\n\t}\n}\n\nvoid show() {\n\tconst char * symbol = \" @.\";\n int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tpositional_putch(i \/ w, i % w,\n\t\t\tboard[i] < 0 ? '#' : symbol[board[i]]);\n\tupdate_screen();\n}\n\nint main (int argc, char * argv[]) {\n\tinit_screen();\n\tstart();\n\tdo {\n\t\tshow();\n\t\tswitch(nonblocking_getch()) {\n\t\t\tcase 'i': dir = N; break;\n\t\t\tcase 'j': dir = W; break;\n\t\t\tcase 'k': dir = S; break;\n\t\t\tcase 'l': dir = E; break;\n\t\t\tcase 'q': quit = 1; break;\n\t\t}\n\t\tstep();\n\t\tmillisecond_sleep(100); \n\t\t\n\t}\n\twhile(!quit);\n\tmillisecond_sleep(999);\n\tclose_screen();\n\treturn 0;\n}\n","Rust":"\n\n#![windows_subsystem = \"windows\"]\n\nuse rand::Rng;\nuse std::{cell::RefCell, rc::Rc};\nuse winsafe::{co, gui, prelude::*, COLORREF, HBRUSH, HPEN, SIZE};\n\nconst STEP: i32 = 3; \nconst FPS: u32 = 90;\nconst CELL: i32 = 21; \nconst FIELD_W: i32 = 20; \nconst SNAKE_W: i32 = 20; \nconst ROUNDING: SIZE = SIZE::new(SNAKE_W \/ 2, SNAKE_W \/ 2);\n\nconst RATIO: i32 = CELL \/ STEP;\nconst START_CELL: i32 = FIELD_W \/ 2 * RATIO;\n\nconst TW: i32 = (FIELD_W + 2) * RATIO;\n#[derive(Clone, Copy)]\n#[repr(i32)]\nenum Direction {\n Start = 0,\n A = -1,\n D = 1,\n W = -TW,\n S = TW,\n}\nuse Direction::*;\n\nstruct Context {\n wnd: gui::WindowMain,\n snake: Vec, \n id_r: [i32; 6], \n gap: i32, \n dir: Direction,\n ordered_dir: Direction,\n}\nimpl Context {\n fn new(wnd: gui::WindowMain, len: usize) -> Self {\n Self {\n wnd,\n snake: vec![START_CELL; len.saturating_sub(RATIO as usize)],\n id_r: [START_CELL; 6],\n gap: 0,\n dir: Start,\n ordered_dir: S,\n }\n }\n}\n\npub fn main() {\n let [bg, tail, turn, body, food, head] = [0usize, 1, 2, 3, 4, 5];\n let mut colors = [(0x00, 0xF0, 0xA0); 6]; \n colors[bg] = (0x00, 0x50, 0x90);\n colors[food] = (0xFF, 0x50, 0x00);\n colors[head] = (0xFF, 0xFF, 0x00);\n let brushes = COLORREF::new_array(&colors).map(|c| HBRUSH::CreateSolidBrush(c).unwrap());\n\n let wnd = gui::WindowMain::new(gui::WindowMainOpts {\n title: \"Snake - Start: Space, then press W-A-S-D\".to_string(),\n size: winsafe::SIZE::new(FIELD_W * RATIO * STEP, FIELD_W * RATIO * STEP),\n ex_style: co::WS_EX::CLIENTEDGE,\n class_bg_brush: brushes[bg],\n ..Default::default()\n });\n\n let context = Rc::new(RefCell::new(Context::new(wnd.clone(), 0)));\n\n wnd.on().wm_key_down({\n let context = Rc::clone(&context);\n move |k| {\n let mut ctx = context.borrow_mut();\n match (ctx.dir, k.char_code as u8) {\n (Start, bt @ (b' ' | 113)) => {\n let len = ctx.snake.len(); \n *ctx = Context::new(ctx.wnd.clone(), if bt == b' ' { len } else { 0 });\n ctx.wnd.hwnd().InvalidateRect(None, true)?; \n ctx.wnd.hwnd().SetTimer(1, 1000 \/ FPS, None)?;\n }\n (W | S, bt @ (b'A' | b'D')) => ctx.ordered_dir = if bt == b'A' { A } else { D },\n (A | D, bt @ (b'S' | b'W')) => ctx.ordered_dir = if bt == b'S' { S } else { W },\n _ => (),\n }\n Ok(())\n }\n });\n\n wnd.on().wm_timer(1, {\n let context = Rc::clone(&context);\n let cells: Vec = (1..=FIELD_W)\n .flat_map(|y| (1..=FIELD_W).map(move |x| (y * TW + x) * RATIO))\n .collect();\n move || {\n let mut ctx = context.borrow_mut();\n let new_h = ctx.id_r[head] + ctx.dir as i32;\n ctx.id_r[body] = ctx.id_r[head];\n ctx.id_r[head] = new_h;\n if ctx.gap < 0 {\n ctx.id_r[bg] = ctx.snake.remove(0);\n ctx.id_r[tail] = ctx.snake[0];\n ctx.id_r[turn] = ctx.snake[RATIO as usize \/ 2];\n }\n ctx.gap -= ctx.gap.signum();\n if ctx.gap == 0 {\n let hw = ctx.wnd.hwnd();\n let eat = new_h == ctx.id_r[food];\n let mut snk_cells: Vec<_> = ctx.snake.iter().step_by(RATIO as usize).collect();\n if !eat && (cells.binary_search(&new_h).is_err() || snk_cells.contains(&&new_h)) {\n hw.KillTimer(1)?;\n hw.SetWindowText(&(hw.GetWindowText()? + \" Restart: F2 (with save - Space)\"))?;\n ctx.dir = Start;\n return Ok(());\n } else if eat || ctx.id_r[food] == START_CELL && ctx.id_r[tail] != START_CELL {\n if eat {\n hw.SetWindowText(&format!(\"Snake - Eaten: {}.\", snk_cells.len()))?;\n }\n if eat && snk_cells.len() == cells.len() - 2 {\n hw.SetWindowText(&(hw.GetWindowText()? + \" ALL\u00a0!!!\"))?;\n ctx.id_r[food] = 0; \n } else if new_h != START_CELL {\n snk_cells.sort();\n ctx.id_r[food] = *(cells.iter())\n .filter(|i| **i != new_h && snk_cells.binary_search(i).is_err())\n .nth(rand::thread_rng().gen_range(0..cells.len() - snk_cells.len() - 1))\n .unwrap();\n }\n }\n ctx.dir = ctx.ordered_dir;\n ctx.gap = if eat { RATIO } else { -RATIO }\n }\n ctx.snake.push(new_h);\n ctx.wnd.hwnd().InvalidateRect(None, false)?; \n Ok(())\n }\n });\n\n wnd.on().wm_paint(move || {\n let ctx = context.borrow();\n let mut ps = winsafe::PAINTSTRUCT::default();\n let hdc = ctx.wnd.hwnd().BeginPaint(&mut ps)?;\n hdc.SelectObjectPen(HPEN::CreatePen(co::PS::NULL, 0, COLORREF::new(0, 0, 0))?)?;\n for (&id_rect, &brush) in ctx.id_r.iter().zip(&brushes) {\n hdc.SelectObjectBrush(brush)?;\n let left = id_rect % TW * STEP - (STEP * RATIO + SNAKE_W) \/ 2;\n let top = id_rect \/ TW * STEP - (STEP * RATIO + SNAKE_W) \/ 2;\n hdc.RoundRect(\n winsafe::RECT {\n left,\n top,\n right: left + SNAKE_W,\n bottom: top + SNAKE_W,\n },\n ROUNDING,\n )?;\n }\n ctx.wnd.hwnd().EndPaint(&ps);\n Ok(())\n });\n\n if let Err(e) = wnd.run_main(None) {\n winsafe::HWND::NULL\n .MessageBox(&e.to_string(), \"Uncaught error\", co::MB::ICONERROR)\n .unwrap();\n }\n}\n"} {"name":"Sorting algorithms_Pancake sort","C":"int pancake_sort(int *list, unsigned int length)\n{\n \n if(length<2)\n return 0;\n\n int i,a,max_num_pos,moves;\n moves=0;\n\n for(i=length;i>1;i--)\n {\n \n max_num_pos=0;\n for(a=0;alist[max_num_pos])\n max_num_pos=a;\n }\n\n if(max_num_pos==i-1)\n \n continue;\n\n\n \n if(max_num_pos)\n {\n moves++;\n do_flip(list, length, max_num_pos+1);\n }\n\n\n \n moves++;\n do_flip(list, length, i);\n\n \n\n }\n\n return moves;\n}\n","Rust":"fn pancake_sort(v: &mut [T]) {\n let len = v.len();\n \n if len < 2 {\n return;\n }\n for i in (0..len).rev() {\n \n let max_index = v.iter()\n .take(i + 1)\n .enumerate()\n .max_by_key(|&(_, elem)| elem)\n .map(|(idx, _)| idx)\n \n .unwrap();\n \n \n if max_index != i {\n flip(v, max_index);\n flip(v, i);\n }\n }\n}\n\n\nfn flip(v: &mut [E], num: usize) {\n v[0..num + 1].reverse();\n}\n\nfn main() {\n \n let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];\n println!(\"Before: {:?}\", numbers);\n pancake_sort(&mut numbers);\n println!(\"After: {:?}\", numbers);\n\n \n let mut strings = [\"beach\", \"hotel\", \"airplane\", \"car\", \"house\", \"art\"];\n println!(\"Before: {:?}\", strings);\n pancake_sort(&mut strings);\n println!(\"After: {:?}\", strings);\n}\n"} {"name":"Sorting algorithms_Shell sort","C":"#include \n\nvoid shell_sort (int *a, int n) {\n int h, i, j, t;\n for (h = n; h \/= 2;) {\n for (i = h; i < n; i++) {\n t = a[i];\n for (j = i; j >= h && t < a[j - h]; j -= h) {\n a[j] = a[j - h];\n }\n a[j] = t;\n }\n }\n}\n\nint main (int ac, char **av) {\n int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n int n = sizeof a \/ sizeof a[0];\n int i;\n for (i = 0; i < n; i++)\n printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n shell_sort(a, n);\n for (i = 0; i < n; i++)\n printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n return 0;\n}\n","Rust":"fn shell_sort(v: &mut [T]) {\n let mut gap = v.len() \/ 2;\n let len = v.len();\n while gap > 0 {\n for i in gap..len {\n let temp = v[i];\n let mut j = i;\n while j >= gap && v[j - gap] > temp {\n v[j] = v[j - gap];\n j -= gap;\n }\n v[j] = temp;\n }\n gap \/= 2;\n }\n}\n\nfn main() {\n let mut numbers = [4i32, 65, 2, -31, 0, 99, 2, 83, 782, 1];\n println!(\"Before: {:?}\", numbers);\n shell_sort(&mut numbers);\n println!(\"After: {:?}\", numbers);\n}\n"} {"name":"Sorting algorithms_Stooge sort","C":"#include \n\n#define SWAP(r,s) do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n int t;\n \n if (a[j] < a[i]) SWAP(a[i], a[j]);\n if (j - i > 1)\n {\n t = (j - i + 1) \/ 3;\n StoogeSort(a, i, j - t);\n StoogeSort(a, i + t, j);\n StoogeSort(a, i, j - t);\n }\n}\n \nint main(int argc, char *argv[])\n{\n int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n int i, n;\n \n n = sizeof(nums)\/sizeof(int);\n StoogeSort(nums, 0, n-1);\n \n for(i = 0; i <= n-1; i++)\n printf(\"%5d\", nums[i]);\n \n return 0;\n}\n","Rust":"fn stoogesort(a: &mut [E])\n where E: PartialOrd\n{\n let len = a.len();\n\n if a.first().unwrap() > a.last().unwrap() {\n a.swap(0, len - 1);\n }\n if len - 1 > 1 {\n let t = len \/ 3;\n stoogesort(&mut a[..len - 1]);\n stoogesort(&mut a[t..]);\n stoogesort(&mut a[..len - 1]);\n }\n}\n\nfn main() {\n let mut numbers = vec![1_i32, 9, 4, 7, 6, 5, 3, 2, 8];\n println!(\"Before: {:?}\", &numbers);\n stoogesort(&mut numbers);\n println!(\"After: {:?}\", &numbers);\n}\n"} {"name":"String comparison","C":"\nif (strcmp(a,b)) action_on_equality();\n","Rust":"use std::ascii::AsciiExt; \n\nfn main() {\n \n \n \n let a: &str = \"abc\";\n let b: String = \"Bac\".to_owned();\n\n \n if a == b { println!(\"The strings are equal\") }\n if a != b { println!(\"The strings are not equal\") }\n if a > &b { println!(\"The first string is lexically after the second\") }\n if a < &b { println!(\"The first string is lexically before the second\") }\n if a >= &b { println!(\"The first string is not lexically before the second\") }\n if a <= &b { println!(\"The first string is not lexically after the second\") }\n\n \n\n \n \n if a.eq_ignore_ascii_case(&b) { println!(\"Both strings are equal when ignoring case\") }\n\n \n let a2 = a.to_ascii_uppercase();\n let b2 = b.to_ascii_uppercase();\n\n \n}\n"} {"name":"Substring_Top and tail","C":"#include \n#include \n#include \n\nint main( int argc, char ** argv ){\n const char * str_a = \"knight\";\n const char * str_b = \"socks\";\n const char * str_c = \"brooms\";\n\n char * new_a = malloc( strlen( str_a ) - 1 );\n char * new_b = malloc( strlen( str_b ) - 1 );\n char * new_c = malloc( strlen( str_c ) - 2 );\n\n strcpy( new_a, str_a + 1 );\n strncpy( new_b, str_b, strlen( str_b ) - 1 );\n strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n free( new_a );\n free( new_b );\n free( new_c );\n\n return 0;\n}\n","Rust":"fn main() {\n let s = String::from(\"\u017elu\u0165ou\u010dk\u00fd k\u016f\u0148\");\n\n let mut modified = s.clone();\n modified.remove(0);\n println!(\"{}\", modified);\n\n let mut modified = s.clone();\n modified.pop();\n println!(\"{}\", modified);\n\n let mut modified = s;\n modified.remove(0);\n modified.pop();\n println!(\"{}\", modified);\n}\n"} {"name":"Sum data type","C":"#include\n\ntypedef union data{\n int i;\n float f;\n char c;\n}united;\n\nint main()\n{\n united udat;\n\n udat.i = 5;\n udat.f = 3.14159;\n udat.c = 'C';\n\n printf(\"Integer i = %d , address of i = %p\\n\",udat.i,&udat.i);\n printf(\"Float f = %f , address of f = %p\\n\",udat.f,&udat.f);\n printf(\"Character c = %c , address of c = %p\\n\",udat.c,&udat.c);\n\n return 0;\n}\n","Rust":"enum IpAddr {\n V4(u8, u8, u8, u8),\n V6(String),\n}\n\nlet home = IpAddr::V4(127, 0, 0, 1);\n\nlet loopback = IpAddr::V6(String::from(\"::1\"));\n"} {"name":"Sum of first n cubes","C":"#include \n\nint main() {\n for (int i = 0, sum = 0; i < 50; ++i) {\n sum += i * i * i;\n printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n }\n return 0;\n}\n","Rust":"fn main() {\n (0..50)\n .scan(0, |sum, x| {\n *sum += x * x * x;\n Some(*sum)\n })\n .enumerate()\n .for_each(|(i, n)| {\n print!(\"{:7}\", n);\n if (i + 1) % 5 == 0 {\n println!();\n } else {\n print!(\" \");\n }\n });\n}\n"} {"name":"Sutherland-Hodgman polygon clipping","C":"#include \n#include \n#include \n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) \/ dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)\/sizeof(vec_t))\n#define slen (sizeof(s)\/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"\/l {lineto} def \/m{moveto} def \/s{setrgbcolor} def\"\n\t\t\"\/c {closepath} def \/gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n","Rust":"#[derive(Debug, Clone)]\nstruct Point {\n x: f64,\n y: f64,\n}\n\n#[derive(Debug, Clone)]\nstruct Polygon(Vec);\n\nfn is_inside(p: &Point, cp1: &Point, cp2: &Point) -> bool {\n (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)\n}\n\nfn compute_intersection(cp1: &Point, cp2: &Point, s: &Point, e: &Point) -> Point {\n let dc = Point {\n x: cp1.x - cp2.x,\n y: cp1.y - cp2.y,\n };\n let dp = Point {\n x: s.x - e.x,\n y: s.y - e.y,\n };\n let n1 = cp1.x * cp2.y - cp1.y * cp2.x;\n let n2 = s.x * e.y - s.y * e.x;\n let n3 = 1.0 \/ (dc.x * dp.y - dc.y * dp.x);\n Point {\n x: (n1 * dp.x - n2 * dc.x) * n3,\n y: (n1 * dp.y - n2 * dc.y) * n3,\n }\n}\n\nfn sutherland_hodgman_clip(subject_polygon: &Polygon, clip_polygon: &Polygon) -> Polygon {\n let mut result_ring = subject_polygon.0.clone();\n let mut cp1 = clip_polygon.0.last().unwrap();\n for cp2 in &clip_polygon.0 {\n let input = result_ring;\n let mut s = input.last().unwrap();\n result_ring = vec![];\n for e in &input {\n if is_inside(e, cp1, cp2) {\n if !is_inside(s, cp1, cp2) {\n result_ring.push(compute_intersection(cp1, cp2, s, e));\n }\n result_ring.push(e.clone());\n } else if is_inside(s, cp1, cp2) {\n result_ring.push(compute_intersection(cp1, cp2, s, e));\n }\n s = e;\n }\n cp1 = cp2;\n }\n Polygon(result_ring)\n}\n\nfn main() {\n let _p = |x: f64, y: f64| Point { x, y };\n let subject_polygon = Polygon(vec![\n _p(50.0, 150.0), _p(200.0, 50.0), _p(350.0, 150.0), _p(350.0, 300.0), _p(250.0, 300.0),\n _p(200.0, 250.0), _p(150.0, 350.0), _p(100.0, 250.0), _p(100.0, 200.0),\n ]);\n let clip_polygon = Polygon(vec![\n _p(100.0, 100.0),_p(300.0, 100.0),_p(300.0, 300.0),_p(100.0, 300.0),\n ]);\n let result = sutherland_hodgman_clip(&subject_polygon, &clip_polygon);\n println!(\"{:?}\", result);\n}\n"} {"name":"Text between","C":"\nchar* textBetween(char* thisText, char* startText, char* endText, char* returnText)\n{\n\t\n\n char* startPointer = NULL;\n int stringLength = 0;\n\n char* endPointer = NULL;\n int endLength = 0;\n\n\tif (strstr(startText, \"start\") != NULL)\n\t{\n\t\t\n\t\tstartPointer = thisText;\n\t} else {\n\t\tstartPointer = strstr(thisText, startText);\n\n \tif (startPointer != NULL)\n\t {\n \tstartPointer = startPointer + strlen(startText);\n }\n\t} \n \n if (startPointer != NULL)\n {\n\n\t\tif (strstr(endText, \"end\") != NULL)\n\t\t{\n\t\t\t\n\t\t\tendPointer = thisText;\n\t\t\tendLength = 0;\n\t\t} else {\n\t\t\tendPointer = strstr(startPointer, endText);\n\t\t\tendLength = (int)strlen(endPointer);\n\t\t} \n\n stringLength = strlen(startPointer) - endLength;\n \n if (stringLength == 0)\n {\n\t\t returnText = \"\";\n\t\t startPointer = NULL;\n } else {\n\t \n \t strncpy(returnText,startPointer, stringLength);\n\t returnText[stringLength++] = '\\0';\n\t\t}\n \n } else {\n\t \n\t returnText = \"\";\n\t \n } \n \n return startPointer;\n} \n","Rust":"\nfn text_between>(input: S, start: S, end: S) -> String {\n \n let search_str = input.into();\n let start_str = start.into();\n let end_str = end.into();\n\n let start_idx = if start_str.as_str() == \"start\" {\n 0\n } else {\n let start_point = search_str.find(start_str.as_str());\n if start_point.is_none() {\n return String::from(\"\");\n }\n start_point.unwrap() + start_str.len()\n };\n let remaining = &search_str[start_idx..];\n\n let end_idx = if end_str.as_str() == \"end\" {\n remaining.len()\n } else {\n remaining.find(end_str.as_str()).unwrap_or(remaining.len())\n };\n\n return remaining[..end_idx].to_string()\n}\n\nfn main() {\n println!(\"'{}'\", text_between(\"Hello Rosetta Code world\", \"Hello \", \" world\"));\n println!(\"'{}'\", text_between(\"Hello Rosetta Code world\", \"start\", \" world\"));\n println!(\"'{}'\", text_between(\"Hello Rosetta Code world\", \"Hello\", \"end\"));\n println!(\"'{}'\", text_between(\"<\/div>
\u4f60\u597d\u55ce<\/div>\", \"
\", \"<\/div>\"));\n println!(\"'{}'\", text_between(\"Hello Rosetta Code<\/span> world<\/text>\", \"\", \"
\"));\n println!(\"'{}'\", text_between(\"
hello world<\/td><\/tr><\/table>\", \"\", \"<\/table>\"));\n println!(\"'{}'\", text_between(\"The quick brown fox jumps over the lazy other fox\", \"quick \", \" fox\"));\n println!(\"'{}'\", text_between(\"One fish two fish red fish blue fish\", \"fish \", \" red\"));\n println!(\"'{}'\", text_between(\"FooBarBazFooBuxQuux\", \"Foo\", \"Foo\"));\n}\n"} {"name":"Thiele's interpolation formula","C":"#include \n#include \n#include \n\n#define N 32\n#define N2 (N * (N - 1) \/ 2)\n#define STEP .05\n\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\n\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\n\n\n\ndouble rho(double *x, double *y, double *r, int i, int n)\n{\n\tif (n < 0) return 0;\n\tif (!n) return y[i];\n\n\tint idx = (N - 1 - n) * (N - n) \/ 2 + i;\n\tif (r[idx] != r[idx]) \n\t\tr[idx] = (x[i] - x[i + n])\n\t\t\t\/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n\t\t\t+ rho(x, y, r, i + 1, n - 2);\n\treturn r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, int n)\n{\n\tif (n > N - 1) return 1;\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n\t\t+ (xin - x[n]) \/ thiele(x, y, r, xin, n + 1);\n}\n\n#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)\n#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)\n#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\txval[i] = i * STEP;\n\t\tt_sin[i] = sin(xval[i]);\n\t\tt_cos[i] = cos(xval[i]);\n\t\tt_tan[i] = t_sin[i] \/ t_cos[i];\n\t}\n\tfor (i = 0; i < N2; i++)\n\t\t\n\t\tr_sin[i] = r_cos[i] = r_tan[i] = 0\/0.;\n\n\tprintf(\"%16.14f\\n\", 6 * i_sin(.5));\n\tprintf(\"%16.14f\\n\", 3 * i_cos(.5));\n\tprintf(\"%16.14f\\n\", 4 * i_tan(1.));\n\treturn 0;\n}\n","Rust":"const N: usize = 32;\nconst STEP: f64 = 0.05;\n\nfn main() {\n let x: Vec = (0..N).map(|i| i as f64 * STEP).collect();\n let sin = x.iter().map(|x| x.sin()).collect::>();\n let cos = x.iter().map(|x| x.cos()).collect::>();\n let tan = x.iter().map(|x| x.tan()).collect::>();\n\n println!(\n \"{}\\n{}\\n{}\",\n 6. * thiele(&sin, &x, 0.5),\n 3. * thiele(&cos, &x, 0.5),\n 4. * thiele(&tan, &x, 1.)\n );\n}\n\nfn thiele(x: &[f64], y: &[f64], xin: f64) -> f64 {\n let mut p: Vec> = (0..N).map(|i| (i..N).map(|_| 0.0).collect()).collect();\n\n (0..N).for_each(|i| p[i][0] = y[i]);\n\n (0..N - 1).for_each(|i| p[i][1] = (x[i] - x[i + 1]) \/ (p[i][0] - p[i + 1][0]));\n\n (2..N).for_each(|i| {\n (0..N - i).for_each(|j| {\n p[j][i] = (x[j] - x[j + i]) \/ (p[j][i - 1] - p[j + 1][i - 1]) + p[j + 1][i - 2];\n })\n });\n\n let mut a = 0.;\n (2..N).rev().for_each(|i| {\n a = (xin - x[i - 1]) \/ (p[0][i] - p[0][i - 2] + a);\n });\n y[0] + (xin - x[0]) \/ (p[0][1] + a)\n}\n"} {"name":"Trabb Pardo\u2013Knuth algorithm","C":"#include\n#include\n\nint\nmain ()\n{\n double inputs[11], check = 400, result;\n int i;\n\n printf (\"\\nPlease enter 11 numbers\u00a0:\");\n\n for (i = 0; i < 11; i++)\n {\n scanf (\"%lf\", &inputs[i]);\n }\n\n printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs\u00a0:\");\n\n for (i = 10; i >= 0; i--)\n {\n result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n printf (\"\\nf(%lf) = \");\n\n if (result > check)\n {\n printf (\"Overflow!\");\n }\n\n else\n {\n printf (\"%lf\", result);\n }\n }\n\n return 0;\n}\n","Rust":"use std::io::{self, BufRead};\n\nfn op(x: f32) -> Option {\n let y = x.abs().sqrt() + 5.0 * x * x * x;\n if y < 400.0 {\n Some(y)\n } else {\n None\n }\n}\n\nfn main() {\n println!(\"Please enter 11 numbers (one number per line)\");\n let stdin = io::stdin();\n\n let xs = stdin\n .lock()\n .lines()\n .map(|ox| ox.unwrap().trim().to_string())\n .flat_map(|s| str::parse::(&s))\n .take(11)\n .collect::>();\n\n for x in xs.into_iter().rev() {\n match op(x) {\n Some(y) => println!(\"{}\", y),\n None => println!(\"overflow\"),\n };\n }\n}\n"} {"name":"Truncate a file","C":"#include \n#include \n#include \n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n","Rust":"use std::path::Path;\nuse std::fs;\n\nfn truncate_file>(filename: P, filesize: usize) -> Result<(), Error> {\n use Error::*;\n let file = fs::read(&filename).or(Err(NotFound))?;\n\n if filesize > file.len() {\n return Err(FilesizeTooSmall)\n }\n\n fs::write(&filename, &file[..filesize]).or(Err(UnableToWrite))?;\n Ok(())\n}\n\n#[derive(Debug)]\nenum Error {\n \n NotFound,\n \n FilesizeTooSmall,\n \n UnableToWrite,\n}\n"} {"name":"URL encoding","C":"#include \n#include \n \nchar rfc3986[256] = {0};\nchar html5[256] = {0};\n\n\nvoid encode(const char *s, char *enc, char *tb)\n{\n\tfor (; *s; s++) {\n\t\tif (tb[*s]) sprintf(enc, \"%c\", tb[*s]);\n\t\telse sprintf(enc, \"%%%02X\", *s);\n\t\twhile (*++enc);\n\t}\n}\n \nint main()\n{\n\tconst char url[] = \"http:\n\tchar enc[(strlen(url) * 3) + 1];\n \n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\trfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'\n\t\t\t? i : 0;\n\t\thtml5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'\n\t\t\t? i : (i == ' ') ? '+' : 0;\n\t}\n \n\tencode(url, enc, rfc3986);\n\tputs(enc);\n \n\treturn 0;\n}\n","Rust":"const INPUT: &str = \"http:\nconst MAX_CHAR_VAL: u32 = std::char::MAX as u32;\n \nfn main() {\n let mut buff = [0; 4];\n println!(\"{}\", INPUT.chars()\n .map(|ch| {\n match ch as u32 {\n 0 ..= 47 | 58 ..= 64 | 91 ..= 96 | 123 ..= MAX_CHAR_VAL => {\n ch.encode_utf8(&mut buff);\n buff[0..ch.len_utf8()].iter().map(|&byte| format!(\"%{:X}\", byte)).collect::()\n },\n _ => ch.to_string(),\n }\n })\n .collect::()\n );\n}\n"} {"name":"Ulam spiral (for primes)","C":"#include \n#include \n#include \n#include \n\ntypedef uint32_t bitsieve;\n\nunsigned sieve_check(bitsieve *b, const unsigned v)\n{\n if ((v != 2 && !(v & 1)) || (v < 2))\n return 0;\n else\n return !(b[v >> 6] & (1 << (v >> 1 & 31)));\n}\n\nbitsieve* sieve(const unsigned v)\n{\n unsigned i, j;\n bitsieve *b = calloc((v >> 6) + 1, sizeof(uint32_t));\n\n for (i = 3; i <= sqrt(v); i += 2)\n if (!(b[i >> 6] & (1 << (i >> 1 & 31))))\n for (j = i*i; j < v; j += (i << 1))\n b[j >> 6] |= (1 << (j >> 1 & 31));\n\n return b;\n}\n\n#define max(x,y) ((x) > (y)\u00a0? (x)\u00a0: (y))\n\n\nint ulam_get_map(int x, int y, int n)\n{\n x -= (n - 1) \/ 2;\n y -= n \/ 2;\n\n int mx = abs(x), my = abs(y);\n int l = 2 * max(mx, my);\n int d = y >= x ? l * 3 + x + y : l - x - y;\n\n return pow(l - 1, 2) + d;\n}\n\n\nvoid output_ulam_spiral(int n, const char glyph)\n{\n \n n -= n % 2 == 0 ? 1 : 0;\n\n const char *spaces = \".................\";\n int mwidth = log10(n * n) + 1;\n\n bitsieve *b = sieve(n * n + 1);\n int x, y;\n\n for (x = 0; x < n; ++x) {\n for (y = 0; y < n; ++y) {\n int z = ulam_get_map(y, x, n);\n\n if (glyph == 0) {\n if (sieve_check(b, z))\n printf(\"%*d \", mwidth, z);\n else\n printf(\"%.*s \", mwidth, spaces);\n }\n else {\n printf(\"%c\", sieve_check(b, z) ? glyph : spaces[0]);\n }\n }\n printf(\"\\n\");\n }\n\n free(b);\n}\n\nint main(int argc, char *argv[])\n{\n const int n = argc < 2 ? 9 : atoi(argv[1]);\n\n output_ulam_spiral(n, 0);\n printf(\"\\n\");\n\n output_ulam_spiral(n, '#');\n printf(\"\\n\");\n\n return 0;\n}\n","Rust":"use std::fmt;\n\nenum Direction { RIGHT, UP, LEFT, DOWN }\nuse ulam::Direction::*;\n\n\nfn is_prime(a: u32) -> bool {\n match a {\n 2 => true,\n x if x <= 1 || x % 2 == 0 => false,\n _ => {\n let max = f64::sqrt(a as f64) as u32;\n let mut x = 3;\n while x <= max {\n if a % x == 0 { return false; }\n x += 2;\n }\n true\n }\n }\n}\n\npub struct Ulam { u : Vec> }\n\nimpl Ulam {\n \n pub fn new(n: u32, s: u32, c: char) -> Ulam {\n let mut spiral = vec![vec![String::new(); n as usize]; n as usize];\n let mut dir = RIGHT;\n let mut y = (n \/ 2) as usize;\n let mut x = if n % 2 == 0 { y - 1 } else { y }; \n for j in s..n * n + s {\n spiral[y][x] = if is_prime(j) {\n if c == '\\0' { format!(\"{:4}\", j) } else { format!(\" {} \", c) }\n }\n else { String::from(\" ---\") };\n\n match dir {\n RIGHT => if x as u32 <= n - 1 && spiral[y - 1][x].is_empty() && j > s { dir = UP; },\n UP => if spiral[y][x - 1].is_empty() { dir = LEFT; },\n LEFT => if x == 0 || spiral[y + 1][x].is_empty() { dir = DOWN; },\n DOWN => if spiral[y][x + 1].is_empty() { dir = RIGHT; }\n };\n\n match dir { RIGHT => x += 1, UP => y -= 1, LEFT => x -= 1, DOWN => y += 1 };\n }\n Ulam { u: spiral }\n }\n}\n\nimpl fmt::Display for Ulam {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n for row in &self.u {\n writeln!(f, \"{}\", format!(\"{:?}\", row).replace(\"\\\"\", \"\").replace(\", \", \"\"));\n };\n writeln!(f, \"\")\n }\n}\n"} {"name":"Use another language to call a function","C":"#include \n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n char Buffer [1024];\n size_t Size = sizeof (Buffer);\n \n if (0 == Query (Buffer, &Size))\n {\n printf (\"failed to call Query\\n\");\n }\n else\n {\n char * Ptr = Buffer;\n while (Size-- > 0) putchar (*Ptr++);\n putchar ('\\n');\n }\n}\n","Rust":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#![crate_type = \"cdylib\"]\n\nextern crate libc;\n\nuse std::ffi::CString;\n\nuse libc::{c_char, c_int, size_t};\n\n#[no_mangle]\n#[allow(non_snake_case)]\n#[allow(clippy::missing_safety_doc)]\npub unsafe extern \"C\" fn Query(data: *mut c_char, length: *mut size_t) -> c_int {\n let string = \"Here am I\";\n if *length + 1 < string.len() {\n 0\n } else {\n let c_string = CString::new(string).unwrap();\n libc::strcpy(data, c_string.as_ptr());\n *length = string.len();\n 1\n }\n}\n"} {"name":"Validate International Securities Identification Number","C":"#include \n\nint check_isin(char *a) {\n int i, j, k, v, s[24];\n \n j = 0;\n for(i = 0; i < 12; i++) {\n k = a[i];\n if(k >= '0' && k <= '9') {\n if(i < 2) return 0;\n s[j++] = k - '0';\n } else if(k >= 'A' && k <= 'Z') {\n if(i == 11) return 0;\n k -= 'A' - 10;\n s[j++] = k \/ 10;\n s[j++] = k % 10;\n } else {\n return 0;\n }\n }\n \n if(a[i]) return 0;\n \n v = 0;\n for(i = j - 2; i >= 0; i -= 2) {\n k = 2 * s[i];\n v += k > 9 ? k - 9 : k;\n }\n \n for(i = j - 1; i >= 0; i -= 2) {\n v += s[i];\n }\n \n return v % 10 == 0;\n}\n\nint main() {\n char *test[7] = {\"US0378331005\", \"US0373831005\", \"U50378331005\",\n \"US03378331005\", \"AU0000XVGZA3\", \"AU0000VXGZA3\",\n \"FR0000988040\"};\n int i;\n for(i = 0; i < 7; i++) printf(\"%c%c\", check_isin(test[i]) ? 'T' : 'F', i == 6 ? '\\n' : ' ');\n return 0;\n}\n\n\n","Rust":"extern crate luhn_cc;\n\nuse luhn_cc::compute_luhn;\n\nfn main() {\n assert_eq!(validate_isin(\"US0378331005\"), true);\n assert_eq!(validate_isin(\"US0373831005\"), false);\n assert_eq!(validate_isin(\"U50378331005\"), false);\n assert_eq!(validate_isin(\"US03378331005\"), false);\n assert_eq!(validate_isin(\"AU0000XVGZA3\"), true);\n assert_eq!(validate_isin(\"AU0000VXGZA3\"), true);\n assert_eq!(validate_isin(\"FR0000988040\"), true);\n}\n\nfn validate_isin(isin: &str) -> bool {\n \n if !isin.chars().all(|x| x.is_alphanumeric()) || isin.len() != 12 {\n return false;\n }\n if !isin[..2].chars().all(|x| x.is_alphabetic())\n || !isin[2..12].chars().all(|x| x.is_alphanumeric())\n || !isin.chars().last().unwrap().is_numeric()\n {\n return false;\n }\n\n \n let bytes = isin.as_bytes();\n\n let s2 = bytes.iter()\n .flat_map(|&c| {\n if c.is_ascii_digit() {\n vec![c]\n }\n else {\n (c + 10 - ('A' as u8)).to_string().into_bytes()\n }\n }).collect::>();\n\n let string = std::str::from_utf8(&s2).unwrap();\n let number = string.parse::().unwrap();\n\n return compute_luhn(number);\n}\n"} {"name":"Verify distribution uniformity_Chi-squared test","C":"#include \n#include \n#include \n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n int j;\n double l1;\n double h = (b-a)\/N;\n double h1 = h\/3.0;\n double sum = f(a) + f(b);\n\n for (j=3*N-1; j>0; j--) {\n l1 = (j%3)? 3.0 : 2.0;\n sum += l1*f(a+h1*j) ;\n }\n return h*sum\/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n int k;\n static double cspace[A];\n static double *coefs = NULL;\n double accum;\n double a = A;\n\n if (!coefs) {\n double k1_factrl = 1.0;\n coefs = cspace;\n coefs[0] = sqrt(2.0*M_PI);\n for(k=1; k 2.0e-8) && (y < x)) y += .4;\n if (y>x) y=x;\n\n return 1.0 - Simpson3_8( &f0, 0, y, (int)(y\/h))\/Gamma_Spouge(a);\n}\n","Rust":"use statrs::function::gamma::gamma_li;\n\nfn chi_distance(dataset: &[u32]) -> f64 {\n let expected = f64::from(dataset.iter().sum::()) \/ dataset.len() as f64;\n dataset\n .iter()\n .fold(0., |acc, &elt| acc + (elt as f64 - expected).powf(2.))\n \/ expected\n}\n\nfn chi2_probability(dof: f64, distance: f64) -> f64 {\n 1. - gamma_li(dof * 0.5, distance * 0.5)\n}\n\nfn chi2_uniform(dataset: &[u32], significance: f64) -> bool {\n let d = chi_distance(&dataset);\n chi2_probability(dataset.len() as f64 - 1., d) > significance\n}\n\nfn main() {\n let dsets = vec![\n vec![199809, 200665, 199607, 200270, 199649],\n vec![522573, 244456, 139979, 71531, 21461],\n ];\n\n for ds in dsets {\n println!(\"Data set: {:?}\", ds);\n let d = chi_distance(&ds);\n print!(\"Distance: {:.6} \", d);\n print!(\n \"Chi2 probability: {:.6} \",\n chi2_probability(ds.len() as f64 - 1., d)\n );\n print!(\"Uniform? {}\\n\", chi2_uniform(&ds, 0.05));\n }\n}\n"} {"name":"Vigen\u00e8re cipher_Cryptanalysis","C":"#include \n#include \n#include \n#include \n#include \n\nconst char *encoded =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\"\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\"\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\"\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\"\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\"\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\"\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\"\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\"\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\"\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\"\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\"\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\"\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\"\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\"\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\"\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\"\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst double freq[] = {\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n\nint best_match(const double *a, const double *b) {\n double sum = 0, fit, d, best_fit = 1e100;\n int i, rotate, best_rotate = 0;\n for (i = 0; i < 26; i++)\n sum += a[i];\n for (rotate = 0; rotate < 26; rotate++) {\n fit = 0;\n for (i = 0; i < 26; i++) {\n d = a[(i + rotate) % 26] \/ sum - b[i];\n fit += d * d \/ b[i];\n }\n\n if (fit < best_fit) {\n best_fit = fit;\n best_rotate = rotate;\n }\n }\n\n return best_rotate;\n}\n\ndouble freq_every_nth(const int *msg, int len, int interval, char *key) {\n double sum, d, ret;\n double out[26], accu[26] = {0};\n int i, j, rot;\n\n for (j = 0; j < interval; j++) {\n for (i = 0; i < 26; i++)\n out[i] = 0;\n for (i = j; i < len; i += interval)\n out[msg[i]]++;\n key[j] = rot = best_match(out, freq);\n key[j] += 'A';\n for (i = 0; i < 26; i++)\n accu[i] += out[(i + rot) % 26];\n }\n\n for (i = 0, sum = 0; i < 26; i++)\n sum += accu[i];\n\n for (i = 0, ret = 0; i < 26; i++) {\n d = accu[i] \/ sum - freq[i];\n ret += d * d \/ freq[i];\n }\n\n key[interval] = '\\0';\n return ret;\n}\n\nint main() {\n int txt[strlen(encoded)];\n int len = 0, j;\n char key[100];\n double fit, best_fit = 1e100;\n\n for (j = 0; encoded[j] != '\\0'; j++)\n if (isupper(encoded[j]))\n txt[len++] = encoded[j] - 'A';\n\n for (j = 1; j < 30; j++) {\n fit = freq_every_nth(txt, len, j, key);\n printf(\"%f, key length: %2d, %s\", fit, j, key);\n if (fit < best_fit) {\n best_fit = fit;\n printf(\" <--- best so far\");\n }\n printf(\"\\n\");\n }\n\n return 0;\n}\n","Rust":"use std::iter::FromIterator;\n\nconst CRYPTOGRAM: &str = \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst FREQUENCIES: [f32; 26] = [\n 0.08167, 0.01492, 0.02202, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153,\n 0.01292, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09356,\n 0.02758, 0.00978, 0.02560, 0.00150, 0.01994, 0.00077,\n];\n\nfn best_match(a: &[f32]) -> u8 {\n let sum: f32 = a.iter().sum();\n let mut best_fit = std::f32::MAX;\n let mut best_rotate = 0;\n for rotate in 0..=25 {\n let mut fit = 0.;\n for i in 0..=25 {\n let char_freq = FREQUENCIES[i];\n let idx = (i + rotate as usize) % 26 as usize;\n let d = a[idx] \/ sum - char_freq;\n fit += d * d \/ char_freq;\n }\n if fit < best_fit {\n best_fit = fit;\n best_rotate = rotate;\n }\n }\n\n best_rotate\n}\n\nfn freq_every_nth(msg: &[u8], key: &mut [char]) -> f32 {\n let len = msg.len();\n let interval = key.len();\n let mut accu = [0.; 26];\n for j in 0..interval {\n let mut out = [0.; 26];\n for i in (j..len).step_by(interval) {\n let idx = msg[i] as usize;\n out[idx] += 1.;\n }\n let rot = best_match(&out);\n key[j] = char::from(rot + b'A');\n for i in 0..=25 {\n let idx: usize = (i + rot as usize) % 26;\n accu[i] += out[idx];\n }\n }\n let sum: f32 = accu.iter().sum();\n let mut ret = 0.;\n for i in 0..=25 {\n let char_freq = FREQUENCIES[i];\n let d = accu[i] \/ sum - char_freq;\n ret += d * d \/ char_freq;\n }\n ret\n}\n\nfn decrypt(text: &str, key: &str) -> String {\n let key_chars_cycle = key.as_bytes().iter().map(|b| *b as i32).cycle();\n let is_ascii_uppercase = |c: &u8| (b'A'..=b'Z').contains(c);\n text.as_bytes()\n .iter()\n .filter(|c| is_ascii_uppercase(c))\n .map(|b| *b as i32)\n .zip(key_chars_cycle)\n .fold(String::new(), |mut acc, (c, key_char)| {\n let ci: u8 = ((c - key_char + 26) % 26) as u8;\n acc.push(char::from(b'A' + ci));\n acc\n })\n}\nfn main() {\n let enc = CRYPTOGRAM\n .split_ascii_whitespace()\n .collect::>()\n .join(\"\");\n let cryptogram: Vec = enc.as_bytes().iter().map(|b| u8::from(b - b'A')).collect();\n let mut best_fit = std::f32::MAX;\n let mut best_key = String::new();\n for j in 1..=26 {\n let mut key = vec!['\\0'; j];\n let fit = freq_every_nth(&cryptogram, &mut key);\n let s_key = String::from_iter(key); \n if fit < best_fit {\n best_fit = fit;\n best_key = s_key;\n }\n }\n\n println!(\"best key: {}\", &best_key);\n println!(\"\\nDecrypted text:\\n{}\", decrypt(&enc, &best_key));\n}\n"} {"name":"Water collected between towers","C":"#include\n#include\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;iarr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage\u00a0: %s \");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i usize {\n let mut total = 0;\n for (idx, val) in pattern.iter().enumerate() {\n let l_peak = pattern[..idx].iter().max();\n let r_peak = pattern[idx + 1..].iter().max();\n if l_peak.is_some() && r_peak.is_some() {\n let peak = min(l_peak.unwrap(), r_peak.unwrap());\n if peak > val {\n total += peak - val;\n }\n }\n }\n total\n}\n\nfn main() {\n let patterns = vec![\n vec![1, 5, 3, 7, 2],\n vec![5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n vec![2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n vec![5, 5, 5, 5],\n vec![5, 6, 7, 8],\n vec![8, 7, 7, 6],\n vec![6, 7, 10, 7, 6],\n ];\n\n for pattern in patterns {\n println!(\"pattern: {:?}, fill: {}\", &pattern, getfill(&pattern));\n }\n}\n"} {"name":"Wireworld","C":"\n#define ANIMATE_VT100_POSIX\n#include \n#include \n#ifdef ANIMATE_VT100_POSIX\n#include \n#endif\n\nchar world_7x14[2][512] = {\n {\n \"+-----------+\\n\"\n \"|tH.........|\\n\"\n \"|. . |\\n\"\n \"| ... |\\n\"\n \"|. . |\\n\"\n \"|Ht.. ......|\\n\"\n \"+-----------+\\n\"\n }\n};\n\nvoid next_world(const char *in, char *out, int w, int h)\n{\n int i;\n\n for (i = 0; i < w*h; i++) {\n switch (in[i]) {\n case ' ': out[i] = ' '; break;\n case 't': out[i] = '.'; break;\n case 'H': out[i] = 't'; break;\n case '.': {\n int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') +\n (in[i-1] == 'H') + (in[i+1] == 'H') +\n (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H');\n out[i] = (hc == 1 || hc == 2) ? 'H' : '.';\n break;\n }\n default:\n out[i] = in[i];\n }\n }\n out[i] = in[i];\n}\n\nint main()\n{\n int f;\n\n for (f = 0; ; f = 1 - f) {\n puts(world_7x14[f]);\n next_world(world_7x14[f], world_7x14[1-f], 14, 7);\n#ifdef ANIMATE_VT100_POSIX\n printf(\"\\x1b[%dA\", 8);\n printf(\"\\x1b[%dD\", 14);\n {\n static const struct timespec ts = { 0, 100000000 };\n nanosleep(&ts, 0);\n }\n#endif\n }\n\n return 0;\n}\n","Rust":"use std::str::FromStr;\n\n#[derive(Debug, Copy, Clone, PartialEq)]\npub enum State {\n Empty,\n Conductor,\n ElectronTail,\n ElectronHead,\n}\n\nimpl State {\n fn next(&self, e_nearby: usize) -> State {\n match self {\n State::Empty => State::Empty,\n State::Conductor => {\n if e_nearby == 1 || e_nearby == 2 {\n State::ElectronHead\n } else {\n State::Conductor\n }\n }\n State::ElectronTail => State::Conductor,\n State::ElectronHead => State::ElectronTail,\n }\n }\n}\n\n#[derive(Debug, Clone, PartialEq)]\npub struct WireWorld {\n pub width: usize,\n pub height: usize,\n pub data: Vec,\n}\n\nimpl WireWorld {\n pub fn new(width: usize, height: usize) -> Self {\n WireWorld {\n width,\n height,\n data: vec![State::Empty; width * height],\n }\n }\n\n pub fn get(&self, x: usize, y: usize) -> Option {\n if x >= self.width || y >= self.height {\n None\n } else {\n self.data.get(y * self.width + x).copied()\n }\n }\n\n pub fn set(&mut self, x: usize, y: usize, state: State) {\n self.data[y * self.width + x] = state;\n }\n\n fn neighbors(&self, x: usize, y: usize, mut f: F) -> usize \n where F: FnMut(State) -> bool\n {\n let (x, y) = (x as i32, y as i32);\n let neighbors = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)];\n\n neighbors.iter().filter_map(|&(x, y)| self.get(x as usize, y as usize)).filter(|&s| f(s)).count()\n }\n\n pub fn next(&mut self) {\n let mut next_state = vec![];\n for y in 0..self.height {\n for x in 0..self.width {\n let e_count = self.neighbors(x, y, |e| e == State::ElectronHead);\n next_state.push(self.get(x, y).unwrap().next(e_count));\n }\n }\n self.data = next_state;\n }\n}\n\nimpl FromStr for WireWorld {\n type Err = ();\n fn from_str(s: &str) -> Result {\n let s = s.trim();\n let height = s.lines().count();\n let width = s.lines().map(|l| l.trim_end().len()).max().unwrap_or(0);\n let mut world = WireWorld::new(width, height);\n\n for (y, line) in s.lines().enumerate() {\n for (x, ch) in line.trim_end().chars().enumerate() {\n let state = match ch {\n '.' => State::Conductor,\n 't' => State::ElectronTail,\n 'H' => State::ElectronHead,\n _ => State::Empty,\n };\n world.set(x, y, state);\n }\n }\n Ok(world)\n }\n}\n"} {"name":"Yellowstone sequence","C":"#include \n#include \n#include \n\ntypedef struct lnode_t {\n struct lnode_t *prev;\n struct lnode_t *next;\n int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n Lnode *node = malloc(sizeof(Lnode));\n if (node == NULL) {\n return NULL;\n }\n node->v = v;\n node->prev = NULL;\n node->next = NULL;\n return node;\n}\n\nvoid free_lnode(Lnode *node) {\n if (node == NULL) {\n return;\n }\n\n node->v = 0;\n node->prev = NULL;\n free_lnode(node->next);\n node->next = NULL;\n}\n\ntypedef struct list_t {\n Lnode *front;\n Lnode *back;\n size_t len;\n} List;\n\nList *make_list() {\n List *list = malloc(sizeof(List));\n if (list == NULL) {\n return NULL;\n }\n list->front = NULL;\n list->back = NULL;\n list->len = 0;\n return list;\n}\n\nvoid free_list(List *list) {\n if (list == NULL) {\n return;\n }\n list->len = 0;\n list->back = NULL;\n free_lnode(list->front);\n list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n Lnode *node;\n\n if (list == NULL) {\n return;\n }\n\n node = make_list_node(v);\n if (list->front == NULL) {\n list->front = node;\n list->back = node;\n list->len = 1;\n } else {\n node->prev = list->back;\n list->back->next = node;\n list->back = node;\n list->len++;\n }\n}\n\nvoid list_print(List *list) {\n Lnode *it;\n\n if (list == NULL) {\n return;\n }\n\n for (it = list->front; it != NULL; it = it->next) {\n printf(\"%d \", it->v);\n }\n}\n\nint list_get(List *list, int idx) {\n Lnode *it = NULL;\n\n if (list != NULL && list->front != NULL) {\n int i;\n if (idx < 0) {\n it = list->back;\n i = -1;\n while (it != NULL && i > idx) {\n it = it->prev;\n i--;\n }\n } else {\n it = list->front;\n i = 0;\n while (it != NULL && i < idx) {\n it = it->next;\n i++;\n }\n }\n }\n\n if (it == NULL) {\n return INT_MIN;\n }\n return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n int k;\n bool v;\n struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n Mnode *node = malloc(sizeof(Mnode));\n if (node == NULL) {\n return node;\n }\n node->k = k;\n node->v = v;\n node->next = NULL;\n return node;\n}\n\nvoid free_mnode(Mnode *node) {\n if (node == NULL) {\n return;\n }\n node->k = 0;\n node->v = false;\n free_mnode(node->next);\n node->next = NULL;\n}\n\ntypedef struct map_t {\n Mnode *front;\n} Map;\n\nMap *make_map() {\n Map *map = malloc(sizeof(Map));\n if (map == NULL) {\n return NULL;\n }\n map->front = NULL;\n return map;\n}\n\nvoid free_map(Map *map) {\n if (map == NULL) {\n return;\n }\n free_mnode(map->front);\n map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n if (map == NULL) {\n return;\n }\n if (map->front == NULL) {\n map->front = make_map_node(k, v);\n } else {\n Mnode *it = map->front;\n while (it->next != NULL) {\n it = it->next;\n }\n it->next = make_map_node(k, v);\n }\n}\n\nbool map_get(Map *map, int k) {\n if (map != NULL) {\n Mnode *it = map->front;\n while (it != NULL && it->k != k) {\n it = it->next;\n }\n if (it != NULL) {\n return it->v;\n }\n }\n return false;\n}\n\n\n\nint gcd(int u, int v) {\n if (u < 0) u = -u;\n if (v < 0) v = -v;\n if (v) {\n while ((u %= v) && (v %= u));\n }\n return u + v;\n}\n\nList *yellow(size_t n) {\n List *a;\n Map *b;\n int i;\n\n a = make_list();\n list_insert(a, 1);\n list_insert(a, 2);\n list_insert(a, 3);\n\n b = make_map();\n map_insert(b, 1, true);\n map_insert(b, 2, true);\n map_insert(b, 3, true);\n\n i = 4;\n\n while (n > a->len) {\n if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n list_insert(a, i);\n map_insert(b, i, true);\n i = 4;\n }\n i++;\n }\n\n free_map(b);\n return a;\n}\n\nint main() {\n List *a = yellow(30);\n list_print(a);\n free_list(a);\n putc('\\n', stdout);\n return 0;\n}\n","Rust":"\n\n\n\nuse num::integer::gcd;\nuse plotters::prelude::*;\nuse std::collections::HashSet;\n\nfn yellowstone_sequence() -> impl std::iter::Iterator {\n let mut sequence: HashSet = HashSet::new();\n let mut min = 1;\n let mut n = 0;\n let mut n1 = 0;\n let mut n2 = 0;\n std::iter::from_fn(move || {\n n2 = n1;\n n1 = n;\n if n < 3 {\n n += 1;\n } else {\n n = min;\n while !(!sequence.contains(&n) && gcd(n1, n) == 1 && gcd(n2, n) > 1) {\n n += 1;\n }\n }\n sequence.insert(n);\n while sequence.contains(&min) {\n sequence.remove(&min);\n min += 1;\n }\n Some(n)\n })\n}\n\n\n\nfn plot_yellowstone(filename: &str) -> Result<(), Box> {\n let root = BitMapBackend::new(filename, (800, 600)).into_drawing_area();\n root.fill(&WHITE)?;\n let mut chart = ChartBuilder::on(&root)\n .caption(\"Yellowstone Sequence\", (\"sans-serif\", 24).into_font())\n .margin(10)\n .x_label_area_size(20)\n .y_label_area_size(20)\n .build_ranged(0usize..100usize, 0u32..180u32)?;\n chart.configure_mesh().draw()?;\n chart.draw_series(LineSeries::new(\n yellowstone_sequence().take(100).enumerate(),\n &BLUE,\n ))?;\n Ok(())\n}\n\nfn main() {\n println!(\"First 30 Yellowstone numbers:\");\n for y in yellowstone_sequence().take(30) {\n print!(\"{} \", y);\n }\n println!();\n match plot_yellowstone(\"yellowstone.png\") {\n Ok(()) => {}\n Err(error) => eprintln!(\"Error: {}\", error),\n }\n}\n"}