code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use strict; use warnings; my @pts = ('', qw( 01 23 03 12 012 13 013 132 0132) ); my @dots = qw( 4-0 8-0 4-4 8-4 ); my @images = map { sprintf("%-9s\n", "$_:") . draw($_) } 0, 1, 20, 300, 4000, 5555, 6789, 1133; for ( 1 .. 13 ) { s/(.+)\n/ print " $1"; '' /e for @images; print "\n"; } sub draw { my $n = shift; local $_ = " my $quadrant = 0; for my $digit ( reverse split //, sprintf "%04d", $n ) { my ($oldx, $oldy); for my $cell ( split //, $pts[$digit] ) { my ($x, $y) = split /-/, $dots[$cell]; if( defined $oldx ) { my $dirx = $x <=> $oldx; my $diry = $y <=> $oldy; for my $place ( 0 .. 3 ) { substr $_, $oldx + $oldy * 10, 1, ' $oldx += $dirx; $oldy += $diry; } } ($oldx, $oldy) = ($x, $y); } s/.+/ reverse $& /ge; ++$quadrant & 1 or $_ = join '', reverse /.+\n/g; } return $_; }
1,035Cistercian numerals
2perl
otl8x
import random def is_Prime(n): if n!=int(n): return False n=int(n) if n==0 or n==1 or n==4 or n==6 or n==8 or n==9: return False if n==2 or n==3 or n==5 or n==7: return True s = 0 d = n-1 while d%2==0: d>>=1 s+=1 assert(2**s * d == n-1) def trial_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True for i in range(8): a = random.randrange(2, n) if trial_composite(a): return False return True def isPrime(n: int) -> bool: ''' https: ''' if (n <= 1): return False if (n <= 3): return True if (n% 2 == 0 or n% 3 == 0): return False i = 5 while(i * i <= n): if (n% i == 0 or n% (i + 2) == 0): return False i = i + 6 return True def rotations(n: int)-> set((int,)): ''' >>> {123, 231, 312} == rotations(123) True ''' a = str(n) return set(int(a[i:] + a[:i]) for i in range(len(a))) def isCircular(n: int) -> bool: ''' >>> [isCircular(n) for n in (11, 31, 47,)] [True, True, False] ''' return all(isPrime(int(o)) for o in rotations(n)) from itertools import product def main(): result = [2, 3, 5, 7] first = '137' latter = '1379' for i in range(1, 6): s = set(int(''.join(a)) for a in product(first, *((latter,) * i))) while s: a = s.pop() b = rotations(a) if isCircular(a): result.append(min(b)) s -= b result.sort() return result assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main() repunit = lambda n: int('1' * n) def repmain(n: int) -> list: ''' returns the first n repunit primes, probably. ''' result = [] i = 2 while len(result) < n: if is_Prime(repunit(i)): result.append(i) i += 1 return result assert [2, 19, 23, 317, 1031] == repmain(5)
1,034Circular primes
3python
j1o7p
package main import ( "fmt" "math/big" ) var ( zero = new(big.Int) prod = new(big.Int) fact = new(big.Int) ) func ccFactors(n, m uint64) (*big.Int, bool) { prod.SetUint64(6*m + 1) if !prod.ProbablyPrime(0) { return zero, false } fact.SetUint64(12*m + 1) if !fact.ProbablyPrime(0) {
1,040Chernick's Carmichael numbers
0go
4hp52
import Unsafe.Coerce ( unsafeCoerce ) type Church a = (a -> a) -> a -> a churchZero :: Church a churchZero = const id churchOne :: Church a churchOne = id succChurch :: Church a -> Church a succChurch = (<*>) (.) addChurch :: Church a -> Church a -> Church a addChurch = (<*>). fmap (.) multChurch :: Church a -> Church a -> Church a multChurch = (.) expChurch :: Church a -> Church a -> Church a expChurch basech expch = unsafeCoerce expch basech isChurchZero :: Church a -> Church a isChurchZero ch = unsafeCoerce ch (const churchZero) churchOne predChurch :: Church a -> Church a predChurch ch f x = unsafeCoerce ch (\ g h -> h (g f)) (const x) id minusChurch :: Church a -> Church a -> Church a minusChurch ach bch = unsafeCoerce bch predChurch ach divChurch :: Church a -> Church a -> Church a divChurch dvdnd dvsr = let divr n d = (\ v -> v (const $ succChurch $ divr v d) churchZero ) (minusChurch n d) in divr (unsafeCoerce succChurch dvdnd) $ unsafeCoerce dvsr churchFromInt :: Int -> Church a churchFromInt 0 = churchZero churchFromInt n = succChurch $ churchFromInt (n - 1) intFromChurch :: Church Int -> Int intFromChurch ch = ch succ 0 main :: IO () main = do let [cThree, cFour, cEleven, cTwelve] = churchFromInt <$> [3, 4, 11, 12] print $ fmap intFromChurch [ addChurch cThree cFour , multChurch cThree cFour , expChurch cFour cThree , expChurch cThree cFour , isChurchZero churchZero , predChurch cFour , minusChurch cEleven cThree , divChurch cEleven cThree , divChurch cTwelve cThree ]
1,039Church numerals
8haskell
e0nai
funcs={} for i=1,10 do table.insert(funcs, function() return i*i end) end funcs[2]() funcs[3]()
1,033Closures/Value capture
1lua
fygdp
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class ChernicksCarmichaelNumbers { public static void main(String[] args) { for ( long n = 3 ; n < 10 ; n++ ) { long m = 0; boolean foundComposite = true; List<Long> factors = null; while ( foundComposite ) { m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5); factors = U(n, m); foundComposite = false; for ( long factor : factors ) { if ( ! isPrime(factor) ) { foundComposite = true; break; } } } System.out.printf("U(%d,%d) =%s =%s%n", n, m, display(factors), multiply(factors)); } } private static String display(List<Long> factors) { return factors.toString().replace("[", "").replace("]", "").replaceAll(", ", " * "); } private static BigInteger multiply(List<Long> factors) { BigInteger result = BigInteger.ONE; for ( long factor : factors ) { result = result.multiply(BigInteger.valueOf(factor)); } return result; } private static List<Long> U(long n, long m) { List<Long> factors = new ArrayList<>(); factors.add(6*m + 1); factors.add(12*m + 1); for ( int i = 1 ; i <= n-2 ; i++ ) { factors.add(((long)Math.pow(2, i)) * 9 * m + 1); } return factors; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() {
1,040Chernick's Carmichael numbers
9java
px0b3
package lvijay; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class Church { public static interface ChurchNum extends Function<ChurchNum, ChurchNum> { } public static ChurchNum zero() { return f -> x -> x; } public static ChurchNum next(ChurchNum n) { return f -> x -> f.apply(n.apply(f).apply(x)); } public static ChurchNum plus(ChurchNum a) { return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x)); } public static ChurchNum pow(ChurchNum m) { return n -> m.apply(n); } public static ChurchNum mult(ChurchNum a) { return b -> f -> x -> b.apply(a.apply(f)).apply(x); } public static ChurchNum toChurchNum(int n) { if (n <= 0) { return zero(); } return next(toChurchNum(n - 1)); } public static int toInt(ChurchNum c) { AtomicInteger counter = new AtomicInteger(0); ChurchNum funCounter = f -> { counter.incrementAndGet(); return f; }; plus(zero()).apply(c).apply(funCounter).apply(x -> x); return counter.get(); } public static void main(String[] args) { ChurchNum zero = zero(); ChurchNum three = next(next(next(zero))); ChurchNum four = next(next(next(next(zero)))); System.out.println("3+4=" + toInt(plus(three).apply(four)));
1,039Church numerals
9java
haqjm
def _init(): digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '', _digits[0][d[0]])), ''.join((_digits[0][ 0], '', _digits[0][ 0])), ''.join((_digits[3][d[3]], '', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
1,035Cistercian numerals
3python
iz2of
double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf(, A[i * n + j]); printf(); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf(); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
1,042Cholesky decomposition
5c
tm9f4
int main() { int jobs = 41, tid; omp_set_num_threads(5); { tid = omp_get_thread_num(); while (jobs > 0) { if (!jobs) break; printf(, tid, jobs--); usleep(100000 + rand() / (double) RAND_MAX * 3000000); printf(, tid); } printf(, tid); } return 0; }
1,043Checkpoint synchronization
5c
2gglo
class Combinations(val m: Int, val n: Int) { private val combination = IntArray(m) init { generate(0) } private fun generate(k: Int) { if (k >= m) { for (i in 0 until m) print("${combination[i]} ") println() } else { for (j in 0 until n) if (k == 0 || j > combination[k - 1]) { combination[k] = j generate(k + 1) } } } } fun main(args: Array<String>) { Combinations(3, 5) }
1,031Combinations
11kotlin
qilx1
(() => { 'use strict';
1,039Church numerals
10javascript
asi10
package main import ( "fmt" "math" "math/rand" "time" ) type xy struct { x, y float64 } const n = 1000 const scale = 100. func d(p1, p2 xy) float64 { return math.Hypot(p2.x-p1.x, p2.y-p1.y) } func main() { rand.Seed(time.Now().Unix()) points := make([]xy, n) for i := range points { points[i] = xy{rand.Float64() * scale, rand.Float64() * scale} } p1, p2 := closestPair(points) fmt.Println(p1, p2) fmt.Println("distance:", d(p1, p2)) } func closestPair(points []xy) (p1, p2 xy) { if len(points) < 2 { panic("at least two points expected") } min := 2 * scale for i, q1 := range points[:len(points)-1] { for _, q2 := range points[i+1:] { if dq := d(q1, q2); dq < min { p1, p2 = q1, q2 min = dq } } } return }
1,036Closest-pair problem
0go
bwikh
require 'gmp' require 'prime' candidate_primes = Enumerator.new do |y| DIGS = [1,3,7,9] [2,3,5,7].each{|n| y << n.to_s} (2..).each do |size| DIGS.repeated_permutation(size) do |perm| y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0 end end end def min_rotation(ar) = Array.new(ar.size){|n| ar.rotate(n)}.min def circular?(num_str) chars = num_str.chars return GMP::Z(num_str).probab_prime? > 0 if chars.all?() chars.size.times.all? do GMP::Z(chars.rotate!.join).probab_prime? > 0 end end puts puts candidate_primes.lazy.select{|cand| circular?(cand)}.take(19).to_a.join(), puts reps = Prime.each.lazy.select{|pr| circular?(*pr)}.take(5).to_a puts reps.map{|r| + r.to_s}.join(), [5003, 9887, 15073, 25031].each {|rep| puts 1 }
1,034Circular primes
14ruby
kenhg
int main() { puts(isatty(fileno(stdout)) ? : ); return 0; }
1,044Check output device is a terminal
5c
pxwby
int main(void) { puts(isatty(fileno(stdin)) ? : ); return 0; }
1,045Check input device is a terminal
5c
w8sec
class Point { final Number x, y Point(Number x = 0, Number y = 0) { this.x = x; this.y = y } Number distance(Point that) { ((this.x - that.x)**2 + (this.y - that.y)**2)**0.5 } String toString() { "{x:${x}, y:${y}}" } }
1,036Closest-pair problem
7groovy
rbqgh
null
1,034Circular primes
15rust
bwdkx
object CircularPrimes { def main(args: Array[String]): Unit = { println("First 19 circular primes:") var p = 2 var count = 0 while (count < 19) { if (isCircularPrime(p)) { if (count > 0) { print(", ") } print(p) count += 1 } p += 1 } println() println("Next 4 circular primes:") var repunit = 1 var digits = 1 while (repunit < p) { repunit = 10 * repunit + 1 digits += 1 } var bignum = BigInt.apply(repunit) count = 0 while (count < 4) { if (bignum.isProbablePrime(15)) { if (count > 0) { print(", ") } print(s"R($digits)") count += 1 } digits += 1 bignum = bignum * 10 bignum = bignum + 1 } println() testRepunit(5003) testRepunit(9887) testRepunit(15073) testRepunit(25031) } def isPrime(n: Int): Boolean = { if (n < 2) { return false } if (n % 2 == 0) { return n == 2 } if (n % 3 == 0) { return n == 3 } var p = 5 while (p * p <= n) { if (n % p == 0) { return false } p += 2 if (n % p == 0) { return false } p += 4 } true } def cycle(n: Int): Int = { var m = n var p = 1 while (m >= 10) { p *= 10 m /= 10 } m + 10 * (n % p) } def isCircularPrime(p: Int): Boolean = { if (!isPrime(p)) { return false } var p2 = cycle(p) while (p2 != p) { if (p2 < p || !isPrime(p2)) { return false } p2 = cycle(p2) } true } def testRepunit(digits: Int): Unit = { val ru = repunit(digits) if (ru.isProbablePrime(15)) { println(s"R($digits) is probably prime.") } else { println(s"R($digits) is not prime.") } } def repunit(digits: Int): BigInt = { val ch = Array.fill(digits)('1') BigInt.apply(new String(ch)) } }
1,034Circular primes
16scala
asz1n
typedef struct{ double x,y; }point; double distance(point p1,point p2) { return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } void findCircles(point p1,point p2,double radius) { double separation = distance(p1,p2),mirrorDistance; if(separation == 0.0) { radius == 0.0 ? printf(,p1.x,p1.y): printf(,p1.x,p1.y); } else if(separation == 2*radius) { printf(,(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius); } else if(separation > 2*radius) { printf(,radius); } else { mirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2)); printf(); printf(,(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius); } } int main() { int i; point cases[] = { {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345}, {0.1234, 0.9876}, {0.1234, 0.9876} }; double radii[] = {2.0,1.0,2.0,0.5,0.0}; for(i=0;i<5;i++) { printf(,i+1); findCircles(cases[2*i],cases[2*i+1],radii[i]); } return 0; }
1,046Circles of given radius through two points
5c
c529c
(ns checkpoint.core (:gen-class) (:require [clojure.core.async:as async:refer [go <! >! <!! >!! alts! close!]] [clojure.string:as string])) (defn coordinate [ctl-ch resp-ch combine] (go (<! (async/timeout 2000)) (loop [members {}, received {}] (let [rcvd-count (count received) release #(doseq [outch (vals members)] (go (>! outch %))) received (if (and (pos? rcvd-count) (= rcvd-count (count members))) (do (-> received vals combine release) {}) received) [v ch] (alts! (cons ctl-ch (keys members)))] (if (= ch ctl-ch) (let [[op inch outch] v] (condp = op :join (do (>! resp-ch:ok) (recur (assoc members inch outch) received)) :part (do (>! resp-ch:ok) (close! inch) (close! outch) (recur (dissoc members inch) (dissoc received inch))) :exit:exit)) (if (nil? v) (do (close! (get members ch)) (recur (dissoc members ch) (dissoc received ch))) (recur members (assoc received ch v)))))))) (defprotocol ICheckpoint (join [this]) (part [this inch outch])) (deftype Checkpoint [ctl-ch resp-ch sync] ICheckpoint (join [this] (let [inch (async/chan), outch (async/chan 1)] (go (>! ctl-ch [:join inch outch]) (<! resp-ch) [inch outch]))) (part [this inch outch] (go (>! ctl-ch [:part inch outch])))) (defn checkpoint [combine] (let [ctl-ch (async/chan), resp-ch (async/chan 1)] (->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine)))) (defn worker ([ckpt repeats] (worker ckpt repeats (fn [& args] nil))) ([ckpt repeats mon] (go (let [[send recv] (<! (join ckpt))] (doseq [n (range repeats)] (<! (async/timeout (rand-int 5000))) (>! send n) (mon "sent" n) (<! recv) (mon "recvd")) (part ckpt send recv))))) (defn -main [& args] (let [ckpt (checkpoint identity) monitor (fn [id] (fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))] (worker ckpt 10 (monitor 1)) (worker ckpt 10 (monitor 2))))
1,043Checkpoint synchronization
6clojure
gkk4f
if x == 0: foo() elif x == 1: bar() elif x == 2: baz() else: boz()
1,023Conditional structures
3python
7pmrm
int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf(, chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
1,047Chinese remainder theorem
5c
l42cy
use 5.020; use warnings; use ntheory qw/:all/; use experimental qw/signatures/; sub chernick_carmichael_factors ($n, $m) { (6*$m + 1, 12*$m + 1, (map { (1 << $_) * 9*$m + 1 } 1 .. $n-2)); } sub chernick_carmichael_number ($n, $callback) { my $multiplier = ($n > 4) ? (1 << ($n-4)) : 1; for (my $m = 1 ; ; ++$m) { my @f = chernick_carmichael_factors($n, $m * $multiplier); next if not vecall { is_prime($_) } @f; $callback->(@f); last; } } foreach my $n (3..9) { chernick_carmichael_number($n, sub (@f) { say "a($n) = ", vecprod(@f) }); }
1,040Chernick's Carmichael numbers
2perl
fycd7
def initN n = Array.new(15){Array.new(11, ' ')} for i in 1..15 n[i - 1][5] = 'x' end return n end def horiz(n, c1, c2, r) for c in c1..c2 n[r][c] = 'x' end end def verti(n, r1, r2, c) for r in r1..r2 n[r][c] = 'x' end end def diagd(n, c1, c2, r) for c in c1..c2 n[r+c-c1][c] = 'x' end end def diagu(n, c1, c2, r) for c in c1..c2 n[r-c+c1][c] = 'x' end end def initDraw draw = [] draw[1] = lambda do |n| horiz(n, 6, 10, 0) end draw[2] = lambda do |n| horiz(n, 6, 10, 4) end draw[3] = lambda do |n| diagd(n, 6, 10, 0) end draw[4] = lambda do |n| diagu(n, 6, 10, 4) end draw[5] = lambda do |n| draw[1].call(n) draw[4].call(n) end draw[6] = lambda do |n| verti(n, 0, 4, 10) end draw[7] = lambda do |n| draw[1].call(n) draw[6].call(n) end draw[8] = lambda do |n| draw[2].call(n) draw[6].call(n) end draw[9] = lambda do |n| draw[1].call(n) draw[8].call(n) end draw[10] = lambda do |n| horiz(n, 0, 4, 0) end draw[20] = lambda do |n| horiz(n, 0, 4, 4) end draw[30] = lambda do |n| diagu(n, 0, 4, 4) end draw[40] = lambda do |n| diagd(n, 0, 4, 0) end draw[50] = lambda do |n| draw[10].call(n) draw[40].call(n) end draw[60] = lambda do |n| verti(n, 0, 4, 0) end draw[70] = lambda do |n| draw[10].call(n) draw[60].call(n) end draw[80] = lambda do |n| draw[20].call(n) draw[60].call(n) end draw[90] = lambda do |n| draw[10].call(n) draw[80].call(n) end draw[100] = lambda do |n| horiz(n, 6, 10, 14) end draw[200] = lambda do |n| horiz(n, 6, 10, 10) end draw[300] = lambda do |n| diagu(n, 6, 10, 14) end draw[400] = lambda do |n| diagd(n, 6, 10, 10) end draw[500] = lambda do |n| draw[100].call(n) draw[400].call(n) end draw[600] = lambda do |n| verti(n, 10, 14, 10) end draw[700] = lambda do |n| draw[100].call(n) draw[600].call(n) end draw[800] = lambda do |n| draw[200].call(n) draw[600].call(n) end draw[900] = lambda do |n| draw[100].call(n) draw[800].call(n) end draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end draw[5000] = lambda do |n| draw[1000].call(n) draw[4000].call(n) end draw[6000] = lambda do |n| verti(n, 10, 14, 0) end draw[7000] = lambda do |n| draw[1000].call(n) draw[6000].call(n) end draw[8000] = lambda do |n| draw[2000].call(n) draw[6000].call(n) end draw[9000] = lambda do |n| draw[1000].call(n) draw[8000].call(n) end return draw end def printNumeral(n) for a in n for b in a print b end print end print end draw = initDraw() for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999] n = initN() print number, thousands = (number / 1000).floor number = number % 1000 hundreds = (number / 100).floor number = number % 100 tens = (number / 10).floor ones = number % 10 if thousands > 0 then draw[thousands * 1000].call(n) end if hundreds > 0 then draw[hundreds * 100].call(n) end if tens > 0 then draw[tens * 10].call(n) end if ones > 0 then draw[ones].call(n) end printNumeral(n) end
1,035Cistercian numerals
14ruby
d6uns
import Data.List (minimumBy, tails, unfoldr, foldl1') import System.Random (newStdGen, randomRs) import Control.Arrow ((&&&)) import Data.Ord (comparing) vecLeng [[a, b], [p, q]] = sqrt $ (a - p) ^ 2 + (b - q) ^ 2 findClosestPair = foldl1'' ((minimumBy (comparing vecLeng) .) . (. return) . (:)) . concatMap (\(x:xs) -> map ((x:) . return) xs) . init . tails testCP = do g <- newStdGen let pts :: [[Double]] pts = take 1000 . unfoldr (Just . splitAt 2) $ randomRs (-1, 1) g print . (id &&& vecLeng) . findClosestPair $ pts main = testCP foldl1'' = foldl1'
1,036Closest-pair problem
8haskell
d6vn4
package main import ( "os" "fmt" ) func main() { if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal") } }
1,044Check output device is a terminal
0go
6lc3p
module Main where import System.Posix.Terminal (queryTerminal) import System.Posix.IO (stdOutput) main :: IO () main = do istty <- queryTerminal stdOutput putStrLn (if istty then "stdout is tty" else "stdout is not tty")
1,044Check output device is a terminal
8haskell
j1p7g
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec L))))
1,042Cholesky decomposition
6clojure
mvuyq
package main import ( "golang.org/x/crypto/ssh/terminal" "fmt" "os" ) func main() { if terminal.IsTerminal(int(os.Stdin.Fd())) { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal.") } }
1,045Check input device is a terminal
0go
c5v9g
module Main (main) where import System.Posix.IO (stdInput) import System.Posix.Terminal (queryTerminal) main :: IO () main = do isTTY <- queryTerminal stdInput putStrLn $ if isTTY then "stdin is TTY" else "stdin is not TTY"
1,045Check input device is a terminal
8haskell
pxebt
function map(f, a, ...) if a then return f(a), map(f, ...) end end function incr(k) return function(a) return k > a and a or a+1 end end function combs(m, n) if m * n == 0 then return {{}} end local ret, old = {}, combs(m-1, n-1) for i = 1, n do for k, v in ipairs(old) do ret[#ret+1] = {i, map(incr(i), unpack(v))} end end return ret end for k, v in ipairs(combs(3, 5)) do print(unpack(v)) end
1,031Combinations
1lua
sn2q8
function churchZero() return function(x) return x end end function churchSucc(c) return function(f) return function(x) return f(c(f)(x)) end end end function churchAdd(c, d) return function(f) return function(x) return c(f)(d(f)(x)) end end end function churchMul(c, d) return function(f) return c(d(f)) end end function churchExp(c, e) return e(c) end function numToChurch(n) local ret = churchZero for i = 1, n do ret = succ(ret) end return ret end function churchToNum(c) return c(function(x) return x + 1 end)(0) end three = churchSucc(churchSucc(churchSucc(churchZero))) four = churchSucc(churchSucc(churchSucc(churchSucc(churchZero)))) print("'three'\t=", churchToNum(three)) print("'four' \t=", churchToNum(four)) print("'three' * 'four' =", churchToNum(churchMul(three, four))) print("'three' + 'four' =", churchToNum(churchAdd(three, four))) print("'three' ^ 'four' =", churchToNum(churchExp(three, four))) print("'four' ^ 'three' =", churchToNum(churchExp(four, three)))
1,039Church numerals
1lua
gka4j
const char* animals[] = { ,,,,,,,,,,, }; const char* elements[] = { ,,,, }; const char* getElement(int year) { int element = (int)floor((year - 4) % 10 / 2); return elements[element]; } const char* getAnimal(int year) { return animals[(year - 4) % 12]; } const char* getYY(int year) { if (year % 2 == 0) { return ; } else { return ; } } int main() { int years[] = { 1935, 1938, 1968, 1972, 1976, 2017 }; int i; for (i = 0; i < 6; ++i) { int year = years[i]; printf(, year, getElement(year), getAnimal(year), getYY(year)); } return 0; }
1,048Chinese zodiac
5c
z9ztx
null
1,044Check output device is a terminal
11kotlin
9uvmh
local function isTTY ( fd ) fd = tonumber( fd ) or 1 local ok, exit, signal = os.execute( string.format( "test -t%d", fd ) ) return (ok and exit == "exit") and signal == 0 or false end print( "stdin", isTTY( 0 ) ) print( "stdout", isTTY( 1 ) ) print( "stderr", isTTY( 2 ) )
1,044Check output device is a terminal
1lua
c5u92
null
1,045Check input device is a terminal
11kotlin
vr421
use strict; use warnings; use 5.010; if (-t) { say "Input comes from tty."; } else { say "Input doesn't come from tty."; }
1,045Check input device is a terminal
2perl
0dis4
from sympy import isprime def primality_pretest(k): if not (k% 3) or not (k% 5) or not (k% 7) or not (k% 11) or not(k% 13) or not (k% 17) or not (k% 19) or not (k% 23): return (k <= 23) return True def is_chernick(n, m): t = 9 * m if not primality_pretest(6 * m + 1): return False if not primality_pretest(12 * m + 1): return False for i in range(1,n-1): if not primality_pretest((t << i) + 1): return False if not isprime(6 * m + 1): return False if not isprime(12 * m + 1): return False for i in range(1,n - 1): if not isprime((t << i) + 1): return False return True for n in range(3,10): if n > 4: multiplier = 1 << (n - 4) else: multiplier = 1 if n > 5: multiplier *= 5 k = 1 while True: m = k * multiplier if is_chernick(n, m): print(+str(n)++str(m)) break k += 1
1,040Chernick's Carmichael numbers
3python
tmlfw
my @f = map(sub { $_ * $_ }, 0 .. 9); print $f[$_](), "\n" for (0 .. 8);
1,033Closures/Value capture
2perl
j1i7f
from sys import stdin if stdin.isatty(): print() else: print()
1,045Check input device is a terminal
3python
8fn0o
char *months[] = { , , , , , , , , , , , , }; struct Date { int month, day; bool active; } dates[] = { {5,15,true}, {5,16,true}, {5,19,true}, {6,17,true}, {6,18,true}, {7,14,true}, {7,16,true}, {8,14,true}, {8,15,true}, {8,17,true} }; void printRemaining() { int i, c; for (i = 0, c = 0; i < UPPER_BOUND; i++) { if (dates[i].active) { c++; } } printf(, c); } void printAnswer() { int i; for (i = 0; i < UPPER_BOUND; i++) { if (dates[i].active) { printf(, months[dates[i].month], dates[i].day); } } } void firstPass() { int i, j, c; for (i = 0; i < UPPER_BOUND; i++) { c = 0; for (j = 0; j < UPPER_BOUND; j++) { if (dates[j].day == dates[i].day) { c++; } } if (c == 1) { for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].month == dates[i].month) { dates[j].active = false; } } } } } void secondPass() { int i, j, c; for (i = 0; i < UPPER_BOUND; i++) { if (!dates[i].active) continue; c = 0; for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].day == dates[i].day) { c++; } } if (c > 1) { for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].day == dates[i].day) { dates[j].active = false; } } } } } void thirdPass() { int i, j, c; for (i = 0; i < UPPER_BOUND; i++) { if (!dates[i].active) continue; c = 0; for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].month == dates[i].month) { c++; } } if (c > 1) { for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].month == dates[i].month) { dates[j].active = false; } } } } } int main() { printRemaining(); firstPass(); printRemaining(); secondPass(); printRemaining(); thirdPass(); printAnswer(); return 0; }
1,049Cheryl's birthday
5c
6cz32
x <- 0 if(x == 0) print("foo") x <- 1 if(x == 0) print("foo") if(x == 0) print("foo") else print("bar")
1,023Conditional structures
13r
5jzuy
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bzout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder n a))
1,047Chinese remainder theorem
6clojure
4hg5o
package main import "fmt" func chowla(n int) int { if n < 1 { panic("argument must be a positive integer") } sum := 0 for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i if i == j { sum += i } else { sum += i + j } } } return sum } func sieve(limit int) []bool {
1,041Chowla numbers
0go
y2u64
<?php $funcs = array(); for ($i = 0; $i < 10; $i++) { $funcs[] = function () use ($i) { return $i * $i; }; } echo $funcs[3](), ; ?>
1,033Closures/Value capture
12php
tmrf1
$ perl -e "warn -t STDOUT? 'Terminal': 'Other'" Terminal $ perl -e "warn -t STDOUT? 'Terminal': 'Other'" > x.tmp Other
1,044Check output device is a terminal
2perl
w80e6
if(posix_isatty(STDOUT)) { echo .PHP_EOL; } else { echo .PHP_EOL; }
1,044Check output device is a terminal
12php
l45cj
from sys import stdout if stdout.isatty(): print 'The output device is a teletype. Or something like a teletype.' else: print 'The output device isn\'t like a teletype.'
1,044Check output device is a terminal
3python
xo8wr
(ns tanevaulator (:gen-class)) (def test-cases [ [[1, 1, 2], [1, 1, 3]], [[2, 1, 3], [1, 1, 7]], [[4, 1, 5], [-1, 1, 239]], [[5, 1, 7], [2, 3, 79]], [[1, 1, 2], [1, 1, 5], [1, 1, 8]], [[4, 1, 5], [-1, 1, 70], [1, 1, 99]], [[5, 1, 7], [4, 1, 53], [2, 1, 4443]], [[6, 1, 8], [2, 1, 57], [1, 1, 239]], [[8, 1, 10], [-1, 1, 239], [-4, 1, 515]], [[12, 1, 18], [8, 1, 57], [-5, 1, 239]], [[16, 1, 21], [3, 1, 239], [4, 3, 1042]], [[22, 1, 28], [2, 1, 443], [-5, 1, 1393], [-10, 1, 11018]], [[22, 1, 38], [17, 7, 601], [10, 7, 8149]], [[44, 1, 57], [7, 1, 239], [-12, 1, 682], [24, 1, 12943]], [[88, 1, 172], [51, 1, 239], [32, 1, 682], [44, 1, 5357], [68, 1, 12943]], [[88, 1, 172], [51, 1, 239], [32, 1, 682], [44, 1, 5357], [68, 1, 12944]] ]) (defn tan-sum [a b] " tan (a + b) " (/ (+ a b) (- 1 (* a b)))) (defn tan-eval [m] " Evaluates tan of a triplet (e.g. [1, 1, 2])" (let [coef (first m) rat (/ (nth m 1) (nth m 2))] (cond (= 1 coef) rat (neg? coef) (tan-eval [(- (nth m 0)) (- (nth m 1)) (nth m 2)]) :else (let [ ca (quot coef 2) cb (- coef ca) a (tan-eval [ca (nth m 1) (nth m 2)]) b (tan-eval [cb (nth m 1) (nth m 2)])] (tan-sum a b))))) (defn tans [m] " Evaluates tan of set of triplets (e.g. [[1, 1, 2], [1, 1, 3]])" (if (= 1 (count m)) (tan-eval (nth m 0)) (let [a (tan-eval (first m)) b (tans (rest m))] (tan-sum a b)))) (doseq [q test-cases] " Display results " (println "tan " q " = "(tans q)))
1,050Check Machin-like formulas
6clojure
4jv5o
File.new().isatty File.new().isatty
1,045Check input device is a terminal
14ruby
izfoh
extern crate libc; fn main() { let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) }!= 0; if istty { println!("stdout is tty"); } else { println!("stdout is not tty"); } }
1,045Check input device is a terminal
15rust
n3ti4
import org.fusesource.jansi.internal.CLibrary._ object IsATty extends App { var enabled = true def apply(enabled: Boolean): Boolean = {
1,045Check input device is a terminal
16scala
tm6fb
package main import ( "log" "math/rand" "sync" "time" ) func worker(part string) { log.Println(part, "worker begins part") time.Sleep(time.Duration(rand.Int63n(1e6))) log.Println(part, "worker completes part") wg.Done() } var ( partList = []string{"A", "B", "C", "D"} nAssemblies = 3 wg sync.WaitGroup ) func main() { rand.Seed(time.Now().UnixNano()) for c := 1; c <= nAssemblies; c++ { log.Println("begin assembly cycle", c) wg.Add(len(partList)) for _, part := range partList { go worker(part) } wg.Wait() log.Println("assemble. cycle", c, "complete") } }
1,043Checkpoint synchronization
0go
qiixz
import Control.Parallel data Task a = Idle | Make a type TaskList a = [a] type Results a = [a] type TaskGroups a = [TaskList a] type WorkerList a = [Worker a] type Worker a = [Task a] runTasks :: TaskList a -> Results a runTasks [] = [] runTasks (x:[]) = x: [] runTasks (x:y:[]) = y `par` x: y: [] runTasks (x:y:ys) = y `par` x: y: runTasks ys groupTasks :: WorkerList a -> TaskGroups a groupTasks [] = [] groupTasks xs | allWorkersIdle xs = [] | otherwise = concatMap extractTask xs: groupTasks (map removeTask xs) extractTask :: Worker a -> [a] extractTask [] = [] extractTask (Idle:_) = [] extractTask (Make a:_) = [a] removeTask :: Worker a -> Worker a removeTask = drop 1 allWorkersIdle :: WorkerList a -> Bool allWorkersIdle = all null . map extractTask worker1 :: Worker Integer worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ] worker2 :: Worker Integer worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ] worker3 :: Worker Integer worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ] worker4 :: Worker Integer worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ] worker5 :: Worker Integer worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ] tasks :: TaskGroups Integer tasks = groupTasks [worker1, worker2, worker3, worker4, worker5] workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO () workshop func a = mapM_ doWork $ zip [1..length a] a where doWork (x, y) = do putStrLn $ "Doing task " ++ show x ++ "." putStrLn $ "There are " ++ show (length y) ++ " workers for this task." putStrLn "Waiting for all workers..." print $ func $ runTasks y putStrLn $ "Task " ++ show x ++ " done." main = workshop sum tasks
1,043Checkpoint synchronization
8haskell
mvvyf
class Chowla { static int chowla(int n) { if (n < 1) throw new RuntimeException("argument must be a positive integer") int sum = 0 int i = 2 while (i * i <= n) { if (n % i == 0) { int j = (int) (n / i) sum += (i == j) ? i: i + j } i++ } return sum } static boolean[] sieve(int limit) {
1,041Chowla numbers
7groovy
fy9dn
use 5.020; use feature qw<signatures>; no warnings qw<experimental::signatures>; use constant zero => sub ($f) { sub ($x) { $x }}; use constant succ => sub ($n) { sub ($f) { sub ($x) { $f->($n->($f)($x)) }}}; use constant add => sub ($n) { sub ($m) { sub ($f) { sub ($x) { $m->($f)($n->($f)($x)) }}}}; use constant mult => sub ($n) { sub ($m) { sub ($f) { sub ($x) { $m->($n->($f))($x) }}}}; use constant power => sub ($b) { sub ($e) { $e->($b) }}; use constant countup => sub ($i) { $i + 1 }; use constant countdown => sub ($i) { $i == 0 ? zero : succ->( __SUB__->($i - 1) ) }; use constant to_int => sub ($f) { $f->(countup)->(0) }; use constant from_int => sub ($x) { countdown->($x) }; use constant three => succ->(succ->(succ->(zero))); use constant four => from_int->(4); say join ' ', map { to_int->($_) } ( add ->( three )->( four ), mult ->( three )->( four ), power->( four )->( three ), power->( three )->( four ), );
1,039Church numerals
2perl
izmo3
import java.util.*; public class ClosestPair { public static class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } } public static class Pair { public Point point1 = null; public Point point2 = null; public double distance = 0.0; public Pair() { } public Pair(Point point1, Point point2) { this.point1 = point1; this.point2 = point2; calcDistance(); } public void update(Point point1, Point point2, double distance) { this.point1 = point1; this.point2 = point2; this.distance = distance; } public void calcDistance() { this.distance = distance(point1, point2); } public String toString() { return point1 + "-" + point2 + ": " + distance; } } public static double distance(Point p1, Point p2) { double xdist = p2.x - p1.x; double ydist = p2.y - p1.y; return Math.hypot(xdist, ydist); } public static Pair bruteForce(List<? extends Point> points) { int numPoints = points.size(); if (numPoints < 2) return null; Pair pair = new Pair(points.get(0), points.get(1)); if (numPoints > 2) { for (int i = 0; i < numPoints - 1; i++) { Point point1 = points.get(i); for (int j = i + 1; j < numPoints; j++) { Point point2 = points.get(j); double distance = distance(point1, point2); if (distance < pair.distance) pair.update(point1, point2, distance); } } } return pair; } public static void sortByX(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.x < point2.x) return -1; if (point1.x > point2.x) return 1; return 0; } } ); } public static void sortByY(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.y < point2.y) return -1; if (point1.y > point2.y) return 1; return 0; } } ); } public static Pair divideAndConquer(List<? extends Point> points) { List<Point> pointsSortedByX = new ArrayList<Point>(points); sortByX(pointsSortedByX); List<Point> pointsSortedByY = new ArrayList<Point>(points); sortByY(pointsSortedByY); return divideAndConquer(pointsSortedByX, pointsSortedByY); } private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY) { int numPoints = pointsSortedByX.size(); if (numPoints <= 3) return bruteForce(pointsSortedByX); int dividingIndex = numPoints >>> 1; List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex); List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints); List<Point> tempList = new ArrayList<Point>(leftOfCenter); sortByY(tempList); Pair closestPair = divideAndConquer(leftOfCenter, tempList); tempList.clear(); tempList.addAll(rightOfCenter); sortByY(tempList); Pair closestPairRight = divideAndConquer(rightOfCenter, tempList); if (closestPairRight.distance < closestPair.distance) closestPair = closestPairRight; tempList.clear(); double shortestDistance =closestPair.distance; double centerX = rightOfCenter.get(0).x; for (Point point : pointsSortedByY) if (Math.abs(centerX - point.x) < shortestDistance) tempList.add(point); for (int i = 0; i < tempList.size() - 1; i++) { Point point1 = tempList.get(i); for (int j = i + 1; j < tempList.size(); j++) { Point point2 = tempList.get(j); if ((point2.y - point1.y) >= shortestDistance) break; double distance = distance(point1, point2); if (distance < closestPair.distance) { closestPair.update(point1, point2, distance); shortestDistance = distance; } } } return closestPair; } public static void main(String[] args) { int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]); List<Point> points = new ArrayList<Point>(); Random r = new Random(); for (int i = 0; i < numPoints; i++) points.add(new Point(r.nextDouble(), r.nextDouble())); System.out.println("Generated " + numPoints + " random points"); long startTime = System.currentTimeMillis(); Pair bruteForceClosestPair = bruteForce(points); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair); startTime = System.currentTimeMillis(); Pair dqClosestPair = divideAndConquer(points); elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair); if (bruteForceClosestPair.distance != dqClosestPair.distance) System.out.println("MISMATCH"); } }
1,036Closest-pair problem
9java
snyq0
(def base-year 4) (def celestial-stems ["" "" "" "" "" "" "" "" "" ""]) (def terrestrial-branches ["" "" "" "" "" "" "" "" "" "" "" ""]) (def zodiac-animals ["Rat" "Ox" "Tiger" "Rabbit" "Dragon" "Snake" "Horse" "Goat" "Monkey" "Rooster" "Dog" "Pig"]) (def elements ["Wood" "Fire" "Earth" "Metal" "Water"]) (def aspects ["yang" "yin"]) (def pinyin (zipmap (concat celestial-stems terrestrial-branches) '("ji" "y" "bng" "dng" "w" "j" "gng" "xn" "rn" "gi" "z" "chu" "yn" "mo" "chn" "s" "w" "wi" "shn" "yu" "x" "hi"))) (defn chinese-zodiac [year] (let [cycle-year (- year base-year) cycle-position (inc (mod cycle-year 60)) stem-number (mod cycle-year 10) stem-han (nth celestial-stems stem-number) stem-pinyin (get pinyin stem-han) element-number (int (Math/floor (/ stem-number 2))) element (nth elements element-number) branch-number (mod cycle-year 12) branch-han (nth terrestrial-branches branch-number) branch-pinyin (get pinyin branch-han) zodiac-animal (nth zodiac-animals branch-number) aspect-number (mod cycle-year 2) aspect (nth aspects aspect-number)] (println (format "%s:%s%s (%s-%s,%s%s year stem-han branch-han stem-pinyin branch-pinyin element zodiac-animal aspect cycle-position)))) (defn -main [& args] (doseq [years (map read-string args)] (chinese-zodiac years)))
1,048Chinese zodiac
6clojure
9u9ma
f = File.open() p f.isatty p STDOUT.isatty
1,044Check output device is a terminal
14ruby
sniqw
extern crate libc; fn main() { let istty = unsafe { libc::isatty(libc::STDOUT_FILENO as i32) }!= 0; if istty { println!("stdout is tty"); } else { println!("stdout is not tty"); } }
1,044Check output device is a terminal
15rust
0dnsl
import org.fusesource.jansi.internal.CLibrary._ object IsATty extends App { var enabled = true def apply(enabled: Boolean): Boolean = {
1,044Check output device is a terminal
16scala
iztox
import Control.Concurrent (setNumCapabilities) import Control.Monad.Par (runPar, get, spawnP) import Control.Monad (join, (>=>)) import Data.List.Split (chunksOf) import Data.List (intercalate, mapAccumL, genericTake, genericDrop) import Data.Bifunctor (bimap) import GHC.Conc (getNumProcessors) import Math.NumberTheory.Primes (factorise, unPrime) import Text.Printf (printf) chowla :: Word -> Word chowla 1 = 0 chowla n = f n where f = (-) =<< pred . product . fmap sumFactor . factorise sumFactor (n, e) = foldr (\p s -> s + unPrime n^p) 1 [1..e] chowlas :: [Word] -> [(Word, Word)] chowlas [] = [] chowlas xs = runPar $ join <$> (mapM (spawnP . fmap ((,) <*> chowla)) >=> mapM get) (chunksOf (10^6) xs) chowlaPrimes :: [(Word, Word)] -> (Word, Word) -> (Word, Word) chowlaPrimes chowlas range = (count chowlas, snd range) where isPrime (1, n) = False isPrime (_, n) = n == 0 count = fromIntegral . length . filter isPrime . between range between (min, max) = genericTake (max - pred min) . genericDrop (pred min) chowlaPerfects :: [(Word, Word)] -> [Word] chowlaPerfects = fmap fst . filter isPerfect where isPerfect (1, _) = False isPerfect (n, c) = c == pred n commas :: (Show a, Integral a) => a -> String commas = reverse . intercalate "," . chunksOf 3 . reverse . show main :: IO () main = do cores <- getNumProcessors setNumCapabilities cores printf "Using%d cores\n" cores mapM_ (uncurry (printf "chowla(%2d) =%d\n")) $ take 37 allChowlas mapM_ (uncurry (printf "There are%8s primes <%10s\n")) (chowlaP [ (1, 10^2) , (succ $ 10^2, 10^3) , (succ $ 10^3, 10^4) , (succ $ 10^4, 10^5) , (succ $ 10^5, 10^6) , (succ $ 10^6, 10^7) ]) mapM_ (printf "%10s is a perfect number.\n" . commas) perfects printf "There are%2d perfect numbers < 35,000,000\n" $ length perfects where chowlaP = fmap (bimap commas commas) . snd . mapAccumL (\total (count, max) -> (total + count, (total + count, max))) 0 . fmap (chowlaPrimes $ take (10^7) allChowlas) perfects = chowlaPerfects allChowlas allChowlas = chowlas [1..35*10^6]
1,041Chowla numbers
8haskell
hawju
function distance(p1, p2) { var dx = Math.abs(p1.x - p2.x); var dy = Math.abs(p1.y - p2.y); return Math.sqrt(dx*dx + dy*dy); } function bruteforceClosestPair(arr) { if (arr.length < 2) { return Infinity; } else { var minDist = distance(arr[0], arr[1]); var minPoints = arr.slice(0, 2); for (var i=0; i<arr.length-1; i++) { for (var j=i+1; j<arr.length; j++) { if (distance(arr[i], arr[j]) < minDist) { minDist = distance(arr[i], arr[j]); minPoints = [ arr[i], arr[j] ]; } } } return { distance: minDist, points: minPoints }; } }
1,036Closest-pair problem
10javascript
n32iy
package main import "fmt" func main() { var a []interface{} a = append(a, 3) a = append(a, "apples", "oranges") fmt.Println(a) }
1,037Collections
0go
n3li1
public class Chowla { public static void main(String[] args) { int[] chowlaNumbers = findChowlaNumbers(37); for (int i = 0; i < chowlaNumbers.length; i++) { System.out.printf("chowla(%d) =%d%n", (i+1), chowlaNumbers[i]); } System.out.println(); int[][] primes = countPrimes(100, 10_000_000); for (int i = 0; i < primes.length; i++) { System.out.printf(Locale.US, "There is%,d primes up to%,d%n", primes[i][1], primes[i][0]); } System.out.println(); int[] perfectNumbers = findPerfectNumbers(35_000_000); for (int i = 0; i < perfectNumbers.length; i++) { System.out.printf("%d is a perfect number%n", perfectNumbers[i]); } System.out.printf(Locale.US, "There are%d perfect numbers <%,d%n", perfectNumbers.length, 35_000_000); } public static int chowla(int n) { if (n < 0) throw new IllegalArgumentException("n is not positive"); int sum = 0; for (int i = 2, j; i * i <= n; i++) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j); return sum; } protected static int[][] countPrimes(int power, int limit) { int count = 0; int[][] num = new int[countMultiplicity(limit, power)][2]; for (int n = 2, i=0; n <= limit; n++) { if (chowla(n) == 0) count++; if (n % power == 0) { num[i][0] = power; num[i][1] = count; i++; power *= 10; } } return num; } protected static int countMultiplicity(int limit, int start) { int count = 0; int cur = limit; while(cur >= start) { count++; cur = cur/10; } return count; } protected static int[] findChowlaNumbers(int limit) { int[] num = new int[limit]; for (int i = 0; i < limit; i++) { num[i] = chowla(i+1); } return num; } protected static int[] findPerfectNumbers(int limit) { int count = 0; int[] num = new int[count]; int k = 2, kk = 3, p; while ((p = k * kk) < limit) { if (chowla(p) == p - 1) { num = increaseArr(num); num[count++] = p; } k = kk + 1; kk += k; } return num; } private static int[] increaseArr(int[] arr) { int[] tmp = new int[arr.length + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); return tmp; } }
1,041Chowla numbers
9java
5jkuf
<?php $zero = function($f) { return function ($x) { return $x; }; }; $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; }; $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($f))(($n($f))($x)); }; }; }; $mult = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($n($f)))($x); }; }; }; $power = function($b,$e) { return $e($b); }; $to_int = function($f) { $count_up = function($i) { return $i+1; }; return ($f($count_up))(0); }; $from_int = function($x) { $countdown = function($i) use (&$countdown) { global $zero, $succ; if ( $i == 0 ) { return $zero; } else { return $succ($countdown($i-1)); }; }; return $countdown($x); }; $three = $succ($succ($succ($zero))); $four = $from_int(4); foreach (array($add($three,$four), $mult($three,$four), $power($three,$four), $power($four,$three)) as $ch) { print($to_int($ch)); print(); } ?>
1,039Church numerals
12php
rbege
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
1,033Closures/Value capture
3python
hanjw
int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, , connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf (, handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, , connections[handle]->name); ret = 1; } else { sprintf(output, , connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror(); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror (); } else if (handle > FD_SETSIZE) { printf (); close(handle); } else { if (write(handle, , 12) >= 0) { printf(, handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf (, tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror(); return -1; } if (listen(tsocket, 10) == -1) { perror(); } ChatLoop(); return 0; }
1,051Chat server
5c
7b5rg
import java.util.Scanner; import java.util.Random; public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks(in.nextInt()); } private static void runTasks(int nTasks){ for(int i = 0; i < nTasks; i++){ System.out.println("Starting task number " + (i+1) + "."); runThreads(); Worker.checkpoint(); } } private static void runThreads(){ for(int i = 0; i < Worker.nWorkers; i ++){ new Thread(new Worker(i+1)).start(); } } public static class Worker implements Runnable{ public Worker(int threadID){ this.threadID = threadID; } public void run(){ work(); } private synchronized void work(){ try { int workTime = rgen.nextInt(900) + 100; System.out.println("Worker " + threadID + " will work for " + workTime + " msec."); Thread.sleep(workTime);
1,043Checkpoint synchronization
9java
fyydv
def emptyList = [] assert emptyList.isEmpty(): "These are not the items you're looking for" assert emptyList.size() == 0: "Empty list has size 0" assert ! emptyList: "Empty list evaluates as boolean 'false'" def initializedList = [ 1, "b", java.awt.Color.BLUE ] assert initializedList.size() == 3 assert initializedList: "Non-empty list evaluates as boolean 'true'" assert initializedList[2] == java.awt.Color.BLUE: "referencing a single element (zero-based indexing)" assert initializedList[-1] == java.awt.Color.BLUE: "referencing a single element (reverse indexing of last element)" def combinedList = initializedList + [ "more stuff", "even more stuff" ] assert combinedList.size() == 5 assert combinedList[1..3] == ["b", java.awt.Color.BLUE, "more stuff"]: "referencing a range of elements" combinedList << "even more stuff" assert combinedList.size() == 6 assert combinedList[-1..-3] == \ ["even more stuff", "even more stuff", "more stuff"] \ : "reverse referencing last 3 elements" println ([combinedList: combinedList])
1,037Collections
7groovy
sn6q1
s <- sapply (1:10, function (x) { x function (i=x) i*i }) s[[5]]() [1] 25
1,033Closures/Value capture
13r
gk047
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}}, {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}}, {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}}, {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}}, {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}}, {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}}, {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}}, {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}}, } func main() { for _, m := range testCases { fmt.Printf("tan%v =%v\n", m, tans(m)) } } var one = big.NewRat(1, 1) func tans(m []mTerm) *big.Rat { if len(m) == 1 { return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d)) } half := len(m) / 2 a := tans(m[:half]) b := tans(m[half:]) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) } func tanEval(coef int64, f *big.Rat) *big.Rat { if coef == 1 { return f } if coef < 0 { r := tanEval(-coef, f) return r.Neg(r) } ca := coef / 2 cb := coef - ca a := tanEval(ca, f) b := tanEval(cb, f) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }
1,050Check Machin-like formulas
0go
x8awf
null
1,043Checkpoint synchronization
11kotlin
8ff0q
[1, 2, 3, 4, 5]
1,037Collections
8haskell
u71v2
null
1,041Chowla numbers
11kotlin
c5g98
'''Church numerals''' from itertools import repeat from functools import reduce def churchZero(): '''The identity function. No applications of any supplied f to its argument. ''' return lambda f: identity def churchSucc(cn): '''The successor of a given Church numeral. One additional application of f. Equivalent to the arithmetic addition of one. ''' return lambda f: compose(f)(cn(f)) def churchAdd(m): '''The arithmetic sum of two Church numerals.''' return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): '''The arithmetic product of two Church numerals.''' return lambda n: compose(m)(n) def churchExp(m): '''Exponentiation of Church numerals. m^n''' return lambda n: n(m) def churchFromInt(n): '''The Church numeral equivalent of a given integer. ''' return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): '''The Church numeral equivalent of a given integer, by explicit recursion. ''' if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): '''The integer equivalent of a given Church numeral. ''' return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): '''A left to right composition of two functions f and g''' return lambda g: lambda x: g(f(x)) def foldl(f): '''Left to right reduction of a list, using the binary operator f, and starting with an initial value a. ''' def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): '''The identity function.''' return x def replicate(n): '''A list of length n in which every element has the value x. ''' return lambda x: repeat(x, n) def succ(x): '''The successor of a value. For numeric types, (1 +). ''' return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
1,039Church numerals
3python
n39iz
package main import "fmt"
1,038Classes
0go
5j1ul
null
1,036Closest-pair problem
11kotlin
asf13
int main(){ time_t t; double side, vertices[3][3],seedX,seedY,windowSide; int i,iter,choice; printf(); scanf(,&side); printf(); scanf(,&iter); windowSide = 10 + 2*side; initwindow(windowSide,windowSide,); for(i=0;i<3;i++){ vertices[i][0] = windowSide/2 + side*cos(i*2*pi/3); vertices[i][1] = windowSide/2 + side*sin(i*2*pi/3); putpixel(vertices[i][0],vertices[i][1],15); } srand((unsigned)time(&t)); seedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4); seedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4); putpixel(seedX,seedY,15); for(i=0;i<iter;i++){ choice = rand()%3; seedX = (seedX + vertices[choice][0])/2; seedY = (seedY + vertices[choice][1])/2; putpixel(seedX,seedY,15); } getch(); closegraph(); return 0; }
1,052Chaos game
5c
f68d3
import Data.Ratio import Data.List (foldl') tanPlus:: Fractional a => a -> a -> a tanPlus a b = (a + b) / (1 - a * b) tanEval:: (Integral a, Fractional b) => (a, b) -> b tanEval (0,_) = 0 tanEval (coef,f) | coef < 0 = -tanEval (-coef, f) | odd coef = tanPlus f $ tanEval (coef - 1, f) | otherwise = tanPlus a a where a = tanEval (coef `div` 2, f) tans:: (Integral a, Fractional b) => [(a, b)] -> b tans = foldl' tanPlus 0 . map tanEval machins = [ [(1, 1%2), (1, 1%3)], [(2, 1%3), (1, 1%7)], [(12, 1%18), (8, 1%57), (-5, 1%239)], [(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12943)]] not_machin = [(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12944)] main = do putStrLn "Machins:" mapM_ (\x -> putStrLn $ show (tans x) ++ " < putStr "\nnot Machin: "; print not_machin print (tans not_machin)
1,050Check Machin-like formulas
8haskell
ylz66
package main import ( "fmt" "math" )
1,042Cholesky decomposition
0go
haejq
package main import ( "fmt" "time" ) type birthday struct{ month, day int } func (b birthday) String() string { return fmt.Sprintf("%s%d", time.Month(b.month), b.day) } func (b birthday) monthUniqueIn(bds []birthday) bool { count := 0 for _, bd := range bds { if bd.month == b.month { count++ } } if count == 1 { return true } return false } func (b birthday) dayUniqueIn(bds []birthday) bool { count := 0 for _, bd := range bds { if bd.day == b.day { count++ } } if count == 1 { return true } return false } func (b birthday) monthWithUniqueDayIn(bds []birthday) bool { for _, bd := range bds { if bd.month == b.month && bd.dayUniqueIn(bds) { return true } } return false } func main() { choices := []birthday{ {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}, }
1,049Cheryl's birthday
0go
pwkbg
function chowla(n) local sum = 0 local i = 2 local j = 0 while i * i <= n do if n % i == 0 then j = math.floor(n / i) sum = sum + i if i ~= j then sum = sum + j end end i = i + 1 end return sum end function sieve(limit)
1,041Chowla numbers
1lua
l4rck
class Stuff { def guts Stuff(injectedGuts) { guts = injectedGuts } def flangulate() { println "This stuff is flangulating its guts: ${guts}" } }
1,038Classes
7groovy
c5j9i
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FILE_NAME = "MachinFormula.txt"; public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } } private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } } private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); } private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); } private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); } private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
1,050Check Machin-like formulas
9java
d3on9
def decompose = { a -> assert a.size > 0 && a[0].size == a.size def m = a.size def l = [].withEagerDefault { [].withEagerDefault { 0 } } (0..<m).each { i -> (0..i).each { k -> Number s = (0..<k).sum { j -> l[i][j] * l[k][j] } ?: 0 l[i][k] = (i == k) ? Math.sqrt(a[i][i] - s) : (1.0 / l[k][k] * (a[i][k] - s)) } } l }
1,042Cholesky decomposition
7groovy
4hk5f
import java.time.Month class Main { private static class Birthday { private Month month private int day Birthday(Month month, int day) { this.month = month this.day = day } Month getMonth() { return month } int getDay() { return day } @Override String toString() { return month.toString() + " " + day } } static void main(String[] args) { List<Birthday> choices = [ new Birthday(Month.MAY, 15), new Birthday(Month.MAY, 16), new Birthday(Month.MAY, 19), new Birthday(Month.JUNE, 17), new Birthday(Month.JUNE, 18), new Birthday(Month.JULY, 14), new Birthday(Month.JULY, 16), new Birthday(Month.AUGUST, 14), new Birthday(Month.AUGUST, 15), new Birthday(Month.AUGUST, 17) ] println("There are ${choices.size()} candidates remaining.")
1,049Cheryl's birthday
7groovy
7bgrz
use warnings; use strict; use v5.10; use Socket; my $nr_items = 3; sub short_sleep($) { (my $seconds) = @_; select undef, undef, undef, $seconds; } sub be_worker($$) { my ($socket, $value) = @_; for (1 .. $nr_items) { sysread $socket, my $dummy, 1; short_sleep rand 0.5; syswrite $socket, $value; ++$value; } exit; } sub fork_worker($) { (my $value) = @_; socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die "socketpair: $!"; if (fork // die "fork: $!") { close $dadsock; return $kidsock; } else { close $kidsock; be_worker $dadsock, $value; } } my $alpha_sock = fork_worker 'A'; my $digit_sock = fork_worker 1; for (1 .. $nr_items) { syswrite $_, 'x' for $alpha_sock, $digit_sock; sysread $alpha_sock, my $alpha, 1; sysread $digit_sock, my $digit, 1; say $alpha, $digit; } wait; wait;
1,043Checkpoint synchronization
2perl
4hh5d
zero <- function(f) {function(x) x} succ <- function(n) {function(f) {function(x) f(n(f)(x))}} add <- function(n) {function(m) {function(f) {function(x) m(f)(n(f)(x))}}} mult <- function(n) {function(m) {function(f) m(n(f))}} expt <- function(n) {function(m) m(n)} natToChurch <- function(n) {if(n == 0) zero else succ(natToChurch(n - 1))} churchToNat <- function(n) {(n(function(x) x + 1))(0)} three <- natToChurch(3) four <- natToChurch(4) churchToNat(add(three)(four)) churchToNat(mult(three)(four)) churchToNat(expt(three)(four)) churchToNat(expt(four)(three))
1,039Church numerals
13r
0d3sg
class Shape a where perimeter :: a -> Double area :: a -> Double data Rectangle = Rectangle Double Double data Circle = Circle Double instance Shape Rectangle where perimeter (Rectangle width height) = 2 * width + 2 * height area (Rectangle width height) = width * height instance Shape Circle where perimeter (Circle radius) = 2 * pi * radius area (Circle radius) = pi * radius^2 apRatio :: Shape a => a -> Double apRatio shape = area shape / perimeter shape main = do print $ apRatio $ Circle 5 print $ apRatio $ Rectangle 5 5
1,038Classes
8haskell
xotw4
procs = Array.new(10){|i| ->{i*i} } p procs[7].call
1,033Closures/Value capture
14ruby
bwfkq
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe only a single circle." Far = "Points too far apart to form circles." ) type point struct{ x, y float64 } func circles(p1, p2 point, r float64) (c1, c2 point, Case string) { if p1 == p2 { if r == 0 { return p1, p1, CoR0 } Case = Co return } if r == 0 { return p1, p2, R0 } dx := p2.x - p1.x dy := p2.y - p1.y q := math.Hypot(dx, dy) if q > 2*r { Case = Far return } m := point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2} if q == 2*r { return m, m, Diam } d := math.Sqrt(r*r - q*q/4) ox := d * dx / q oy := d * dy / q return point{m.x - oy, m.y + ox}, point{m.x + oy, m.y - ox}, Two } var td = []struct { p1, p2 point r float64 }{ {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 2.0}, {point{0.0000, 2.0000}, point{0.0000, 0.0000}, 1.0}, {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 2.0}, {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 0.5}, {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 0.0}, } func main() { for _, tc := range td { fmt.Println("p1: ", tc.p1) fmt.Println("p2: ", tc.p2) fmt.Println("r: ", tc.r) c1, c2, Case := circles(tc.p1, tc.p2, tc.r) fmt.Println(" ", Case) switch Case { case CoR0, Diam: fmt.Println(" Center: ", c1) case Two: fmt.Println(" Center 1: ", c1) fmt.Println(" Center 2: ", c2) } fmt.Println() } }
1,046Circles of given radius through two points
0go
w8qeg
null
1,050Check Machin-like formulas
11kotlin
0nxsf
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
1,042Cholesky decomposition
8haskell
iz3or
import Data.List as L (filter, groupBy, head, length, sortOn) import Data.Map.Strict as M (Map, fromList, keys, lookup) import Data.Text as T (Text, splitOn, words) import Data.Maybe (fromJust) import Data.Ord (comparing) import Data.Function (on) import Data.Tuple (swap) import Data.Bool (bool) data DatePart = Month | Day type M = Text type D = Text main :: IO () main = print $ uniquePairing Month $ uniquePairing Day $ monthsWithUniqueDays False $ (\(x:y:_) -> (x, y)) . T.words <$> splitOn ", " "May 15, May 16, May 19, June 17, June 18, \ \July 14, July 16, Aug 14, Aug 15, Aug 17" monthsWithUniqueDays :: Bool -> [(M, D)] -> [(M, D)] monthsWithUniqueDays bln xs = let months = fst <$> uniquePairing Day xs in L.filter (bool not id bln . (`elem` months) . fst) xs uniquePairing :: DatePart -> [(M, D)] -> [(M, D)] uniquePairing dp xs = let f = case dp of Month -> fst Day -> snd in (\md -> let dct = f md uniques = L.filter ((1 ==) . L.length . fromJust . flip M.lookup dct) (keys dct) in L.filter ((`elem` uniques) . f) xs) ((((,) . mapFromPairs) <*> mapFromPairs . fmap swap) xs) mapFromPairs :: [(M, D)] -> Map Text [Text] mapFromPairs xs = M.fromList $ ((,) . fst . L.head) <*> fmap snd <$> L.groupBy (on (==) fst) (L.sortOn fst xs)
1,049Cheryl's birthday
8haskell
f6nd1
List arrayList = new ArrayList(); arrayList.add(new Integer(0));
1,037Collections
9java
mv7ym
fn main() { let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect(); println!("7th val: {}", fs[7]()); }
1,033Closures/Value capture
15rust
pxtbu
val closures=for(i <- 0 to 9) yield (()=>i*i) 0 to 8 foreach (i=> println(closures(i)())) println("---\n"+closures(7)())
1,033Closures/Value capture
16scala
e06ab
class Circles { private static class Point { private final double x, y Point(Double x, Double y) { this.x = x this.y = y } double distanceFrom(Point other) { double dx = x - other.x double dy = y - other.y return Math.sqrt(dx * dx + dy * dy) } @Override boolean equals(Object other) {
1,046Circles of given radius through two points
7groovy
bw1ky