code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
cat("")
135Terminal control/Display an extended character
13r
saoqy
use warnings; use strict; use Math::Random::ISAAC; my $message = "a Top Secret secret"; my $key = "this is my secret key"; my $enc = xor_isaac($key, $message); my $dec = xor_isaac($key, join "", pack "H*", $enc); print "Message: $message\n"; print "Key : $key\n"; print "XOR : $enc\n"; print "XOR dcr: ", join("", pack "H*", $dec), "\n"; sub xor_isaac { my($key, $msg) = @_; my $rng = Math::Random::ISAAC->new( map { ord } split "",$key ); my @iranda = map { $_ % 95 + 32 } reverse map { $rng->irand } 0..255; join "", map { sprintf "%02X",$_ } map { ord($_) ^ shift(@iranda) } split "", $msg; }
128The ISAAC Cipher
2perl
q1zx6
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5e-2) False >>> isint(float('nan')) False >>> isint(float('inf')) False >>> isint(5.0+0.0j) True >>> isint(5-5j) False
129Test integerness
3python
zivtt
(let [numbers '(first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth) gifts ["And a partridge in a pear tree", "Two turtle doves", "Three French hens", "Four calling birds", "Five gold rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming"] day (fn [n] (printf "On the%s day of Christmas, my true love sent to me\n" (nth numbers n)))] (day 0) (println (clojure.string/replace (first gifts) "And a" "A")) (dorun (for [d (range 1 12)] (do (println) (day d) (dorun (for [n (range d -1 -1)] (println (nth gifts n))))))))
139The Twelve Days of Christmas
6clojure
nqoik
use Term::Size; ($cols, $rows) = Term::Size::chars; print "The terminal has $cols columns and $rows lines\n";
137Terminal control/Dimensions
2perl
kgbhc
puts
135Terminal control/Display an extended character
14ruby
d0zns
object ExtendedCharacter extends App { println("") println("") }
135Terminal control/Display an extended character
16scala
3nmzy
out, max_out, max_times = 0, -1, [] for job in open('mlijobs.txt'): out += 1 if in job else -1 if out > max_out: max_out, max_times = out, [] if out == max_out: max_times.append(job.split()[3]) print(% max_out) print(' ' + '\n '.join(max_times))
125Text processing/Max licenses in use
3python
g2q4h
char *strings[] = {, , , , , , , }; int main() { int i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; clrscr(); cprintf(); getch(); for(i=0;i<8;i++) { clrscr(); gotoxy(5,MAXROW/2); cprintf(,strings[i]); getch(); switch(i){ case 0:gotoxy(wherex()-1,wherey()); break; case 1:gotoxy(wherex()+1,wherey()); break; case 2:gotoxy(wherex(),wherey()-1); break; case 3:gotoxy(wherex(),wherey()+1); break; case 4:for(j=0;j<strlen(strings[i]);j++){ gotoxy(wherex()-1,wherey()); delay(100); } break; case 5:gotoxy(wherex()-strlen(strings[i]),wherey()); for(j=0;j<strlen(strings[i]);j++){ gotoxy(wherex()+1,wherey()); delay(100); } break; case 6:while(wherex()!=1) { gotoxy(wherex()-1,wherey()); delay(100); } while(wherey()!=1) { gotoxy(wherex(),wherey()-1); delay(100); } break; case 7:while(wherex()!=MAXCOL) { gotoxy(wherex()+1,wherey()); delay(100); } while(wherey()!=MAXROW) { gotoxy(wherex(),wherey()+1); delay(100); } break; }; getch(); } clrscr(); cprintf(); getch(); return 0; }
141Terminal control/Cursor movement
5c
17hpj
use Term::Cap; my $t = Term::Cap->Tgetent; print $t->Tgoto("cm", 2, 5); print "Hello";
140Terminal control/Cursor positioning
2perl
f0id7
dfr <- read.table("mlijobs.txt") dfr <- dfr[,c(2,4)] n.checked.out <- cumsum(ifelse(dfr$V2=="OUT", 1, -1)) times <- strptime(dfr$V4, "%Y/%m/%d_%H:%M:%S") most.checked.out <- max(n.checked.out) when.most.checked.out <- times[which(n.checked.out==most.checked.out)] plot(times, n.checked.out, type="s")
125Text processing/Max licenses in use
13r
vma27
import os def get_windows_terminal(): from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if not res: return 80, 25 import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\ = struct.unpack(, csbi.raw) width = right - left + 1 height = bottom - top + 1 return width, height def get_linux_terminal(): width = os.popen('tput cols', 'r').readline() height = os.popen('tput lines', 'r').readline() return int(width), int(height) print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
137Terminal control/Dimensions
3python
brpkr
void table(const char *title, const char *mode) { int f, b; printf(, title); for (b = 40; b <= 107; b++) { if (b == 48) b = 100; printf(, b, mode, b); for (f = 30; f <= 97; f++) { if (f == 38) f = 90; printf(, f, f); } puts(); } } int main(void) { int fg, bg, blink, inverse; table(, ); table(, ); table(, ); table(, ); table(, ); table(, ); table(, ); return 0; }
142Terminal control/Coloured text
5c
t8of4
echo .$x..$y.; echo .$n.; echo .$n.; echo .$n.; echo .$n.; echo ;
140Terminal control/Cursor positioning
12php
h5rjf
import random import collections INT_MASK = 0xFFFFFFFF class IsaacRandom(random.Random): def seed(self, seed=None): def mix(): init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_state[1] &= INT_MASK init_state[1] ^= (init_state[2]>>2) ; init_state[4] += init_state[1]; init_state[4] &= INT_MASK; init_state[2] += init_state[3]; init_state[2] &= INT_MASK init_state[2] ^= ((init_state[3]<<8 )&INT_MASK); init_state[5] += init_state[2]; init_state[5] &= INT_MASK; init_state[3] += init_state[4]; init_state[3] &= INT_MASK init_state[3] ^= (init_state[4]>>16) ; init_state[6] += init_state[3]; init_state[6] &= INT_MASK; init_state[4] += init_state[5]; init_state[4] &= INT_MASK init_state[4] ^= ((init_state[5]<<10)&INT_MASK); init_state[7] += init_state[4]; init_state[7] &= INT_MASK; init_state[5] += init_state[6]; init_state[5] &= INT_MASK init_state[5] ^= (init_state[6]>>4 ) ; init_state[0] += init_state[5]; init_state[0] &= INT_MASK; init_state[6] += init_state[7]; init_state[6] &= INT_MASK init_state[6] ^= ((init_state[7]<<8 )&INT_MASK); init_state[1] += init_state[6]; init_state[1] &= INT_MASK; init_state[7] += init_state[0]; init_state[7] &= INT_MASK init_state[7] ^= (init_state[0]>>9 ) ; init_state[2] += init_state[7]; init_state[2] &= INT_MASK; init_state[0] += init_state[1]; init_state[0] &= INT_MASK super().seed(0) if seed is not None: if isinstance(seed, str): seed = [ord(x) for x in seed] elif isinstance(seed, collections.Iterable): seed = [x & INT_MASK for x in seed] elif isinstance(seed, int): val = abs(seed) seed = [] while val: seed.append(val & INT_MASK) val >>= 32 else: raise TypeError('Seed must be string, integer or iterable of integer') if len(seed)>256: del seed[256:] elif len(seed)<256: seed.extend([0]*(256-len(seed))) self.aa = self.bb = self.cc = 0 self.mm = [] init_state = [0x9e3779b9]*8 for _ in range(4): mix() for i in range(0, 256, 8): if seed is not None: for j in range(8): init_state[j] += seed[i+j] init_state[j] &= INT_MASK mix() self.mm += init_state if seed is not None: for i in range(0, 256, 8): for j in range(8): init_state[j] += self.mm[i+j] init_state[j] &= INT_MASK mix() for j in range(8): self.mm[i+j] = init_state[j] self.rand_count = 256 self.rand_result = [0]*256 def getstate(self): return super().getstate(), self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result def setstate(self, state): super().setstate(state[0]) _, self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result = state def _generate(self): self.cc = (self.cc + 1) & INT_MASK self.bb = (self.bb + self.cc) & INT_MASK for i in range(256): x = self.mm[i] mod = i & 3 if mod==0: self.aa ^= ((self.aa << 13) & INT_MASK) elif mod==1: self.aa ^= (self.aa >> 6) elif mod==2: self.aa ^= ((self.aa << 2) & INT_MASK) else: self.aa ^= (self.aa >> 16) self.aa = (self.mm[i^128] + self.aa) & INT_MASK y = self.mm[i] = (self.mm[(x>>2) & 0xFF] + self.aa + self.bb) & INT_MASK self.rand_result[i] = self.bb = (self.mm[(y>>10) & 0xFF] + x) & INT_MASK self.rand_count = 0 def next_int(self): if self.rand_count == 256: self._generate() result = self.rand_result[self.rand_count] self.rand_count += 1 return result def getrandbits(self, k): result = 0 ints_needed = (k+31) ints_used = 0 while ints_used < ints_needed: if self.rand_count == 256: self._generate() ints_to_take = min(256-self.rand_count, ints_needed) for val in self.rand_result[self.rand_count: self.rand_count+ints_to_take]: result = (result << 32) | val self.rand_count += ints_to_take ints_used += ints_to_take result &= ((1<<k)-1) return result def random(self): return self.getrandbits(53) * (2**-53) def rand_char(self): return self.next_int()% 95 + 32 def vernam(self, msg): return bytes((self.rand_char() & 0xFF) ^ x for x in msg) ENCIPHER = 'encipher' DECIPHER = 'decipher' @staticmethod def _caesar(ciphermode, ch, shift, modulo, start): if ciphermode == IsaacRandom.DECIPHER: shift = -shift n = ((ch-start)+shift)% modulo if n<0: n += modulo return start+n def caesar(self, ciphermode, msg, modulo, start): return bytes(self._caesar(ciphermode, ch, self.rand_char(), modulo, start) for ch in msg) if __name__=='__main__': import binascii def hexify(b): return binascii.hexlify(b).decode('ascii').upper() MOD = 95 START = 32 msg = 'a Top Secret secret' key = 'this is my secret key' isaac_random = IsaacRandom(key) vernam_encoded = isaac_random.vernam(msg.encode('ascii')) caesar_encoded = isaac_random.caesar(IsaacRandom.ENCIPHER, msg.encode('ascii'), MOD, START) isaac_random.seed(key) vernam_decoded = isaac_random.vernam(vernam_encoded).decode('ascii') caesar_decoded = isaac_random.caesar(IsaacRandom.DECIPHER, caesar_encoded, MOD, START).decode('ascii') print('Message:', msg) print('Key :', key) print('XOR :', hexify(vernam_encoded)) print('XOR dcr:', vernam_decoded) print('MOD :', hexify(caesar_encoded)) print('MOD dcr:', caesar_decoded)
128The ISAAC Cipher
3python
sa3q9
class Numeric def to_i? self == self.to_i rescue false end end ar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, Float::NAN, Float::INFINITY, 2r, 2.5r, 2+0i, 2+0.0i, 5-5i] ar.each{|num| puts }
129Test integerness
14ruby
6d53t
use strict; use warnings; use Test; my %tests; BEGIN { %tests = ( 'A man, a plan, a canal: Panama.' => 1, 'My dog has fleas' => 0, "Madam, I'm Adam." => 1, '1 on 1' => 0, 'In girum imus nocte et consumimur igni' => 1, '' => 1, ); plan tests => (keys(%tests) * 4); } use Palindrome; for my $key (keys %tests) { $_ = lc $key; s/[\W_]//g; my $expect = $tests{$key}; my $note = ("\"$key\" should " . ($expect ? '' : 'not ') . "be a palindrome."); ok palindrome == $expect, 1, "palindrome: $note"; ok palindrome_c == $expect, 1, "palindrome_c: $note"; ok palindrome_r == $expect, 1, "palindrome_r: $note"; ok palindrome_e == $expect, 1, "palindrome_e: $note"; }
130Test a function
2perl
g214e
def winsize require 'io/console' IO.console.winsize rescue LoadError [Integer(`tput li`), Integer(`tput co`)] end rows, cols = winsize printf , rows, cols
137Terminal control/Dimensions
14ruby
1japw
package main import ( "fmt" "time" "os" "os/exec" "strconv" ) func main() { tput("clear")
141Terminal control/Cursor movement
0go
ydt64
print()
140Terminal control/Cursor positioning
3python
t8nfw
int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(file, , &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return NULL; } GPtrArray* dict = g_ptr_array_new_full(1024, g_free); GString* line = g_string_sized_new(64); gsize term_pos; while (g_io_channel_read_line_string(channel, line, &term_pos, &error) == G_IO_STATUS_NORMAL) { char* word = g_strdup(line->str); word[term_pos] = '\0'; g_ptr_array_add(dict, word); } g_string_free(line, TRUE); g_io_channel_unref(channel); if (error != NULL) { g_propagate_error(error_ptr, error); g_ptr_array_free(dict, TRUE); return NULL; } g_ptr_array_sort(dict, string_compare); return dict; } void rotate(char* str, size_t len) { char c = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = c; } char* dictionary_search(const GPtrArray* dictionary, const char* word) { char** result = bsearch(&word, dictionary->pdata, dictionary->len, sizeof(char*), string_compare); return result != NULL ? *result : NULL; } void find_teacup_words(GPtrArray* dictionary) { GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal); GPtrArray* teacup_words = g_ptr_array_new(); GString* temp = g_string_sized_new(8); for (size_t i = 0, n = dictionary->len; i < n; ++i) { char* word = g_ptr_array_index(dictionary, i); size_t len = strlen(word); if (len < 3 || g_hash_table_contains(found, word)) continue; g_ptr_array_set_size(teacup_words, 0); g_string_assign(temp, word); bool is_teacup_word = true; for (size_t i = 0; i < len - 1; ++i) { rotate(temp->str, len); char* w = dictionary_search(dictionary, temp->str); if (w == NULL) { is_teacup_word = false; break; } if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL)) g_ptr_array_add(teacup_words, w); } if (is_teacup_word && teacup_words->len > 0) { printf(, word); g_hash_table_add(found, word); for (size_t i = 0; i < teacup_words->len; ++i) { char* teacup_word = g_ptr_array_index(teacup_words, i); printf(, teacup_word); g_hash_table_add(found, teacup_word); } printf(); } } g_string_free(temp, TRUE); g_ptr_array_free(teacup_words, TRUE); g_hash_table_destroy(found); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, , argv[0]); return EXIT_FAILURE; } GError* error = NULL; GPtrArray* dictionary = load_dictionary(argv[1], &error); if (dictionary == NULL) { if (error != NULL) { fprintf(stderr, , argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } find_teacup_words(dictionary); g_ptr_array_free(dictionary, TRUE); return EXIT_SUCCESS; }
143Teacup rim text
5c
266lo
val (lines, columns) = (System.getenv("LINES"), System.getenv("COLUMNS")) println(s"Lines = $lines, Columns = $columns")
137Terminal control/Dimensions
16scala
xpqwg
null
141Terminal control/Cursor movement
11kotlin
cz698
require 'curses' Curses.init_screen begin Curses.setpos(6, 3) Curses.addstr() Curses.getch ensure Curses.close_screen end
140Terminal control/Cursor positioning
14ruby
3ifz7
object Main extends App { print("\u001Bc")
140Terminal control/Cursor positioning
16scala
9t6m5
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) const ( filename = "readings.txt" readings = 24
136Text processing/1
0go
br1kh
out = 0 max_out = -1 max_times = [] File.foreach('mlijobs.txt') do |line| out += line.include?()? 1: -1 if out > max_out max_out = out max_times = [] end max_times << line.split[3] if out == max_out end puts max_times.each {|time| puts }
125Text processing/Max licenses in use
14ruby
7u0ri
system "tput cub1"; sleep 1; system "tput cuf1"; sleep 1; system "tput cuu1"; sleep 1; system "tput cud1"; sleep 1; system "tput cr"; sleep 1; system "tput home"; sleep 1; $_ = qx[stty -a </dev/tty 2>&1]; my($rows,$cols) = /(\d+) rows; (\d+) col/; $rows--; $cols--; system "tput cup $rows $cols"; sleep 1;
141Terminal control/Cursor movement
2perl
xb1w8
import Data.List import Numeric import Control.Arrow import Control.Monad import Text.Printf import System.Environment import Data.Function type Date = String type Value = Double type Flag = Bool readFlg :: String -> Flag readFlg = (> 0).read readNum :: String -> Value readNum = fst.head.readFloat take2 = takeWhile(not.null).unfoldr (Just.splitAt 2) parseData :: [String] -> (Date,[(Value,Flag)]) parseData = head &&& map(readNum.head &&& readFlg.last).take2.tail sumAccs :: (Date,[(Value,Flag)]) -> (Date, ((Value,Int),[Flag])) sumAccs = second (((sum &&& length).concat.uncurry(zipWith(\v f -> [v|f])) &&& snd).unzip) maxNAseq :: [Flag] -> [(Int,Int)] maxNAseq = head.groupBy((==) `on` fst).sortBy(flip compare) . concat.uncurry(zipWith(\i (r,b)->[(r,i)|not b])) . first(init.scanl(+)0). unzip . map ((fst &&& id).(length &&& head)). group main = do file:_ <- getArgs f <- readFile file let dat :: [(Date,((Value,Int),[Flag]))] dat = map (sumAccs. parseData. words).lines $ f summ = ((sum *** sum). unzip *** maxNAseq.concat). unzip $ map snd dat totalFmt = "\nSummary\t\t accept:%d\t total:%.3f \taverage:%6.3f\n\n" lineFmt = "%8s\t accept:%2d\t total:%11.3f \taverage:%6.3f\n" maxFmt = "Maximum of%d consecutive false readings, starting on line /%s/ and ending on line /%s/\n" putStrLn "\nSome lines:\n" mapM_ (\(d,((v,n),_)) -> printf lineFmt d n v (v/fromIntegral n)) $ take 4 $ drop 2200 dat (\(t,n) -> printf totalFmt n t (t/fromIntegral n)) $ fst summ mapM_ ((\(l, d1,d2) -> printf maxFmt l d1 d2) . (\(a,b)-> (a,(fst.(dat!!).(`div`24))b,(fst.(dat!!).(`div`24))(a+b)))) $ snd summ
136Text processing/1
8haskell
d0tn4
type Timestamp = String; fn compute_usage<R, S, E>(lines: R) -> Result<(u32, Vec<Timestamp>), E> where S: AsRef<str>, R: Iterator<Item = Result<S, E>>, { let mut timestamps = Vec::new(); let mut current = 0; let mut maximum = 0; for line in lines { let line = line?; let line = line.as_ref(); if line.starts_with("License IN") { current -= 1; } else if line.starts_with("License OUT") { current += 1; if maximum <= current { let date = line.split_whitespace().nth(3).unwrap().to_string(); if maximum < current { maximum = current; timestamps.clear(); } timestamps.push(date); } } } Ok((maximum, timestamps)) } fn main() -> std::io::Result<()> { use std::io::{BufRead, BufReader}; let file = std::fs::OpenOptions::new().read(true).open("mlijobs.txt")?; let (max, timestamps) = compute_usage(BufReader::new(file).lines())?; println!("Maximum licenses out: {}", max); println!("At time(s): {:?}", timestamps); Ok(()) }
125Text processing/Max licenses in use
15rust
j5872
import java.io.{BufferedReader, InputStreamReader} import java.net.URL object License0 extends App { val url = new URL("https:
125Text processing/Max licenses in use
16scala
brnk6
def is_palindrome(s): ''' >>> is_palindrome('') True >>> is_palindrome('a') True >>> is_palindrome('aa') True >>> is_palindrome('baa') False >>> is_palindrome('baab') True >>> is_palindrome('ba_ab') True >>> is_palindrome('ba_ ab') False >>> is_palindrome('ba _ ab') True >>> is_palindrome('ab'*2) False >>> x = 'ab' *2**15 >>> len(x) 65536 >>> xreversed = x[::-1] >>> is_palindrome(x+xreversed) True >>> len(x+xreversed) 131072 >>> ''' return s == s[::-1] def _test(): import doctest doctest.testmod() if __name__ == : _test()
130Test a function
3python
rvagq
typedef unsigned long long xint; typedef unsigned uint; typedef struct { uint x, y; xint value; } sum_t; xint *cube; uint n_cubes; sum_t *pq; uint pq_len, pq_cap; void add_cube(void) { uint x = n_cubes++; cube = realloc(cube, sizeof(xint) * (n_cubes + 1)); cube[n_cubes] = (xint) n_cubes*n_cubes*n_cubes; if (x < 2) return; if (++pq_len >= pq_cap) { if (!(pq_cap *= 2)) pq_cap = 2; pq = realloc(pq, sizeof(*pq) * pq_cap); } sum_t tmp = (sum_t) { x, 1, cube[x] + 1 }; uint i, j; for (i = pq_len; i >= 1 && pq[j = i>>1].value > tmp.value; i = j) pq[i] = pq[j]; pq[i] = tmp; } void next_sum(void) { redo: while (!pq_len || pq[1].value >= cube[n_cubes]) add_cube(); sum_t tmp = pq[0] = pq[1]; if (++tmp.y >= tmp.x) { tmp = pq[pq_len--]; if (!pq_len) goto redo; } else tmp.value += cube[tmp.y] - cube[tmp.y-1]; uint i, j; for (i = 1; (j = i<<1) <= pq_len; pq[i] = pq[j], i = j) { if (j < pq_len && pq[j+1].value < pq[j].value) ++j; if (pq[j].value >= tmp.value) break; } pq[i] = tmp; } uint next_taxi(sum_t *hist) { do next_sum(); while (pq[0].value != pq[1].value); uint len = 1; hist[0] = pq[0]; do { hist[len++] = pq[1]; next_sum(); } while (pq[0].value == pq[1].value); return len; } int main(void) { uint i, l; sum_t x[10]; for (i = 1; i <= 2006; i++) { l = next_taxi(x); if (25 < i && i < 2000) continue; printf(, i, x[0].value); while (l--) printf(, x[l].x, x[l].y); putchar('\n'); } return 0; }
144Taxicab numbers
5c
prgby
unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int count = 0; unsigned int n; printf(, limit); for (n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { printf(, n); ++count; if (count % 10 == 0) { printf(); } } } return 0; }
145Tau number
5c
wkjec
struct edge { void *from; void *to; }; struct components { int nnodes; void **nodes; struct components *next; }; struct node { int index; int lowlink; bool onStack; void *data; }; struct tjstate { int index; int sp; int nedges; struct edge *edges; struct node **stack; struct components *head; struct components *tail; }; static int nodecmp(const void *l, const void *r) { return (ptrdiff_t)l -(ptrdiff_t)((struct node *)r)->data; } static int strongconnect(struct node *v, struct tjstate *tj) { struct node *w; v->index = tj->index; v->lowlink = tj->index; tj->index++; tj->stack[tj->sp] = v; tj->sp++; v->onStack = true; for (int i = 0; i<tj->nedges; i++) { if (tj->edges[i].from != v) { continue; } w = tj->edges[i].to; if (w->index == -1) { int r = strongconnect(w, tj); if (r != 0) return r; v->lowlink = min(v->lowlink, w->lowlink); } else if (w->onStack) { v->lowlink = min(v->lowlink, w->index); } } if (v->lowlink == v->index) { struct components *ng = malloc(sizeof(struct components)); if (ng == NULL) { return 2; } if (tj->tail == NULL) { tj->head = ng; } else { tj->tail->next = ng; } tj->tail = ng; ng->next = NULL; ng->nnodes = 0; do { tj->sp--; w = tj->stack[tj->sp]; w->onStack = false; ng->nnodes++; } while (w != v); ng->nodes = malloc(ng->nnodes*sizeof(void *)); if (ng == NULL) { return 2; } for (int i = 0; i<ng->nnodes; i++) { ng->nodes[i] = tj->stack[tj->sp+i]->data; } } return 0; } static int ptrcmp(const void *l, const void *r) { return (ptrdiff_t)((struct node *)l)->data - (ptrdiff_t)((struct node *)r)->data; } struct components *tarjans( int nnodes, void *nodedata[], int nedges, struct edge *edgedata[], int *error) { struct node nodes[nnodes]; struct edge edges[nedges]; struct node *stack[nnodes]; struct node *from, *to; struct tjstate tj = {0, 0, nedges, edges, stack, NULL, .tail=NULL}; for (int i = 0; i<nnodes; i++) { nodes[i] = (struct node){-1, -1, false, nodedata[i]}; } qsort(nodes, nnodes, sizeof(struct node), ptrcmp); for (int i = 0; i<nedges; i++) { from = bsearch(edgedata[i]->from, nodes, nnodes, sizeof(struct node), nodecmp); if (from == NULL) { *error = 1; return NULL; } to = bsearch(edgedata[i]->to, nodes, nnodes, sizeof(struct node), nodecmp); if (to == NULL) { *error = 1; return NULL; } edges[i] = (struct edge){.from=from, .to=to}; } for (int i = 0; i < nnodes; i++) { if (nodes[i].index == -1) { *error = strongconnect(&nodes[i], &tj); if (*error != 0) return NULL; } } return tj.head; }
146Tarjan
5c
czd9c
package main import ( "bufio" "fmt" "log" "os" "sort" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if len(word) >= 3 { words = append(words, word) } } check(scanner.Err()) return words } func rotate(runes []rune) { first := runes[0] copy(runes, runes[1:]) runes[len(runes)-1] = first } func main() { dicts := []string{"mit_10000.txt", "unixdict.txt"}
143Teacup rim text
0go
qppxz
null
128The ISAAC Cipher
15rust
oxm83
checkTrue(palindroc("aba")) checkTrue(!palindroc("ab")) checkException(palindroc()) checkTrue(palindroc(""))
130Test a function
13r
u9kvx
import curses scr = curses.initscr() def move_left(): y,x = curses.getyx() curses.move(y,x-1) def move_right(): y,x = curses.getyx() curses.move(y,x+1) def move_up(): y,x = curses.getyx() curses.move(y-1,x) def move_down(): y,x = curses.getyx() curses.move(y+1,x) def move_line_home() y,x = curses.getyx() curses.move(y,0) def move_line_end() y,x = curses.getyx() maxy,maxx = scr.getmaxyx() curses.move(y,maxx) def move_page_home(): curses.move(0,0) def move_page_end(): y,x = scr.getmaxyx() curses.move(y,x)
141Terminal control/Cursor movement
3python
qpaxi
import Data.List (groupBy, intercalate, sort, sortBy) import qualified Data.Set as S import Data.Ord (comparing) import Data.Function (on) main :: IO () main = readFile "mitWords.txt" >>= (putStrLn . showGroups . circularWords . lines) circularWords :: [String] -> [String] circularWords ws = let lexicon = S.fromList ws in filter (isCircular lexicon) ws isCircular :: S.Set String -> String -> Bool isCircular lex w = 2 < length w && all (`S.member` lex) (rotations w) rotations :: [a] -> [[a]] rotations = fmap <$> rotated <*> (enumFromTo 0 . pred . length) rotated :: [a] -> Int -> [a] rotated [] _ = [] rotated xs n = zipWith const (drop n (cycle xs)) xs showGroups :: [String] -> String showGroups xs = unlines $ intercalate " -> " . fmap snd <$> filter ((1 <) . length) (groupBy (on (==) fst) (sortBy (comparing fst) (((,) =<< sort) <$> xs)))
143Teacup rim text
8haskell
mffyf
package main import ( "fmt" "os" "os/exec" ) func main() { color(red) fmt.Println("Red") color(green) fmt.Println("Green") color(blue) fmt.Println("Blue") } const ( blue = "1" green = "2" red = "4" ) func color(c string) { cmd := exec.Command("tput", "setf", c) cmd.Stdout = os.Stdout cmd.Run() }
142Terminal control/Coloured text
0go
h54jq
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } catch (Exception ex) { System.err.println(ex.getMessage()); } }
143Teacup rim text
9java
f00dv
import java.io.File; import java.util.*; import static java.lang.System.out; public class TextProcessing1 { public static void main(String[] args) throws Exception { Locale.setDefault(new Locale("en", "US")); Metrics metrics = new Metrics(); int dataGap = 0; String gapBeginDate = null; try (Scanner lines = new Scanner(new File("readings.txt"))) { while (lines.hasNextLine()) { double lineTotal = 0.0; int linePairs = 0; int lineInvalid = 0; String lineDate; try (Scanner line = new Scanner(lines.nextLine())) { lineDate = line.next(); while (line.hasNext()) { final double value = line.nextDouble(); if (line.nextInt() <= 0) { if (dataGap == 0) gapBeginDate = lineDate; dataGap++; lineInvalid++; continue; } lineTotal += value; linePairs++; metrics.addDataGap(dataGap, gapBeginDate, lineDate); dataGap = 0; } } metrics.addLine(lineTotal, linePairs); metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal); } metrics.report(); } } private static class Metrics { private List<String[]> gapDates; private int maxDataGap = -1; private double total; private int pairs; private int lineResultCount; void addLine(double tot, double prs) { total += tot; pairs += prs; } void addDataGap(int gap, String begin, String end) { if (gap > 0 && gap >= maxDataGap) { if (gap > maxDataGap) { maxDataGap = gap; gapDates = new ArrayList<>(); } gapDates.add(new String[]{begin, end}); } } void lineResult(String date, int invalid, int prs, double tot) { if (lineResultCount >= 3) return; out.printf("%10s out:%2d in:%2d tot:%10.3f avg:%10.3f%n", date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0); lineResultCount++; } void report() { out.printf("%ntotal =%10.3f%n", total); out.printf("readings =%6d%n", pairs); out.printf("average =%010.3f%n", total / pairs); out.printf("%nmaximum run(s) of%d invalid measurements:%n", maxDataGap); for (String[] dates : gapDates) out.printf("begins at%s and ends at%s%n", dates[0], dates[1]); } } }
136Text processing/1
9java
sa8q0
#!/usr/bin/runhaskell import System.Console.ANSI colorStrLn :: ColorIntensity -> Color -> ColorIntensity -> Color -> String -> IO () colorStrLn fgi fg bgi bg str = do setSGR [SetColor Foreground fgi fg, SetColor Background bgi bg] putStr str setSGR [] putStrLn "" main = do colorStrLn Vivid White Vivid Red "This is red on white." colorStrLn Vivid White Dull Blue "This is white on blue." colorStrLn Vivid Green Dull Black "This is green on black." colorStrLn Vivid Yellow Dull Black "This is yellow on black." colorStrLn Dull Black Vivid Blue "This is black on light blue."
142Terminal control/Coloured text
8haskell
ixqor
object CursorMovement extends App { val ESC = "\u001B"
141Terminal control/Cursor movement
16scala
nq0ic
(ns test-project-intellij.core (:gen-class)) (defn cube [x] "Cube a number through triple multiplication" (* x x x)) (defn sum3 [[i j]] " [i j] -> i^3 + j^3" (+ (cube i) (cube j))) (defn next-pair [[i j]] " Generate next [i j] pair of sequence (producing lower triangle pairs) " (if (< j i) [i (inc j)] [(inc i) 1])) (def pairs-seq (iterate next-pair [1 1])) (defn dict-inc [m pair] " Add pair to pair map m, with the key of the map based upon the cubic sum (sum3) and the value appends the pair " (update-in m [(sum3 pair)] (fnil #(conj % pair) []))) (defn enough? [m n-to-generate] " Checks if we have enough taxi numbers (i.e. if number in map >= count-needed " (->> m (filter #(if (> (count (second %)) 1) true false)) (count) (<= n-to-generate))) (defn find-taxi-numbers [n-to-generate] " Generates 1st n-to-generate taxi numbers" (loop [m {} p pairs-seq num-tried 0 check-after 1] (if (and (= num-tried check-after) (enough? m n-to-generate)) (sort-by first (into [] (filter #(> (count (second %)) 1) m))) (if (= num-tried check-after) (recur (dict-inc m (first p)) (rest p) (inc num-tried) (* 2 check-after)) (recur (dict-inc m (first p)) (rest p) (inc num-tried) check-after))))) (def result (find-taxi-numbers 2006)) (defn show-result [n sample] " Prints one line of result " (print (format "%4d:%10d" n (first sample))) (doseq [q (second sample) :let [[i j] q]] (print (format " =%4d^3 +%4d^3" i j))) (println)) (doseq [n (range 1 26) :let [sample (nth result (dec n))]] (show-result n sample)) (doseq [n (range 2000 2007) :let [sample (nth result (dec n))]] (show-result n sample)) }
144Taxicab numbers
6clojure
xbkwk
package main import ( "fmt" "math/big" )
146Tarjan
0go
wk7eg
(() => { 'use strict';
143Teacup rim text
10javascript
ydd6r
package main import "fmt" type trit int8 const ( trFalse trit = iota - 1 trMaybe trTrue ) func (t trit) String() string { switch t { case trFalse: return "False" case trMaybe: return "Maybe" case trTrue: return "True " } panic("Invalid trit") } func trNot(t trit) trit { return -t } func trAnd(s, t trit) trit { if s < t { return s } return t } func trOr(s, t trit) trit { if s > t { return s } return t } func trEq(s, t trit) trit { return s * t } func main() { trSet := []trit{trFalse, trMaybe, trTrue} fmt.Println("t not t") for _, t := range trSet { fmt.Println(t, trNot(t)) } fmt.Println("\ns t s and t") for _, s := range trSet { for _, t := range trSet { fmt.Println(s, t, trAnd(s, t)) } } fmt.Println("\ns t s or t") for _, s := range trSet { for _, t := range trSet { fmt.Println(s, t, trOr(s, t)) } } fmt.Println("\ns t s eq t") for _, s := range trSet { for _, t := range trSet { fmt.Println(s, t, trEq(s, t)) } } }
138Ternary logic
0go
5c5ul
var filename = 'readings.txt'; var show_lines = 5; var file_stats = { 'num_readings': 0, 'total': 0, 'reject_run': 0, 'reject_run_max': 0, 'reject_run_date': '' }; var fh = new ActiveXObject("Scripting.FileSystemObject").openTextFile(filename, 1);
136Text processing/1
10javascript
nsfiy
def palindrome?(s) s == s.reverse end require 'test/unit' class MyTests < Test::Unit::TestCase def test_palindrome_ok assert(palindrome? ) end def test_palindrome_nok assert_equal(false, palindrome?()) end def test_object_without_reverse assert_raise(NoMethodError) {palindrome? 42} end def test_wrong_number_args assert_raise(ArgumentError) {palindrome? , } end def test_show_failing_test assert(palindrome?(), ) end end
130Test a function
14ruby
j5w7x
null
130Test a function
15rust
h4xj2
null
146Tarjan
11kotlin
s1kq7
unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf(, limit); for (n = 1; n <= limit; ++n) { printf(, divisor_count(n)); if (n % 20 == 0) { printf(); } } return 0; }
147Tau function
5c
l3dcy
enum Trit { TRUE, MAYBE, FALSE private Trit nand(Trit that) { switch ([this,that]) { case { FALSE in it }: return TRUE case { MAYBE in it }: return MAYBE default : return FALSE } } private Trit nor(Trit that) { this.or(that).not() } Trit and(Trit that) { this.nand(that).not() } Trit or(Trit that) { this.not().nand(that.not()) } Trit not() { this.nand(this) } Trit imply(Trit that) { this.nand(that.not()) } Trit equiv(Trit that) { this.and(that).or(this.nor(that)) } }
138Ternary logic
7groovy
c3c9i
import org.scalacheck._ import Prop._ import Gen._ object PalindromeCheck extends Properties("Palindrome") { property("A string concatenated with its reverse is a palindrome") = forAll { s: String => isPalindrome(s + s.reverse) } property("A string concatenated with any character and its reverse is a palindrome") = forAll { (s: String, c: Char) => isPalindrome(s + c + s.reverse) } property("If the first half of a string is equal to the reverse of its second half, it is a palindrome") = forAll { (s: String) => s.take(s.length / 2) != s.drop((s.length + 1) / 2).reverse || isPalindrome(s) } property("If the first half of a string is different than the reverse of its second half, it isn't a palindrome") = forAll { (s: String) => s.take(s.length / 2) == s.drop((s.length + 1) / 2).reverse || !isPalindrome(s) } }
130Test a function
16scala
p70bj
null
142Terminal control/Coloured text
11kotlin
pr7b6
const char *code = ; int main() { sqlite3 *db = NULL; char *errmsg; if ( sqlite3_open(, &db) == SQLITE_OK ) { if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) { fprintf(stderr, errmsg); sqlite3_free(errmsg); sqlite3_close(db); exit(EXIT_FAILURE); } sqlite3_close(db); } else { fprintf(stderr, ); sqlite3_close(db); exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
148Table creation/Postal addresses
5c
zoxtx
(require '[clojure.java.jdbc:as sql]) (def db {:classname "org.h2.Driver" :subprotocol "h2:file" :subname "db/my-dbname"}) (sql/db-do-commands db (sql/create-table-ddl:address [:id "bigint primary key auto_increment"] [:street "varchar"] [:city "varchar"] [:state "varchar"] [:zip "varchar"]))
148Table creation/Postal addresses
6clojure
9toma
use strict; use warnings; use feature <say state current_sub>; use List::Util qw(min); sub tarjan { my (%k) = @_; my (%onstack, %index, %lowlink, @stack, @connected); my sub strong_connect { my ($vertex, $i) = @_; $index{$vertex} = $i; $lowlink{$vertex} = $i + 1; $onstack{$vertex} = 1; push @stack, $vertex; for my $connection (@{$k{$vertex}}) { if (not defined $index{$connection}) { __SUB__->($connection, $i + 1); $lowlink{$vertex} = min($lowlink{$connection}, $lowlink{$vertex}); } elsif ($onstack{$connection}) { $lowlink{$vertex} = min($index{$connection}, $lowlink{$vertex}); } } if ($lowlink{$vertex} eq $index{$vertex}) { my @node; do { push @node, pop @stack; $onstack{$node[-1]} = 0; } while $node[-1] ne $vertex; push @connected, [@node]; } } for (sort keys %k) { strong_connect($_, 0) unless $index{$_}; } @connected; } my %test1 = ( 0 => [1], 1 => [2], 2 => [0], 3 => [1, 2, 4], 4 => [3, 5], 5 => [2, 6], 6 => [5], 7 => [4, 6, 7] ); my %test2 = ( 'Andy' => ['Bart'], 'Bart' => ['Carl'], 'Carl' => ['Andy'], 'Dave' => [qw<Bart Carl Earl>], 'Earl' => [qw<Dave Fred>], 'Fred' => [qw<Carl Gary>], 'Gary' => ['Fred'], 'Hank' => [qw<Earl Gary Hank>] ); print "Strongly connected components:\n"; print join(', ', sort @$_) . "\n" for tarjan(%test1); print "\nStrongly connected components:\n"; print join(', ', sort @$_) . "\n" for tarjan(%test2);
146Tarjan
2perl
um3vr
import Prelude hiding (Bool(..), not, (&&), (||), (==)) main = mapM_ (putStrLn . unlines . map unwords) [ table "not" $ unary not , table "and" $ binary (&&) , table "or" $ binary (||) , table "implies" $ binary (=->) , table "equals" $ binary (==) ] data Trit = False | Maybe | True deriving (Show) False `nand` _ = True _ `nand` False = True True `nand` True = False _ `nand` _ = Maybe not a = nand a a a && b = not $ a `nand` b a || b = not a `nand` not b a =-> b = a `nand` not b a == b = (a && b) || (not a && not b) inputs1 = [True, Maybe, False] inputs2 = [(a,b) | a <- inputs1, b <- inputs1] unary f = map (\a -> [a, f a]) inputs1 binary f = map (\(a,b) -> [a, b, f a b]) inputs2 table name xs = map (map pad) . (header:) $ map (map show) xs where header = map (:[]) (take ((length $ head xs) - 1) ['A'..]) ++ [name] pad s = s ++ replicate (5 - length s) ' '
138Ternary logic
8haskell
xpxw4
import Cocoa import XCTest class PalindromTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testPalindrome() {
130Test a function
17swift
7uerq
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } return count } func main() { fmt.Println("The first 100 tau numbers are:") count := 0 i := 1 for count < 100 { tf := countDivisors(i) if i%tf == 0 { fmt.Printf("%4d ", i) count++ if count%10 == 0 { fmt.Println() } } i++ } }
145Tau number
0go
czf9g
null
136Text processing/1
11kotlin
ahw13
package main import ( "fmt" ) func main() { days := []string{"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"} gifts := []string{"A Partridge in a Pear Tree", "Two Turtle Doves and", "Three French Hens", "Four Calling Birds", "Five Gold Rings", "Six Geese a-Laying", "Seven Swans a-Swimming", "Eight Maids a-Milking", "Nine Ladies Dancing", "Ten Lords a-Leaping", "Eleven Pipers Piping", "Twelve Drummers Drumming"} for i := 0; i < 12; i++ { fmt.Printf("On the%s day of Christmas,\n", days[i]) fmt.Println("My true love sent to me:") for j := i; j >= 0; j-- { fmt.Println(gifts[j]) } fmt.Println() } }
139The Twelve Days of Christmas
0go
vyl2m
print("Normal \027[1mBold\027[0m \027[4mUnderline\027[0m \027[7mInverse\027[0m") colors = { 30,31,32,33,34,35,36,37,90,91,92,93,94,95,96,97 } for _,bg in ipairs(colors) do for _,fg in ipairs(colors) do io.write("\027["..fg..";"..(bg+10).."mX") end print("\027[0m")
142Terminal control/Coloured text
1lua
17jpo
package main import ( "database/sql" "fmt" "log" _ "github.com/mattn/go-sqlite3" ) func main() {
148Table creation/Postal addresses
0go
k4lhz
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) isTau :: Integral a => a -> Bool isTau n = 0 == mod n (tau n) main = print . take 100 . filter isTau $ [1..]
145Tau number
8haskell
pr4bt
from collections import defaultdict def from_edges(edges): '''translate list of edges to list of nodes''' class Node: def __init__(self): self.root = None self.succ = [] nodes = defaultdict(Node) for v,w in edges: nodes[v].succ.append(nodes[w]) for i,v in nodes.items(): v.id = i return nodes.values() def trajan(V): def strongconnect(v, S): v.root = pos = len(S) S.append(v) for w in v.succ: if w.root is None: yield from strongconnect(w, S) if w.root >= 0: v.root = min(v.root, w.root) if v.root == pos: res, S[pos:] = S[pos:], [] for w in res: w.root = -1 yield [r.id for r in res] for v in V: if v.root is None: yield from strongconnect(v, []) tables = [ [(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2), (4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)], [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]] for table in (tables): for g in trajan(from_edges(table)): print(g) print()
146Tarjan
3python
596ux
use strict; use warnings; use feature 'say'; use List::Util qw(uniqstr any); my(%words,@teacups,%seen); open my $fh, '<', 'ref/wordlist.10000'; while (<$fh>) { chomp(my $w = uc $_); next if length $w < 3; push @{$words{join '', sort split //, $w}}, $w;} for my $these (values %words) { next if @$these < 3; MAYBE: for (@$these) { my $maybe = $_; next if $seen{$_}; my @print; for my $i (0 .. length $maybe) { if (any { $maybe eq $_ } @$these) { push @print, $maybe; $maybe = substr($maybe,1) . substr($maybe,0,1) } else { @print = () and next MAYBE } } if (@print) { push @teacups, [@print]; $seen{$_}++ for @print; } } } say join ', ', uniqstr @$_ for sort @teacups;
143Teacup rim text
2perl
4cc5d
filename = "readings.txt" io.input( filename ) file_sum, file_cnt_data, file_lines = 0, 0, 0 max_rejected, n_rejected = 0, 0 max_rejected_date, rejected_date = "", "" while true do data = io.read("*line") if data == nil then break end date = string.match( data, "%d+%-%d+%-%d+" ) if date == nil then break end val = {} for w in string.gmatch( data, "%s%-*%d+[%.%d]*" ) do val[#val+1] = tonumber(w) end sum, cnt = 0, 0 for i = 1, #val, 2 do if val[i+1] > 0 then sum = sum + val[i] cnt = cnt + 1 n_rejected = 0 else if n_rejected == 0 then rejected_date = date end n_rejected = n_rejected + 1 if n_rejected > max_rejected then max_rejected = n_rejected max_rejected_date = rejected_date end end end file_sum = file_sum + sum file_cnt_data = file_cnt_data + cnt file_lines = file_lines + 1 print( string.format( "%s:\tRejected:%d\tAccepted:%d\tLine_total:%f\tLine_average:%f", date, #val/2-cnt, cnt, sum, sum/cnt ) ) end print( string.format( "\nFile:\t %s", filename ) ) print( string.format( "Total:\t %f", file_sum ) ) print( string.format( "Readings:%d", file_lines ) ) print( string.format( "Average: %f", file_sum/file_cnt_data ) ) print( string.format( "Maximum%d consecutive false readings starting at%s.", max_rejected, max_rejected_date ) )
136Text processing/1
1lua
ekxac
def presents = ['A partridge in a pear tree.', 'Two turtle doves', 'Three french hens', 'Four calling birds', 'Five golden rings', 'Six geese a-laying', 'Seven swans a-swimming', 'Eight maids a-milking', 'Nine ladies dancing', 'Ten lords a-leaping', 'Eleven pipers piping', 'Twelve drummers drumming'] ['first', 'second', 'third', 'forth', 'fifth', 'sixth', 'seventh', 'eight', 'ninth', 'tenth', 'eleventh', 'Twelfth'].eachWithIndex{ day, dayIndex -> println "On the $day day of Christmas" println 'My true love gave to me:' (dayIndex..0).each { p -> print presents[p] println p == 1 ? ' and': '' } println() }
139The Twelve Days of Christmas
7groovy
mf6y5
void fail(const char *message) { perror(message); exit(1); } cothread_t reader; cothread_t printer; struct { char *buf; size_t len; size_t cap; } line; size_t count; void reader_entry(void) { FILE *input; size_t newcap; int c, eof, eol; char *newbuf; input = fopen(, ); if (input == NULL) fail(); line.buf = malloc(line.cap = 4096); if (line.buf == NULL) fail(); line.len = 0; do { c = fgetc(input); if (ferror(input)) fail(); eof = (c == EOF); if (eof) { eol = (line.len > 0); } else { if (line.len == line.cap) { newcap = line.cap * 2; newbuf = realloc(line.buf, newcap); if (newbuf == NULL) fail(); line.buf = newbuf; line.cap = newcap; } line.buf[line.len++] = c; eol = (c == '\n'); } if (eol) { co_switch(printer); line.len = 0; } } while (!eof); free(line.buf); line.buf = NULL; printf(, count); co_switch(printer); } int main() { reader = co_create(4096, reader_entry); printer = co_active(); count = 0; for (;;) { co_switch(reader); if (line.buf == NULL) break; fwrite(line.buf, 1, line.len, stdout); count++; } co_delete(reader); return 0; }
149Synchronous concurrency
5c
6nq32
import Database.SQLite.Simple main = do db <- open "postal.db" execute_ db "\ \CREATE TABLE address (\ \addrID INTEGER PRIMARY KEY AUTOINCREMENT, \ \addrStreet TEXT NOT NULL, \ \addrCity TEXT NOT NULL, \ \addrState TEXT NOT NULL, \ \addrZIP TEXT NOT NULL \ \)" close db
148Table creation/Postal addresses
8haskell
nq1ie
null
148Table creation/Postal addresses
11kotlin
17upd
int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, ))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, ))) { tm = time(0); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, , argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 0; }
150Take notes on the command line
5c
l3ocy
public class Tau { private static long divisorCount(long n) { long total = 1;
145Tau number
9java
r2cg0
package main import ( "os" "os/exec" ) func main() { c := exec.Command("clear") c.Stdout = os.Stdout c.Run() }
151Terminal control/Clear the screen
0go
dsbne
import System.Console.ANSI main = clearScreen
151Terminal control/Clear the screen
8haskell
59dug
public class Logic{ public static enum Trit{ TRUE, MAYBE, FALSE; public Trit and(Trit other){ if(this == TRUE){ return other; }else if(this == MAYBE){ return (other == FALSE) ? FALSE: MAYBE; }else{ return FALSE; } } public Trit or(Trit other){ if(this == TRUE){ return TRUE; }else if(this == MAYBE){ return (other == TRUE) ? TRUE: MAYBE; }else{ return other; } } public Trit tIf(Trit other){ if(this == TRUE){ return other; }else if(this == MAYBE){ return (other == TRUE) ? TRUE: MAYBE; }else{ return TRUE; } } public Trit not(){ if(this == TRUE){ return FALSE; }else if(this == MAYBE){ return MAYBE; }else{ return TRUE; } } public Trit equals(Trit other){ if(this == TRUE){ return other; }else if(this == MAYBE){ return MAYBE; }else{ return other.not(); } } } public static void main(String[] args){ for(Trit a:Trit.values()){ System.out.println("not " + a + ": " + a.not()); } for(Trit a:Trit.values()){ for(Trit b:Trit.values()){ System.out.println(a+" and "+b+": "+a.and(b)+ "\t "+a+" or "+b+": "+a.or(b)+ "\t "+a+" implies "+b+": "+a.tIf(b)+ "\t "+a+" = "+b+": "+a.equals(b)); } } } }
138Ternary logic
9java
brbk3
gifts :: [String] gifts = [ "And a partridge in a pear tree!", "Two turtle doves,", "Three french hens,", "Four calling birds,", "FIVE GOLDEN RINGS,", "Six geese a-laying,", "Seven swans a-swimming,", "Eight maids a-milking,", "Nine ladies dancing,", "Ten lords a-leaping,", "Eleven pipers piping,", "Twelve drummers drumming," ] days :: [String] days = [ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ] verseOfTheDay :: Int -> IO () verseOfTheDay day = do putStrLn $ "On the " <> days !! day <> " day of Christmas my true love gave to me... " mapM_ putStrLn [dayGift day d | d <- [day, day -1 .. 0]] putStrLn "" where dayGift 0 _ = "A partridge in a pear tree!" dayGift _ gift = gifts !! gift main :: IO () main = mapM_ verseOfTheDay [0 .. 11]
139The Twelve Days of Christmas
8haskell
eh1ai
null
148Table creation/Postal addresses
1lua
aj51v
char *super = 0; int pos, cnt[MAX]; int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; } int r(int n) { if (!n) return 0; char c = super[pos - n]; if (!--cnt[n]) { cnt[n] = n; if (!r(n-1)) return 0; } super[pos++] = c; return 1; } void superperm(int n) { int i, len; pos = n; len = fact_sum(n); super = realloc(super, len + 1); super[len] = '\0'; for (i = 0; i <= n; i++) cnt[i] = i; for (i = 1; i <= n; i++) super[i - 1] = i + '0'; while (r(n)); } int main(void) { int n; for (n = 0; n < MAX; n++) { printf(, n); superperm(n); printf(, (int)strlen(super)); putchar('\n'); } return 0; }
152Superpermutation minimisation
5c
f0bd3
function divisor_count(n) local total = 1
145Tau number
1lua
um6vl
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
151Terminal control/Clear the screen
9java
9tsmu
var L3 = new Object(); L3.not = function(a) { if (typeof a == "boolean") return !a; if (a == undefined) return undefined; throw("Invalid Ternary Expression."); } L3.and = function(a, b) { if (typeof a == "boolean" && typeof b == "boolean") return a && b; if ((a == true && b == undefined) || (a == undefined && b == true)) return undefined; if ((a == false && b == undefined) || (a == undefined && b == false)) return false; if (a == undefined && b == undefined) return undefined; throw("Invalid Ternary Expression."); } L3.or = function(a, b) { if (typeof a == "boolean" && typeof b == "boolean") return a || b; if ((a == true && b == undefined) || (a == undefined && b == true)) return true; if ((a == false && b == undefined) || (a == undefined && b == false)) return undefined; if (a == undefined && b == undefined) return undefined; throw("Invalid Ternary Expression."); }
138Ternary logic
10javascript
wbwe2
(ns rosettacode.notes (:use [clojure.string:only [join]])) (defn notes [notes] (if (seq notes) (spit "NOTES.txt" (str (java.util.Date.) "\n" "\t" (join " " notes) "\n") :append true) (println (slurp "NOTES.txt")))) (notes *command-line-args*)
150Take notes on the command line
6clojure
4ct5o
use std::collections::{BTreeMap, BTreeSet};
146Tarjan
15rust
r29g5
'''Teacup rim text''' from itertools import chain, groupby from os.path import expanduser from functools import reduce def main(): '''Circular anagram groups, of more than one word, and containing words of length > 2, found in: https: ''' print('\n'.join( concatMap(circularGroup)( anagrams(3)( lines(readFile('~/mitWords.txt')) ) ) )) def anagrams(n): '''Groups of anagrams, of minimum group size n, found in the given word list. ''' def go(ws): def f(xs): return [ [snd(x) for x in xs] ] if n <= len(xs) >= len(xs[0][0]) else [] return concatMap(f)(groupBy(fst)(sorted( [(''.join(sorted(w)), w) for w in ws], key=fst ))) return go def circularGroup(ws): '''Either an empty list, or a list containing a string showing any circular subset found in ws. ''' lex = set(ws) iLast = len(ws) - 1 (i, blnCircular) = until( lambda tpl: tpl[1] or (tpl[0] > iLast) )( lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]])) )( (0, False) ) return [' -> '.join(allRotations(ws[i]))] if blnCircular else [] def isCircular(lexicon): '''True if all of a word's rotations are found in the given lexicon. ''' def go(w): def f(tpl): (i, _, x) = tpl return (1 + i, x in lexicon, rotated(x)) iLast = len(w) - 1 return until( lambda tpl: iLast < tpl[0] or (not tpl[1]) )(f)( (0, True, rotated(w)) )[1] return go def allRotations(w): '''All rotations of the string w.''' return takeIterate(len(w) - 1)( rotated )(w) def concatMap(f): '''A concatenated list over which a function has been mapped. The list monad can be derived by using a function f which wraps its output in a list, (using an empty list to represent computational failure). ''' def go(xs): return chain.from_iterable(map(f, xs)) return go def fst(tpl): '''First member of a pair.''' return tpl[0] def groupBy(f): '''The elements of xs grouped, preserving order, by equality in terms of the key function f. ''' def go(xs): return [ list(x[1]) for x in groupby(xs, key=f) ] return go def lines(s): '''A list of strings, (containing no newline characters) derived from a single new-line delimited string. ''' return s.splitlines() def mapAccumL(f): '''A tuple of an accumulation and a list derived by a combined map and fold, with accumulation from left to right. ''' def go(a, x): tpl = f(a[0], x) return (tpl[0], a[1] + [tpl[1]]) return lambda acc: lambda xs: ( reduce(go, xs, (acc, [])) ) def readFile(fp): '''The contents of any file at the path derived by expanding any ~ in fp. ''' with open(expanduser(fp), 'r', encoding='utf-8') as f: return f.read() def rotated(s): '''A string rotated 1 character to the right.''' return s[1:] + s[0] def snd(tpl): '''Second member of a pair.''' return tpl[1] def takeIterate(n): '''Each value of n iterations of f over a start value of x. ''' def go(f): def g(x): def h(a, i): v = f(a) if i else x return (v, v) return mapAccumL(h)(x)( range(0, 1 + n) )[1] return g return go def until(p): '''The result of repeatedly applying f until p holds. The initial seed value is x. ''' def go(f): def g(x): v = x while not p(v): v = f(v) return v return g return go if __name__ == '__main__': main()
143Teacup rim text
3python
gll4h
public class TwelveDaysOfChristmas { final static String[] gifts = { "A partridge in a pear tree.", "Two turtle doves and", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming", "And a partridge in a pear tree.", "Two turtle doves" }; final static String[] days = { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "Twelfth" }; public static void main(String[] args) { for (int i = 0; i < days.length; i++) { System.out.printf("%nOn the%s day of Christmas%n", days[i]); System.out.println("My true love gave to me:"); for (int j = i; j >= 0; j--) System.out.println(gifts[i == 11 && j < 2 ? j + 12 : j]); } } }
139The Twelve Days of Christmas
9java
h57jm
my %colors = ( red => "\e[1;31m", green => "\e[1;32m", yellow => "\e[1;33m", blue => "\e[1;34m", magenta => "\e[1;35m", cyan => "\e[1;36m" ); $clr = "\e[0m"; print "$colors{$_}$_ text $clr\n" for sort keys %colors; use feature 'say'; use Term::ANSIColor; say colored('RED ON WHITE', 'bold red on_white'); say colored('GREEN', 'bold green'); say colored('BLUE ON YELLOW', 'bold blue on_yellow'); say colored('MAGENTA', 'bold magenta'); say colored('CYAN ON RED', 'bold cyan on_red'); say colored('YELLOW', 'bold yellow');
142Terminal control/Coloured text
2perl
ydf6u
(use '[clojure.java.io:as io]) (def writer (agent 0)) (defn write-line [state line] (println line) (inc state))
149Synchronous concurrency
6clojure
l3icb
package main import ( "container/heap" "fmt" "strings" ) type CubeSum struct { x, y uint16 value uint64 } func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] } type CubeSumHeap []*CubeSum func (h CubeSumHeap) Len() int { return len(h) } func (h CubeSumHeap) Less(i, j int) bool { return h[i].value < h[j].value } func (h CubeSumHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *CubeSumHeap) Push(x interface{}) { (*h) = append(*h, x.(*CubeSum)) } func (h *CubeSumHeap) Pop() interface{} { x := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return x } type TaxicabGen struct { n int h CubeSumHeap } var cubes []uint64
144Taxicab numbers
0go
6ni3p
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } return count } func main() { fmt.Println("The tau functions for the first 100 positive integers are:") for i := 1; i <= 100; i++ { fmt.Printf("%2d ", countDivisors(i)) if i%20 == 0 { fmt.Println() } } }
147Tau function
0go
xb7wf
null
151Terminal control/Clear the screen
11kotlin
zoats
use strict; use warnings; my $nodata = 0; my $nodata_max = -1; my $nodata_maxline = "!"; my $infiles = join ", ", @ARGV; my $tot_file = 0; my $num_file = 0; while (<>) { chomp; my $tot_line = 0; my $num_line = 0; my $rejects = 0; my ($date, @fields) = split; while (@fields and my ($datum, $flag) = splice @fields, 0, 2) { if ($flag+1 < 2) { $nodata++; $rejects++; next; } if($nodata_max == $nodata and $nodata > 0){ $nodata_maxline = "$nodata_maxline, $date"; } if($nodata_max < $nodata and $nodata > 0){ $nodata_max = $nodata; $nodata_maxline = $date; } $nodata = 0; $tot_line += $datum; $num_line++; } $tot_file += $tot_line; $num_file += $num_line; printf "Line:%11s Reject:%2i Accept:%2i Line_tot:%10.3f Line_avg:%10.3f\n", $date, $rejects, $num_line, $tot_line, ($num_line>0)? $tot_line/$num_line: 0; } printf "\n"; printf "File(s) =%s\n", $infiles; printf "Total =%10.3f\n", $tot_file; printf "Readings =%6i\n", $num_file; printf "Average =%10.3f\n", $tot_file / $num_file; printf "\nMaximum run(s) of%i consecutive false readings ends at line starting with date(s):%s\n", $nodata_max, $nodata_maxline;
136Text processing/1
2perl
9zlmn
var days = [ 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', ]; var gifts = [ "A partridge in a pear tree", "Two turtle doves", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming" ]; var lines, verses = [], song; for ( var i = 0; i < 12; i++ ) { lines = []; lines[0] = "On the " + days[i] + " day of Christmas, my true love gave to me"; var j = i + 1; var k = 0; while ( j-- > 0 ) lines[++k] = gifts[j]; verses[i] = lines.join('\n'); if ( i == 0 ) gifts[0] = "And a partridge in a pear tree"; } song = verses.join('\n\n'); document.write(song);
139The Twelve Days of Christmas
10javascript
ajp10
use DBI; my $db = DBI->connect('DBI:mysql:database:server','login','password'); my $statment = <<EOF; CREATE TABLE `Address` ( `addrID` int(11) NOT NULL auto_increment, `addrStreet` varchar(50) NOT NULL default '', `addrCity` varchar(25) NOT NULL default '', `addrState` char(2) NOT NULL default '', `addrZIP` char(10) NOT NULL default '', PRIMARY KEY (`addrID`) ); EOF my $exec = $db->prepare($statment); $exec->execute;
148Table creation/Postal addresses
2perl
mf8yz
int main() { for (unsigned int d = 2; d <= 9; ++d) { printf(, d); char digits[16] = { 0 }; memset(digits, '0' + d, d); mpz_t bignum; mpz_init(bignum); for (unsigned int count = 0, n = 1; count < 10; ++n) { mpz_ui_pow_ui(bignum, n, d); mpz_mul_ui(bignum, bignum, d); char* str = mpz_get_str(NULL, 10, bignum); if (strstr(str, digits)) { printf(, n); ++count; } free(str); } mpz_clear(bignum); printf(); } return 0; }
153Super-d numbers
5c
0a4st
import Data.List (groupBy, sortOn, tails, transpose) import Data.Function (on) taxis :: Int -> [[(Int, ((Int, Int), (Int, Int)))]] taxis nCubes = filter ((> 1) . length) $ groupBy (on (==) fst) $ sortOn fst [ (fst x + fst y, (x, y)) | (x:t) <- tails $ ((^ 3) >>= (,)) <$> [1 .. nCubes] , y <- t ] main :: IO () main = mapM_ putStrLn $ concat <$> transpose (((<$>) =<< flip justifyRight ' ' . maximum . (length <$>)) <$> transpose (taxiRow <$> (take 25 xs <> take 7 (drop 1999 xs)))) where xs = zip [1 ..] (taxis 1200) justifyRight n c = (drop . length) <*> (replicate n c <>) taxiRow :: (Int, [(Int, ((Int, Int), (Int, Int)))]) -> [String] taxiRow (n, [(a, ((axc, axr), (ayc, ayr))), (b, ((bxc, bxr), (byc, byr)))]) = concat [ [show n, ". ", show a, " = "] , term axr axc " + " , term ayr ayc " or " , term bxr bxc " + " , term byr byc [] ] where term r c l = ["(", show r, "^3=", show c, ")", l]
144Taxicab numbers
8haskell
juv7g