code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
.startswith() .endswith() in in loc = .find() loc = .find() loc = .find(,loc+1)
188String matching
3python
yne6q
s <- "abcdefgh" n <- 2; m <- 2; char <- 'd'; chars <- 'cd' substring(s, n, n + m) substring(s, n) substring(s, 1, nchar(s)-1) indx <- which(strsplit(s, '')[[1]]%in% strsplit(char, '')[[1]]) substring(s, indx, indx + m) indx <- which(strsplit(s, '')[[1]]%in% strsplit(chars, '')[[1]])[1] substring(s, indx, indx + m)
183Substring
13r
23dlg
use utf8; use Encode qw(encode); print length encode 'UTF-8', "Hello, world! "; print length encode 'UTF-16', "Hello, world! ";
190String length
2perl
3obzs
<?php foreach (array('mse', '', 'Jos') as $s1) { printf('String measured with strlen:%d mb_strlen:%s grapheme_strlen%s%s', $s1, strlen($s1),mb_strlen($s1), grapheme_strlen($s1), PHP_EOL); }
190String length
12php
pg6ba
puts (1..1000).inject{ |sum, x| sum + 1.0 / x ** 2 }
171Sum of a series
14ruby
dstns
.downcase .upcase .swapcase .capitalize
189String case
14ruby
t0kf2
fn main() { println!("{}", "jalapeo".to_uppercase());
189String case
15rust
z8bto
val s="alphaBETA" println(s.toUpperCase)
189String case
16scala
yna63
p 'abcd'.start_with?('ab') p 'abcd'.end_with?('ab') p 'abab'.include?('bb') p 'abab'.include?('ab') p 'abab'['bb'] p 'abab'['ab'] p 'abab'.index('bb') p 'abab'.index('ab') p 'abab'.index('ab', 1) p 'abab'.rindex('ab')
188String matching
14ruby
9fxmz
const LOWER: i32 = 1; const UPPER: i32 = 1000;
171Sum of a series
15rust
f0zd6
fn print_match(possible_match: Option<usize>) { match possible_match { Some(match_pos) => println!("Found match at pos {}", match_pos), None => println!("Did not find any matches") } } fn main() { let s1 = "abcd"; let s2 = "abab"; let s3 = "ab";
188String matching
15rust
ctq9z
scala> 1 to 1000 map (x => 1.0 / (x * x)) sum res30: Double = 1.6439345666815615
171Sum of a series
16scala
3iyzy
"abcd".startsWith("ab")
188String matching
16scala
v682s
str = 'abcdefgh' n = 2 m = 3 puts str[n, m] puts str[n..m] puts str[n..-1] puts str[0..-2] puts str[str.index('d'), m] puts str[str.index('de'), m] puts str[/a.*d/]
183Substring
14ruby
rlygs
print len('ascii')
190String length
3python
6ip3w
let s = "abcdef"; let n = 2; let m = 3;
183Substring
15rust
72mrc
a <- "m\u00f8\u00f8se" print(nchar(a, type="bytes"))
190String length
13r
fsjdc
DECLARE @s VARCHAR(10) SET @s = 'alphaBETA' print UPPER(@s) print LOWER(@s)
189String case
19sql
ctx9p
var str = "Hello, playground" str.hasPrefix("Hell")
188String matching
17swift
mdwyk
object Substring {
183Substring
16scala
k5lhk
CREATE TABLE t1 (n REAL); -- this is postgresql specific, fill the table INSERT INTO t1 (SELECT generate_series(1,1000)::REAL); WITH tt AS ( SELECT 1/(n*n) AS recip FROM t1 ) SELECT SUM(recip) FROM tt;
171Sum of a series
19sql
mfcyl
import Foundation println("alphaBETA".uppercaseString) println("alphaBETA".lowercaseString) println("foO BAr".capitalizedString)
189String case
17swift
fshdk
func sumSeries(var n: Int) -> Double { var ret: Double = 0 for i in 1...n { ret += (1 / pow(Double(i), 2)) } return ret } output: 1.64393456668156
171Sum of a series
17swift
nqfil
.bytesize
190String length
14ruby
mdayj
fn main() { let s = "";
190String length
15rust
9femm
object StringLength extends App { val s1 = "mse" val s3 = List("\uD835\uDD18", "\uD835\uDD2B", "\uD835\uDD26", "\uD835\uDD20", "\uD835\uDD2C", "\uD835\uDD21", "\uD835\uDD22").mkString val s4 = "J\u0332o\u0332s\u0332e\u0301\u0332" List(s1, s3, s4).foreach(s => println( s"The string: $s, characterlength= ${s.length} UTF8bytes= ${ s.getBytes("UTF-8").size } UTF16bytes= ${s.getBytes("UTF-16LE").size}")) }
190String length
16scala
23qlb
let string = "Hello, Swift language" let (n, m) = (5, 4)
183Substring
17swift
gc649
VALUES LENGTH('mse', CODEUNITS16); VALUES LENGTH('mse', CODEUNITS32); VALUES CHARACTER_LENGTH('mse', CODEUNITS32); VALUES LENGTH2('mse'); VALUES LENGTH4('mse'); VALUES LENGTH('', CODEUNITS16); VALUES LENGTH('', CODEUNITS32); VALUES CHARACTER_LENGTH('', CODEUNITS32); VALUES LENGTH2(''); VALUES LENGTH4(''); VALUES LENGTH('Jos', CODEUNITS16); VALUES LENGTH('Jos', CODEUNITS32); VALUES CHARACTER_LENGTH('Jos', CODEUNITS32); VALUES LENGTH2('Jos'); VALUES LENGTH4('Jos');
190String length
19sql
5m8u3
let numberOfCharacters = "mse".characters.count
190String length
17swift
yn16e
typedef struct stirling_cache_tag { int max; int* values; } stirling_cache; int stirling_number2(stirling_cache* sc, int n, int k) { if (k == n) return 1; if (k == 0 || k > n || n > sc->max) return 0; return sc->values[n*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf(); for (int k = 0; k <= max; ++k) printf(k == 0 ? : , k); printf(); for (int n = 0; n <= max; ++n) { printf(, n); for (int k = 0; k <= n; ++k) printf(k == 0 ? : , stirling_number2(sc, n, k)); printf(); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, ); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
191Stirling numbers of the second kind
5c
ejmav
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has%d digits.\n", len(max.String())) }
191Stirling numbers of the second kind
0go
9famt
import Text.Printf (printf) import Data.List (groupBy) import qualified Data.MemoCombinators as Memo stirling2 :: Integral a => (a, a) -> a stirling2 = Memo.pair Memo.integral Memo.integral f where f (n, k) | n == 0 && k == 0 = 1 | (n > 0 && k == 0) || (n == 0 && k > 0) = 0 | n == k = 1 | k > n = 0 | otherwise = k * stirling2 (pred n, k) + stirling2 (pred n, pred k) main :: IO () main = do printf "n/k" mapM_ (printf "%10d") ([0..12] :: [Int]) >> printf "\n" printf "%s\n" $ replicate (13 * 10 + 3) '-' mapM_ (\row -> printf "%2d|" (fst $ head row) >> mapM_ (printf "%10d" . stirling2) row >> printf "\n") table printf "\nThe maximum value of S2(100, k):\n%d\n" $ maximum ([stirling2 (100, n) | n <- [1..100]] :: [Integer]) where table :: [[(Int, Int)]] table = groupBy (\a b -> fst a == fst b) $ (,) <$> [0..12] <*> [0..12]
191Stirling numbers of the second kind
8haskell
b4zk2
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k =%d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
191Stirling numbers of the second kind
9java
gco4m
package main import ( "fmt" "log" "math" ) type Matrix [][]float64 func (m Matrix) rows() int { return len(m) } func (m Matrix) cols() int { return len(m[0]) } func (m Matrix) add(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the same dimensions.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m.cols()) for j := 0; j < m.cols(); j++ { c[i][j] = m[i][j] + m2[i][j] } } return c } func (m Matrix) sub(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the same dimensions.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m.cols()) for j := 0; j < m.cols(); j++ { c[i][j] = m[i][j] - m2[i][j] } } return c } func (m Matrix) mul(m2 Matrix) Matrix { if m.cols() != m2.rows() { log.Fatal("Cannot multiply these matrices.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m2.cols()) for j := 0; j < m2.cols(); j++ { for k := 0; k < m2.rows(); k++ { c[i][j] += m[i][k] * m2[k][j] } } } return c } func (m Matrix) toString(p int) string { s := make([]string, m.rows()) pow := math.Pow(10, float64(p)) for i := 0; i < m.rows(); i++ { t := make([]string, m.cols()) for j := 0; j < m.cols(); j++ { r := math.Round(m[i][j]*pow) / pow t[j] = fmt.Sprintf("%g", r) if t[j] == "-0" { t[j] = "0" } } s[i] = fmt.Sprintf("%v", t) } return fmt.Sprintf("%v", s) } func params(r, c int) [4][6]int { return [4][6]int{ {0, r, 0, c, 0, 0}, {0, r, c, 2 * c, 0, c}, {r, 2 * r, 0, c, r, 0}, {r, 2 * r, c, 2 * c, r, c}, } } func toQuarters(m Matrix) [4]Matrix { r := m.rows() / 2 c := m.cols() / 2 p := params(r, c) var quarters [4]Matrix for k := 0; k < 4; k++ { q := make(Matrix, r) for i := p[k][0]; i < p[k][1]; i++ { q[i-p[k][4]] = make([]float64, c) for j := p[k][2]; j < p[k][3]; j++ { q[i-p[k][4]][j-p[k][5]] = m[i][j] } } quarters[k] = q } return quarters } func fromQuarters(q [4]Matrix) Matrix { r := q[0].rows() c := q[0].cols() p := params(r, c) r *= 2 c *= 2 m := make(Matrix, r) for i := 0; i < c; i++ { m[i] = make([]float64, c) } for k := 0; k < 4; k++ { for i := p[k][0]; i < p[k][1]; i++ { for j := p[k][2]; j < p[k][3]; j++ { m[i][j] = q[k][i-p[k][4]][j-p[k][5]] } } } return m } func strassen(a, b Matrix) Matrix { if a.rows() != a.cols() || b.rows() != b.cols() || a.rows() != b.rows() { log.Fatal("Matrices must be square and of equal size.") } if a.rows() == 0 || (a.rows()&(a.rows()-1)) != 0 { log.Fatal("Size of matrices must be a power of two.") } if a.rows() == 1 { return a.mul(b) } qa := toQuarters(a) qb := toQuarters(b) p1 := strassen(qa[1].sub(qa[3]), qb[2].add(qb[3])) p2 := strassen(qa[0].add(qa[3]), qb[0].add(qb[3])) p3 := strassen(qa[0].sub(qa[2]), qb[0].add(qb[1])) p4 := strassen(qa[0].add(qa[1]), qb[3]) p5 := strassen(qa[0], qb[1].sub(qb[3])) p6 := strassen(qa[3], qb[2].sub(qb[0])) p7 := strassen(qa[2].add(qa[3]), qb[0]) var q [4]Matrix q[0] = p1.add(p2).sub(p4).add(p6) q[1] = p4.add(p5) q[2] = p6.add(p7) q[3] = p2.sub(p3).add(p5).sub(p7) return fromQuarters(q) } func main() { a := Matrix{{1, 2}, {3, 4}} b := Matrix{{5, 6}, {7, 8}} c := Matrix{{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}} d := Matrix{{4, -3, 4.0 / 3, -1.0 / 4}, {-13.0 / 3, 19.0 / 4, -7.0 / 3, 11.0 / 24}, {3.0 / 2, -2, 7.0 / 6, -1.0 / 4}, {-1.0 / 6, 1.0 / 4, -1.0 / 6, 1.0 / 24}} e := Matrix{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} f := Matrix{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} fmt.Println("Using 'normal' matrix multiplication:") fmt.Printf(" a * b =%v\n", a.mul(b)) fmt.Printf(" c * d =%v\n", c.mul(d).toString(6)) fmt.Printf(" e * f =%v\n", e.mul(f)) fmt.Println("\nUsing 'Strassen' matrix multiplication:") fmt.Printf(" a * b =%v\n", strassen(a, b)) fmt.Printf(" c * d =%v\n", strassen(c, d).toString(6)) fmt.Printf(" e * f =%v\n", strassen(e, f)) }
192Strassen's algorithm
0go
lzecw
import java.math.BigInteger fun main() { println("Stirling numbers of the second kind:") val max = 12 print("n/k") for (n in 0..max) { print("%10d".format(n)) } println() for (n in 0..max) { print("%-3d".format(n)) for (k in 0..n) { print("%10s".format(sterling2(n, k))) } println() } println("The maximum value of S2(100, k) = ") var previous = BigInteger.ZERO for (k in 1..100) { val current = sterling2(100, k) previous = if (current > previous) { current } else { println("%s%n(%d digits, k =%d)".format(previous, previous.toString().length, k - 1)) break } } } private val COMPUTED: MutableMap<String, BigInteger> = HashMap() private fun sterling2(n: Int, k: Int): BigInteger { val key = "$n,$k" if (COMPUTED.containsKey(key)) { return COMPUTED[key]!! } if (n == 0 && k == 0) { return BigInteger.valueOf(1) } if (n > 0 && k == 0 || n == 0 && k > 0) { return BigInteger.ZERO } if (n == k) { return BigInteger.valueOf(1) } if (k > n) { return BigInteger.ZERO } val result = BigInteger.valueOf(k.toLong()) * sterling2(n - 1, k) + sterling2(n - 1, k - 1) COMPUTED[key] = result return result }
191Stirling numbers of the second kind
11kotlin
23xli
use strict; use warnings; use bigint; use feature 'say'; use feature 'state'; no warnings 'recursion'; use List::Util qw(max); sub Stirling2 { my($n, $k) = @_; my $n1 = $n - 1; return 1 if $n1 == $k; return 0 unless $n1 && $k; state %seen; return ($seen{"{$n1}|{$k}" } //= Stirling2($n1,$k ) * $k) + ($seen{"{$n1}|{$k-1}"} //= Stirling2($n1,$k-1)) } my $upto = 12; my $width = 1 + length max map { Stirling2($upto+1,$_) } 0..$upto+1; say 'Unsigned Stirling2 numbers of the second kind: S2(n, k):'; print 'n\k' . sprintf "%${width}s"x(1+$upto)."\n", 0..$upto; for my $row (1..$upto+1) { printf '%-3d', $row-1; printf "%${width}d", Stirling2($row, $_) for 0..$row-1; print "\n"; } say "\nMaximum value from the S2(100, *) row:"; say max map { Stirling2(101,$_) } 0..100;
191Stirling numbers of the second kind
2perl
sp2q3
from __future__ import annotations from itertools import chain from typing import List from typing import NamedTuple from typing import Optional class Shape(NamedTuple): rows: int cols: int class Matrix(List): @classmethod def block(cls, blocks) -> Matrix: m = Matrix() for hblock in blocks: for row in zip(*hblock): m.append(list(chain.from_iterable(row))) return m def dot(self, b: Matrix) -> Matrix: assert self.shape.cols == b.shape.rows m = Matrix() for row in self: new_row = [] for c in range(len(b[0])): col = [b[r][c] for r in range(len(b))] new_row.append(sum(x * y for x, y in zip(row, col))) m.append(new_row) return m def __matmul__(self, b: Matrix) -> Matrix: return self.dot(b) def __add__(self, b: Matrix) -> Matrix: assert self.shape == b.shape rows, cols = self.shape return Matrix( [[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)] ) def __sub__(self, b: Matrix) -> Matrix: assert self.shape == b.shape rows, cols = self.shape return Matrix( [[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)] ) def strassen(self, b: Matrix) -> Matrix: rows, cols = self.shape assert rows == cols, assert self.shape == b.shape, assert rows and (rows & rows - 1) == 0, if rows == 1: return self.dot(b) p = rows a11 = Matrix([n[:p] for n in self[:p]]) a12 = Matrix([n[p:] for n in self[:p]]) a21 = Matrix([n[:p] for n in self[p:]]) a22 = Matrix([n[p:] for n in self[p:]]) b11 = Matrix([n[:p] for n in b[:p]]) b12 = Matrix([n[p:] for n in b[:p]]) b21 = Matrix([n[:p] for n in b[p:]]) b22 = Matrix([n[p:] for n in b[p:]]) m1 = (a11 + a22).strassen(b11 + b22) m2 = (a21 + a22).strassen(b11) m3 = a11.strassen(b12 - b22) m4 = a22.strassen(b21 - b11) m5 = (a11 + a12).strassen(b22) m6 = (a21 - a11).strassen(b11 + b12) m7 = (a12 - a22).strassen(b21 + b22) c11 = m1 + m4 - m5 + m7 c12 = m3 + m5 c21 = m2 + m4 c22 = m1 - m2 + m3 + m6 return Matrix.block([[c11, c12], [c21, c22]]) def round(self, ndigits: Optional[int] = None) -> Matrix: return Matrix([[round(i, ndigits) for i in row] for row in self]) @property def shape(self) -> Shape: cols = len(self[0]) if self else 0 return Shape(len(self), cols) def examples(): a = Matrix( [ [1, 2], [3, 4], ] ) b = Matrix( [ [5, 6], [7, 8], ] ) c = Matrix( [ [1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], ] ) d = Matrix( [ [4, -3, 4 / 3, -1 / 4], [-13 / 3, 19 / 4, -7 / 3, 11 / 24], [3 / 2, -2, 7 / 6, -1 / 4], [-1 / 6, 1 / 4, -1 / 6, 1 / 24], ] ) e = Matrix( [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] ) f = Matrix( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) print() print(f) print(f) print(f) print() print(f) print(f) print(f) if __name__ == : examples()
192Strassen's algorithm
3python
oeu81
null
192Strassen's algorithm
17swift
iw5o0
computed = {} def sterling2(n, k): key = str(n) + + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if (n > 0 and k == 0) or (n == 0 and k > 0): return 0 if n == k: return 1 if k > n: return 0 result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1) computed[key] = result return result print() MAX = 12 print(.ljust(10), end=) for n in range(MAX + 1): print(str(n).rjust(10), end=) print() for n in range(MAX + 1): print(str(n).ljust(10), end=) for k in range(n + 1): print(str(sterling2(n, k)).rjust(10), end=) print() print() previous = 0 for k in range(1, 100 + 1): current = sterling2(100, k) if current > previous: previous = current else: print(.format(previous, len(str(previous)), k - 1)) break
191Stirling numbers of the second kind
3python
01vsq
int main() { char str[24]=; char *cstr=; char *cstr2=; int x=0; if(sizeof(str)>strlen(str)+strlen(cstr)+strlen(cstr2)) { strcat(str,cstr); x=strlen(str); sprintf(&str[x],,cstr2); printf(,str); } return 0; }
193String append
5c
ynk6f
@memo = {} def sterling2(n, k) key = [n,k] return @memo[key] if @memo.key?(key) return 1 if n.zero? and k.zero? return 0 if n.zero? or k.zero? return 1 if n == k return 0 if k > n res = k * sterling2(n-1, k) + sterling2(n - 1, k-1) @memo[key] = res end r = (0..12) puts puts %11d r.each do |row| print % row puts %11d end puts ; puts (1..100).map{|a| sterling2(100,a)}.max
191Stirling numbers of the second kind
14ruby
oe58v
const char *table[ROWS][COLS] = { { , , , , , , , , , }, { , , , NULL, , , , NULL, , }, { , , , , , , , , , }, { , , , , , , , , , NPRX } }; GHashTable *create_table_from_array(const char *table[ROWS][COLS], bool is_encoding) { char buf[16]; GHashTable *r = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); size_t i, j, k, m; for(i = 0, m = 0; i < COLS; i++) { if (table[1][i] == NULL) m++; } const size_t SELNUM = m; size_t selectors[SELNUM]; size_t numprefix_row, numprefix_col; bool has_numprefix = false; for(i = 0, k = 0; i < COLS && k < SELNUM; i++) { if ( table[1][i] == NULL ) { selectors[k] = i; k++; } } for(j = 1; j < ROWS; j++) { for(i = 0; i < COLS; i++) { if (table[j][i] == NULL) continue; if ( strcmp(table[j][i], NPRX) == 0 ) { numprefix_col = i; numprefix_row = j; has_numprefix = true; break; } } } for(i = has_numprefix ? 0 : 1; i < ROWS; i++) { for(j = 0; j < COLS; j++) { if (table[i][j] == NULL) continue; if (strlen(table[i][j]) > 1) { fprintf(stderr, ); continue; } if (has_numprefix && i == (ROWS-1) && j == numprefix_col && i == numprefix_row) continue; if (has_numprefix && i == 0) { snprintf(buf, sizeof(buf), , table[0][selectors[SELNUM-1]], table[0][numprefix_col], table[0][j]); } else if (i == 1) { snprintf(buf, sizeof(buf), , table[0][j]); } else { snprintf(buf, sizeof(buf), , table[0][selectors[i-2]], table[0][j]); } if (is_encoding) g_hash_table_insert(r, strdup(table[i][j]), strdup(buf)); else g_hash_table_insert(r, strdup(buf), strdup(table[i][j])); } } if (is_encoding) g_hash_table_insert(r, strdup(), strdup()); else g_hash_table_insert(r, strdup(), strdup()); return r; } char *decode(GHashTable *et, const char *enctext) { char *r = NULL; if (et == NULL || enctext == NULL || strlen(enctext) == 0 || g_hash_table_lookup(et, ) == NULL || strcmp(g_hash_table_lookup(et, ), ) != 0) return NULL; GString *res = g_string_new(NULL); GString *en = g_string_new(NULL); for( ; *enctext != '\0'; enctext++ ) { if (en->len < 3) { g_string_append_c(en, *enctext); r = g_hash_table_lookup(et, en->str); if (r == NULL) continue; g_string_append(res, r); g_string_truncate(en, 0); } else { fprintf(stderr, ); break; } } r = res->str; g_string_free(res, FALSE); g_string_free(en, TRUE); return r; } char *encode(GHashTable *et, const char *plaintext, int (*trasf)(int), bool compress_spaces) { GString *s; char *r = NULL; char buf[2] = { 0 }; if (plaintext == NULL || et == NULL || g_hash_table_lookup(et, ) == NULL || strcmp(g_hash_table_lookup(et, ), ) != 0) return NULL; s = g_string_new(NULL); for(buf[0] = trasf ? trasf(*plaintext) : *plaintext; buf[0] != '\0'; buf[0] = trasf ? trasf(*++plaintext) : *++plaintext) { if ( (r = g_hash_table_lookup(et, buf)) != NULL ) { g_string_append(s, r); } else if (isspace(buf[0])) { if (!compress_spaces) g_string_append(s, buf); } else { fprintf(stderr, , isprint(buf[0]) ? buf : , !compress_spaces ? : ); if (!compress_spaces) g_string_append_c(s, ' '); } } r = s->str; g_string_free(s, FALSE); return r; } int main() { GHashTable *enctab = create_table_from_array(table, true); GHashTable *dectab = create_table_from_array(table, false); const char *text = ; char *encoded = encode(enctab, text, toupper, true); printf(, encoded); char *decoded = decode(dectab, encoded); printf(, decoded); free(decoded); free(encoded); g_hash_table_destroy(enctab); g_hash_table_destroy(dectab); return 0; }
194Straddling checkerboard
5c
v6e2o
typedef struct stirling_cache_tag { int max; int* values; } stirling_cache; int stirling_number1(stirling_cache* sc, int n, int k) { if (k == 0) return n == 0 ? 1 : 0; if (n > sc->max || k > n) return 0; return sc->values[n*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k <= n; ++k) { int s1 = stirling_number1(sc, n - 1, k - 1); int s2 = stirling_number1(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * (n - 1); } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf(); for (int k = 0; k <= max; ++k) printf(k == 0 ? : , k); printf(); for (int n = 0; n <= max; ++n) { printf(, n); for (int k = 0; k <= n; ++k) printf(k == 0 ? : , stirling_number1(sc, n, k)); printf(); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, ); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
195Stirling numbers of the first kind
5c
uyev4
user=> (def s "app") #'user/s user=> s "app" user=> (def s (str s "end")) #'user/s user=> s "append"
193String append
6clojure
23el1
void merge(FILE* f1, FILE* f2, FILE* out) { int b1; int b2; if(f1) GET(1) if(f2) GET(2) while ( f1 && f2 ) { if ( b1 <= b2 ) PUT(1) else PUT(2) } while (f1 ) PUT(1) while (f2 ) PUT(2) } int main(int argc, char* argv[]) { if ( argc < 3 || argc > 3 ) { puts(); exit(EXIT_FAILURE); } else merge(fopen(argv[1],),fopen(argv[2],),stdout); return EXIT_SUCCESS; }
196Stream merge
5c
gcx45
package main import ( "fmt" "strings" ) func main() { key := ` 8752390146 ET AON RIS 5BC/FGHJKLM 0PQD.VWXYZU` p := "you have put on 7.5 pounds since I saw you." fmt.Println(p) c := enc(key, p) fmt.Println(c) fmt.Println(dec(key, c)) } func enc(bd, pt string) (ct string) { enc := make(map[byte]string) row := strings.Split(bd, "\n")[1:] r2d := row[2][:1] r3d := row[3][:1] for col := 1; col <= 10; col++ { d := string(row[0][col]) enc[row[1][col]] = d enc[row[2][col]] = r2d+d enc[row[3][col]] = r3d+d } num := enc['/'] delete(enc, '/') delete(enc, ' ') for i := 0; i < len(pt); i++ { if c := pt[i]; c <= '9' && c >= '0' { ct += num + string(c) } else { if c <= 'z' && c >= 'a' { c -= 'a'-'A' } ct += enc[c] } } return } func dec(bd, ct string) (pt string) { row := strings.Split(bd, "\n")[1:] var cx [10]int for i := 1; i <= 10; i++ { cx[row[0][i]-'0'] = i } r2d := row[2][0]-'0' r3d := row[3][0]-'0' for i := 0; i < len(ct); i++ { var r int switch d := ct[i]-'0'; d { case r2d: r = 2 case r3d: r = 3 default: pt += string(row[1][cx[d]]) continue } i++ if b := row[r][cx[ct[i]-'0']]; b == '/' { i++ pt += string(ct[i]) } else { pt += string(b) } } return }
194Straddling checkerboard
0go
sp9qa
import Data.Char import Data.Map charToInt :: Char -> Int charToInt c = ord c - ord '0' decodeChar :: String -> (Char,String) decodeChar ('7':'9':r:rs) = (r,rs) decodeChar ('7':r:rs) = ("PQUVWXYZ. " !! charToInt r, rs) decodeChar ('3':r:rs) = ("ABCDFGIJKN" !! charToInt r, rs) decodeChar (r:rs) = ("HOL MES RT" !! charToInt r, rs) decode :: String -> String decode [] = [] decode st = let (c, s) = decodeChar st in c:decode s revEnc :: String -> (Char, String) revEnc enc = let (dec, rm) = decodeChar enc in (dec, take (length enc - length rm) enc) ds :: String ds = ['0'..'9'] encodeMap :: Map Char String encodeMap = fromList [ revEnc [d2,d1,d0] | d2 <- ds, d1 <- ds, d0 <- ds ] encodeChar :: Char -> String encodeChar c = findWithDefault "" c encodeMap encode :: String -> String encode st = concatMap encodeChar $ fmap toUpper st main = let orig = "One night-it was on the twentieth of March, 1888-I was returning" enc = encode orig dec = decode enc in mapM_ putStrLn [ "Original: " ++ orig , "Encoded: " ++ enc , "Decoded: " ++ dec ]
194Straddling checkerboard
8haskell
9fbmo
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } } s1[0][0].SetInt64(int64(1)) var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(n - 1)) t.Mul(&t, s1[n-1][k]) if unsigned { s1[n][k].Add(s1[n-1][k-1], &t) } else { s1[n][k].Sub(s1[n-1][k-1], &t) } } } fmt.Println("Unsigned Stirling numbers of the first kind: S1(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s1[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S1(100, *) row:") max := new(big.Int).Set(s1[limit][0]) for k := 1; k <= limit; k++ { if s1[limit][k].Cmp(max) > 0 { max.Set(s1[limit][k]) } } fmt.Println(max) fmt.Printf("which has%d digits.\n", len(max.String())) }
195Stirling numbers of the first kind
0go
019sk
import Text.Printf (printf) import Data.List (groupBy) import qualified Data.MemoCombinators as Memo stirling1 :: Integral a => (a, a) -> a stirling1 = Memo.pair Memo.integral Memo.integral f where f (n, k) | n == 0 && k == 0 = 1 | n > 0 && k == 0 = 0 | k > n = 0 | otherwise = stirling1 (pred n, pred k) + pred n * stirling1 (pred n, k) main :: IO () main = do printf "n/k" mapM_ (printf "%10d") ([0..12] :: [Int]) >> printf "\n" printf "%s\n" $ replicate (13 * 10 + 3) '-' mapM_ (\row -> printf "%2d|" (fst $ head row) >> mapM_ (printf "%10d" . stirling1) row >> printf "\n") table printf "\nThe maximum value of S1(100, k):\n%d\n" $ maximum ([stirling1 (100, n) | n <- [1..100]] :: [Integer]) where table :: [[(Int, Int)]] table = groupBy (\a b -> fst a == fst b) $ (,) <$> [0..12] <*> [0..12]
195Stirling numbers of the first kind
8haskell
ctb94
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersFirstKind { public static void main(String[] args) { System.out.println("Unsigned Stirling numbers of the first kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling1(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S1(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling1(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k =%d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling1(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( n > 0 && k == 0 ) { return BigInteger.ZERO; } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = sterling1(n-1, k-1).add(BigInteger.valueOf(n-1).multiply(sterling1(n-1, k))); COMPUTED.put(key, result); return result; } }
195Stirling numbers of the first kind
9java
z8gtq
import java.util.HashMap; import java.util.Map; import java.util.regex.*; public class StraddlingCheckerboard { final static String[] keyvals = {"H:0", "O:1", "L:2", "M:4", "E:5", "S:6", "R:8", "T:9", "A:30", "B:31", "C:32", "D:33", "F:34", "G:35", "I:36", "J:37", "K:38", "N:39", "P:70", "Q:71", "U:72", "V:73", "W:74", "X:75", "Y:76", "Z:77", ".:78", "/:79", "0:790", "1:791", "2:792", "3:793", "4:794", "5:795", "6:796", "7:797", "8:798", "9:799"}; final static Map<String, String> val2key = new HashMap<>(); final static Map<String, String> key2val = new HashMap<>(); public static void main(String[] args) { for (String keyval : keyvals) { String[] kv = keyval.split(":"); val2key.put(kv[0], kv[1]); key2val.put(kv[1], kv[0]); } String enc = encode("One night-it was on the twentieth of March, " + "1888-I was returning"); System.out.println(enc); System.out.println(decode(enc)); } static String encode(String s) { StringBuilder sb = new StringBuilder(); for (String c : s.toUpperCase().split("")) { c = val2key.get(c); if (c != null) sb.append(c); } return sb.toString(); } static String decode(String s) { Matcher m = Pattern.compile("(79.|3.|7.|.)").matcher(s); StringBuilder sb = new StringBuilder(); while (m.find()) { String v = key2val.get(m.group(1)); if (v != null) sb.append(v); } return sb.toString(); } }
194Straddling checkerboard
9java
t0gf9
package main import ( "container/heap" "fmt" "io" "log" "os" "strings" ) var s1 = "3 14 15" var s2 = "2 17 18" var s3 = "" var s4 = "2 3 5 7" func main() { fmt.Print("merge2: ") merge2( os.Stdout, strings.NewReader(s1), strings.NewReader(s2)) fmt.Println() fmt.Print("mergeN: ") mergeN( os.Stdout, strings.NewReader(s1), strings.NewReader(s2), strings.NewReader(s3), strings.NewReader(s4)) fmt.Println() } func r1(r io.Reader) (v int, ok bool) { switch _, err := fmt.Fscan(r, &v); { case err == nil: return v, true case err != io.EOF: log.Fatal(err) } return } func merge2(m io.Writer, s1, s2 io.Reader) { v1, d1 := r1(s1) v2, d2 := r1(s2) var v int for d1 || d2 { if !d2 || d1 && v1 < v2 { v = v1 v1, d1 = r1(s1) } else { v = v2 v2, d2 = r1(s2) } fmt.Fprint(m, v, " ") } } type sv struct { s io.Reader v int } type sh []sv func (s sh) Len() int { return len(s) } func (s sh) Less(i, j int) bool { return s[i].v < s[j].v } func (s sh) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (p *sh) Push(x interface{}) { *p = append(*p, x.(sv)) } func (p *sh) Pop() interface{} { s := *p last := len(s) - 1 v := s[last] *p = s[:last] return v } func mergeN(m io.Writer, s ...io.Reader) { var h sh for _, s := range s { if v, d := r1(s); d { h = append(h, sv{s, v}) } } heap.Init(&h) for len(h) > 0 { p := heap.Pop(&h).(sv) fmt.Fprint(m, p.v, " ") if v, d := r1(p.s); d { heap.Push(&h, sv{p.s, v}) } } }
196Stream merge
0go
iwlog
<script> var alphabet=new Array("ESTONIA R","BCDFGHJKLM","PQUVWXYZ./")
194Straddling checkerboard
10javascript
mdkyv
import java.math.BigInteger fun main() { println("Unsigned Stirling numbers of the first kind:") val max = 12 print("n/k") for (n in 0..max) { print("%10d".format(n)) } println() for (n in 0..max) { print("%-3d".format(n)) for (k in 0..n) { print("%10s".format(sterling1(n, k))) } println() } println("The maximum value of S1(100, k) = ") var previous = BigInteger.ZERO for (k in 1..100) { val current = sterling1(100, k) previous = if (current!! > previous) { current } else { println("$previous\n(${previous.toString().length} digits, k = ${k - 1})") break } } } private val COMPUTED: MutableMap<String, BigInteger?> = HashMap() private fun sterling1(n: Int, k: Int): BigInteger? { val key = "$n,$k" if (COMPUTED.containsKey(key)) { return COMPUTED[key] } if (n == 0 && k == 0) { return BigInteger.valueOf(1) } if (n > 0 && k == 0) { return BigInteger.ZERO } if (k > n) { return BigInteger.ZERO } val result = sterling1(n - 1, k - 1)!!.add(BigInteger.valueOf(n - 1.toLong()).multiply(sterling1(n - 1, k))) COMPUTED[key] = result return result }
195Stirling numbers of the first kind
11kotlin
iw2o4
import Control.Monad.Trans.Resource (runResourceT) import qualified Data.ByteString.Char8 as BS import Data.Conduit (($$), (=$=)) import Data.Conduit.Binary (sinkHandle, sourceFile) import qualified Data.Conduit.Binary as Conduit import qualified Data.Conduit.List as Conduit import Data.Conduit.Merge (mergeSources) import System.Environment (getArgs) import System.IO (stdout) main :: IO () main = do inputFileNames <- getArgs let inputs = [sourceFile file =$= Conduit.lines | file <- inputFileNames] runResourceT $ mergeSources inputs $$ sinkStdoutLn where sinkStdoutLn = Conduit.map (`BS.snoc` '\n') =$= sinkHandle stdout
196Stream merge
8haskell
v612k
double mean(double* values, int n) { int i; double s = 0; for ( i = 0; i < n; i++ ) s += values[i]; return s / n; } double stddev(double* values, int n) { int i; double average = mean(values,n); double s = 0; for ( i = 0; i < n; i++ ) s += (values[i] - average) * (values[i] - average); return sqrt(s / (n - 1)); } double* generate(int n) { int i; int m = n + n % 2; double* values = (double*)calloc(m,sizeof(double)); double average, deviation; if ( values ) { for ( i = 0; i < m; i += 2 ) { double x,y,rsq,f; do { x = 2.0 * rand() / (double)RAND_MAX - 1.0; y = 2.0 * rand() / (double)RAND_MAX - 1.0; rsq = x * x + y * y; }while( rsq >= 1. || rsq == 0. ); f = sqrt( -2.0 * log(rsq) / rsq ); values[i] = x * f; values[i+1] = y * f; } } return values; } void printHistogram(double* values, int n) { const int width = 50; int max = 0; const double low = -3.05; const double high = 3.05; const double delta = 0.1; int i,j,k; int nbins = (int)((high - low) / delta); int* bins = (int*)calloc(nbins,sizeof(int)); if ( bins != NULL ) { for ( i = 0; i < n; i++ ) { int j = (int)( (values[i] - low) / delta ); if ( 0 <= j && j < nbins ) bins[j]++; } for ( j = 0; j < nbins; j++ ) if ( max < bins[j] ) max = bins[j]; for ( j = 0; j < nbins; j++ ) { printf(, low + j * delta, low + (j + 1) * delta ); k = (int)( (double)width * (double)bins[j] / (double)max ); while(k-- > 0) putchar('*'); printf(, bins[j] * 100.0 / (double)n); putchar('\n'); } free(bins); } } int main(void) { double* seq; srand((unsigned int)time(NULL)); if ( (seq = generate(NMAX)) != NULL ) { printf(, mean(seq,NMAX), stddev(seq,NMAX)); printHistogram(seq,NMAX); free(seq); printf(, ); getchar(); return EXIT_SUCCESS; } return EXIT_FAILURE; }
197Statistics/Normal distribution
5c
23blo
import java.util.Iterator; import java.util.List; import java.util.Objects; public class StreamMerge { private static <T extends Comparable<T>> void merge2(Iterator<T> i1, Iterator<T> i2) { T a = null, b = null; while (i1.hasNext() || i2.hasNext()) { if (null == a && i1.hasNext()) { a = i1.next(); } if (null == b && i2.hasNext()) { b = i2.next(); } if (null != a) { if (null != b) { if (a.compareTo(b) < 0) { System.out.print(a); a = null; } else { System.out.print(b); b = null; } } else { System.out.print(a); a = null; } } else if (null != b) { System.out.print(b); b = null; } } if (null != a) { System.out.print(a); } if (null != b) { System.out.print(b); } } @SuppressWarnings("unchecked") @SafeVarargs private static <T extends Comparable<T>> void mergeN(Iterator<T>... iter) { Objects.requireNonNull(iter); if (iter.length == 0) { throw new IllegalArgumentException("Must have at least one iterator"); } Object[] pa = new Object[iter.length]; boolean done; do { done = true; for (int i = 0; i < iter.length; i++) { Iterator<T> t = iter[i]; if (null == pa[i] && t.hasNext()) { pa[i] = t.next(); } } T min = null; int idx = -1; for (int i = 0; i < pa.length; ++i) { T t = (T) pa[i]; if (null != t) { if (null == min) { min = t; idx = i; done = false; } else if (t.compareTo(min) < 0) { min = t; idx = i; done = false; } } } if (idx != -1) { System.out.print(min); pa[idx] = null; } } while (!done); } public static void main(String[] args) { List<Integer> l1 = List.of(1, 4, 7, 10); List<Integer> l2 = List.of(2, 5, 8, 11); List<Integer> l3 = List.of(3, 6, 9, 12); merge2(l1.iterator(), l2.iterator()); System.out.println(); mergeN(l1.iterator(), l2.iterator(), l3.iterator()); System.out.println(); System.out.flush(); } }
196Stream merge
9java
yn76g
null
194Straddling checkerboard
11kotlin
oe28z
use strict; use warnings; use bigint; use feature 'say'; use feature 'state'; no warnings 'recursion'; use List::Util qw(max); sub Stirling1 { my($n, $k) = @_; return 1 unless $n || $k; return 0 unless $n && $k; state %seen; return ($seen{"{$n-1}|{$k-1}"} //= Stirling1($n-1, $k-1)) + ($seen{"{$n-1}|{$k}" } //= Stirling1($n-1, $k )) * ($n-1) } my $upto = 12; my $width = 1 + length max map { Stirling1($upto,$_) } 0..$upto; say 'Unsigned Stirling1 numbers of the first kind: S1(n, k):'; print 'n\k' . sprintf "%${width}s"x(1+$upto)."\n", 0..$upto; for my $row (0..$upto) { printf '%-3d', $row; printf "%${width}d", Stirling1($row, $_) for 0..$row; print "\n"; } say "\nMaximum value from the S1(100, *) row:"; say max map { Stirling1(100,$_) } 0..100;
195Stirling numbers of the first kind
2perl
rlsgd
null
196Stream merge
11kotlin
fsudo
local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" } local dicE, dicD, s1, s2 = {}, {}, 0, 0 function dec( txt ) local i, numb, s, t, c = 1, false while( i < #txt ) do c = txt:sub( i, i ) if not numb then if tonumber( c ) == s1 then i = i + 1; s = string.format( "%d%s", s1, txt:sub( i, i ) ) t = dicD[s] elseif tonumber( c ) == s2 then i = i + 1; s = string.format( "%d%s", s2, txt:sub( i, i ) ) t = dicD[s] else t = dicD[c] end if t == "/" then numb = true else io.write( t ) end else io.write( c ) numb = false end i = i + 1 end print() end function enc( txt ) local c for i = 1, #txt do c = txt:sub( i, i ) if c >= "A" and c <= "Z" then io.write( dicE[c] ) elseif c >= "0" and c <= "9" then io.write( string.format( "%s%s", dicE["/"], c ) ) end end print() end function createDictionaries() for i = 1, 10 do c = brd[1]:sub( i, i ) if c == " " then if s1 == 0 then s1 = i - 1 elseif s2 == 0 then s2 = i - 1 end else dicE[c] = string.format( "%d", i - 1 ) dicD[string.format( "%d", i - 1 )] = c end end for i = 1, 10 do dicE[brd[2]:sub( i, i )] = string.format( "%d%d", s1, i - 1 ) dicE[brd[3]:sub( i, i )] = string.format( "%d%d", s2, i - 1 ) dicD[string.format( "%d%d", s1, i - 1 )] = brd[2]:sub( i, i ) dicD[string.format( "%d%d", s2, i - 1 )] = brd[3]:sub( i, i ) end end function enterText() createDictionaries() io.write( "\nEncrypt or Decrypt (E/D)? " ) d = io.read() io.write( "\nEnter the text:\n" ) txt = io.read():upper() if d == "E" or d == "e" then enc( txt ) elseif d == "D" or d == "d" then dec( txt ) end end
194Straddling checkerboard
1lua
iwvot
s := "foo" s += "bar"
193String append
0go
1rzp5
class Append{ static void main(String[] args){ def c="Hello "; def d="world"; def e=c+d; println(e); } }
193String append
7groovy
jvi7o
use strict; use warnings; use English; use String::Tokenizer; use Heap::Simple; my $stream1 = <<"END_STREAM_1"; Integer vel neque ligula. Etiam a ipsum a leo eleifend viverra sit amet ac arcu. Suspendisse odio libero, ullamcorper eu sem vitae, gravida dignissim ipsum. Aenean tincidunt commodo feugiat. Nunc viverra dolor a tincidunt porta. Ut malesuada quis mauris eget vestibulum. Fusce sit amet libero id augue mattis auctor et sit amet ligula. END_STREAM_1 my $stream2 = <<"END_STREAM_2"; In luctus odio nulla, ut finibus elit aliquet in. In auctor vitae purus quis tristique. Mauris sed erat pulvinar, venenatis lectus auctor, malesuada neque. Integer a hendrerit tortor. Suspendisse aliquet pellentesque lorem, nec tincidunt arcu aliquet non. Phasellus eu diam massa. Integer vitae volutpat augue. Nulla condimentum consectetur ante, ut consequat lectus suscipit eget. END_STREAM_2 my $stream3 = <<"END_STREAM_3"; In hendrerit eleifend mi nec ultricies. Vestibulum euismod, tellus sit amet eleifend ultrices, velit nisi dignissim lectus, non vestibulum sem nisi sed mi. Nulla scelerisque ut purus sed ultricies. Donec pulvinar eleifend malesuada. In viverra faucibus enim a luctus. Vivamus tellus erat, congue quis quam in, lobortis varius mi. Nulla ante orci, porttitor id dui ac, iaculis consequat ligula. END_STREAM_3 my $stream4 = <<"END_STREAM_4"; Suspendisse elementum nunc ex, ac pulvinar mauris finibus sed. Ut non ex sed tortor ultricies feugiat non at eros. Donec et scelerisque est. In vestibulum fringilla metus eget varius. Aenean fringilla pellentesque massa, non ullamcorper mi commodo non. Sed aliquam molestie congue. Nunc lobortis turpis at nunc lacinia, id laoreet ipsum bibendum. END_STREAM_4 my $stream5 = <<"END_STREAM_5"; Donec sit amet urna nulla. Duis nec consectetur lacus, et viverra ex. Aliquam lobortis tristique hendrerit. Suspendisse viverra vehicula lorem id gravida. Pellentesque at ligula lorem. Cras gravida accumsan lacus sit amet tincidunt. Curabitur quam nisi, viverra vel nulla vel, rhoncus facilisis massa. Aliquam erat volutpat. END_STREAM_5 my $stream6 = <<"END_STREAM_6"; Curabitur nec enim eu nisi maximus suscipit rutrum non sem. Donec lobortis nulla et rutrum bibendum. Duis varius, tellus in commodo gravida, lorem neque finibus quam, sagittis elementum leo mauris sit amet justo. Sed vestibulum velit eget sapien bibendum, sit amet porta lorem fringilla. Morbi bibendum in turpis ac blandit. Mauris semper nibh nec dignissim dapibus. Proin sagittis lacus est. END_STREAM_6 merge_two_streams(map {String::Tokenizer->new($ARG)->iterator()} ($stream1, $stream2)); merge_N_streams(6, map {String::Tokenizer->new($ARG)->iterator()} ($stream1, $stream2, $stream3, $stream4, $stream5, $stream6)); exit 0; sub merge_two_streams { my ($iter1, $iter2) = @ARG; print "Merge of 2 streams:\n"; while (1) { if (!$iter1->hasNextToken() && !$iter2->hasNextToken()) { print "\n\n"; last; } elsif (!$iter1->hasNextToken()) { print $iter2->nextToken(), q{ }; } elsif (!$iter2->hasNextToken()) { print $iter1->nextToken(), q{ }; } elsif ($iter1->lookAheadToken() lt $iter2->lookAheadToken()) { print $iter1->nextToken(), q{ }; } else { print $iter2->nextToken(), q{ }; } } return; } sub merge_N_streams { my $N = shift; print "Merge of $N streams:\n"; my @iters = @ARG; my $heap = Heap::Simple->new(order => 'lt', elements => 'Array'); for (my $i=0; $i<$N; $i++) { my $iter = $iters[$i]; $iter->hasNextToken() or die "Each stream must have >= 1 element"; $heap->insert([$iter->nextToken() . q{ }, $i]); } $heap->count == $N or die "Problem with initial population of heap"; while (1) { my ($token, $iter_idx) = @{ $heap->extract_top }; print $token; my $to_insert = _fetch_next_element($iter_idx, $N, @iters); if (! $to_insert) { print join('', map {$ARG->[0]} $heap->extract_all); last; } $heap->insert($to_insert); } return; } sub _fetch_next_element { my $starting_idx = shift; my $N = shift; my @iters = @ARG; my @round_robin_idxs = map {$ARG % $N} ($starting_idx .. $starting_idx + $N - 1); foreach my $iter_idx (@round_robin_idxs) { my $iter = $iters[$iter_idx]; if ($iter->hasNextToken()) { return [$iter->nextToken() . q{ }, $iter_idx]; } } return; }
196Stream merge
2perl
hu8jl
main = putStrLn ("Hello" ++ "World")
193String append
8haskell
t0rf7
use strict; use warnings; use feature 'say'; use List::Util <min max>; my(%encode,%decode,@table); sub build { my($u,$v,$alphabet) = @_; my(@flat_board,%p2c,%c2p); my $numeric_escape = '/'; @flat_board = split '', uc $alphabet; splice @flat_board, min($u,$v), 0, undef; splice @flat_board, max($u,$v), 0, undef; push @table, [' ', 0..9]; push @table, [' ', map { defined $_ ? $_ : ' '} @flat_board[ 0 .. 9] ]; push @table, [$u, @flat_board[10 .. 19]]; push @table, [$v, @flat_board[20 .. 29]]; my @nums = my @order = 0..9; push @nums, (map { +"$u$_" } @order), map { +"$v$_" } @order; @c2p{@nums} = @flat_board; for (keys %c2p) { delete $c2p{$_} unless defined $c2p{$_} } @p2c{values %c2p} = keys %c2p; $p2c{$_} = $p2c{$numeric_escape} . $_ for 0..9; while (my ($k, $v) = each %p2c) { $encode{$k} = $v; $decode{$v} = $k unless $k eq $numeric_escape; } } sub decode { my($string) = @_; my $keys = join '|', keys %decode; $string =~ s/($keys)/$decode{$1}/gr; } sub encode { my($string) = uc shift; $string =~ s } my $sc = build(3, 7, 'HOLMESRTABCDFGIJKNPQUVWXYZ./'); say join ' ', @$_ for @table; say ''; say 'Original: ', my $original = 'One night-it was on the twentieth of March, 1888-I was returning'; say 'Encoded: ', my $en = encode($original); say 'Decoded: ', decode($en);
194Straddling checkerboard
2perl
gcs4e
computed = {} def sterling1(n, k): key = str(n) + + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if n > 0 and k == 0: return 0 if k > n: return 0 result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k) computed[key] = result return result print() MAX = 12 print(.ljust(10), end=) for n in range(MAX + 1): print(str(n).rjust(10), end=) print() for n in range(MAX + 1): print(str(n).ljust(10), end=) for k in range(n + 1): print(str(sterling1(n, k)).rjust(10), end=) print() print() previous = 0 for k in range(1, 100 + 1): current = sterling1(100, k) if current > previous: previous = current else: print(.format(previous, len(str(previous)), k - 1)) break
195Stirling numbers of the first kind
3python
720rm
String sa = "Hello"; sa += ", World!"; System.out.println(sa); StringBuilder ba = new StringBuilder(); ba.append("Hello"); ba.append(", World!"); System.out.println(ba.toString());
193String append
9java
8a206
import heapq import sys sources = sys.argv[1:] for item in heapq.merge(open(source) for source in sources): print(item)
196Stream merge
3python
k5ohf
var s1 = "Hello"; s1 += ", World!"; print(s1); var s2 = "Goodbye";
193String append
10javascript
fsgdg
int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf(, j ? : , ++i); printf(, x[j] % 10); } } int main() { 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 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
198Stem-and-leaf plot
5c
nxci6
$key2val = [=>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>, =>]; $val2key = array_flip($key2val); function encode(string $s) : string { global $key2val; $callback = function($c) use ($key2val) { return $key2val[$c]?? ''; }; return implode(array_map($callback, str_split(strtoupper($s)))); } function decode(string $s) : string { global $val2key; $callback = function($c) use ($val2key) { return $val2key[$c]?? ''; }; preg_match_all('/79.|7.|3.|./', $s, $m); return implode(array_map($callback, $m[0])); } function main($s) { $encoded = encode($s); echo $encoded; echo ; echo decode($encoded); } main('One night-it was on the twentieth of March, 1888-I was returning');
194Straddling checkerboard
12php
nxuig
const char *states[] = { , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , }; int n_states = sizeof(states)/sizeof(*states); typedef struct { unsigned char c[26]; const char *name[2]; } letters; void count_letters(letters *l, const char *s) { int c; if (!l->name[0]) l->name[0] = s; else l->name[1] = s; while ((c = *s++)) { if (c >= 'a' && c <= 'z') l->c[c - 'a']++; if (c >= 'A' && c <= 'Z') l->c[c - 'A']++; } } int lcmp(const void *aa, const void *bb) { int i; const letters *a = aa, *b = bb; for (i = 0; i < 26; i++) if (a->c[i] > b->c[i]) return 1; else if (a->c[i] < b->c[i]) return -1; return 0; } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } void no_dup() { int i, j; qsort(states, n_states, sizeof(const char*), scmp); for (i = j = 0; i < n_states;) { while (++i < n_states && !strcmp(states[i], states[j])); if (i < n_states) states[++j] = states[i]; } n_states = j + 1; } void find_mix() { int i, j, n; letters *l, *p; no_dup(); n = n_states * (n_states - 1) / 2; p = l = calloc(n, sizeof(letters)); for (i = 0; i < n_states; i++) for (j = i + 1; j < n_states; j++, p++) { count_letters(p, states[i]); count_letters(p, states[j]); } qsort(l, n, sizeof(letters), lcmp); for (j = 0; j < n; j++) { for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) { if (l[j].name[0] == l[i].name[0] || l[j].name[1] == l[i].name[0] || l[j].name[1] == l[i].name[1]) continue; printf(, l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]); } } free(l); } int main(void) { find_mix(); return 0; }
199State name puzzle
5c
jvx70
int start { printf(); return 0; }
200Start from a main routine
5c
a7o11
$cache = {} def sterling1(n, k) if n == 0 and k == 0 then return 1 end if n > 0 and k == 0 then return 0 end if k > n then return 0 end key = [n, k] if $cache[key] then return $cache[key] end value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k) $cache[key] = value return value end MAX = 12 def main print print for n in 0 .. MAX print % [n] end print for n in 0 .. MAX print % [n] for k in 0 .. n print % [sterling1(n, k)] end print end print previous = 0 for k in 1 .. 100 current = sterling1(100, k) if previous < current then previous = current else print previous, print % [previous.to_s.length, k - 1] break end end end main()
195Stirling numbers of the first kind
14ruby
huojx
fun main(args: Array<String>) { var s = "a" s += "b" s += "c" println(s) println("a" + "b" + "c") val a = "a" val b = "b" val c = "c" println("$a$b$c") }
193String append
11kotlin
whyek
package main import ( "fmt" "math" "math/rand" "strings" )
197Statistics/Normal distribution
0go
qb3xz
def stream_merge(*files) fio = files.map{|fname| open(fname)} merge(fio.map{|io| [io, io.gets]}) end def merge(fdata) until fdata.empty? io, min = fdata.min_by{|_,data| data} puts min if (next_data = io.gets).nil? io.close fdata.delete([io, min]) else i = fdata.index{|x,_| x == io} fdata[i] = [io, next_data] end end end files = %w(temp1.dat temp2.dat temp3.dat) files.each do |fname| data = IO.read(fname).gsub(, ) puts end stream_merge(*files)
196Stream merge
14ruby
pgnbh
MODULE MainProcedure IMPORT StdLog PROCEDURE Do* BEGIN StdLog.String("From Do") END Do PROCEDURE Main* BEGIN StdLog.String("From Main") END Main END MainProcedure.
200Start from a main routine
6clojure
sptqr
T = [[, , , , , , , , , , ], [, , , , , , , , , , ], [, , , , , , , , , , ], [, , , , , , , , , , ]] def straddle(s): return .join(L[0]+T[0][L.index(c)] for c in s.upper() for L in T if c in L) def unstraddle(s): s = iter(s) for c in s: if c in [T[2][0], T[3][0]]: i = [T[2][0], T[3][0]].index(c) n = T[2 + i][T[0].index(s.next())] yield s.next() if n == else n else: yield T[1][T[0].index(c)] O = print , straddle(O) print , .join(unstraddle(straddle(O)))
194Straddling checkerboard
3python
rl0gq
import Data.Map (Map, empty, insert, findWithDefault, toList) import Data.Maybe (fromMaybe) import Text.Printf (printf) import Data.Function (on) import Data.List (sort, maximumBy, minimumBy) import Control.Monad.Random (RandomGen, Rand, evalRandIO, getRandomR) import Control.Monad (replicateM) getNorm :: RandomGen g => Rand g Double getNorm = do u0 <- getRandomR (0.0, 1.0) u1 <- getRandomR (0.0, 1.0) let r = sqrt $ (-2.0) * log u0 theta = 2.0 * pi * u1 return $ r * sin theta putInBin :: Double -> Map Int Int -> Double -> Map Int Int putInBin binWidth t v = let bin = round (v / binWidth) count = findWithDefault 0 bin t in insert bin (count+1) t runTest :: Int -> IO () runTest n = do rs <- evalRandIO $ replicateM n getNorm let binWidth = 0.1 tally v (sv, sv2, t) = (sv+v, sv2 + v*v, putInBin binWidth t v) (sum, sum2, tallies) = foldr tally (0.0, 0.0, empty) rs tallyList = sort $ toList tallies printStars tallies binWidth maxCount selection = let count = findWithDefault 0 selection tallies bin = binWidth * fromIntegral selection maxStars = 100 starCount = if maxCount <= maxStars then count else maxStars * count `div` maxCount stars = replicate starCount '*' in printf "%5.2f:%s %d\n" bin stars count mean = sum / fromIntegral n stddev = sqrt (sum2/fromIntegral n - mean*mean) printf "\n" printf "sample count:%d\n" n printf "mean: %9.7f\n" mean printf "stddev: %9.7f\n" stddev let maxCount = snd $ maximumBy (compare `on` snd) tallyList maxBin = fst $ maximumBy (compare `on` fst) tallyList minBin = fst $ minimumBy (compare `on` fst) tallyList mapM_ (printStars tallies binWidth maxCount) [minBin..maxBin] main = do runTest 1000 runTest 2000000
197Statistics/Normal distribution
8haskell
md7yf
def mergeN[A : Ordering](is: Iterator[A]*): Iterator[A] = is.reduce((a, b) => merge2(a, b)) def merge2[A : Ordering](i1: Iterator[A], i2: Iterator[A]): Iterator[A] = { merge2Buffered(i1.buffered, i2.buffered) } def merge2Buffered[A](i1: BufferedIterator[A], i2: BufferedIterator[A])(implicit ord: Ordering[A]): Iterator[A] = { if (!i1.hasNext) { i2 } else if (!i2.hasNext) { i1 } else { val nextHead = if (ord.lt(i1.head, i2.head)) { Iterator.single(i1.next) } else { Iterator.single(i2.next) } nextHead ++ merge2Buffered(i1, i2) } }
196Stream merge
16scala
whzes
(ns clojure-sandbox.statenames (:require [clojure.data.csv:as csv] [clojure.java.io:as io] [clojure.string:refer [lower-case]] [clojure.math.combinatorics:as c] [clojure.pprint:as pprint])) (def made-up-states ["New Kory" "Wen Kory" "York New" "Kory New" "New Kory"]) (def real-states (with-open [in-file (io/reader (io/resource "states.csv"))] (->> (doall (csv/read-csv in-file)) (map first)))) (defn- state->charset [state-name] "Convert state name into sorted list of characters with no spaces" (->> state-name char-array sort (filter (set (map char (range 97 123)))))) (defn- add-charsets [states] "Calculate sorted character list for each state and store with name" (->> states (map lower-case) set (map (fn [s] {:name s :characters (state->charset s)})))) (defn- pair-chars [state1 state2] "Join the characters of two states together and sort them" (-> state1 :characters (concat (:characters state2)) sort)) (defn- pair [[state1 state2]] "Record representing two state names and the total characters used in them" {:inputs [(:name state1) (:name state2)] :characters (pair-chars state1 state2)}) (defn- find-all-pairs [elements] (c/combinations elements 2)) (defn- pairs-to-search [state-names] "Create character lists for all states and return a list of all possible pairs" (->> state-names add-charsets find-all-pairs (map pair))) (defn- pairs-have-same-letters? [[pair1 pair2]] (= (:characters pair1) (:characters pair2))) (defn- inputs-are-distinct? [[pair1 pair2:as pairs]] "Check that two pairs of states don't contain the same state" (= 4 (->> pairs (map:inputs) flatten set count))) (defn- search [pairs] (->> pairs find-all-pairs (filter pairs-have-same-letters?) (filter inputs-are-distinct?))) (defn find-matches [state-names] "Find all state pairs and return pairs of them using the same letters" (-> state-names pairs-to-search search)) (defn- format-match-output [[pair1 pair2]] "Format a pair of state pairs to print out" (str (first (:inputs pair1)) " + " (last (:inputs pair1)) " = " (first (:inputs pair2)) " + " (last (:inputs pair2)))) (defn- evaluate-and-print [states] (->> states find-matches (map format-match-output) pprint/pprint)) (defn -main [& args] (println "Solutions for 50 real states") (evaluate-and-print real-states) (println "Solutions with made up states added") (evaluate-and-print (concat real-states made-up-states)))
199State name puzzle
6clojure
1ropy
package main import "fmt" var count = 0 func foo() { fmt.Println("foo called") } func init() { fmt.Println("first init called") foo() } func init() { fmt.Println("second init called") main() } func main() { count++ fmt.Println("main called when count is", count) }
200Start from a main routine
0go
md4yi
function string:show () print(self) end function string:append (s) self = self .. s end x = "Hi " x:show() x:append("there!") x:show()
193String append
1lua
xkmwz
import static java.lang.Math.*; import static java.util.Arrays.stream; import java.util.Locale; import java.util.function.DoubleSupplier; import static java.util.stream.Collectors.joining; import java.util.stream.DoubleStream; import static java.util.stream.IntStream.range; public class Test implements DoubleSupplier { private double mu, sigma; private double[] state = new double[2]; private int index = state.length; Test(double m, double s) { mu = m; sigma = s; } 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(); } @Override public double getAsDouble() { index++; if (index >= state.length) { double r = sqrt(-2 * log(random())) * sigma; double x = 2 * PI * random(); state = new double[]{mu + r * sin(x), mu + r * cos(x)}; index = 0; } return state[index]; } public static void main(String[] args) { Locale.setDefault(Locale.US); double[] data = DoubleStream.generate(new Test(0.0, 0.5)).limit(100_000) .toArray(); double[] res = meanStdDev(data); System.out.printf("Mean:%8.6f, SD:%8.6f%n", res[0], res[1]); showHistogram01(stream(data).map(a -> max(0.0, min(0.9999, a / 3 + 0.5))) .toArray()); } }
197Statistics/Normal distribution
9java
fsvdv
(def 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 146 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]) (defn calc-stem [number] (int (Math/floor (/ number 10)))) (defn calc-leaf [number] (mod number 10)) (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors. (new-plant 2) [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map)))) (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf)) (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves)))))) (stem-and-leaf data)
198Stem-and-leaf plot
6clojure
3o5zr
Welcome to Kotlin version 1.1.1 (JRE 1.8.0_121-b13) Type:help for help,:quit for quit >>> println("Look no main!") Look no main! >>>:quit
200Start from a main routine
11kotlin
lz7cp
typedef unsigned int uint; uint f(uint n) { return n < 2 ? n : (n&1) ? f(n/2) + f(n/2 + 1) : f(n/2); } uint gcd(uint a, uint b) { return a ? a < b ? gcd(b%a, a) : gcd(a%b, b) : b; } void find(uint from, uint to) { do { uint n; for (n = 1; f(n) != from ; n++); printf(, from, n); } while (++from <= to); } int main(void) { uint n; for (n = 1; n < 16; n++) printf(, f(n)); puts(); find(1, 10); find(100, 0); for (n = 1; n < 1000 && gcd(f(n), f(n+1)) == 1; n++); printf(n == 1000 ? : , n, n+1); return 0; }
201Stern-Brocot sequence
5c
iw6o2
void print_stack_trace() { void *buffer[MAX_BT]; int n; n = backtrace(buffer, MAX_BT); fprintf(stderr, , n); backtrace_symbols_fd(buffer, n, STDERR_FILENO); } void inner(int k) { print_stack_trace(); } void middle(int x, int y) { inner(x*y); } void outer(int a, int b, int c) { middle(a+b, b+c); } int main() { outer(2,3,5); return EXIT_SUCCESS; }
202Stack traces
5c
v672o
package main import ( "fmt" "unicode" ) var states = []string{"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"} func main() { play(states) play(append(states, "New Kory", "Wen Kory", "York New", "Kory New", "New Kory")) } func play(states []string) { fmt.Println(len(states), "states:")
199State name puzzle
0go
fsld0
BEGIN {...} CHECK {...} INIT {...} END {...}
200Start from a main routine
2perl
qbfx6
class StraddlingCheckerboard EncodableChars = SortedChars = + [*..].join def initialize(board = nil) if board.nil? rest = .chars.shuffle @board = [.chars.shuffle, rest[0..9], rest[10..19]] elsif board.chars.sort.join == SortedChars @board = board.chars.each_slice(10).to_a else raise ArgumentError, end @row_labels = @board[0].each_with_index.select {|v, i| v == }.map {|v,i| i} @mapping = {} @board[0].each_with_index {|char, idx| @mapping[char] = idx.to_s unless char == } @board[1..2].each_with_index do |row, row_idx| row.each_with_index do |char, idx| @mapping[char] = % [@row_labels[row_idx], idx] end end end def encode(message) msg = message.upcase.delete() msg.chars.inject() do |crypt, char| crypt << (char =~ /[0-9]/? @mapping[] + char: @mapping[char]) end end def decode(code) msg = tokens = code.chars until tokens.empty? token = tokens.shift itoken = token.to_i unless @row_labels.include?(itoken) msg << @board[0][itoken] else token2 = tokens.shift if @mapping[] == token + token2 msg << tokens.shift else msg << @board[1+@row_labels.index(itoken)][token2.to_i] end end end msg end def to_s @board.inject() {|res, row| res << row.join} end def inspect % [self.class, to_s, @row_labels, @mapping] end end
194Straddling checkerboard
14ruby
jvo7x
null
197Statistics/Normal distribution
11kotlin
8am0q
(doall (map println (.dumpAllThreads (java.lang.management.ManagementFactory/getThreadMXBean) false false)))
202Stack traces
6clojure
rlpg2
import Data.Char (isLetter, toLower) import Data.Function (on) import Data.List (groupBy, nub, sort, sortBy) puzzle :: [String] -> [((String, String), (String, String))] puzzle states = concatMap ((filter isValid . pairs) . map snd) ( filter ((> 1) . length) $ groupBy ((==) `on` fst) $ sortBy (compare `on` fst) [ (pkey (a <> b), (a, b)) | (a, b) <- pairs (nub $ sort states) ] ) where pkey = sort . filter isLetter . map toLower isValid ((a0, a1), (b0, b1)) = (a0 /= b0) && (a0 /= b1) && (a1 /= b0) && (a1 /= b1) pairs :: [a] -> [(a, a)] pairs [] = [] pairs (y: ys) = map (y,) ys <> pairs ys main :: IO () main = do putStrLn $ "Matching pairs generated from " <> show (length stateNames) <> " state names and " <> show (length fakeStateNames) <> " fake state names:" mapM_ print $ puzzle $ stateNames <> fakeStateNames stateNames :: [String] stateNames = [ "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" ] fakeStateNames :: [String] fakeStateNames = [ "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" ]
199State name puzzle
8haskell
4915s
object StraddlingCheckerboard extends App { private val dictonary = Map("H" -> "0", "O" -> "1", "L" -> "2", "M" -> "4", "E" -> "5", "S" -> "6", "R" -> "8", "T" -> "9", "A" -> "30", "B" -> "31", "C" -> "32", "D" -> "33", "F" -> "34", "G" -> "35", "I" -> "36", "J" -> "37", "K" -> "38", "N" -> "39", "P" -> "70", "Q" -> "71", "U" -> "72", "V" -> "73", "W" -> "74", "X" -> "75", "Y" -> "76", "Z" -> "77", "." -> "78", "/" -> "79", "0" -> "790", "1" -> "791", "2" -> "792", "3" -> "793", "4" -> "794", "5" -> "795", "6" -> "796", "7" -> "797", "8" -> "798", "9" -> "799") private def encode(s: String) = s.toUpperCase.map { case ch: Char => dictonary.getOrElse(ch.toString, "") }.mkString private def decode(s: String) = { val revDictionary: Map[String, String] = dictonary.map {case (k, v) => (v, k)} val pat = "(79.|3.|7.|.)".r pat.findAllIn(s).map { el => revDictionary.getOrElse(el, "")}.addString(new StringBuilder) } val enc = encode( "One night-it was on the twentieth of March, " + "1888-I was returning" ) println(enc) println(decode(enc)) }
194Straddling checkerboard
16scala
pgfbj
BEGIN { } END { }
200Start from a main routine
14ruby
8a301
object PrimaryMain extends App { Console.println("Hello World: " + (args mkString ", ")) } object MainTheSecond extends App { Console.println("Goodbye, World: " + (args mkString ", ")) }
200Start from a main routine
16scala
dq9ng
function gaussian (mean, variance) return math.sqrt(-2 * variance * math.log(math.random())) * math.cos(2 * math.pi * math.random()) + mean end function mean (t) local sum = 0 for k, v in pairs(t) do sum = sum + v end return sum / #t end function std (t) local squares, avg = 0, mean(t) for k, v in pairs(t) do squares = squares + ((avg - v) ^ 2) end local variance = squares / #t return math.sqrt(variance) end function showHistogram (t) local lo = math.ceil(math.min(unpack(t))) local hi = math.floor(math.max(unpack(t))) local hist, barScale = {}, 200 for i = lo, hi do hist[i] = 0 for k, v in pairs(t) do if math.ceil(v - 0.5) == i then hist[i] = hist[i] + 1 end end io.write(i .. "\t" .. string.rep('=', hist[i] / #t * barScale)) print(" " .. hist[i]) end end math.randomseed(os.time()) local t, average, variance = {}, 50, 10 for i = 1, 1000 do table.insert(t, gaussian(average, variance)) end print("Mean:", mean(t) .. ", expected " .. average) print("StdDev:", std(t) .. ", expected " .. math.sqrt(variance) .. "\n") showHistogram(t)
197Statistics/Normal distribution
1lua
oe98h