code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
(defn sb-step [v] (let [i (quot (count v) 2)] (conj v (+ (v (dec i)) (v i)) (v i)))) (def all-sbs (sequence (map peek) (iterate sb-step [1 1]))) (defn first-appearance [n] (first (keep-indexed (fn [i x] (when (= x n) i)) all-sbs))) (defn gcd [a b] (loop [a (if (neg? a) (- a) a) b (if (neg? b) (- b) b)] (if (zero? b) a (recur b (rem a b))))) (defn check-pairwise-gcd [cnt] (let [sbs (take (inc cnt) all-sbs)] (every? #(= 1 %) (map gcd sbs (rest sbs))))) (defn report-sb [] (println "First 15 Stern-Brocot members:" (take 15 all-sbs)) (println "First appearance of N at 1-based index:") (doseq [n [1 2 3 4 5 6 7 8 9 10 100]] (println " first" n "at" (inc (first-appearance n)))) (println "Check pairwise GCDs = 1 ..." (check-pairwise-gcd 1000)) true) (report-sb)
201Stern-Brocot sequence
6clojure
z8ltj
void step_up(void) { while (!step()) { step_up(); } }
203Stair-climbing puzzle
5c
9fum1
import java.util.*; import java.util.stream.*; public class StateNamePuzzle { static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory",}; public static void main(String[] args) { solve(Arrays.asList(states)); } static void solve(List<String> input) { Map<String, String> orig = input.stream().collect(Collectors.toMap( s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s)); input = new ArrayList<>(orig.keySet()); Map<String, List<String[]>> map = new HashMap<>(); for (int i = 0; i < input.size() - 1; i++) { String pair0 = input.get(i); for (int j = i + 1; j < input.size(); j++) { String[] pair = {pair0, input.get(j)}; String s = pair0 + pair[1]; String key = Arrays.toString(s.chars().sorted().toArray()); List<String[]> val = map.getOrDefault(key, new ArrayList<>()); val.add(pair); map.put(key, val); } } map.forEach((key, list) -> { for (int i = 0; i < list.size() - 1; i++) { String[] a = list.get(i); for (int j = i + 1; j < list.size(); j++) { String[] b = list.get(j); if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4) continue; System.out.printf("%s +%s =%s +%s%n", orig.get(a[0]), orig.get(a[1]), orig.get(b[0]), orig.get(b[1])); } } }); } }
199State name puzzle
9java
ct79h
(def level (atom 41)) (def prob 0.5001) (defn step [] (let [success (< (rand) prob)] (swap! level (if success inc dec)) success) )
203Stair-climbing puzzle
6clojure
uy7vi
my $str = 'Foo'; $str .= 'bar'; print $str;
193String append
2perl
lzac5
package main import ( "fmt" "runtime" ) func main() { stackTrace := make([]byte, 1024) n := runtime.Stack(stackTrace, true) stackTrace = stackTrace[:n] fmt.Printf("%s\n", stackTrace) fmt.Printf("(%d bytes)\n", len(stackTrace)) }
202Stack traces
0go
spdqa
null
199State name puzzle
11kotlin
3ouz5
def rawTrace = { Thread.currentThread().stackTrace }
202Stack traces
7groovy
a701p
use constant pi => 3.14159265; use List::Util qw(sum reduce min max); sub normdist { my($m, $sigma) = @_; my $r = sqrt -2 * log rand; my $theta = 2 * pi * rand; $r * cos($theta) * $sigma + $m; } $size = 100000; $mean = 50; $stddev = 4; push @dataset, normdist($mean,$stddev) for 1..$size; my $m = sum(@dataset) / $size; print "m = $m\n"; my $sigma = sqrt( (reduce { $a + $b **2 } 0,@dataset) / $size - $m**2 ); print "sigma = $sigma\n"; $hash{int $_}++ for @dataset; my $scale = 180 * $stddev / $size; my @subbar = < >; for $i (min(@dataset)..max(@dataset)) { my $x = ($hash{$i} // 0) * $scale; my $full = int $x; my $part = 8 * ($x - $full); my $t1 = '' x $full; my $t2 = $subbar[$part]; print "$i\t$t1$t2\n"; }
197Statistics/Normal distribution
2perl
49e5d
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42`
198Stem-and-leaf plot
0go
rlwgm
public class StackTracer { public static void printStackTrace() { StackTraceElement[] elems = Thread.currentThread().getStackTrace(); System.out.println("Stack trace:"); for (int i = elems.length-1, j = 2 ; i >= 3 ; i--, j+=2) { System.out.printf("%" + j + "s%s.%s%n", "", elems[i].getClassName(), elems[i].getMethodName()); } } }
202Stack traces
9java
t09f9
try { throw new Error; } catch(e) { alert(e.stack); }
202Stack traces
10javascript
mduyv
import Data.List import Control.Arrow import Control.Monad nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128" ++ " 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115" ++ " 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146" nls :: [Int] nls = map read $ words nlsRaw groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) $ groupWith fst $ stems ++ map (second return) stemLeaf where stemLeaf = map (`quotRem` 10) ds stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b fb = length $ show $ maximum $ map abs ds
198Stem-and-leaf plot
8haskell
016s7
null
202Stack traces
11kotlin
oez8z
use warnings; use strict; use feature qw{ say }; sub uniq { my %uniq; undef @uniq{ @_ }; return keys %uniq } sub puzzle { my @states = uniq(@_); my %pairs; for my $state1 (@states) { for my $state2 (@states) { next if $state1 le $state2; my $both = join q(), grep ' ' ne $_, sort split //, lc "$state1$state2"; push @{ $pairs{$both} }, [ $state1, $state2 ]; } } for my $pair (keys %pairs) { next if 2 > @{ $pairs{$pair} }; for my $pair1 (@{ $pairs{$pair} }) { for my $pair2 (@{ $pairs{$pair} }) { next if 4 > uniq(@$pair1, @$pair2) or $pair1->[0] lt $pair2->[0]; say join ' = ', map { join ' + ', @$_ } $pair1, $pair2; } } } } my @states = ( 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', ); my @fictious = ( 'New Kory', 'Wen Kory', 'York New', 'Kory New', 'New Kory' ); say scalar @states, ' states:'; puzzle(@states); say @states + @fictious, ' states:'; puzzle(@states, @fictious);
199State name puzzle
2perl
pg8b0
str = ; str += ; print(str)
193String append
3python
23elz
function Inner( k ) print( debug.traceback() ) print "Program continues..." end function Middle( x, y ) Inner( x+y ) end function Outer( a, b, c ) Middle( a*b, c ) end Outer( 2, 3, 5 )
202Stack traces
1lua
iw3ot
const unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11}; unsigned long long gcd(unsigned long long a, unsigned long long b) { while (b != 0) { a %= b; a ^= b; b ^= a; a ^= b; } return a; } unsigned long long SQUFOF( unsigned long long N ) { unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s; unsigned long L, B, i; s = (unsigned long long)(sqrtl(N)+0.5); if (s*s == N) return s; for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) { D = multiplier[k]*N; Po = Pprev = P = sqrtl(D); Qprev = 1; Q = D - Po*Po; L = 2 * sqrtl( 2*s ); B = 3 * L; for (i = 2 ; i < B ; i++) { b = (unsigned long long)((Po + P)/Q); P = b*Q - P; q = Q; Q = Qprev + b*(Pprev - P); r = (unsigned long long)(sqrtl(Q)+0.5); if (!(i & 1) && r*r == Q) break; Qprev = q; Pprev = P; }; if (i >= B) continue; b = (unsigned long long)((Po - P)/r); Pprev = P = b*r + P; Qprev = r; Q = (D - Pprev*Pprev)/Qprev; i = 0; do { b = (unsigned long long)((Po + P)/Q); Pprev = P; P = b*Q - P; q = Q; Q = Qprev + b*(Pprev - P); Qprev = q; i++; } while (P != Pprev); r = gcd(N, Qprev); if (r != 1 && r != N) return r; } return 0; } int main(int argc, char *argv[]) { int i; const unsigned long long data[] = { 2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791, 9007199254740931, 11111111111111111, 314159265358979323, 384307168202281507, 419244183493398773, 658812288346769681, 922337203685477563, 1000000000000000127, 1152921505680588799, 1537228672809128917, 4611686018427387877}; for(int i = 0; i < nelems(data); i++) { unsigned long long example, factor, quotient; example = data[i]; factor = SQUFOF(example); if(factor == 0) { printf(, example); } else { quotient = example / factor; printf(, example, factor, quotient); } } }
204Square form factorization
5c
md2ys
typedef unsigned char bool; typedef unsigned long long uint64; void sieve(uint64 limit, uint64 *primes, uint64 *length) { uint64 i, count, p, p2; bool *c = calloc(limit + 1, sizeof(bool)); primes[0] = 2; count = 1; p = 3; for (;;) { p2 = p * p; if (p2 > limit) break; for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE; for (;;) { p += 2; if (!c[p]) break; } } for (i = 3; i <= limit; i += 2) { if (!c[i]) primes[count++] = i; } *length = count; free(c); } void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) { uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to); uint64 *primes = malloc((limit + 1) * sizeof(uint64)); bool add; sieve(limit, primes, &np); for (i = from; i <= to; ++i) { add = TRUE; for (j = 0; j < np; ++j) { p = primes[j]; p2 = p * p; if (p2 > i) break; if (i % p2 == 0) { add = FALSE; break; } } if (add) results[count++] = i; } *len = count; free(primes); } int main() { uint64 i, *sf, len; sf = malloc(1000000 * sizeof(uint64)); printf(); squareFree(1, 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 20 == 0) { printf(); } printf(, sf[i]); } printf(, TRILLION, TRILLION + 145); squareFree(TRILLION, TRILLION + 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 5 == 0) { printf(); } printf(, sf[i]); } printf(); int a[5] = {100, 1000, 10000, 100000, 1000000}; for (i = 0; i < 5; ++i) { squareFree(1, a[i], sf, &len); printf(, 1, a[i], len); } free(sf); return 0; }
205Square-free integers
5c
4975t
from __future__ import division import matplotlib.pyplot as plt import random mean, stddev, size = 50, 4, 100000 data = [random.gauss(mean, stddev) for c in range(size)] mn = sum(data) / size sd = (sum(x*x for x in data) / size - (sum(data) / size) ** 2) ** 0.5 print( % (mn, sd, max(data), min(data), size)) plt.hist(data,bins=50)
197Statistics/Normal distribution
3python
gcw4h
func step_up(){for !step(){step_up()}}
203Stair-climbing puzzle
0go
ej0a6
class Stair_climbing{ static void main(String[] args){ } static def step_up(){ while not step(){ step_up(); } } }
203Stair-climbing puzzle
7groovy
k5eh7
stepUp :: Robot () stepUp = untilM step stepUp untilM :: Monad m => m Bool -> m () -> m () untilM test action = do result <- test if result then return () else action >> untilM test action
203Stair-climbing puzzle
8haskell
3oczj
n <- 100000 u <- sqrt(-2*log(runif(n))) v <- 2*pi*runif(n) x <- u*cos(v) y <- v*sin(v) hist(x)
197Statistics/Normal distribution
13r
v6p27
public void stepUp() { while (!step()) stepUp(); }
203Stair-climbing puzzle
9java
iwzos
package main import ( "fmt" "math" ) func isqrt(x uint64) uint64 { x0 := x >> 1 x1 := (x0 + x/x0) >> 1 for x1 < x0 { x0 = x1 x1 = (x0 + x/x0) >> 1 } return x0 } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } var multiplier = []uint64{ 1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11, } func squfof(N uint64) uint64 { s := uint64(math.Sqrt(float64(N)) + 0.5) if s*s == N { return s } for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ { D := multiplier[k] * N P := isqrt(D) Pprev := P Po := Pprev Qprev := uint64(1) Q := D - Po*Po L := uint32(isqrt(8 * s)) B := 3 * L i := uint32(2) var b, q, r uint64 for ; i < B; i++ { b = uint64((Po + P) / Q) P = b*Q - P q = Q Q = Qprev + b*(Pprev-P) r = uint64(math.Sqrt(float64(Q)) + 0.5) if (i&1) == 0 && r*r == Q { break } Qprev = q Pprev = P } if i >= B { continue } b = uint64((Po - P) / r) P = b*r + P Pprev = P Qprev = r Q = (D - Pprev*Pprev) / Qprev i = 0 for { b = uint64((Po + P) / Q) Pprev = P P = b*Q - P q = Q Q = Qprev + b*(Pprev-P) Qprev = q i++ if P == Pprev { break } } r = gcd(N, Qprev) if r != 1 && r != N { return r } } return 0 } func main() { examples := []uint64{ 2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791, 9007199254740931, 11111111111111111, 314159265358979323, 384307168202281507, 419244183493398773, 658812288346769681, 922337203685477563, 1000000000000000127, 1152921505680588799, 1537228672809128917, 4611686018427387877, } fmt.Println("Integer Factor Quotient") fmt.Println("------------------------------------------") for _, N := range examples { fact := squfof(N) quot := "fail" if fact > 0 { quot = fmt.Sprintf("%d", N/fact) } fmt.Printf("%-20d%-10d%s\n", N, fact, quot) } }
204Square form factorization
0go
a7q1f
from collections import defaultdict states = [, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] states = sorted(set(states)) smap = defaultdict(list) for i, s1 in enumerate(states[:-1]): for s2 in states[i + 1:]: smap[.join(sorted(s1 + s2))].append(s1 + + s2) for pairs in sorted(smap.itervalues()): if len(pairs) > 1: print .join(pairs)
199State name puzzle
3python
1ropc
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1;
198Stem-and-leaf plot
9java
a7n1y
null
203Stair-climbing puzzle
11kotlin
qbix1
double rand01() { return rand() / (RAND_MAX + 1.0); } double avg(int count, double *stddev, int *hist) { double x[count]; double m = 0, s = 0; for (int i = 0; i < n_bins; i++) hist[i] = 0; for (int i = 0; i < count; i++) { m += (x[i] = rand01()); hist[(int)(x[i] * n_bins)] ++; } m /= count; for (int i = 0; i < count; i++) s += x[i] * x[i]; *stddev = sqrt(s / count - m * m); return m; } void hist_plot(int *hist) { int max = 0, step = 1; double inc = 1.0 / n_bins; for (int i = 0; i < n_bins; i++) if (hist[i] > max) max = hist[i]; if (max >= 60) step = (max + 59) / 60; for (int i = 0; i < n_bins; i++) { printf(, i * inc, (i + 1) * inc, hist[i]); for (int j = 0; j < hist[i]; j += step) printf(); printf(); } } typedef struct { uint64_t size; double sum, x2; uint64_t hist[n_bins]; } moving_rec; void moving_avg(moving_rec *rec, double *data, int count) { double sum = 0, x2 = 0; for (int i = 0; i < count; i++) { sum += data[i]; x2 += data[i] * data[i]; rec->hist[(int)(data[i] * n_bins)]++; } rec->sum += sum; rec->x2 += x2; rec->size += count; } int main() { double m, stddev; int hist[n_bins], samples = 10; while (samples <= 10000) { m = avg(samples, &stddev, hist); printf(, samples, m, stddev); samples *= 10; } printf(); hist_plot(hist); printf(); moving_rec rec = { 0, 0, 0, {0} }; double data[100]; for (int i = 0; i < 10000; i++) { for (int j = 0; j < 100; j++) data[j] = rand01(); moving_avg(&rec, data, 100); if ((i % 1000) == 999) { printf(, rec.size/1000, rec.sum / rec.size, sqrt(rec.x2 * rec.size - rec.sum * rec.sum)/rec.size ); } } }
206Statistics/Basic
5c
5mguk
s = s += s << puts s
193String append
14ruby
uyxvz
use std::ops::Add; fn main(){ let hello = String::from("Hello world"); println!("{}", hello.add("!!!!")); }
193String append
15rust
5mquq
<!DOCTYPE html PUBLIC "-
198Stem-and-leaf plot
10javascript
sp3qz
use Carp 'cluck'; sub g {cluck 'Hello from &g';} sub f {g;} f;
202Stack traces
2perl
gcb4e
function step_up() while not step() do step_up() end end
203Stair-climbing puzzle
1lua
spnq8
use strict; use warnings; use feature 'say'; use ntheory <is_prime gcd forcomb vecprod>; my @multiplier; my @p = <3 5 7 11>; forcomb { push @multiplier, vecprod @p[@_] } scalar @p; sub sff { my($N) = shift; return 1 if is_prime $N; return sqrt $N if sqrt($N) == int sqrt $N; for my $k (@multiplier) { my $P0 = int sqrt($k*$N); my $Q0 = 1; my $Q = $k*$N - $P0**2; my $P1 = $P0; my $Q1 = $Q0; my $P = 0; my $Qn = 0; my $b = 0; until (sqrt($Q) == int(sqrt($Q))) { $b = int( int(sqrt($k*$N) + $P1 ) / $Q); $P = $b*$Q - $P1; $Qn = $Q1 + $b*($P1 - $P); ($Q1, $Q, $P1) = ($Q, $Qn, $P); } $b = int( int( sqrt($k*$N)+$P ) / $Q ); $P1 = $b*$Q0 - $P; $Q = ( $k*$N - $P1**2 )/$Q0; $Q1 = $Q0; while () { $b = int( int(sqrt($k*$N)+$P1 ) / $Q ); $P = $b*$Q - $P1; $Qn = $Q1 + $b*($P1 - $P); last if $P == $P1; ($Q1, $Q, $P1) = ($Q, $Qn, $P); } for (gcd $N, $P) { return $_ if $_ != 1 and $_ != $N } } return 0 } for my $data ( 11111, 2501, 12851, 13289, 75301, 120787, 967009, 997417, 4558849, 7091569, 13290059, 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791, 11111111111111111, 384307168202281507, 1000000000000000127, 9007199254740931, 922337203685477563, 314159265358979323, 1152921505680588799, 658812288346769681, 419244183493398773, 1537228672809128917) { my $v = sff($data); if ($v == 0) { say 'The number ' . $data . ' is not factored.' } elsif ($v == 1) { say 'The number ' . $data . ' is a prime.' } else { say "$data = " . join ' * ', sort {$a <=> $b} $v, int $data/int($v) } }
204Square form factorization
2perl
234lf
var d = "Hello"
193String append
16scala
rl8gn
class NormalFromUniform def initialize() @next = nil end def rand() if @next retval, @next = @next, nil return retval else u = v = s = nil loop do u = Random.rand(-1.0..1.0) v = Random.rand(-1.0..1.0) s = u**2 + v**2 break if (s > 0.0) && (s <= 1.0) end f = Math.sqrt(-2.0 * Math.log(s) / s) @next = v * f return u * f end end end
197Statistics/Normal distribution
14ruby
72qri
package main import ( "fmt" "sternbrocot" ) func main() {
201Stern-Brocot sequence
0go
gcp4n
<?php class StackTraceDemo { static function inner() { debug_print_backtrace(); } static function middle() { self::inner(); } static function outer() { self::middle(); } } StackTraceDemo::outer(); ?>
202Stack traces
12php
nx6ig
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1)
205Square-free integers
0go
oed8q
require 'set' Primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] States = [ , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] def print_answer(states) goedel = lambda {|str| str.chars.map {|c| Primes[c.ord - 65]}.reduce(:*)} pairs = Hash.new {|h,k| h[k] = Array.new} map = states.uniq.map {|state| [state, goedel[state.upcase.delete()]]} map.combination(2) {|(s1,g1), (s2,g2)| pairs[g1 * g2] << [s1, s2]} result = [] pairs.values.select {|val| val.length > 1}.each do |list_of_pairs| list_of_pairs.combination(2) do |pair1, pair2| if Set[*pair1, *pair2].length == 4 result << [pair1, pair2] end end end result.each_with_index do |(pair1, pair2), i| puts % [i+1, pair1.join(', '), pair2.join(', ')] end end puts print_answer(States) puts puts print_answer(States + [, , , , ])
199State name puzzle
14ruby
ejnax
null
197Statistics/Normal distribution
15rust
jvs72
import Data.List (elemIndex) sb :: [Int] sb = 1: 1: f (tail sb) sb where f (a: aa) (b: bb) = a + b: a: f aa bb main :: IO () main = do print $ take 15 sb print [ (i, 1 + (\(Just i) -> i) (elemIndex i sb)) | i <- [1 .. 10] <> [100] ] print $ all (\(a, b) -> 1 == gcd a b) $ take 1000 $ zip sb (tail sb)
201Stern-Brocot sequence
8haskell
spfqk
import traceback def f(): return g() def g(): traceback.print_stack() f()
202Stack traces
3python
rlpgq
import Data.List.Split (chunksOf) import Math.NumberTheory.Primes (factorise) import Text.Printf (printf) isSquareFree :: Integer -> Bool isSquareFree = all ((== 1) . snd) . factorise squareFrees :: Integer -> Integer -> [Integer] squareFrees lo hi = filter isSquareFree [lo..hi] counts :: (Ord a, Num b) => [a] -> [a] -> [b] counts = go 0 where go c lims@(l:ls) (v:vs) | v > l = c: go (c+1) ls vs | otherwise = go (c+1) lims vs go _ [] _ = [] go c ls [] = replicate (length ls) c printSquareFrees :: Int -> Integer -> Integer -> IO () printSquareFrees cols lo hi = let ns = squareFrees lo hi title = printf "Square free numbers from%d to%d\n" lo hi body = unlines $ map concat $ chunksOf cols $ map (printf "%3d") ns in putStrLn $ title ++ body printSquareFreeCounts :: [Integer] -> Integer -> Integer -> IO () printSquareFreeCounts lims lo hi = let cs = counts lims $ squareFrees lo hi :: [Integer] title = printf "Counts of square-free numbers\n" body = unlines $ zipWith (printf " from 1 to%d:%d") lims cs in putStrLn $ title ++ body main :: IO () main = do printSquareFrees 20 1 145 printSquareFrees 5 1000000000000 1000000000145 printSquareFreeCounts [100, 1000, 10000, 100000, 1000000] 1 1000000
205Square-free integers
8haskell
235ll
object StateNamePuzzle extends App {
199State name puzzle
16scala
spzqo
var s = "foo"
193String append
17swift
v6w2r
null
198Stem-and-leaf plot
11kotlin
husj3
foo <- function() { bar <- function() { sys.calls() } bar() } foo()
202Stack traces
13r
uyjvx
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1];
205Square-free integers
9java
6i93z
data = { 12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, 31,116,146 } table.sort( data ) min, max = data[1], data[#data] p = 1 for stem = math.floor(min/10), math.floor(max/10) do io.write( string.format( "%2d | ", stem ) ) while data[p] ~= nil and math.floor( data[p]/10 ) == stem do io.write( string.format( "%2d ", data[p] % 10 ) ) p = p + 1 end print "" end
198Stem-and-leaf plot
1lua
k50h2
import java.math.BigInteger; import java.util.LinkedList; public class SternBrocot { static LinkedList<Integer> sequence = new LinkedList<Integer>(){{ add(1); add(1); }}; private static void genSeq(int n){ for(int conIdx = 1; sequence.size() < n; conIdx++){ int consider = sequence.get(conIdx); int pre = sequence.get(conIdx - 1); sequence.add(consider + pre); sequence.add(consider); } } public static void main(String[] args){ genSeq(1200); System.out.println("The first 15 elements are: " + sequence.subList(0, 15)); for(int i = 1; i <= 10; i++){ System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1)); } System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1)); boolean failure = false; for(int i = 0; i < 999; i++){ failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE); } System.out.println("All GCDs are" + (failure ? " not": "") + " 1"); } }
201Stern-Brocot sequence
9java
1r0p2
sub step_up { step_up until step; }
203Stair-climbing puzzle
2perl
v6r20
void end_with_db(void); MYSQL *mysql = NULL; bool connect_db(const char *host, const char *user, const char *pwd, const char *db, unsigned int port) { if ( mysql == NULL ) { if (mysql_library_init(0, NULL, NULL)) return false; mysql = mysql_init(NULL); if ( mysql == NULL ) return false; MYSQL *myp = mysql_real_connect(mysql, host, user, pwd, db, port, NULL, 0); if (myp == NULL) { fprintf(stderr, , mysql_error(mysql)); end_with_db(); return false; } } return true; } bool create_user(const char *username, const char *password) { int i; char binarysalt[SALTBYTE]; char salt[SALTBYTE*2+1]; char md5hash[MD5_DIGEST_LENGTH]; char saltpass[SALTBYTE+PASSWORDLIMIT+1]; char pass_md5[MD5_DIGEST_LENGTH*2 + 1]; char user[USERNAMELIMIT*2 + 1]; char *q = NULL; static const char query[] = ; static const size_t qlen = sizeof query; for(i=0; username[i] != '\0' && i < USERNAMELIMIT; i++) ; if ( username[i] != '\0' ) return false; for(i=0; password[i] != '\0' && i < PASSWORDLIMIT; i++) ; if ( password[i] != '\0' ) return false; srand(time(NULL)); for(i=0; i < SALTBYTE; i++) { binarysalt[i] = rand()%256; } (void)mysql_hex_string(salt, binarysalt, SALTBYTE); for(i=0; i < SALTBYTE; i++) saltpass[i] = binarysalt[i]; strcpy(saltpass+SALTBYTE, password); (void)MD5(saltpass, SALTBYTE + strlen(password), md5hash); (void)mysql_hex_string(pass_md5, md5hash, MD5_DIGEST_LENGTH); (void)mysql_real_escape_string(mysql, user, username, strlen(username)); q = malloc(qlen + USERNAMELIMIT*2 + MD5_DIGEST_LENGTH*2 + SALTBYTE*2 + 1); if ( q == NULL ) return false; sprintf(q, query, user, salt, pass_md5); fprintf(stderr, , q); int res = mysql_query(mysql, q); free(q); if ( res != 0 ) { fprintf(stderr, , mysql_error(mysql)); return false; } return true; } bool authenticate_user(const char *username, const char *password) { char user[USERNAMELIMIT*2 + 1]; char md5hash[MD5_DIGEST_LENGTH]; char saltpass[SALTBYTE+PASSWORDLIMIT+1]; bool authok = false; char *q = NULL; int i; static const char query[] = ; static const size_t qlen = sizeof query; for(i=0; username[i] != '\0' && i < USERNAMELIMIT; i++) ; if ( username[i] != '\0' ) return false; for(i=0; password[i] != '\0' && i < PASSWORDLIMIT; i++) ; if ( password[i] != '\0' ) return false; (void)mysql_real_escape_string(mysql, user, username, strlen(username)); q = malloc(qlen + strlen(user) + 1); if (q == NULL) return false; sprintf(q, query, username); int res = mysql_query(mysql, q); free(q); if ( res != 0 ) { fprintf(stderr, , mysql_error(mysql)); return false; } MYSQL_RES *qr = mysql_store_result(mysql); if ( qr == NULL ) return false; if ( mysql_num_rows(qr) != 1 ) { mysql_free_result(qr); return false; } MYSQL_ROW row = mysql_fetch_row(qr); unsigned long *len = mysql_fetch_lengths(qr); memcpy(saltpass, row[2], len[2]); memcpy(saltpass + len[2], password, strlen(password)); (void)MD5(saltpass, SALTBYTE + strlen(password), md5hash); authok = memcmp(md5hash, row[3], len[3]) == 0; mysql_free_result(qr); return authok; } void end_with_db(void) { mysql_close(mysql); mysql = NULL; mysql_library_end(); } int main(int argc, char **argv) { if ( argc < 4 ) return EXIT_FAILURE; if ( connect_db(, , , , 0 ) ) { if ( strcmp(argv[1], ) == 0 ) { if (create_user(argv[2], argv[3])) printf(); } else if ( strcmp(argv[1], ) == 0 ) { if (authenticate_user(argv[2], argv[3])) printf(); else printf(); } else { printf(); } end_with_db(); } return EXIT_SUCCESS; }
207SQL-based authentication
5c
qbsxc
import 'dart:math' as Math show sqrt, pow, Random;
206Statistics/Basic
18dart
9flm8
(() => { 'use strict'; const main = () => {
201Stern-Brocot sequence
10javascript
qbdx8
def outer(a,b,c) middle a+b, b+c end def middle(d,e) inner d+e end def inner(f) puts caller(0) puts end outer 2,3,5
202Stack traces
14ruby
jva7x
package main import ( "bytes" "crypto/md5" "crypto/rand" "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func connectDB() (*sql.DB, error) { return sql.Open("mysql", "rosetta:code@/rc") } func createUser(db *sql.DB, user, pwd string) error { salt := make([]byte, 16) rand.Reader.Read(salt) _, err := db.Exec(`insert into users (username, pass_salt, pass_md5) values (?,?,?)`, user, salt, saltHash(salt, pwd)) if err != nil { return fmt.Errorf("User%s already exits", user) } return nil } func authenticateUser(db *sql.DB, user, pwd string) error { var salt, hash []byte row := db.QueryRow(`select pass_salt, pass_md5 from users where username=?`, user) if err := row.Scan(&salt, &hash); err != nil { return fmt.Errorf("User%s unknown", user) } if !bytes.Equal(saltHash(salt, pwd), hash) { return fmt.Errorf("User%s invalid password", user) } return nil } func saltHash(salt []byte, pwd string) []byte { h := md5.New() h.Write(salt) h.Write([]byte(pwd)) return h.Sum(nil) } func main() {
207SQL-based authentication
0go
23vl7
null
205Square-free integers
11kotlin
dqznz
def callStack = try { error("exception") } catch { case ex => ex.getStackTrace drop 2 } def printStackTrace = callStack drop 1 foreach println
202Stack traces
16scala
pgqbj
def step_up1(): deficit = 1 while deficit > 0: if step(): deficit -= 1 else: deficit += 1
203Stair-climbing puzzle
3python
uy7vd
step <- function() { success <- runif(1) > p level <<- level - 1 + (2 * success) success }
203Stair-climbing puzzle
13r
ct595
import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.math.BigInteger; class UserManager { private Connection dbConnection; public UserManager() { } private String md5(String aString) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; String hex; StringBuffer hexString; byte[] bytesOfMessage; byte[] theDigest; hexString = new StringBuffer(); bytesOfMessage = aString.getBytes("UTF-8"); md = MessageDigest.getInstance("MD5"); theDigest = md.digest(bytesOfMessage); for (int i = 0; i < theDigest.length; i++) { hex = Integer.toHexString(0xff & theDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } public void connectDB(String host, int port, String db, String user, String password) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); this.dbConnection = DriverManager.getConnection("jdbc:mysql:
207SQL-based authentication
9java
jvh7c
function squareFree (n) for root = 2, math.sqrt(n) do if n % (root * root) == 0 then return false end end return true end function run (lo, hi, showValues) io.write("From " .. lo .. " to " .. hi) io.write(showValues and ":\n" or " = ") local count = 0 for i = lo, hi do if squareFree(i) then if showValues then io.write(i, "\t") else count = count + 1 end end end print(showValues and "\n" or count) end local testCases = { {1, 145, true}, {1000000000000, 1000000000145, true}, {1, 100}, {1, 1000}, {1, 10000}, {1, 100000}, {1, 1000000} } for _, example in pairs(testCases) do run(unpack(example)) end
205Square-free integers
1lua
fs3dp
null
207SQL-based authentication
11kotlin
5m4ua
null
201Stern-Brocot sequence
11kotlin
jve7r
def step_up start_position = $position step until ($position == start_position + 1) end def step if rand < 0.5 $position -= 1 p if $DEBUG return false else $position += 1 p if $DEBUG return true end end $position = 0 step_up
203Stair-climbing puzzle
14ruby
49h5p
int main() { int n = 1, count = 0, sq, cr; for ( ; count < 30; ++n) { sq = n * n; cr = (int)cbrt((double)sq); if (cr * cr * cr != sq) { count++; printf(, sq); } else { printf(, sq); } } return 0; }
208Square but not cube
5c
3o3za
package main import ( "fmt" "math" "math/rand" "strings" ) func main() { sample(100) sample(1000) sample(10000) } func sample(n int) {
206Statistics/Basic
0go
8ai0g
null
201Stern-Brocot sequence
1lua
huwj8
fn step_up() { while!step() { step_up(); } }
203Stair-climbing puzzle
15rust
gck4o
use DBI; sub connect_db { my ($dbname, $host, $user, $pass) = @_; my $db = DBI->connect("dbi:mysql:$dbname:$host", $user, $pass) or die $DBI::errstr; $db->{RaiseError} = 1; $db } sub create_user { my ($db, $user, $pass) = @_; my $salt = pack "C*", map {int rand 256} 1..16; $db->do("INSERT IGNORE INTO users (username, pass_salt, pass_md5) VALUES (?,?, unhex(md5(concat(pass_salt,?))))", undef, $user, $salt, $pass) and $db->{mysql_insertid} or undef } sub authenticate_user { my ($db, $user, $pass) = @_; my $userid = $db->selectrow_array("SELECT userid FROM users WHERE username=? AND pass_md5=unhex(md5(concat(pass_salt,?)))", undef, $user, $pass); $userid }
207SQL-based authentication
2perl
oei8x
import Data.Foldable (foldl') import System.Random (randomRs, newStdGen) import Control.Monad (zipWithM_) import System.Environment (getArgs) intervals :: [(Double, Double)] intervals = map conv [0 .. 9] where xs = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] conv s = let [h, l] = take 2 $ drop s xs in (h, l) count :: [Double] -> [Int] count rands = map (\iv -> foldl'' (loop iv) 0 rands) intervals where loop :: (Double, Double) -> Int -> Double -> Int loop (lo, hi) n x | lo <= x && x < hi = n + 1 | otherwise = n data Pair a b = Pair !a !b sumLen :: [Double] -> Pair Double Double sumLen = fion2 . foldl'' (\(Pair s l) x -> Pair (s + x) (l + 1)) (Pair 0.0 0) where fion2 :: Pair Double Int -> Pair Double Double fion2 (Pair s l) = Pair s (fromIntegral l) divl :: Pair Double Double -> Double divl (Pair _ 0.0) = 0.0 divl (Pair s l) = s / l mean :: [Double] -> Double mean = divl . sumLen stddev :: [Double] -> Double stddev xs = sqrt $ foldl'' (\s x -> s + (x - m) ^ 2) 0 xs / l where p@(Pair s l) = sumLen xs m = divl p main = do nr <- read . head <$> getArgs rands <- take nr . randomRs (0.0, 1.0) <$> newStdGen putStrLn $ "The mean is " ++ show (mean rands) ++ "!" putStrLn $ "The standard deviation is " ++ show (stddev rands) ++ "!" zipWithM_ (\iv fq -> putStrLn $ ivstr iv ++ ": " ++ fqstr fq) intervals (count rands) where fqstr i = replicate (if i > 50 then div i (div i 50) else i) '*' ivstr (lo, hi) = show lo ++ " - " ++ show hi foldl'' = foldl'
206Statistics/Basic
8haskell
lzvch
def stepUp { while (! step) stepUp }
203Stair-climbing puzzle
16scala
jv17i
my @data = sort {$a <=> $b} qw( 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 ); my $columns = @data; my $laststem = undef; for my $value (@data) { my $stem = int($value / 10); my $leaf = $value % 10; while (not defined $laststem or $stem > $laststem) { if (not defined $laststem) { $laststem = $stem - 1; } else { print " \n"; } $laststem++; printf "%3d |", $laststem; } print " $leaf"; }
198Stem-and-leaf plot
2perl
z8utb
function connect_db($database, $db_user, $db_password, $host = 'localhost', $port = NULL, $die = false) { if(!$db_handle = @mysql_connect($host.($port? ':'.$port : ''), $db_user, $db_password)) { if($die) die(.mysql_error()); else return false; } if(!@mysql_select_db($database, $db_handle)) { if($die) die(.mysql_error()); else return false; } return $db_handle; } function create_user($username, $password, $db_handle) { if(strlen($username) > 32) return false; $salt = ''; do { $salt .= chr(mt_rand(32, 254)); } while(strlen($salt) < 16); $pass_md5 = md5($salt.$password); $username = mysql_real_escape_string($username); $salt = mysql_real_escape_string($salt); if(!@mysql_query(, $db_handle)) return false; return mysql_insert_id($db_handle); } function authenticate_user($username, $password, $db_handle) { $safe_username = mysql_real_escape_string($username); if(!$result = @mysql_query(, $db_handle)) return false; $row = @mysql_fetch_assoc($result); if(md5($row['pass_salt'].$password) != $row['pass_md5']) return false; return $row['userid']; }
207SQL-based authentication
12php
gcr42
(def squares (map #(* % %) (drop 1 (range)))) (def square-cubes (map #(int (. Math pow % 6)) (drop 1 (range)))) (def squares-not-cubes (filter #(not (= % (first (drop-while (fn [n] (< n %)) square-cubes)))) squares)) (println "Squares but not cubes:") (println (take 30 squares-not-cubes)) (println "Both squares and cubes:") (println (take 15 square-cubes))
208Square but not cube
6clojure
ctc9b
import static java.lang.Math.pow; import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; import static java.util.stream.IntStream.range; public class Test { static double[] meanStdDev(double[] numbers) { if (numbers.length == 0) return new double[]{0.0, 0.0}; double sx = 0.0, sxx = 0.0; long n = 0; for (double x : numbers) { sx += x; sxx += pow(x, 2); n++; } return new double[]{sx / n, pow((n * sxx - pow(sx, 2)), 0.5) / n}; } static String replicate(int n, String s) { return range(0, n + 1).mapToObj(i -> s).collect(joining()); } static void showHistogram01(double[] numbers) { final int maxWidth = 50; long[] bins = new long[10]; for (double x : numbers) bins[(int) (x * bins.length)]++; double maxFreq = stream(bins).max().getAsLong(); for (int i = 0; i < bins.length; i++) System.out.printf("%3.1f:%s%n", i / (double) bins.length, replicate((int) (bins[i] / maxFreq * maxWidth), "*")); System.out.println(); } public static void main(String[] a) { Locale.setDefault(Locale.US); for (int p = 1; p < 7; p++) { double[] n = range(0, (int) pow(10, p)) .mapToDouble(i -> Math.random()).toArray(); System.out.println((int)pow(10, p) + " numbers:"); double[] res = meanStdDev(n); System.out.printf(" Mean:%8.6f, SD:%8.6f%n", res[0], res[1]); showHistogram01(n); } } }
206Statistics/Basic
9java
3oyzg
func step_up() { while!step() { step_up() } }
203Stair-climbing puzzle
17swift
5mju8
import mysql.connector import hashlib import sys import random DB_HOST = DB_USER = DB_PASS = DB_NAME = def connect_db(): ''' Try to connect DB and return DB instance, if not, return False ''' try: return mysql.connector.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME) except: return False def create_user(username, passwd): ''' if user was successfully created, returns its ID; returns None on error ''' db = connect_db() if not db: print return None cursor = db.cursor() salt = randomValue(16) passwd_md5 = hashlib.md5(salt+passwd).hexdigest() try: cursor.execute(, (username, salt, passwd_md5)) cursor.execute(, (username,) ) id = cursor.fetchone() db.commit() cursor.close() db.close() return id[0] except: print 'Username was already taken. Please select another' return None def authenticate_user(username, passwd): db = connect_db() if not db: print return False cursor = db.cursor() cursor.execute(, (username,)) row = cursor.fetchone() cursor.close() db.close() if row is None: return False salt = row[0] correct_md5 = row[1] tried_md5 = hashlib.md5(salt+passwd).hexdigest() return correct_md5 == tried_md5 def randomValue(length): ''' Creates random value with given length''' salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789' return ''.join(random.choice(salt_chars) for x in range(length)) if __name__ == '__main__': user = randomValue(10) passwd = randomValue(16) new_user_id = create_user(user, passwd) if new_user_id is None: print 'Failed to create user%s'% user sys.exit(1) auth = authenticate_user(user, passwd) if auth: print 'User%s authenticated successfully'% user else: print 'User%s failed'% user
207SQL-based authentication
3python
iwnof
use ntheory qw/is_square_free moebius/; sub square_free_count { my ($n) = @_; my $count = 0; foreach my $k (1 .. sqrt($n)) { $count += moebius($k) * int($n / $k**2); } return $count; } print "Squarefree numbers between 1 and 145:\n"; print join(' ', grep { is_square_free($_) } 1 .. 145), "\n"; print "\nSquare-free numbers between 10^12 and 10^12 + 145:\n"; print join(' ', grep { is_square_free($_) } 1e12 .. 1e12 + 145), "\n"; print "\n"; foreach my $n (2 .. 6) { my $c = square_free_count(10**$n); print "The number of square-free numbers between 1 and 10^$n (inclusive) is: $c\n"; }
205Square-free integers
2perl
jvb7f
void talk(const char *s) { pid_t pid; int status; pid = fork(); if (pid < 0) { perror(); exit(1); } if (pid == 0) { execlp(, , s, (void*)0); perror(); _exit(1); } waitpid(pid, &status, 0); if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) exit(1); } int main() { talk(); return 0; }
209Speech synthesis
5c
rc4g7
require 'mysql2' require 'securerandom' require 'digest' def connect_db(host, port = nil, username, password, db) Mysql2::Client.new( host: host, port: port, username: username, password: password, database: db ) end def create_user(client, username, password) salt = SecureRandom.random_bytes(16) password_md5 = Digest::MD5.hexdigest(salt + password) statement = client.prepare('INSERT INTO users (username, pass_salt, pass_md5) VALUES (?,?,?)') statement.execute(username, salt, password_md5) statement.last_id end def authenticate_user(client, username, password) user_record = client.prepare().first return false unless user_record password_md5 = Digest::MD5.hexdigest(user_record['pass_salt'] + password) password_md5 == user_record['pass_md5'] end
207SQL-based authentication
14ruby
dqfns
(use 'speech-synthesis.say) (say "This is an example of speech synthesis.")
209Speech synthesis
6clojure
b5hkz
null
206Statistics/Basic
11kotlin
nxfij
import math def SquareFree ( _number ): max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number% ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( .format(i), end= ) count += 1 print ( .format(_start, _end, count)) ListSquareFrees( 1, 100 ) ListSquareFrees( 1000000000000, 1000000000145 )
205Square-free integers
3python
hupjw
package main import ( "go/build" "log" "path/filepath" "github.com/unixpickle/gospeech" "github.com/unixpickle/wav" ) const pkgPath = "github.com/unixpickle/gospeech" const input = "This is an example of speech synthesis." func main() { p, err := build.Import(pkgPath, ".", build.FindOnly) if err != nil { log.Fatal(err) } d := filepath.Join(p.Dir, "dict/cmudict-IPA.txt") dict, err := gospeech.LoadDictionary(d) if err != nil { log.Fatal(err) } phonetics := dict.TranslateToIPA(input) synthesized := gospeech.DefaultVoice.Synthesize(phonetics) wav.WriteFile(synthesized, "output.wav") }
209Speech synthesis
0go
nwoi1
'say "This is an example of speech synthesis."'.execute()
209Speech synthesis
7groovy
sbxq1
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |'% ( stemwidth, laststem)) out.append('%0*i'% (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier:%i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
198Stem-and-leaf plot
3python
3o5zc
import System.Process (callProcess) say text = callProcess "espeak" [" main = say "This is an example of speech synthesis."
209Speech synthesis
8haskell
u62v2
var utterance = new SpeechSynthesisUtterance("This is an example of speech synthesis."); window.speechSynthesis.speak(utterance);
209Speech synthesis
10javascript
v3l25
math.randomseed(os.time()) function randList (n)
206Statistics/Basic
1lua
dqtnq
x <- c(12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146) stem(x)
198Stem-and-leaf plot
13r
dqlnt
use strict; use warnings; sub stern_brocot { my @list = (1, 1); sub { push @list, $list[0] + $list[1], $list[1]; shift @list; } } { my $generator = stern_brocot; print join ' ', map &$generator, 1 .. 15; print "\n"; } for (1 .. 10, 100) { my $index = 1; my $generator = stern_brocot; $index++ until $generator->() == $_; print "first occurrence of $_ is at index $index\n"; } { sub gcd { my ($u, $v) = @_; $v ? gcd($v, $u % $v) : abs($u); } my $generator = stern_brocot; my ($a, $b) = ($generator->(), $generator->()); for (1 .. 1000) { die "unexpected GCD for $a and $b" unless gcd($a, $b) == 1; ($a, $b) = ($b, $generator->()); } }
201Stern-Brocot sequence
2perl
t0cfg
null
209Speech synthesis
11kotlin
tsdf0
require class Integer def square_free? prime_division.none?{|pr, exp| exp > 1} end end puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join()} puts m = 10**12 puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join()} puts markers = [100, 1000, 10_000, 100_000, 1_000_000] count = 0 (1..1_000_000).each do |n| count += 1 if n.square_free? puts if markers.include?(n) end
205Square-free integers
14ruby
b4akq
char *split(char *str); int main(int argc,char **argv) { char input[13]=; printf(,split(input)); } char *split(char *str) { char last=*str,*result=malloc(3*strlen(str)),*counter=result; for (char *c=str;*c;c++) { if (*c!=last) { strcpy(counter,); counter+=2; last=*c; } *counter=*c; counter++; } *(counter--)='\0'; return realloc(result,strlen(result)); }
210Split a character string based on change of character
5c
81q04
while:; do for rod in \| / - \\; do printf ' %s\r' $rod; sleep 0.25; done done
211Spinning rod animation/Text
4bash
xh1wb
int main() { int i, j, ms = 250; const char *a = ; time_t start, now; struct timespec delay; delay.tv_sec = 0; delay.tv_nsec = ms * 1000000L; printf(); time(&start); while(1) { for (i = 0; i < 4; i++) { printf(); printf(); for (j = 0; j < 80; j++) { printf(, a[i]); } fflush(stdout); nanosleep(&delay, NULL); } time(&now); if (difftime(now, start) >= 20) break; } printf(); return 0; }
211Spinning rod animation/Text
5c
sbeq5