code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
package main import ( "fmt" "math/big" "rcu" "sort" ) func main() { primes := rcu.Primes(379) primorial := big.NewInt(1) var fortunates []int bPrime := new(big.Int) for _, prime := range primes { bPrime.SetUint64(uint64(prime)) primorial.Mul(primorial, bPrime) for j := 3; ; j += 2 { jj := big.NewInt(int64(j)) bPrime.Add(primorial, jj) if bPrime.ProbablyPrime(5) { fortunates = append(fortunates, j) break } } } m := make(map[int]bool) for _, f := range fortunates { m[f] = true } fortunates = fortunates[:0] for k := range m { fortunates = append(fortunates, k) } sort.Ints(fortunates) fmt.Println("After sorting, the first 50 distinct fortunate numbers are:") for i, f := range fortunates[0:50] { fmt.Printf("%3d ", f) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
809Fortunate numbers
0go
q3bxz
import Data.Numbers.Primes (primes) import Math.NumberTheory.Primes.Testing (isPrime) import Data.List (nub) primorials :: [Integer] primorials = 1: scanl1 (*) primes nextPrime :: Integer -> Integer nextPrime n | even n = head $ dropWhile (not . isPrime) [n+1, n+3..] | even n = nextPrime (n+1) fortunateNumbers :: [Integer] fortunateNumbers = (\p -> nextPrime (p + 2) - p) <$> tail primorials
809Fortunate numbers
8haskell
m7dyf
use strict; use warnings; use List::Util <first uniq>; use ntheory qw<pn_primorial is_prime>; my $upto = 50; my @candidates; for my $p ( map { pn_primorial($_) } 1..2*$upto ) { push @candidates, first { is_prime($_ + $p) } 2..100*$upto; } my @fortunate = sort { $a <=> $b } uniq grep { is_prime $_ } @candidates; print "First $upto distinct fortunate numbers:\n" . (sprintf "@{['%6d' x $upto]}", @fortunate) =~ s/(.{60})/$1\n/gr;
809Fortunate numbers
2perl
4e95d
from sympy.ntheory.generate import primorial from sympy.ntheory import isprime def fortunate_number(n): '''Return the fortunate number for positive integer n.''' i = 3 primorial_ = primorial(n) while True: if isprime(primorial_ + i): return i i += 2 fortunate_numbers = set() for i in range(1, 76): fortunate_numbers.add(fortunate_number(i)) first50 = sorted(list(fortunate_numbers))[:50] print('The first 50 fortunate numbers:') print(('{:<3} ' * 10).format(*(first50[:10]))) print(('{:<3} ' * 10).format(*(first50[10:20]))) print(('{:<3} ' * 10).format(*(first50[20:30]))) print(('{:<3} ' * 10).format(*(first50[30:40]))) print(('{:<3} ' * 10).format(*(first50[40:])))
809Fortunate numbers
3python
gwc4h
require primorials = Enumerator.new do |y| cur = prod = 1 loop {y << prod *= (cur = GMP::Z(cur).nextprime)} end limit = 50 fortunates = [] while fortunates.size < limit*2 do prim = primorials.next fortunates << (GMP::Z(prim+2).nextprime - prim) fortunates = fortunates.uniq.sort end p fortunates[0, limit]
809Fortunate numbers
14ruby
7q2ri
puts
755Hello world/Text
14ruby
700ri
fn main() { print!("Hello world!"); }
755Hello world/Text
15rust
j8872
println("Hello world!")
755Hello world/Text
16scala
bnnk6
func multiply(a, b float64) float64 { return a * b }
808Function definition
0go
icxog
def multiply = { x, y -> x * y }
808Function definition
7groovy
q3pxp
multiply x y = x * y
808Function definition
8haskell
vpy2k
SELECT 'Hello world!' text FROM dual;
755Hello world/Text
19sql
att1t
public class Math { public static int multiply( int a, int b) { return a*b; } public static double multiply(double a, double b) { return a*b; } }
808Function definition
9java
yrd6g
int main() { pid_t pid; if (!(pid = fork())) { usleep(10000); printf(); } else if (pid < 0) { err(1, ); } else { printf(, (int)pid); printf(, (int)wait(0)); } return 0; }
810Fork
5c
nlwi6
function multiply(a, b) { return a*b; }
808Function definition
10javascript
2b6lr
print("Hello world!")
755Hello world/Text
17swift
rssgg
(require '[clojure.java.shell:as shell]) (shell/sh "echo" "foo")
810Fork
6clojure
348zr
null
808Function definition
11kotlin
fv0do
package main import ( "fmt" "os" ) func main() { fmt.Printf("PID:%v\n", os.Getpid()) if len(os.Args) < 2 { fmt.Println("Done.") return } cp, err := os.StartProcess(os.Args[0], nil, &os.ProcAttr{Files: []*os.File{nil, os.Stdout}}, ) if err != nil { fmt.Println(err) }
810Fork
0go
rxcgm
println "BEFORE PROCESS" Process p = Runtime.runtime.exec(''' C:/cygwin/bin/sh -c " /usr/bin/date +'BEFORE LOOP:%T'; for i in 1 2 3 4; do /usr/bin/sleep 1; /usr/bin/echo \$i; done; /usr/bin/date +'AFTER LOOP:%T'" ''') p.consumeProcessOutput(System.out, System.err) (0..<8).each { Thread.sleep(500) print '.' } p.waitFor() println "AFTER PROCESS"
810Fork
7groovy
vp328
import System.Posix.Process main = do forkProcess (putStrLn "This is the new process") putStrLn "This is the original process"
810Fork
8haskell
0yps7
typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , } }; const number_names tens[] = { { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { , , 100 }, { , , 1000 }, { , , 1000000 }, { , , 1000000000 }, { , , 1000000000000 }, { , , 1000000000000000ULL }, { , , 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } typedef struct word_tag { size_t offset; size_t length; } word_t; typedef struct word_list_tag { GArray* words; GString* str; } word_list; void word_list_create(word_list* words) { words->words = g_array_new(FALSE, FALSE, sizeof(word_t)); words->str = g_string_new(NULL); } void word_list_destroy(word_list* words) { g_string_free(words->str, TRUE); g_array_free(words->words, TRUE); } void word_list_clear(word_list* words) { g_string_truncate(words->str, 0); g_array_set_size(words->words, 0); } void word_list_append(word_list* words, const char* str) { size_t offset = words->str->len; size_t len = strlen(str); g_string_append_len(words->str, str, len); word_t word; word.offset = offset; word.length = len; g_array_append_val(words->words, word); } word_t* word_list_get(word_list* words, size_t index) { return &g_array_index(words->words, word_t, index); } void word_list_extend(word_list* words, const char* str) { word_t* word = word_list_get(words, words->words->len - 1); size_t len = strlen(str); word->length += len; g_string_append_len(words->str, str, len); } size_t append_number_name(word_list* words, integer n, bool ordinal) { size_t count = 0; if (n < 20) { word_list_append(words, get_small_name(&small[n], ordinal)); count = 1; } else if (n < 100) { if (n % 10 == 0) { word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal)); } else { word_list_append(words, get_small_name(&tens[n/10 - 2], false)); word_list_extend(words, ); word_list_extend(words, get_small_name(&small[n % 10], ordinal)); } count = 1; } else { const named_number* num = get_named_number(n); integer p = num->number; count += append_number_name(words, n/p, false); if (n % p == 0) { word_list_append(words, get_big_name(num, ordinal)); ++count; } else { word_list_append(words, get_big_name(num, false)); ++count; count += append_number_name(words, n % p, ordinal); } } return count; } size_t count_letters(word_list* words, size_t index) { const word_t* word = word_list_get(words, index); size_t letters = 0; const char* s = words->str->str + word->offset; for (size_t i = 0, n = word->length; i < n; ++i) { if (isalpha((unsigned char)s[i])) ++letters; } return letters; } void sentence(word_list* result, size_t count) { static const char* words[] = { , , , , , , , , , , , , }; word_list_clear(result); size_t n = sizeof(words)/sizeof(words[0]); for (size_t i = 0; i < n; ++i) word_list_append(result, words[i]); for (size_t i = 1; count > n; ++i) { n += append_number_name(result, count_letters(result, i), false); word_list_append(result, ); word_list_append(result, ); n += 2; n += append_number_name(result, i + 1, true); word_list_extend(result, ); } } size_t sentence_length(const word_list* words) { size_t n = words->words->len; if (n == 0) return 0; return words->str->len + n - 1; } int main() { setlocale(LC_ALL, ); size_t n = 201; word_list result = { 0 }; word_list_create(&result); sentence(&result, n); printf(, n); for (size_t i = 0; i < n; ++i) { if (i != 0) printf(, i % 25 == 0 ? '\n' : ' '); printf(, count_letters(&result, i)); } printf(, sentence_length(&result)); for (n = 1000; n <= 10000000; n *= 10) { sentence(&result, n); const word_t* word = word_list_get(&result, n - 1); const char* s = result.str->str + word->offset; printf(, n, (int)word->length, s, count_letters(&result, n - 1)); printf( , sentence_length(&result)); } word_list_destroy(&result); return 0; }
811Four is the number of letters in the ...
5c
jsl70
import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.Arrays; import java.util.List; import java.util.Map; public class RFork { public static void main(String[] args) { ProcessBuilder pb; Process pp; List<String> command; Map<String, String> env; BufferedReader ir; String currentuser; String line; try { command = Arrays.asList(""); pb = new ProcessBuilder(command); env = pb.environment(); currentuser = env.get("USER"); command = Arrays.asList("ps", "-f", "-U", currentuser); pb.command(command); pp = pb.start(); ir = new BufferedReader(new InputStreamReader(pp.getInputStream())); line = "Output of running " + command.toString() + " is:"; do { System.out.println(line); } while ((line = ir.readLine()) != null); } catch (IOException iox) { iox.printStackTrace(); } return; } }
810Fork
9java
adr1y
package main import ( "fmt" "strings" "unicode" ) func main() { f := NewFourIsSeq() fmt.Print("The lengths of the first 201 words are:") for i := 1; i <= 201; i++ { if i%25 == 1 { fmt.Printf("\n%3d: ", i) } _, n := f.WordLen(i) fmt.Printf("%2d", n) } fmt.Println() fmt.Println("Length of sentence so far:", f.TotalLength()) for i := 1000; i <= 1e7; i *= 10 { w, n := f.WordLen(i) fmt.Printf("Word%8d is%q, with%d letters.", i, w, n) fmt.Println(" Length of sentence so far:", f.TotalLength()) } } type FourIsSeq struct { i int
811Four is the number of letters in the ...
0go
fvxd0
null
810Fork
11kotlin
h0vj3
import Data.Char sentence = start ++ foldMap add (zip [2..] $ tail $ words sentence) where start = "Four is the number of letters in the first word of this sentence, " add (i, w) = unwords [spellInteger (alphaLength w), "in the", spellOrdinal i ++ ", "] alphaLength w = fromIntegral $ length $ filter isAlpha w main = mapM_ (putStrLn . say) [1000,10000,100000,1000000] where ws = words sentence say n = let (a, w:_) = splitAt (n-1) ws in "The " ++ spellOrdinal n ++ " word is \"" ++ w ++ "\" which has " ++ spellInteger (alphaLength w) ++ " letters. The sentence length is " ++ show (length $ unwords a) ++ " chars."
811Four is the number of letters in the ...
8haskell
4ey5s
function multiply( a, b ) return a * b end
808Function definition
1lua
tu8fn
import java.util.HashMap; import java.util.Map; public class FourIsTheNumberOfLetters { public static void main(String[] args) { String [] words = neverEndingSentence(201); System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1); for ( int i = 0 ; i < words.length ; i++ ) { System.out.printf("%2d ", numberOfLetters(words[i])); if ( (i+1) % 25 == 0 ) { System.out.printf("%n%3d: ", i+2); } } System.out.printf("%nTotal number of characters in the sentence is%d%n", characterCount(words)); for ( int i = 3 ; i <= 7 ; i++ ) { int index = (int) Math.pow(10, i); words = neverEndingSentence(index); String last = words[words.length-1].replace(",", ""); System.out.printf("Number of letters of the%s word is%d. The word is \"%s\". The sentence length is%,d characters.%n", toOrdinal(index), numberOfLetters(last), last, characterCount(words)); } } @SuppressWarnings("unused") private static void displaySentence(String[] words, int lineLength) { int currentLength = 0; for ( String word : words ) { if ( word.length() + currentLength > lineLength ) { String first = word.substring(0, lineLength-currentLength); String second = word.substring(lineLength-currentLength); System.out.println(first); System.out.print(second); currentLength = second.length(); } else { System.out.print(word); currentLength += word.length(); } if ( currentLength == lineLength ) { System.out.println(); currentLength = 0; } System.out.print(" "); currentLength++; if ( currentLength == lineLength ) { System.out.println(); currentLength = 0; } } System.out.println(); } private static int numberOfLetters(String word) { return word.replace(",","").replace("-","").length(); } private static long characterCount(String[] words) { int characterCount = 0; for ( int i = 0 ; i < words.length ; i++ ) { characterCount += words[i].length() + 1; }
811Four is the number of letters in the ...
9java
chd9h
local posix = require 'posix' local pid = posix.fork() if pid == 0 then print("child process") elseif pid > 0 then print("parent process") else error("unable to fork") end
810Fork
1lua
k8uh2
null
811Four is the number of letters in the ...
11kotlin
340z5
enum fps_type { FPS_CONST = 0, FPS_ADD, FPS_SUB, FPS_MUL, FPS_DIV, FPS_DERIV, FPS_INT, }; typedef struct fps_t *fps; typedef struct fps_t { int type; fps s1, s2; double a0; } fps_t; fps fps_new() { fps x = malloc(sizeof(fps_t)); x->a0 = 0; x->s1 = x->s2 = 0; x->type = 0; return x; } void fps_redefine(fps x, int op, fps y, fps z) { x->type = op; x->s1 = y; x->s2 = z; } fps _binary(fps x, fps y, int op) { fps s = fps_new(); s->s1 = x; s->s2 = y; s->type = op; return s; } fps _unary(fps x, int op) { fps s = fps_new(); s->s1 = x; s->type = op; return s; } double term(fps x, int n) { double ret = 0; int i; switch (x->type) { case FPS_CONST: return n > 0 ? 0 : x->a0; case FPS_ADD: ret = term(x->s1, n) + term(x->s2, n); break; case FPS_SUB: ret = term(x->s1, n) - term(x->s2, n); break; case FPS_MUL: for (i = 0; i <= n; i++) ret += term(x->s1, i) * term(x->s2, n - i); break; case FPS_DIV: if (! term(x->s2, 0)) return NAN; ret = term(x->s1, n); for (i = 1; i <= n; i++) ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0); break; case FPS_DERIV: ret = n * term(x->s1, n + 1); break; case FPS_INT: if (!n) return x->a0; ret = term(x->s1, n - 1) / n; break; default: fprintf(stderr, , x->type); exit(1); } return ret; } fps fps_const(double a0) { fps x = fps_new(); x->type = FPS_CONST; x->a0 = a0; return x; } int main() { int i; fps one = fps_const(1); fps fcos = fps_new(); fps fsin = _integ(fcos); fps ftan = _div(fsin, fcos); fps_redefine(fcos, FPS_SUB, one, _integ(fsin)); fps fexp = fps_const(1); fps_redefine(fexp, FPS_INT, fexp, 0); printf(); for (i = 0; i < 10; i++) printf(, term(fsin, i)); printf(); for (i = 0; i < 10; i++) printf(, term(fcos, i)); printf(); for (i = 0; i < 10; i++) printf(, term(ftan, i)); printf(); for (i = 0; i < 10; i++) printf(, term(fexp, i)); return 0; }
812Formal power series
5c
ad411
(defn ps+ [ps0 ps1] (letfn [(+zs [ps] (concat ps (repeat:z))) (notz? [a] (not=:z a)) (nval [a] (if (notz? a) a 0)) (z+ [a0 a1] (if (=:z a0 a1):z (+ (nval a0) (nval a1))))] (take-while notz? (map z+ (+zs ps0) (+zs ps1))))) (defn ps- [ps0 ps1] (ps+ ps0 (map - ps1)))
812Formal power series
6clojure
s6hqr
use feature 'state'; use Lingua::EN::Numbers qw(num2en num2en_ordinal); my @sentence = split / /, 'Four is the number of letters in the first word of this sentence, '; sub extend_to { my($last) = @_; state $index = 1; until ($ push @sentence, split ' ', num2en(alpha($sentence[$index])) . ' in the ' . no_c(num2en_ordinal(1+$index)) . ','; $index++; } } sub alpha { my($s) = @_; $s =~ s/\W//gi; length $s } sub no_c { my($s) = @_; $s =~ s/\ and|,//g; return $s } sub count { length(join ' ', @sentence[0..-1+$_[0]]) . " characters in the sentence, up to and including this word.\n" } print "First 201 word lengths in the sequence:\n"; extend_to(201); for (0..200) { printf "%3d", alpha($sentence[$_]); print "\n" unless ($_+1) % 32; } print "\n" . count(201) . "\n"; for (1e3, 1e4, 1e5, 1e6, 1e7) { extend_to($_); print ucfirst(num2en_ordinal($_)) . " word, '$sentence[$_-1]' has " . alpha($sentence[$_-1]) . " characters. \n" . count($_) . "\n"; }
811Four is the number of letters in the ...
2perl
pi5b0
FORK: if ($pid = fork()) { } elsif (defined($pid)) { setsid; close(STDOUT); close(STDIN); close(STDERR); open(STDOUT, '>/dev/null'); open(STDIN, '>/dev/null'); open(STDERR, '>>/home/virtual/logs/err.log'); exit; } elsif($! =~ /emporar/){ warn '[' . localtime() . "] Failed to Fork - Will try again in 10 seconds.\n"; sleep(10); goto FORK; } else { warn '[' . localtime() . "] Unable to fork - $!"; exit(0); }
810Fork
2perl
z50tb
import inflect def count_letters(word): count = 0 for letter in word: if letter != ',' and letter !='-' and letter !=' ': count += 1 return count def split_with_spaces(sentence): sentence_list = [] curr_word = for c in sentence: if c == and curr_word != : sentence_list.append(curr_word+) curr_word = else: curr_word += c if len(curr_word) > 0: sentence_list.append(curr_word) return sentence_list def my_num_to_words(p, my_number): number_string_list = p.number_to_words(my_number, wantlist=True, andword='') number_string = number_string_list[0] for i in range(1,len(number_string_list)): number_string += + number_string_list[i] return number_string def build_sentence(p, max_words): sentence_list = split_with_spaces() num_words = 13 word_number = 2 while num_words < max_words: ordinal_string = my_num_to_words(p, p.ordinal(word_number)) word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1])) new_string = +word_number_string++ordinal_string+ new_list = split_with_spaces(new_string) sentence_list += new_list num_words += len(new_list) word_number += 1 return sentence_list, num_words def word_and_counts(word_num): sentence_list, num_words = build_sentence(p, word_num) word_str = sentence_list[word_num - 1].strip(' ,') num_letters = len(word_str) num_characters = 0 for word in sentence_list: num_characters += len(word) print('Word {0:8d} is , with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters)) p = inflect.engine() sentence_list, num_words = build_sentence(p, 201) print() print() print() print('{0:3d}: '.format(1),end='') total_characters = 0 for word_index in range(201): word_length = count_letters(sentence_list[word_index]) total_characters += len(sentence_list[word_index]) print('{0:2d}'.format(word_length),end='') if (word_index+1)% 20 == 0: print() print('{0:3d}: '.format(word_index + 2),end='') else: print(,end='') print() print() print(+str(total_characters)) print() word_and_counts(1000) word_and_counts(10000) word_and_counts(100000) word_and_counts(1000000) word_and_counts(10000000)
811Four is the number of letters in the ...
3python
1n4pc
<?php $pid = pcntl_fork(); if ($pid == 0) echo ; else if ($pid > 0) echo ; else echo ; ?>
810Fork
12php
bo5k9
import os pid = os.fork() if pid > 0: else:
810Fork
3python
348zc
package main import ( "fmt" "math" )
812Formal power series
0go
m7oyi
struct NumberNames { cardinal: &'static str, ordinal: &'static str, } impl NumberNames { fn get_name(&self, ordinal: bool) -> &'static str { if ordinal { return self.ordinal; } self.cardinal } } const SMALL_NAMES: [NumberNames; 20] = [ NumberNames { cardinal: "zero", ordinal: "zeroth", }, NumberNames { cardinal: "one", ordinal: "first", }, NumberNames { cardinal: "two", ordinal: "second", }, NumberNames { cardinal: "three", ordinal: "third", }, NumberNames { cardinal: "four", ordinal: "fourth", }, NumberNames { cardinal: "five", ordinal: "fifth", }, NumberNames { cardinal: "six", ordinal: "sixth", }, NumberNames { cardinal: "seven", ordinal: "seventh", }, NumberNames { cardinal: "eight", ordinal: "eighth", }, NumberNames { cardinal: "nine", ordinal: "ninth", }, NumberNames { cardinal: "ten", ordinal: "tenth", }, NumberNames { cardinal: "eleven", ordinal: "eleventh", }, NumberNames { cardinal: "twelve", ordinal: "twelfth", }, NumberNames { cardinal: "thirteen", ordinal: "thirteenth", }, NumberNames { cardinal: "fourteen", ordinal: "fourteenth", }, NumberNames { cardinal: "fifteen", ordinal: "fifteenth", }, NumberNames { cardinal: "sixteen", ordinal: "sixteenth", }, NumberNames { cardinal: "seventeen", ordinal: "seventeenth", }, NumberNames { cardinal: "eighteen", ordinal: "eighteenth", }, NumberNames { cardinal: "nineteen", ordinal: "nineteenth", }, ]; const TENS: [NumberNames; 8] = [ NumberNames { cardinal: "twenty", ordinal: "twentieth", }, NumberNames { cardinal: "thirty", ordinal: "thirtieth", }, NumberNames { cardinal: "forty", ordinal: "fortieth", }, NumberNames { cardinal: "fifty", ordinal: "fiftieth", }, NumberNames { cardinal: "sixty", ordinal: "sixtieth", }, NumberNames { cardinal: "seventy", ordinal: "seventieth", }, NumberNames { cardinal: "eighty", ordinal: "eightieth", }, NumberNames { cardinal: "ninety", ordinal: "ninetieth", }, ]; struct NamedNumber { cardinal: &'static str, ordinal: &'static str, number: usize, } impl NamedNumber { fn get_name(&self, ordinal: bool) -> &'static str { if ordinal { return self.ordinal; } self.cardinal } } const N: usize = 7; const NAMED_NUMBERS: [NamedNumber; N] = [ NamedNumber { cardinal: "hundred", ordinal: "hundredth", number: 100, }, NamedNumber { cardinal: "thousand", ordinal: "thousandth", number: 1000, }, NamedNumber { cardinal: "million", ordinal: "millionth", number: 1000000, }, NamedNumber { cardinal: "billion", ordinal: "billionth", number: 1000000000, }, NamedNumber { cardinal: "trillion", ordinal: "trillionth", number: 1000000000000, }, NamedNumber { cardinal: "quadrillion", ordinal: "quadrillionth", number: 1000000000000000, }, NamedNumber { cardinal: "quintillion", ordinal: "quintillionth", number: 1000000000000000000, }, ]; fn big_name(n: usize) -> &'static NamedNumber { for i in 1..N { if n < NAMED_NUMBERS[i].number { return &NAMED_NUMBERS[i - 1]; } } &NAMED_NUMBERS[N - 1] } fn count_letters(s: &str) -> usize { let mut count = 0; for c in s.chars() { if c.is_alphabetic() { count += 1; } } count } struct WordList { words: Vec<(usize, usize)>, string: String, } impl WordList { fn new() -> WordList { WordList { words: Vec::new(), string: String::new(), } } fn append(&mut self, s: &str) { let offset = self.string.len(); self.string.push_str(s); self.words.push((offset, offset + s.len())); } fn extend(&mut self, s: &str) { let len = self.words.len(); let mut w = &mut self.words[len - 1]; w.1 += s.len(); self.string.push_str(s); } fn len(&self) -> usize { self.words.len() } fn sentence_length(&self) -> usize { let n = self.words.len(); if n == 0 { return 0; } self.string.len() + n - 1 } fn get_word(&self, index: usize) -> &str { let w = &self.words[index]; &self.string[w.0..w.1] } } fn append_number_name(words: &mut WordList, n: usize, ordinal: bool) -> usize { let mut count = 0; if n < 20 { words.append(SMALL_NAMES[n].get_name(ordinal)); count += 1; } else if n < 100 { if n% 10 == 0 { words.append(TENS[n / 10 - 2].get_name(ordinal)); } else { words.append(TENS[n / 10 - 2].get_name(false)); words.extend("-"); words.extend(SMALL_NAMES[n% 10].get_name(ordinal)); } count += 1; } else { let big = big_name(n); count += append_number_name(words, n / big.number, false); if n% big.number == 0 { words.append(big.get_name(ordinal)); count += 1; } else { words.append(big.get_name(false)); count += 1; count += append_number_name(words, n% big.number, ordinal); } } count } fn sentence(count: usize) -> WordList { let mut result = WordList::new(); const WORDS: &'static [&'static str] = &[ "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,", ]; for s in WORDS { result.append(s); } let mut n = result.len(); let mut i = 1; while count > n { let count = count_letters(result.get_word(i)); n += append_number_name(&mut result, count, false); result.append("in"); result.append("the"); n += 2; n += append_number_name(&mut result, i + 1, true); result.extend(","); i += 1; } result } fn main() { let mut n = 201; let s = sentence(n); println!("Number of letters in first {} words in the sequence:", n); for i in 0..n { if i!= 0 { if i% 25 == 0 { println!(); } else { print!(" "); } } print!("{:2}", count_letters(s.get_word(i))); } println!(); println!("Sentence length: {}", s.sentence_length()); n = 1000; while n <= 10000000 { let s = sentence(n); let word = s.get_word(n - 1); print!( "The {}th word is '{}' and has {} letters. ", n, word, count_letters(word) ); println!("Sentence length: {}", s.sentence_length()); n *= 10; } }
811Four is the number of letters in the ...
15rust
wt7e4
p <- parallel::mcparallel({ Sys.sleep(1) cat("\tChild pid: ", Sys.getpid(), "\n") TRUE }) cat("Main pid: ", Sys.getpid(), "\n") parallel::mccollect(p) p <- parallel:::mcfork() if (inherits(p, "masterProcess")) { Sys.sleep(1) cat("\tChild pid: ", Sys.getpid(), "\n") parallel:::mcexit(, TRUE) } cat("Main pid: ", Sys.getpid(), "\n") unserialize(parallel:::readChildren(2))
810Fork
13r
d2xnt
newtype Series a = S { coeffs :: [a] } deriving (Eq, Show) instance Num a => Num (Series a) where fromInteger n = S $ fromInteger n: repeat 0 negate (S fs) = S $ map negate fs S fs + S gs = S $ zipWith (+) fs gs S (f:ft) * S gs@(g:gt) = S $ f*g: coeffs (S ft * S gs + S (map (f*) gt)) instance Fractional a => Fractional (Series a) where fromRational n = S $ fromRational n: repeat 0 S (f:ft) / S (g:gt) = S qs where qs = f/g: map (/g) (coeffs (S ft - S qs * S gt)) fromFiniteList xs = S (xs ++ repeat 0) int (S fs) = S $ 0: zipWith (/) fs [1..] diff (S (_:ft)) = S $ zipWith (*) ft [1..] sinx,cosx :: Series Rational sinx = int cosx cosx = 1 - int sinx fiboS = 1 / fromFiniteList [1,-1,-1]
812Formal power series
8haskell
k82h0
main(){ float r=7.125; printf(,-r); printf(,r); printf(,r); printf(,-r); printf(,r); printf(,r); return 0; }
813Formatted numeric output
5c
icpo2
pid = fork if pid else end
810Fork
14ruby
yri6n
1/(1+.)
812Formal power series
9java
4e658
(cl-format true "~9,3,,,'0F" 7.125)
813Formatted numeric output
6clojure
z5xtj
use nix::unistd::{fork, ForkResult}; use std::process::id; fn main() { match fork() { Ok(ForkResult::Parent { child, .. }) => { println!( "This is the original process(pid: {}). New child has pid: {}", id(), child ); } Ok(ForkResult::Child) => println!("This is the new process(pid: {}).", id()), Err(_) => println!("Something went wrong."), } }
810Fork
15rust
m7nya
import java.io.IOException object Fork extends App { val builder: ProcessBuilder = new ProcessBuilder() val currentUser: String = builder.environment.get("USER") val command: java.util.List[String] = java.util.Arrays.asList("ps", "-f", "-U", currentUser) builder.command(command) try { val lines = scala.io.Source.fromInputStream(builder.start.getInputStream).getLines() println(s"Output of running $command is:") while (lines.hasNext) println(lines.next()) } catch { case iox: IOException => iox.printStackTrace() } }
810Fork
16scala
lktcq
typedef char pin_t; void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf(, V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
814Four bit adder
5c
vpd2o
null
812Formal power series
11kotlin
lkdcp
powerseries = setmetatable({ __add = function(z1, z2) return powerseries(function(n) return z1.coeff(n) + z2.coeff(n) end) end, __sub = function(z1, z2) return powerseries(function(n) return z1.coeff(n) - z2.coeff(n) end) end, __mul = function(z1, z2) return powerseries(function(n) local ret = 0 for i = 0, n do ret = ret + z1.coeff(i) * z2.coeff(n-i) end return ret end) end, __div = function(z1, z2) return powerseries(function(n) local ret = z1.coeff(n) local function coeffs(a) local c = z1.coeff(a) for j = 0, a - 1 do c = c - coeffs(j) * z2.coeff(a-j) end return c / z2.coeff(0) end for i = 0, n-1 do ret = ret - coeffs(i) * z2.coeff(n-i) end return ret / z2.coeff(0) end) end, __pow = function(z1, p)
812Formal power series
1lua
2bfl3
(ns rosettacode.adder (:use clojure.test)) (defn xor-gate [a b] (or (and a (not b)) (and b (not a)))) (defn half-adder [a b] "output: (S C)" (cons (xor-gate a b) (list (and a b)))) (defn full-adder [a b c] "output: (C S)" (let [HA-ca (half-adder c a) HA-ca->sb (half-adder (first HA-ca) b)] (cons (or (second HA-ca) (second HA-ca->sb)) (list (first HA-ca->sb))))) (defn n-bit-adder "first bits on the list are low order bits 1 = true 2 = false true 3 = true true 4 = false false true..." can add numbers of different bit-length ([a-bits b-bits] (n-bit-adder a-bits b-bits false)) ([a-bits b-bits carry] (let [added (full-adder (first a-bits) (first b-bits) carry)] (if(and (nil? a-bits) (nil? b-bits)) (if carry (list carry) '()) (cons (second added) (n-bit-adder (next a-bits) (next b-bits) (first added))))))) (n-bit-adder [true true true true true true] [true true true true true true]) => (false true true true true true true)
814Four bit adder
6clojure
rx6g2
double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf(, y[i]); putchar('\n'); return 0; }
815Forward difference
5c
9j0m1
typedef struct named_number_tag { const char* name; uint64_t number; } named_number; const named_number named_numbers[] = { { , 100 }, { , 1000 }, { , 1000000 }, { , 1000000000 }, { , 1000000000000 }, { , 1000000000000000ULL }, { , 1000000000000000000ULL } }; const named_number* get_named_number(uint64_t n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_number); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } size_t append_number_name(GString* str, uint64_t n) { static const char* small[] = { , , , , , , , , , , , , , , , , , , , }; static const char* tens[] = { , , , , , , , }; size_t len = str->len; if (n < 20) { g_string_append(str, small[n]); } else if (n < 100) { g_string_append(str, tens[n/10 - 2]); if (n % 10 != 0) { g_string_append_c(str, '-'); g_string_append(str, small[n % 10]); } } else { const named_number* num = get_named_number(n); uint64_t p = num->number; append_number_name(str, n/p); g_string_append_c(str, ' '); g_string_append(str, num->name); if (n % p != 0) { g_string_append_c(str, ' '); append_number_name(str, n % p); } } return str->len - len; } GString* magic(uint64_t n) { GString* str = g_string_new(NULL); for (unsigned int i = 0; ; ++i) { size_t count = append_number_name(str, n); if (i == 0) str->str[0] = g_ascii_toupper(str->str[0]); if (n == 4) { g_string_append(str, ); break; } g_string_append(str, ); append_number_name(str, count); g_string_append(str, ); n = count; } return str; } void test_magic(uint64_t n) { GString* str = magic(n); printf(, str->str); g_string_free(str, TRUE); } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
816Four is magic
5c
m7qys
package FPS; use strict; use warnings; use Math::BigRat; sub new { my $class = shift; return bless {@_}, $class unless @_ == 1; my $arg = shift; return bless { more => $arg }, $class if 'CODE' eq ref $arg; return bless { coeff => $arg }, $class if 'ARRAY' eq ref $arg; bless { coeff => [$arg] }, $class; } sub coeff { my ($self, $i) = @_; my $cache = ($self->{coeff} ||= []); my $more = $self->{more}; for my $j ( @$cache .. $i ) { last unless $more; $cache->[$j] = $more->($j, $self); } $cache->[$i] or 0; } sub invert { my $orig = shift; ref($orig)->new( sub { my ($i, $self) = @_; unless( $i ) { my $a0 = $orig->coeff(0); die "Cannot invert power series with zero constant term." unless $a0; (Math::BigRat->new(1) / $a0); } else { my $sum = 0; my $terms = $self->{coeff}; for my $j (1 .. $i) { $sum += $orig->coeff($j) * $terms->[$i - $j]; } -$terms->[0] * $sum; } } ); } sub fixargs { my ($x, $y, $swap) = @_; my $class = ref $x; $y = $class->new($y) unless UNIVERSAL::isa($y, $class); ($x, $y) = ($y, $x) if $swap; ($class, $x, $y); } use overload '+' => sub { my ($class, $x, $y) = &fixargs; $class->new( sub { $x->coeff($_[0]) + $y->coeff($_[0]) } ); }, '-' => sub { my ($class, $x, $y) = &fixargs; $class->new( sub { $x->coeff($_[0]) - $y->coeff($_[0]) } ); }, '*' => sub { my ($class, $x, $y) = &fixargs; $class->new( sub { my $i = shift; my $sum = 0; $sum += $x->coeff($_) * $y->coeff($i-$_) for 0..$i; $sum; } ); }, '/' => sub { my ($class, $x, $y) = &fixargs; $x * $y->invert; }, '""' => sub { my $self = shift; my $str = $self->coeff(0); for my $i (1..10) { my $c = $self->coeff($i); next unless $c; $str .= ($c < 0) ? (" - " . (-$c)) : (" + ".$c); $str .= "x^$i"; } $str; }; sub differentiate { my $orig = shift; ref($orig)->new( sub { my $i = shift; ($i+1) * $orig->coeff($i); } ); } sub integrate { my $orig = shift; ref($orig)->new( coeff => [0], more => sub { my $i = shift; $orig->coeff($i-1) / Math::BigRat->new($i); } ); } my $sin = __PACKAGE__->new; my $cos = 1 - $sin->integrate; %$sin = %{$cos->integrate}; my $tan = $sin / $cos; my $exp = __PACKAGE__->new(); %$exp = (%{$exp->integrate}, coeff => [1]); print "sin(x) ~= $sin\n"; print "cos(x) ~= $cos\n"; print "tan(x) ~= $tan\n"; print "exp(x) ~= $exp\n"; print "sin^2 + cos^2 = ", $sin*$sin + $cos*$cos, "\n"; 1; __END__
812Formal power series
2perl
q3jx6
(require '[clojure.edn:as edn]) (def names { 0 "zero" 1 "one" 2 "two" 3 "three" 4 "four" 5 "five" 6 "six" 7 "seven" 8 "eight" 9 "nine" 10 "ten" 11 "eleven" 12 "twelve" 13 "thirteen" 14 "fourteen" 15 "fifteen" 16 "sixteen" 17 "seventeen" 18 "eighteen" 19 "nineteen" 20 "twenty" 30 "thirty" 40 "forty" 50 "fifty" 60 "sixty" 70 "seventy" 80 "eighty" 90 "ninety" 100 "hundred" 1000 "thousand" 1000000 "million" 1000000000 "billion" 1000000000000 "trillion" 1000000000000000 "quadrillion" 1000000000000000000 "quintillion" }) (def powers-of-10 (reverse (sort (filter #(clojure.string/ends-with? (str %) "00") (keys names))))) (defn name-of [n] (let [p (first (filter #(>= n %) powers-of-10))] (cond (not (nil? p)) (let [quotient (quot n p) remainder (rem n p)] (str (name-of quotient) " " (names p) (if (> remainder 0) (str " " (name-of remainder))))) (and (nil? p) (> n 20)) (let [remainder (rem n 10) tens (- n remainder)] (str (names tens) (if (> remainder 0) (str " " (name-of remainder))))) true (names n)))) (defn four-is-magic ([n] (four-is-magic n "")) ([n prefix] (let [name ((if (empty? prefix) clojure.string/capitalize identity) (name-of n)) new-prefix (str prefix (if (not (empty? prefix)) ", "))] (if (= n 4) (str new-prefix name " is magic.") (let [len (count name)] (four-is-magic len (str new-prefix name " is " (name-of len)))))))) (defn report [n] (println (str n ": " (four-is-magic n)))) (defn -main [& args] (doall (map (comp report edn/read-string) args))) (if (not= "repl" *command-line-args*) (apply -main *command-line-args*))
816Four is magic
6clojure
vpi2f
(defn fwd-diff [nums order] (nth (iterate #(map - (next %) %) nums) order))
815Forward difference
6clojure
u1dvi
''' \ For a discussion on pipe() and head() see http: ''' from itertools import islice from fractions import Fraction from functools import reduce try: from itertools import izip as zip except: pass def head(n): ''' return a generator that passes through at most n items ''' return lambda seq: islice(seq, n) def pipe(gen, *cmds): ''' pipe(a,b,c,d, ...) -> yield from ...d(c(b(a))) ''' return reduce(lambda gen, cmd: cmd(gen), cmds, gen) def sinepower(): n = 0 fac = 1 sign = +1 zero = 0 yield zero while True: n +=1 fac *= n yield Fraction(1, fac*sign) sign = -sign n +=1 fac *= n yield zero def cosinepower(): n = 0 fac = 1 sign = +1 yield Fraction(1,fac) zero = 0 while True: n +=1 fac *= n yield zero sign = -sign n +=1 fac *= n yield Fraction(1, fac*sign) def pluspower(*powergenerators): for elements in zip(*powergenerators): yield sum(elements) def minuspower(*powergenerators): for elements in zip(*powergenerators): yield elements[0] - sum(elements[1:]) def mulpower(fgen,ggen): 'From: http: a,b = [],[] for f,g in zip(fgen, ggen): a.append(f) b.append(g) yield sum(f*g for f,g in zip(a, reversed(b))) def constpower(n): yield n while True: yield 0 def diffpower(gen): 'differentiatiate power series' next(gen) for n, an in enumerate(gen, start=1): yield an*n def intgpower(k=0): 'integrate power series with constant k' def _intgpower(gen): yield k for n, an in enumerate(gen, start=1): yield an * Fraction(1,n) return _intgpower print() c = list(pipe(cosinepower(), head(10))) print(c) print() s = list(pipe(sinepower(), head(10))) print(s) integc = list(pipe(cosinepower(),intgpower(0), head(10))) integs1 = list(minuspower(pipe(constpower(1), head(10)), pipe(sinepower(),intgpower(0), head(10)))) assert s == integc, assert c == integs1,
812Formal power series
3python
s6hq9
fmt.Printf("%09.3f", 7.125)
813Formatted numeric output
0go
gw64n
printf ("%09.3f", 7.125)
813Formatted numeric output
7groovy
2bdlv
import Text.Printf main = printf "%09.3f" 7.125
813Formatted numeric output
8haskell
s6jqk
List forwardDifference(List _list) { for (int i = _list.length - 1; i > 0; i--) { _list[i] = _list[i] - _list[i - 1]; } _list.removeRange(0, 1); return _list; } void mainAlgorithms() { List _intList = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]; for (int i = _intList.length - 1; i >= 0; i--) { List _list = forwardDifference(_intList); print(_list); } }
815Forward difference
18dart
tuafa
class Fps def initialize(const: nil, delta: nil, iota: nil, init: nil, enum: nil) case when const @coeffenum = make_const(const) when delta @coeffenum = make_delta(delta) when iota @coeffenum = make_iota(iota) when init @coeffenum = make_init(init) when enum @coeffenum = enum else @coeffenum = make_const(0) end @coeffenum.instance_eval do def [](index) self.drop(index).first end end end def [](index) @coeffenum.drop(index).first end def +(other) other = convert(other) Fps.new(enum: Enumerator.new do |yielder, inx: 0| loop do yielder.yield(@coeffenum[inx] + other[inx]) inx += 1 end end.lazy) end def -(other) other = convert(other) Fps.new(enum: Enumerator.new do |yielder, inx: 0| loop do yielder.yield(@coeffenum[inx] - other[inx]) inx += 1 end end.lazy) end def *(other) other = convert(other) Fps.new(enum: Enumerator.new do |yielder, inx: 0| loop do coeff = (0..inx).reduce(0) { |sum, i| sum + (@coeffenum[i] * other[inx - i]) } yielder.yield(coeff) inx += 1 end end.lazy) end def /(other) other = convert(other) Fps.new(enum: Enumerator.new do |yielder, inx: 1| coeffs = [ Rational(@coeffenum[0], other[0]) ] yielder.yield(coeffs[-1]) loop do coeffs << Rational( @coeffenum[inx] - (1..inx).reduce(0) { |sum, i| sum + (other[i] * coeffs[inx - i]) }, other[0]) yielder.yield(coeffs[-1]) inx += 1 end end.lazy) end def deriv() Fps.new(enum: Enumerator.new do |yielder, inx: 0| iota = Fps.new(iota: 1) loop do yielder.yield(@coeffenum[inx + 1] * iota[inx]) inx += 1 end end.lazy) end def integ() Fps.new(enum: Enumerator.new do |yielder, inx: 0| iota = Fps.new(iota: 1) yielder.yield(Rational(0, 1)) loop do yielder.yield(Rational(@coeffenum[inx], iota[inx])) inx += 1 end end.lazy) end def assign(other) other = convert(other) @coeffenum = other.get_enum end def coerce(other) if other.kind_of?(Numeric) [ Fps.new(delta: other), self ] else raise TypeError 'non-numeric can\'t be coerced into FPS type' end end def to_i() @coeffenum[0].to_i end def to_f() @coeffenum[0].to_f end def to_r() @coeffenum[0].to_r end def to_s(count = 0) if count <= 0 super() else retstr = '' count.times do |inx| coeff = (@coeffenum[inx].to_r.denominator == 1)? @coeffenum[inx].to_i: @coeffenum[inx] if!(coeff.zero?) prefix = (retstr!= '')? ' ': '' coeffstr = ((coeff.abs == 1) && (inx!= 0))? '': suffix = (inx == 0)? '': (inx == 1)? 'x': if coeff < 0 prefix << ((retstr!= '')? '- ': '-') else prefix << ((retstr!= '')? '+ ': '') end retstr << end end (retstr == '')? '0': retstr end end def eval(x, count) @coeffenum.first(count).each_with_index.reduce(0) { |sum, (coeff, inx) | sum + coeff * x**inx } end def method_missing(name, *args, &block) @coeffenum.send(name, *args, &block) end def respond_to_missing?(name, incl_priv) @coeffenum.respond_to?(name, incl_priv) end protected def get_enum() @coeffenum end private def make_const(n) Enumerator.new do |yielder| loop { yielder.yield(n) } end.lazy end def make_delta(n) Enumerator.new do |yielder| yielder.yield(n) loop { yielder.yield(0) } end.lazy end def make_iota(n) Enumerator.new do |yielder, i: n| loop { yielder.yield(i); i += 1 } end.lazy end def make_init(array) Enumerator.new do |yielder, inx: -1| loop { yielder.yield((inx < (array.length - 1))? array[inx += 1]: 0) } end.lazy end def convert(other) if other.kind_of?(Fps) other else if other.kind_of?(Numeric) Fps.new(delta: other) else raise TypeError 'non-numeric can\'t be converted to FPS type' end end end end
812Formal power series
14ruby
8mb01
package main import ( "fmt" "math" "strings" ) func main() { for _, n := range [...]int64{ 0, 4, 6, 11, 13, 75, 100, 337, -164, math.MaxInt64, } { fmt.Println(fourIsMagic(n)) } } func fourIsMagic(n int64) string { s := say(n) s = strings.ToUpper(s[:1]) + s[1:] t := s for n != 4 { n = int64(len(s)) s = say(n) t += " is " + s + ", " + s } t += " is magic." return t }
816Four is magic
0go
ad21f
module Main where import Data.List (find) import Data.Char (toUpper) firstNums :: [String] firstNums = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ] tens :: [String] tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] biggerNumbers :: [(Int, String)] biggerNumbers = [(100, "hundred"), (1000, "thousand"), (1000000, "million"), (1000000000, "billion"), (1000000000000, "trillion")] cardinal :: Int -> String cardinal n | n' < 20 = negText ++ firstNums!! n' | n' < 100 = negText ++ tens!! (n' `div` 10 - 2) ++ if n' `mod` 10 /= 0 then "-" ++ firstNums!! (n' `mod` 10) else "" | otherwise = let (num, name) = maybe (last biggerNumbers) fst (find (\((num_, _), (num_', _)) -> n' < num_') (zip biggerNumbers (tail biggerNumbers))) smallerNum = cardinal (n' `div` num) in negText ++ smallerNum ++ " " ++ name ++ if n' `mod` num /= 0 then " " ++ cardinal (n' `mod` num) else "" where n' = abs n negText = if n < 0 then "negative " else "" capitalized:: String -> String capitalized (x: xs) = toUpper x: xs capitalized [] = [] magic:: Int -> String magic = go True where go first num = let cardiNum = cardinal num in (if first then capitalized else id) cardiNum ++ " is " ++ if num == 4 then "magic." else cardinal (length cardiNum) ++ ", " ++ go False (length cardiNum) main:: IO () main = do putStrLn $ magic 3 putStrLn $ magic 15 putStrLn $ magic 4 putStrLn $ magic 10 putStrLn $ magic 20 putStrLn $ magic (-13) putStrLn $ magic 999999
816Four is magic
8haskell
z5at0
sub multiply { return $_[0] * $_[1] }
808Function definition
2perl
h05jl
public class Printing{ public static void main(String[] args){ double value = 7.125; System.out.printf("%09.3f",value);
813Formatted numeric output
9java
1nup2
var n = 123; var str = ("00000" + n).slice(-5); alert(str);
813Formatted numeric output
10javascript
q37x8
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() {
814Four bit adder
0go
s67qa
class Main { static void main(args) { def bit1, bit2, bit3, bit4, carry def fourBitAdder = new FourBitAdder( { value -> bit1 = value }, { value -> bit2 = value }, { value -> bit3 = value }, { value -> bit4 = value }, { value -> carry = value } )
814Four bit adder
7groovy
adu1p
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { String magic = fourIsMagic(n); System.out.printf("%d =%s%n", n, toSentence(magic)); } } private static final String toSentence(String s) { return s.substring(0,1).toUpperCase() + s.substring(1) + "."; } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String fourIsMagic(long n) { if ( n == 4 ) { return numToString(n) + " is magic"; } String result = numToString(n); return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length()); } private static final String numToString(long n) { if ( n < 0 ) { return "negative " + numToString(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : ""); } }
816Four is magic
9java
o9j8d
null
813Formatted numeric output
11kotlin
js97r
import Control.Arrow import Data.List (mapAccumR) bor, band :: Int -> Int -> Int bor = max band = min bnot :: Int -> Int bnot = (1-)
814Four bit adder
8haskell
9j8mo
Object.getOwnPropertyNames(this).includes('BigInt')
816Four is magic
10javascript
tu1fm
typedef struct{ int sourceVertex, destVertex; int edgeWeight; }edge; typedef struct{ int vertices, edges; edge* edgeMatrix; }graph; graph loadGraph(char* fileName){ FILE* fp = fopen(fileName,); graph G; int i; fscanf(fp,,&G.vertices,&G.edges); G.edgeMatrix = (edge*)malloc(G.edges*sizeof(edge)); for(i=0;i<G.edges;i++) fscanf(fp,,&G.edgeMatrix[i].sourceVertex,&G.edgeMatrix[i].destVertex,&G.edgeMatrix[i].edgeWeight); fclose(fp); return G; } void floydWarshall(graph g){ int processWeights[g.vertices][g.vertices], processedVertices[g.vertices][g.vertices]; int i,j,k; for(i=0;i<g.vertices;i++) for(j=0;j<g.vertices;j++){ processWeights[i][j] = SHRT_MAX; processedVertices[i][j] = (i!=j)?j+1:0; } for(i=0;i<g.edges;i++) processWeights[g.edgeMatrix[i].sourceVertex-1][g.edgeMatrix[i].destVertex-1] = g.edgeMatrix[i].edgeWeight; for(i=0;i<g.vertices;i++) for(j=0;j<g.vertices;j++) for(k=0;k<g.vertices;k++){ if(processWeights[j][i] + processWeights[i][k] < processWeights[j][k]){ processWeights[j][k] = processWeights[j][i] + processWeights[i][k]; processedVertices[j][k] = processedVertices[j][i]; } } printf(); for(i=0;i<g.vertices;i++) for(j=0;j<g.vertices;j++){ if(i!=j){ printf(,i+1,j+1,processWeights[i][j],i+1); k = i+1; do{ k = processedVertices[k-1][j]; printf(,k); }while(k!=j+1); } } } int main(int argC,char* argV[]){ if(argC!=2) printf(); else floydWarshall(loadGraph(argV[1])); return 0; }
817Floyd-Warshall algorithm
5c
4ed5t
function multiply( $a, $b ) { return $a * $b; }
808Function definition
12php
z5ot1
null
816Four is magic
11kotlin
xz5ws
function digits(n) return math.floor(math.log(n) / math.log(10))+1 end function fixedprint(num, digs)
813Formatted numeric output
1lua
h0cj8
null
816Four is magic
1lua
q34x0
package main import ( "fmt" "log" "os" "os/exec" ) func reverseBytes(bytes []byte) { for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { bytes[i], bytes[j] = bytes[j], bytes[i] } } func check(err error) { if err != nil { log.Fatal(err) } } func main() { in, err := os.Open("infile.dat") check(err) defer in.Close() out, err := os.Create("outfile.dat") check(err) record := make([]byte, 80) empty := make([]byte, 80) for { n, err := in.Read(record) if err != nil { if n == 0 { break
818Fixed length records
0go
8mg0g
package main import "fmt" func main() { a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73} fmt.Println(a) fmt.Println(fd(a, 9)) } func fd(a []int, ord int) []int { for i := 0; i < ord; i++ { for j := 0; j < len(a)-i-1; j++ { a[j] = a[j+1] - a[j] } } return a[:len(a)-ord] }
815Forward difference
0go
efua6
public class GateLogic {
814Four bit adder
9java
tuef9
null
818Fixed length records
1lua
d2hnq
forwardDifference :: Num a => [a] -> [a] forwardDifference = tail >>= zipWith (-) nthForwardDifference :: Num a => [a] -> Int -> [a] nthForwardDifference = (!!) . iterate forwardDifference main :: IO () main = mapM_ print $ take 10 (iterate forwardDifference [90, 47, 58, 29, 22, 32, 55, 5, 55, 73])
815Forward difference
8haskell
34wzj
function acceptedBinFormat(bin) { if (bin == 1 || bin === 0 || bin === '0') return true; else return bin; } function arePseudoBin() { var args = [].slice.call(arguments), len = args.length; while(len--) if (acceptedBinFormat(args[len]) !== true) throw new Error('argument must be 0, \'0\', 1, or \'1\', argument ' + len + ' was ' + args[len]); return true; }
814Four bit adder
10javascript
m70yv
int main() { int i,j; for (j=1; j<1000; j++) { for (i=0; i<j, i++) { if (exit_early()) goto out; } } out: return 0; }
819Flow-control structures
5c
q3vxc
use Lingua::EN::Numbers qw(num2en); sub cardinal { my($n) = @_; (my $en = num2en($n)) =~ s/\ and|,//g; $en; } sub magic { my($int) = @_; my $str; while () { $str .= cardinal($int) . " is "; if ($int == 4) { $str .= "magic.\n"; last } else { $int = length cardinal($int); $str .= cardinal($int) . ", "; } } ucfirst $str; } print magic($_) for 0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209;
816Four is magic
2perl
2bolf
int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(); for(i = 0; i < sz; i++) printf(, i); printf(); for(i = 1; i <= sz; i++) { printf(, i-1); for(j = 0; j < sz; j++) printf(, b[i][j]); printf(); } printf(); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf(); printb(t, sz); printf(); printb(b, sz); printf(); scanf(, &roc); scanf(, &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror(); break; } printf(, ++mov); if(eq(t, b, sz)) { printf(); eql = 1; } } }
820Flipping bits game
5c
34bza
import random from collections import OrderedDict numbers = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred', 1000: 'thousand', 10 ** 6: 'million', 10 ** 9: 'billion', 10 ** 12: 'trillion', 10 ** 15: 'quadrillion', 10 ** 18: 'quintillion', 10 ** 21: 'sextillion', 10 ** 24: 'septillion', 10 ** 27: 'octillion', 10 ** 30: 'nonillion', 10 ** 33: 'decillion', 10 ** 36: 'undecillion', 10 ** 39: 'duodecillion', 10 ** 42: 'tredecillion', 10 ** 45: 'quattuordecillion', 10 ** 48: 'quinquadecillion', 10 ** 51: 'sedecillion', 10 ** 54: 'septendecillion', 10 ** 57: 'octodecillion', 10 ** 60: 'novendecillion', 10 ** 63: 'vigintillion', 10 ** 66: 'unvigintillion', 10 ** 69: 'duovigintillion', 10 ** 72: 'tresvigintillion', 10 ** 75: 'quattuorvigintillion', 10 ** 78: 'quinquavigintillion', 10 ** 81: 'sesvigintillion', 10 ** 84: 'septemvigintillion', 10 ** 87: 'octovigintillion', 10 ** 90: 'novemvigintillion', 10 ** 93: 'trigintillion', 10 ** 96: 'untrigintillion', 10 ** 99: 'duotrigintillion', 10 ** 102: 'trestrigintillion', 10 ** 105: 'quattuortrigintillion', 10 ** 108: 'quinquatrigintillion', 10 ** 111: 'sestrigintillion', 10 ** 114: 'septentrigintillion', 10 ** 117: 'octotrigintillion', 10 ** 120: 'noventrigintillion', 10 ** 123: 'quadragintillion', 10 ** 153: 'quinquagintillion', 10 ** 183: 'sexagintillion', 10 ** 213: 'septuagintillion', 10 ** 243: 'octogintillion', 10 ** 273: 'nonagintillion', 10 ** 303: 'centillion', 10 ** 306: 'uncentillion', 10 ** 309: 'duocentillion', 10 ** 312: 'trescentillion', 10 ** 333: 'decicentillion', 10 ** 336: 'undecicentillion', 10 ** 363: 'viginticentillion', 10 ** 366: 'unviginticentillion', 10 ** 393: 'trigintacentillion', 10 ** 423: 'quadragintacentillion', 10 ** 453: 'quinquagintacentillion', 10 ** 483: 'sexagintacentillion', 10 ** 513: 'septuagintacentillion', 10 ** 543: 'octogintacentillion', 10 ** 573: 'nonagintacentillion', 10 ** 603: 'ducentillion', 10 ** 903: 'trecentillion', 10 ** 1203: 'quadringentillion', 10 ** 1503: 'quingentillion', 10 ** 1803: 'sescentillion', 10 ** 2103: 'septingentillion', 10 ** 2403: 'octingentillion', 10 ** 2703: 'nongentillion', 10 ** 3003: 'millinillion' } numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True)) def string_representation(i: int) -> str: if i == 0: return 'zero' words = ['negative'] if i < 0 else [] working_copy = abs(i) for key, value in numbers.items(): if key <= working_copy: times = int(working_copy / key) if key >= 100: words.append(string_representation(times)) words.append(value) working_copy -= times * key if working_copy == 0: break return ' '.join(words) def next_phrase(i: int): while not i == 4: str_i = string_representation(i) len_i = len(str_i) yield str_i, 'is', string_representation(len_i) i = len_i yield string_representation(i), 'is', 'magic' def magic(i: int) -> str: phrases = [] for phrase in next_phrase(i): phrases.append(' '.join(phrase)) return f'{.join(phrases)}.'.capitalize() if __name__ == '__main__': for j in (random.randint(0, 10 ** 3) for i in range(5)): print(j, ':\n', magic(j), '\n') for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)): print(j, ':\n', magic(j), '\n')
816Four is magic
3python
vpi29
open $in, '<', 'flr-infile.dat'; open $out, '>', 'flr-outfile.dat'; while ($n=sysread($in, $record, 80)) { syswrite $out, reverse $record; print reverse($record)."\n" } close $out;
818Fixed length records
2perl
7qtrh
infile = open('infile.dat', 'rb') outfile = open('outfile.dat', 'wb') while True: onerecord = infile.read(80) if len(onerecord) < 80: break onerecordreversed = bytes(reversed(onerecord)) outfile.write(onerecordreversed) infile.close() outfile.close()
818Fixed length records
3python
jsz7p
import java.util.Arrays; public class FD { public static void main(String args[]) { double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; System.out.println(Arrays.toString(dif(a, 1))); System.out.println(Arrays.toString(dif(a, 2))); System.out.println(Arrays.toString(dif(a, 9))); System.out.println(Arrays.toString(dif(a, 10)));
815Forward difference
9java
ickos
null
814Four bit adder
11kotlin
o9k8z
uint8_t *field[2], swapu; double prob_f = PROB_F, prob_p = PROB_P, prob_tree = PROB_TREE; enum cell_state { VOID, TREE, BURNING }; double prand() { return (double)rand() / (RAND_MAX + 1.0); } void init_field(void) { int i, j; swapu = 0; for(i = 0; i < WIDTH; i++) { for(j = 0; j < HEIGHT; j++) { *(field[0] + j*WIDTH + i) = prand() > prob_tree ? VOID : TREE; } } } bool burning_neighbor(int, int); pthread_mutex_t synclock = PTHREAD_MUTEX_INITIALIZER; static uint32_t simulate(uint32_t iv, void *p) { int i, j; pthread_mutex_lock(&synclock); for(i = 0; i < WIDTH; i++) { for(j = 0; j < HEIGHT; j++) { enum cell_state s = *(field[swapu] + j*WIDTH + i); switch(s) { case BURNING: *(field[swapu^1] + j*WIDTH + i) = VOID; break; case VOID: *(field[swapu^1] + j*WIDTH + i) = prand() > prob_p ? VOID : TREE; break; case TREE: if (burning_neighbor(i, j)) *(field[swapu^1] + j*WIDTH + i) = BURNING; else *(field[swapu^1] + j*WIDTH + i) = prand() > prob_f ? TREE : BURNING; break; default: fprintf(stderr, ); break; } } } swapu ^= 1; pthread_mutex_unlock(&synclock); return iv; } ? (*(field[swapu] + (J)*WIDTH + (I)) == BURNING): false) bool burning_neighbor(int i, int j) { return NB(i-1,j-1) || NB(i-1, j) || NB(i-1, j+1) || NB(i, j-1) || NB(i, j+1) || NB(i+1, j-1) || NB(i+1, j) || NB(i+1, j+1); } void show(SDL_Surface *s) { int i, j; uint8_t *pixels = (uint8_t *)s->pixels; uint32_t color; SDL_PixelFormat *f = s->format; pthread_mutex_lock(&synclock); for(i = 0; i < WIDTH; i++) { for(j = 0; j < HEIGHT; j++) { switch(*(field[swapu] + j*WIDTH + i)) { case VOID: color = SDL_MapRGBA(f, 0,0,0,255); break; case TREE: color = SDL_MapRGBA(f, 0,255,0,255); break; case BURNING: color = SDL_MapRGBA(f, 255,0,0,255); break; } *(uint32_t*)(pixels + j*s->pitch + i*(BPP>>3)) = color; } } pthread_mutex_unlock(&synclock); } int main(int argc, char **argv) { SDL_Surface *scr = NULL; SDL_Event event[1]; bool quit = false, running = false; SDL_TimerID tid; srand(time(NULL)); double *p; for(argv++, argc--; argc > 0; argc--, argv++) { if ( strcmp(*argv, ) == 0 && argc > 1 ) { p = &prob_f; } else if ( strcmp(*argv, ) == 0 && argc > 1 ) { p = &prob_p; } else if ( strcmp(*argv, ) == 0 && argc > 1 ) { p = &prob_tree; } else continue; argv++; argc--; char *s = NULL; double t = strtod(*argv, &s); if (s != *argv) *p = t; } printf(, prob_f, prob_p, prob_p/prob_f, prob_tree); if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0 ) return EXIT_FAILURE; atexit(SDL_Quit); field[0] = malloc(WIDTH*HEIGHT); if (field[0] == NULL) exit(EXIT_FAILURE); field[1] = malloc(WIDTH*HEIGHT); if (field[1] == NULL) { free(field[0]); exit(EXIT_FAILURE); } scr = SDL_SetVideoMode(WIDTH, HEIGHT, BPP, SDL_HWSURFACE|SDL_DOUBLEBUF); if (scr == NULL) { fprintf(stderr, , SDL_GetError()); free(field[0]); free(field[1]); exit(EXIT_FAILURE); } init_field(); tid = SDL_AddTimer(TIMERFREQ, simulate, NULL); running = true; event->type = SDL_VIDEOEXPOSE; SDL_PushEvent(event); while(SDL_WaitEvent(event) && !quit) { switch(event->type) { case SDL_VIDEOEXPOSE: while(SDL_LockSurface(scr) != 0) SDL_Delay(1); show(scr); SDL_UnlockSurface(scr); SDL_Flip(scr); event->type = SDL_VIDEOEXPOSE; SDL_PushEvent(event); break; case SDL_KEYDOWN: switch(event->key.keysym.sym) { case SDLK_q: quit = true; break; case SDLK_p: if (running) { running = false; pthread_mutex_lock(&synclock); SDL_RemoveTimer(tid); pthread_mutex_unlock(&synclock); } else { running = true; tid = SDL_AddTimer(TIMERFREQ, simulate, NULL); } break; } case SDL_QUIT: quit = true; break; } } if (running) { pthread_mutex_lock(&synclock); SDL_RemoveTimer(tid); pthread_mutex_unlock(&synclock); } free(field[0]); free(field[1]); exit(EXIT_SUCCESS); }
821Forest fire
5c
rxig7
(defn cols [board] (mapv vec (apply map list board))) (defn flipv [v] (mapv #(if (> % 0) 0 1) v)) (defn flip-row [board n] (assoc board n (flipv (get board n)))) (defn flip-col [board n] (cols (flip-row (cols board) n))) (defn play-rand [board n] (if (= n 0) board (let [f (if (= (rand-int 2) 0) flip-row flip-col)] (recur (f board (rand-int (count board))) (dec n))))) (defn rand-binary-vec [size] (vec (take size (repeatedly #(rand-int 2))))) (defn rand-binary-board [size] (vec (take size (repeatedly #(rand-binary-vec size))))) (defn numbers->letters [coll] (map #(char (+ 97 %)) coll)) (defn column-labels [size] (apply str (interpose " " (numbers->letters (range size))))) (defn print-board [board] (let [size (count board)] (println "\t " (column-labels size)) (dotimes [n size] (println (inc n) "\t" (board n))))) (defn key->move [key] (let [start (int (first key)) row-value (try (Long/valueOf key) (catch NumberFormatException e))] (cond (<= 97 start 122) [:col (- start 97)] (<= 65 start 90) [:col (- start 65)] (> row-value 0) [:row (dec row-value)] :else nil))) (defn play-game [target-board current-board n] (println "\nTurn " n) (print-board current-board) (if (= target-board current-board) (println "You win!") (let [move (key->move (read-line)) axis (first move) idx (second move)] (cond (= axis:row) (play-game target-board (flip-row current-board idx) (inc n)) (= axis:col) (play-game target-board (flip-col current-board idx) (inc n)) :else (println "Quitting!"))))) (defn -main "Flip the Bits Game!" [& args] (if-not (empty? args) (let [target-board (rand-binary-board (Long/valueOf (first args)))] (println "Target") (print-board target-board) (play-game target-board (play-rand target-board 3) 0))))
820Flipping bits game
6clojure
chw9b
integerToText <- function(value_n_1) { english_words_for_numbers <- list( simples = c( 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ), tens = c('twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'), powers = c( 'hundred' = 100, 'thousand' = 1000, 'million' = 1000000, 'billion' = 1000000000, 'trillion' = 1000000000000, 'quadrillion' = 1000000000000000, 'quintillion' = 1000000000000000000 ) ) buildResult <- function(x_s) { if (value_n_1 < 0) return(paste('minus', x_s)) x_s } withDash <- function(a_s, b_s) paste(a_s, b_s, sep = '-') val <- abs(value_n_1) if (val < 20L) return(buildResult(english_words_for_numbers$simples[val + 1L])) if (val < 100L) { tens <- val%/% 10L - 1L reminder <- val%% 10L if (reminder == 0L) return(buildResult(english_words_for_numbers$ten[tens])) return(buildResult(withDash(english_words_for_numbers$ten[tens], Recall(reminder)))) } index <- l <- length(english_words_for_numbers$powers) for(power in seq_len(l)) { if (val < english_words_for_numbers$powers[power]) { index <- power - 1L break } } f <- Recall(val%/% english_words_for_numbers$powers[index]) reminder <- val%% english_words_for_numbers$powers[index] if (reminder == 0L) return(buildResult(paste(f, names(english_words_for_numbers$powers)[index]))) buildResult(paste(f, names(english_words_for_numbers$powers)[index], Recall(reminder))) } magic <- function(value_n_1) { text <- vector('character') while(TRUE) { r <- integerToText(value_n_1) nc <- nchar(r) complement <- ifelse(value_n_1 == 4L, "is magic", paste("is", integerToText(nc))) text[length(text) + 1L] <- paste(r, complement) if (value_n_1 == 4L) break value_n_1 <- nc } buildSentence <- function(x_s) paste0(toupper(substr(x_s, 1L, 1L)), substring(x_s, 2L), '.') buildSentence(paste(text, collapse = ', ')) }
816Four is magic
13r
9jsmg
open(, ) do |out_f| open() do |in_f| while record = in_f.read(80) out_f << record.reverse end end end
818Fixed length records
14ruby
k86hg
(() => { 'use strict';
815Forward difference
10javascript
z5et2
use std::fs::File; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; fn reverse_file( input_filename: &str, output_filename: &str, record_len: usize, ) -> std::io::Result<()> { let mut input = BufReader::new(File::open(input_filename)?); let mut output = BufWriter::new(File::create(output_filename)?); let mut buffer = vec![0; record_len]; while input.read(&mut buffer)? == record_len { buffer.reverse(); output.write_all(&buffer)?; } output.flush()?; Ok(()) } fn main() { match reverse_file("infile.dat", "outfile.dat", 80) { Ok(()) => {} Err(error) => eprintln!("I/O error: {}", error), } }
818Fixed length records
15rust
boykx
def multiply(a, b): return a * b
808Function definition
3python
k84hf
int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val; test++; val = (int)(factor * pow(10.0, fmod(test * logv, 1))); if (val == l) { n--; } } return test; } void runTest(int l, int n) { printf(, l, n, p(l, n)); } int main() { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(123, 678910); return 0; }
822First power of 2 that has leading decimal digits of 12
5c
8mv04