code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32 Type , or for more information. >>> import __future__ >>> __future__.all_feature_names ['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL'] >>>
409Pragmatic directives
3python
2ihlz
(defn to-cdf [pdf] (reduce (fn [acc n] (conj acc (+ (or (last acc) 0) n))) [] pdf)) (defn choose [cdf] (let [r (rand)] (count (filter (partial > r) cdf)))) (def *names* '[aleph beth gimel daleth he waw zayin heth]) (def *pdf* (map double [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720])) (let [num-trials 1000000 cdf (to-cdf *pdf*) indexes (range (count *names*)) expected (into (sorted-map) (zipmap indexes *pdf*)) actual (frequencies (repeatedly num-trials #(choose cdf)))] (doseq [[idx exp] expected] (println "Expected number of" (*names* idx) "was" (* num-trials exp) "and actually got" (actual idx))))
410Probabilistic choice
6clojure
r3ag2
data Circle = Circle { x, y, r :: Double } deriving (Show, Eq) data Tangent = Externally | Internally deriving Eq solveApollonius :: Circle -> Circle -> Circle -> Tangent -> Tangent -> Tangent -> Circle solveApollonius c1 c2 c3 t1 t2 t3 = Circle (m + n * rs) (p + q * rs) rs where s1 = if t1 == Externally then 1.0 else -1.0 s2 = if t2 == Externally then 1.0 else -1.0 s3 = if t3 == Externally then 1.0 else -1.0 v11 = 2 * x c2 - 2 * x c1 v12 = 2 * y c2 - 2 * y c1 v13 = x c1 ^ 2 - x c2 ^ 2 + y c1 ^ 2 - y c2 ^ 2 - r c1 ^ 2 + r c2 ^ 2 v14 = 2 * s2 * r c2 - 2 * s1 * r c1 v21 = 2 * x c3 - 2 * x c2 v22 = 2 * y c3 - 2 * y c2 v23 = x c2 ^ 2 - x c3 ^ 2 + y c2 ^ 2 - y c3 ^ 2 - r c2 ^ 2 + r c3 ^ 2; v24 = 2 * s3 * r c3 - 2 * s2 * r c2 w12 = v12 / v11 w13 = v13 / v11 w14 = v14 / v11 w22 = v22 / v21 - w12 w23 = v23 / v21 - w13 w24 = v24 / v21 - w14 p = -w23 / w22 q = w24 / w22 m = -w12 * p - w13 n = w14 - w12 * q a = n * n + q ^ 2 - 1 b = 2 * m * n - 2 * n * x c1 + 2 * p * q - 2 * q * y c1 + 2 * s1 * r c1 c = x c1 ^ 2 + m ^ 2 - 2 * m * x c1 + p ^ 2 + y c1 ^ 2 - 2 * p * y c1 - r c1 ^ 2 d = b ^ 2 - 4 * a * c rs = (-b - sqrt d) / (2 * a) main = do let c1 = Circle 0.0 0.0 1.0 let c2 = Circle 4.0 0.0 1.0 let c3 = Circle 2.0 4.0 2.0 let te = Externally print $ solveApollonius c1 c2 c3 te te te let ti = Internally print $ solveApollonius c1 c2 c3 ti ti ti
405Problem of Apollonius
8haskell
w53ed
uint64_t factorial(uint64_t n) { uint64_t product = 1; if (n < 2) { return 1; } for (; n > 0; n--) { uint64_t prev = product; product *= n; if (product < prev) { fprintf(stderr, ); return product; } } return product; } bool isPrime(uint64_t n) { uint64_t large = factorial(n - 1) + 1; return (large % n) == 0; } int main() { uint64_t n; for (n = 2; n < 22; n++) { printf(, n, isPrime(n)); } return 0; }
412Primality by Wilson's theorem
5c
gzb45
@inline @tailrec
409Pragmatic directives
16scala
r3egn
use List::Util qw(sum uniq); use ntheory qw(nth_prime); my $max = 99; my %tree; sub allocate { my($n, $i, $sum,, $prod) = @_; $i //= 0; $sum //= 0; $prod //= 1; for my $k (0..$max) { next if $k < $i; my $p = nth_prime($k+1); if (($sum + $p) <= $max) { allocate($n, $k, $sum + $p, $prod * $p); } else { last if $sum == $prod; $tree{$sum}{descendants}{$prod} = 1; $tree{$prod}{ancestor} = [uniq $sum, @{$tree{$sum}{ancestor}}] unless $prod > $max || $sum == 0; last; } } } sub abbrev { my(@d) = @_; return @d if @d < 11; @d[0 .. 4], '...', @d[-5 .. -1]; } allocate($_) for 1 .. $max; for (1 .. 15, 46, $max) { printf "%2d,%2d Ancestors:%-15s", $_, (scalar uniq @{$tree{$_}{ancestor}}), '[' . join(' ',uniq @{$tree{$_}{ancestor}}) . ']'; my $dn = 0; my $dl = ''; if ($tree{$_}{descendants}) { $dn = keys %{$tree{$_}{descendants}}; $dl = join ' ', abbrev(sort { $a <=> $b } keys %{$tree{$_}{descendants}}); } printf "%5d Descendants:%s", $dn, "[$dl]\n"; } map { for my $k (keys %{$tree{$_}{descendants}}) { $total += $tree{$_}{descendants}{$k} } } 1..$max; print "\nTotal descendants: $total\n";
406Primes - allocate descendants to their ancestors
2perl
3wgzs
(ns properdivisors (:gen-class)) (defn proper-divisors [n] " Proper divisors of n" (if (= n 1) [] (filter #(= 0 (rem n %)) (range 1 n)))) (def data (for [n (range 1 (inc 20000))] [n (proper-divisors n)])) (defn maximal-key [k x & xs] " Normal max-key only finds one key that produces maximum, while this function finds them all " (reduce (fn [ys x] (let [c (compare (k x) (k (peek ys)))] (cond (pos? c) [x] (neg? c) ys :else (conj ys x)))) [x] xs)) (println "n\tcnt\tPROPER DIVISORS") (doseq [n (range 1 11)] (let [factors (proper-divisors n)] (println n "\t" (count factors) "\t" factors))) (def max-data (apply maximal-key (fn [[i pd]] (count pd)) data)) (doseq [[n factors] max-data] (println n " has " (count factors) " divisors"))
411Proper divisors
6clojure
76ar0
from __future__ import print_function from itertools import takewhile maxsum = 99 def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x% p == 0: break else: lprimes.append(x) return lprimes descendants = [[] for _ in range(maxsum + 1)] ancestors = [[] for _ in range(maxsum + 1)] primes = get_primes(maxsum) for p in primes: descendants[p].append(p) for s in range(1, len(descendants) - p): descendants[s + p] += [p * pr for pr in descendants[s]] for p in primes + [4]: descendants[p].pop() total = 0 for s in range(1, maxsum + 1): descendants[s].sort() for d in takewhile(lambda x: x <= maxsum, descendants[s]): ancestors[d] = ancestors[s] + [s] print([s], , len(ancestors[s])) print(, ancestors[s] if len(ancestors[s]) else ) print(, len(descendants[s]) if len(descendants[s]) else ) if len(descendants[s]): print(descendants[s]) print() total += len(descendants[s]) print(, total)
406Primes - allocate descendants to their ancestors
3python
6xr3w
public class Circle { public double[] center; public double radius; public Circle(double[] center, double radius) { this.center = center; this.radius = radius; } public String toString() { return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1], radius); } } public class ApolloniusSolver { public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1, int s2, int s3) { float x1 = c1.center[0]; float y1 = c1.center[1]; float r1 = c1.radius; float x2 = c2.center[0]; float y2 = c2.center[1]; float r2 = c2.radius; float x3 = c3.center[0]; float y3 = c3.center[1]; float r3 = c3.radius;
405Problem of Apollonius
9java
k9ihm
package main import ( "fmt" "sort" ) func sieve(limit uint64) []bool { limit++
407Prime conspiracy
0go
90jmt
use strict; use warnings; sub main { my $program = $0; print "Program: $program\n"; } unless(caller) { main; }
401Program name
2perl
c8e9a
sub gcd { my ($n, $m) = @_; while($n){ my $t = $n; $n = $m % $n; $m = $t; } return $m; } sub tripel { my $pmax = shift; my $prim = 0; my $count = 0; my $nmax = sqrt($pmax)/2; for( my $n=1; $n<=$nmax; $n++ ) { for( my $m=$n+1; (my $p = 2*$m*($m+$n)) <= $pmax; $m+=2 ) { next unless 1==gcd($m,$n); $prim++; $count += int $pmax/$p; } } printf "Max. perimeter:%d, Total:%d, Primitive:%d\n", $pmax, $count, $prim; } tripel 10**$_ for 1..8;
399Pythagorean triples
2perl
5fou2
import Data.List (group, sort) import Text.Printf (printf) import Data.Numbers.Primes (primes) freq :: [(Int, Int)] -> Float freq xs = realToFrac (length xs) / 100 line :: [(Int, Int)] -> IO () line t@((n1, n2):xs) = printf "%d ->%d count:%5d frequency:%2.2f%%\n" n1 n2 (length t) (freq t) main :: IO () main = mapM_ line $ groups primes where groups = tail . group . sort . (\n -> zip (0: n) n) . fmap (`mod` 10) . take 10000
407Prime conspiracy
8haskell
bcok2
null
405Problem of Apollonius
11kotlin
gzq4d
<?php $program = $_SERVER[]; echo ; ?>
401Program name
12php
x4cw5
public class PrimeConspiracy { public static void main(String[] args) { final int limit = 1000_000; final int sieveLimit = 15_500_000; int[][] buckets = new int[10][10]; int prevDigit = 2; boolean[] notPrime = sieve(sieveLimit); for (int n = 3, primeCount = 1; primeCount < limit; n++) { if (notPrime[n]) continue; int digit = n % 10; buckets[prevDigit][digit]++; prevDigit = digit; primeCount++; } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (buckets[i][j] != 0) { System.out.printf("%d ->%d:%2f%n", i, j, buckets[i][j] / (limit / 100.0)); } } } } public static boolean[] sieve(int limit) { boolean[] composite = new boolean[limit]; composite[0] = composite[1] = true; int max = (int) Math.sqrt(limit); for (int n = 2; n <= max; n++) { if (!composite[n]) { for (int k = n * n; k < limit; k += n) { composite[k] = true; } } } return composite; } }
407Prime conspiracy
9java
gzw4m
void polySpiral(int windowWidth,int windowHeight){ int incr = 0, angle, i, length; double x,y,x1,y1; while(1){ incr = (incr + 5)%360; x = windowWidth/2; y = windowHeight/2; length = 5; angle = incr; for(i=1;i<=150;i++){ x1 = x + length*cos(factor*angle); y1 = y + length*sin(factor*angle); line(x,y,x1,y1); length += 3; angle = (angle + incr)%360; x = x1; y = y1; } delay(LAG); cleardevice(); } } int main() { initwindow(500,500,); polySpiral(500,500); closegraph(); return 0; }
413Polyspiral
5c
2iglo
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
399Pythagorean triples
12php
ohg85
null
407Prime conspiracy
11kotlin
2ibli
null
407Prime conspiracy
1lua
vnp2x
import sys def main(): program = sys.argv[0] print(% program) if __name__ == : main()
401Program name
3python
lowcv
getProgram <- function(args) { sub("--file=", "", args[grep("--file=", args)]) } args <- commandArgs(trailingOnly = FALSE) program <- getProgram(args) cat("Program: ", program, "\n") q("no")
401Program name
13r
yqp6h
if ($problem) { exit integerErrorCode; }
403Program termination
2perl
bcfk4
package main import ( "fmt" "math/big" ) var ( zero = big.NewInt(0) one = big.NewInt(1) prev = big.NewInt(factorial(20)) )
412Primality by Wilson's theorem
0go
ik3og
package main import ( "fmt" "math/rand" "time" ) type mapping struct { item string pr float64 } func main() {
410Probabilistic choice
0go
srtqa
use utf8; use Math::Cartesian::Product; package Circle; sub new { my ($class, $args) = @_; my $self = { x => $args->{x}, y => $args->{y}, r => $args->{r}, }; bless $self, $class; } sub show { my ($self, $args) = @_; sprintf "x =%7.3f y =%7.3f r =%7.3f\n", $args->{x}, $args->{y}, $args->{r}; } package main; sub circle { my($x,$y,$r) = @_; Circle->new({ x => $x, y=> $y, r => $r }); } sub solve_Apollonius { my($c1, $c2, $c3, $s1, $s2, $s3) = @_; my $11 = 2 * $c2->{x} - 2 * $c1->{x}; my $12 = 2 * $c2->{y} - 2 * $c1->{y}; my $13 = $c1->{x}**2 - $c2->{x}**2 + $c1->{y}**2 - $c2->{y}**2 - $c1->{r}**2 + $c2->{r}**2; my $14 = 2 * $s2 * $c2->{r} - 2 * $s1 * $c1->{r}; my $21 = 2 * $c3->{x} - 2 * $c2->{x}; my $22 = 2 * $c3->{y} - 2 * $c2->{y}; my $23 = $c2->{x}**2 - $c3->{x}**2 + $c2->{y}**2 - $c3->{y}**2 - $c2->{r}**2 + $c3->{r}**2; my $24 = 2 * $s3 * $c3->{r} - 2 * $s2 * $c2->{r}; my $12 = $12 / $11; my $13 = $13 / $11; my $14 = $14 / $11; my $22 = $22 / $21 - $12; my $23 = $23 / $21 - $13; my $24 = $24 / $21 - $14; my $ = -$23 / $22; my $ = $24 / $22; my $ = -$12 * $ - $13; my $ = $14 - $12 * $; my $ = $**2 + $**2 - 1; my $ = 2 * $ * $ - 2 * $ * $c1->{x} + 2 * $ * $ - 2 * $ * $c1->{y} + 2 * $s1 * $c1->{r}; my $ = $c1->{x}**2 + $**2 - 2 * $ * $c1->{x} + $**2 + $c1->{y}**2 - 2 * $ * $c1->{y} - $c1->{r}**2; my $ = $**2 - 4 * $ * $; my $rs = (-$ - sqrt $) / (2 * $); my $xs = $ + $ * $rs; my $ys = $ + $ * $rs; circle($xs, $ys, $rs); } $c1 = circle(0, 0, 1); $c2 = circle(4, 0, 1); $c3 = circle(2, 4, 2); for (cartesian {@_} ([-1,1])x3) { print Circle->show( solve_Apollonius $c1, $c2, $c3, @$_); }
405Problem of Apollonius
2perl
nbviw
import qualified Data.Text as T import Data.List main = do putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers putStrLn $ "The first 120 prime numbers are:" putStrLn $ see 20 $ take 120 primes putStrLn "The 1,000th to 1,015th prime numbers are:" putStrLn $ see 16.take 16 $ drop 999 primes numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659] primes = [p | p <- 2:[3,5..], isPrime p] isPrime :: Integer -> Bool isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p bagOf :: Int -> [a] -> [[a]] bagOf _ [] = [] bagOf n xs = let (us,vs) = splitAt n xs in us: bagOf n vs see :: Show a => Int -> [a] -> String see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show) showTable::Bool -> Char -> Char -> Char -> [[String]] -> String showTable _ _ _ _ [] = [] showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr] where vss = map (map length) $ contents ms = map maximum $ transpose vss ::[Int] hr = concatMap (\ n -> sep: replicate n hor) ms ++ [sep] top = replicate (length hr) hor bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
412Primality by Wilson's theorem
8haskell
vn72k
$ convert polyspiral.gif -coalesce polyspiral2.gif $ eog polyspiral2.gif
413Polyspiral
0go
qgixz
import System.Random (newStdGen, randomRs) dataBinCounts :: [Float] -> [Float] -> [Int] dataBinCounts thresholds range = let sampleSize = length range xs = ((-) sampleSize . length . flip filter range . (<)) <$> thresholds in zipWith (-) (xs ++ [sampleSize]) (0: xs) main :: IO () main = do g <- newStdGen let fractions = recip <$> [5 .. 11] :: [Float] expected = fractions ++ [1 - sum fractions] actual = ((/ 1000000.0) . fromIntegral) <$> dataBinCounts (scanl1 (+) expected) (take 1000000 (randomRs (0, 1) g)) piv n = take n . (++ repeat ' ') putStrLn " expected actual" mapM_ putStrLn $ zipWith3 (\l s c -> piv 7 l ++ piv 13 (show s) ++ piv 12 (show c)) ["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"] expected actual
410Probabilistic choice
8haskell
90gmo
if (problem) exit(1);
403Program termination
12php
6xh3g
import java.math.BigInteger; public class PrimaltyByWilsonsTheorem { public static void main(String[] args) { System.out.printf("Primes less than 100 testing by Wilson's Theorem%n"); for ( int i = 0 ; i <= 100 ; i++ ) { if ( isPrime(i) ) { System.out.printf("%d ", i); } } } private static boolean isPrime(long p) { if ( p <= 1) { return false; } return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0; } private static BigInteger fact(long n) { BigInteger fact = BigInteger.ONE; for ( int i = 2 ; i <= n ; i++ ) { fact = fact.multiply(BigInteger.valueOf(i)); } return fact; } }
412Primality by Wilson's theorem
9java
yqv6g
use ntheory qw/forprimes nth_prime/; my $upto = 1_000_000; my %freq; my($this_digit,$last_digit)=(2,0); forprimes { ($last_digit,$this_digit) = ($this_digit, $_ % 10); $freq{$last_digit . $this_digit}++; } 3,nth_prime($upto); print "$upto first primes. Transitions prime% 10 next-prime% 10.\n"; printf "%s %s count:\t%7d\tfrequency:%4.2f%%\n", substr($_,0,1), substr($_,1,1), $freq{$_}, 100*$freq{$_}/$upto for sort keys %freq;
407Prime conspiracy
2perl
sr6q3
typedef struct object *BaseObj; typedef struct sclass *Class; typedef void (*CloneFctn)(BaseObj s, BaseObj clo); typedef const char * (*SpeakFctn)(BaseObj s); typedef void (*DestroyFctn)(BaseObj s); typedef struct sclass { size_t csize; const char *cname; Class parent; CloneFctn clone; SpeakFctn speak; DestroyFctn del; } sClass; typedef struct object { Class class; } SObject; static BaseObj obj_copy( BaseObj s, Class c ) { BaseObj clo; if (c->parent) clo = obj_copy( s, c->parent); else clo = malloc( s->class->csize ); if (clo) c->clone( s, clo ); return clo; } static void obj_del( BaseObj s, Class c ) { if (c->del) c->del(s); if (c->parent) obj_del( s, c->parent); else free(s); } BaseObj ObjClone( BaseObj s ) { return obj_copy( s, s->class ); } const char * ObjSpeak( BaseObj s ) { return s->class->speak(s); } void ObjDestroy( BaseObj s ) { if (s) obj_del( s, s->class ); } static void baseClone( BaseObj s, BaseObj clone) { clone->class = s->class; } static const char *baseSpeak(BaseObj s) { return ; } sClass boc = { sizeof(SObject), , NULL, &baseClone, &baseSpeak, NULL }; Class BaseObjClass = &boc; typedef struct sDogPart { double weight; char color[32]; char name[24]; } DogPart; typedef struct sDog *Dog; struct sDog { Class class; DogPart dog; }; static void dogClone( BaseObj s, BaseObj c) { Dog src = (Dog)s; Dog clone = (Dog)c; clone->dog = src->dog; } static const char *dogSpeak( BaseObj s) { Dog d = (Dog)s; static char response[90]; sprintf(response, , d->dog.name, d->dog.color, d->class->cname); return response; } sClass dogc = { sizeof(struct sDog), , &boc, &dogClone, &dogSpeak, NULL }; Class DogClass = &dogc; BaseObj NewDog( const char *name, const char *color, double weight ) { Dog dog = malloc(DogClass->csize); if (dog) { DogPart *dogp = &dog->dog; dog->class = DogClass; dogp->weight = weight; strncpy(dogp->name, name, 23); strncpy(dogp->color, color, 31); } return (BaseObj)dog; } typedef struct sFerretPart { char color[32]; char name[24]; int age; } FerretPart; typedef struct sFerret *Ferret; struct sFerret { Class class; FerretPart ferret; }; static void ferretClone( BaseObj s, BaseObj c) { Ferret src = (Ferret)s; Ferret clone = (Ferret)c; clone->ferret = src->ferret; } static const char *ferretSpeak(BaseObj s) { Ferret f = (Ferret)s; static char response[90]; sprintf(response, , f->ferret.name, f->ferret.age, f->ferret.color, f->class->cname); return response; } sClass ferretc = { sizeof(struct sFerret), , &boc, &ferretClone, &ferretSpeak, NULL }; Class FerretClass = &ferretc; BaseObj NewFerret( const char *name, const char *color, int age ) { Ferret ferret = malloc(FerretClass->csize); if (ferret) { FerretPart *ferretp = &(ferret->ferret); ferret->class = FerretClass; strncpy(ferretp->name, name, 23); strncpy(ferretp->color, color, 31); ferretp->age = age; } return (BaseObj)ferret; } int main() { BaseObj o1; BaseObj kara = NewFerret( , , 15 ); BaseObj bruce = NewDog(, , 85.0 ); printf(); o1 = ObjClone(kara ); printf(, ObjSpeak(o1)); printf(, ObjSpeak(kara)); ObjDestroy(o1); o1 = ObjClone(bruce ); strncpy(((Dog)o1)->dog.name, , 23); printf(, ObjSpeak(o1)); printf(, ObjSpeak(bruce)); ObjDestroy(o1); return 0; }
414Polymorphic copy
5c
nbzi6
import Reflex import Reflex.Dom import Reflex.Dom.Time import Data.Text (Text, pack) import Data.Map (Map, fromList) import Data.Time.Clock (getCurrentTime) import Control.Monad.Trans (liftIO) type Point = (Float,Float) type Segment = (Point,Point) main = mainWidget $ do dTick <- tickLossy 0.05 =<< liftIO getCurrentTime dCounter <- foldDyn (\_ c -> c+1) (0::Int) dTick let dAngle = fmap (\c -> fromIntegral c / 800.0) dCounter dSpiralMap = fmap toSpiralMap dAngle width = 600 height = 600 boardAttrs = fromList [ ("width" , pack $ show width) , ("height", pack $ show height) , ("viewBox", pack $ show (-width/2) ++ " " ++ show (-height/2) ++ " " ++ show width ++ " " ++ show height) ] elAttr "h1" ("style" =: "color:black") $ text "Polyspiral" elAttr "a" ("href" =: "http://rosettacode.org/wiki/Polyspiral#Haskell") $ text "Rosetta Code / Polyspiral / Haskell" el "br" $ return () elSvgns "svg" (constDyn boardAttrs) (listWithKey dSpiralMap showLine) return () lineAttrs :: Segment -> Map Text Text lineAttrs ((x1,y1), (x2,y2)) = fromList [ ( "x1", pack $ show x1) , ( "y1", pack $ show y1) , ( "x2", pack $ show x2) , ( "y2", pack $ show y2) , ( "style", "stroke:blue") ] showLine :: MonadWidget t m => Int -> Dynamic t Segment -> m () showLine _ dSegment = elSvgns "line" (lineAttrs <$> dSegment) $ return () advance :: Float -> (Point, Float, Float) -> (Point, Float, Float) advance angle ((x,y), len, rot) = let new_x = x + len * cos rot new_y = y + len * sin rot new_len = len + 3.0 new_rot = rot + angle in ((new_x, new_y), new_len, new_rot) toSpiralMap :: Float -> Map Int ((Float,Float),(Float,Float)) toSpiralMap angle = fromList $ zip [0..] $ (\pts -> zip pts $ tail pts) $ take 80 $ (\(pt,_,_) -> pt) <$> iterate (advance angle) ((0, 0), 0, 0) elSvgns :: MonadWidget t m => Text -> Dynamic t (Map Text Text) -> m a -> m a elSvgns t m ma = do (el, val) <- elDynAttrNS' (Just "http://www.w3.org/2000/svg") t m ma return val
413Polyspiral
8haskell
msvyf
puts puts
401Program name
14ruby
vnq2n
double table[][2] = { {0.06, 0.10}, {0.11, 0.18}, {0.16, 0.26}, {0.21, 0.32}, {0.26, 0.38}, {0.31, 0.44}, {0.36, 0.50}, {0.41, 0.54}, {0.46, 0.58}, {0.51, 0.62}, {0.56, 0.66}, {0.61, 0.70}, {0.66, 0.74}, {0.71, 0.78}, {0.76, 0.82}, {0.81, 0.86}, {0.86, 0.90}, {0.91, 0.94}, {0.96, 0.98}, {1.01, 1.00}, {-1, 0}, }; double price_fix(double x) { int i; for (i = 0; table[i][0] > 0; i++) if (x < table[i][0]) return table[i][1]; abort(); } int main() { int i; for (i = 0; i <= 100; i++) printf(, i / 100., price_fix(i / 100.)); return 0; }
415Price fraction
5c
jyb70
fn main() { println!("Program: {}", std::env::args().next().unwrap()); }
401Program name
15rust
udsvj
from fractions import gcd def pt1(maxperimeter=100): ''' ''' trips = [] for a in range(1, maxperimeter): aa = a*a for b in range(a, maxperimeter-a+1): bb = b*b for c in range(b, maxperimeter-b-a+1): cc = c*c if a+b+c > maxperimeter or cc > aa + bb: break if aa + bb == cc: trips.append((a,b,c, gcd(a, b) == 1)) return trips def pytrip(trip=(3,4,5),perim=100, prim=1): a0, b0, c0 = a, b, c = sorted(trip) t, firstprim = set(), prim>0 while a + b + c <= perim: t.add((a, b, c, firstprim>0)) a, b, c, firstprim = a+a0, b+b0, c+c0, False t2 = set() for a, b, c, firstprim in t: a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7 if a5 - b5 + c7 <= perim: t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim) if a5 + b5 + c7 <= perim: t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim) if -a5 + b5 + c7 <= perim: t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim) return t | t2 def pt2(maxperimeter=100): ''' ''' trips = pytrip((3,4,5), maxperimeter, 1) return trips def printit(maxperimeter=100, pt=pt1): trips = pt(maxperimeter) print( % (maxperimeter, len(trips), len([prim for a,b,c,prim in trips if prim]))) for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)): print(algo.__doc__) for maxperimeter in range(mn, mx+1, mn): printit(maxperimeter, algo)
399Pythagorean triples
3python
4ti5k
null
412Primality by Wilson's theorem
1lua
ta9fn
void reoshift(gsl_vector *v, int h) { if ( h > 0 ) { gsl_vector *temp = gsl_vector_alloc(v->size); gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h); gsl_vector_view p1 = gsl_vector_subvector(temp, h, v->size - h); gsl_vector_memcpy(&p1.vector, &p.vector); p = gsl_vector_subvector(temp, 0, h); gsl_vector_set_zero(&p.vector); gsl_vector_memcpy(v, temp); gsl_vector_free(temp); } } gsl_vector *poly_long_div(gsl_vector *n, gsl_vector *d, gsl_vector **r) { gsl_vector *nt = NULL, *dt = NULL, *rt = NULL, *d2 = NULL, *q = NULL; int gn, gt, gd; if ( (n->size >= d->size) && (d->size > 0) && (n->size > 0) ) { nt = gsl_vector_alloc(n->size); assert(nt != NULL); dt = gsl_vector_alloc(n->size); assert(dt != NULL); rt = gsl_vector_alloc(n->size); assert(rt != NULL); d2 = gsl_vector_alloc(n->size); assert(d2 != NULL); gsl_vector_memcpy(nt, n); gsl_vector_set_zero(dt); gsl_vector_set_zero(rt); gsl_vector_view p = gsl_vector_subvector(dt, 0, d->size); gsl_vector_memcpy(&p.vector, d); gsl_vector_memcpy(d2, dt); gn = n->size - 1; gd = d->size - 1; gt = 0; while( gsl_vector_get(d, gd) == 0 ) gd--; while ( gn >= gd ) { reoshift(dt, gn-gd); double v = gsl_vector_get(nt, gn)/gsl_vector_get(dt, gn); gsl_vector_set(rt, gn-gd, v); gsl_vector_scale(dt, v); gsl_vector_sub(nt, dt); gt = MAX(gt, gn-gd); while( (gn>=0) && (gsl_vector_get(nt, gn) == 0.0) ) gn--; gsl_vector_memcpy(dt, d2); } q = gsl_vector_alloc(gt+1); assert(q != NULL); p = gsl_vector_subvector(rt, 0, gt+1); gsl_vector_memcpy(q, &p.vector); if ( r != NULL ) { if ( (gn+1) > 0 ) { *r = gsl_vector_alloc(gn+1); assert( *r != NULL ); p = gsl_vector_subvector(nt, 0, gn+1); gsl_vector_memcpy(*r, &p.vector); } else { *r = gsl_vector_alloc(1); assert( *r != NULL ); gsl_vector_set_zero(*r); } } gsl_vector_free(nt); gsl_vector_free(dt); gsl_vector_free(rt); gsl_vector_free(d2); return q; } else { q = gsl_vector_alloc(1); assert( q != NULL ); gsl_vector_set_zero(q); if ( r != NULL ) { *r = gsl_vector_alloc(n->size); assert( *r != NULL ); gsl_vector_memcpy(*r, n); } return q; } } void poly_print(gsl_vector *p) { int i; for(i=p->size-1; i >= 0; i--) { if ( i > 0 ) printf(, gsl_vector_get(p, i), i); else printf(, gsl_vector_get(p, i)); } } gsl_vector *create_poly(int d, ...) { va_list al; int i; gsl_vector *r = NULL; va_start(al, d); r = gsl_vector_alloc(d); assert( r != NULL ); for(i=0; i < d; i++) gsl_vector_set(r, i, va_arg(al, double)); return r; }
416Polynomial long division
5c
avw11
import java.awt.*; import java.awt.event.ActionEvent; import javax.swing.*; public class PolySpiral extends JPanel { double inc = 0; public PolySpiral() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(40, (ActionEvent e) -> { inc = (inc + 0.05) % 360; repaint(); }).start(); } void drawSpiral(Graphics2D g, int len, double angleIncrement) { double x1 = getWidth() / 2; double y1 = getHeight() / 2; double angle = angleIncrement; for (int i = 0; i < 150; i++) { g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f)); double x2 = x1 + Math.cos(angle) * len; double y2 = y1 - Math.sin(angle) * len; g.drawLine((int) x1, (int) y1, (int) x2, (int) y2); x1 = x2; y1 = y2; len += 3; angle = (angle + angleIncrement) % (Math.PI * 2); } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawSpiral(g, 5, Math.toRadians(inc)); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("PolySpiral"); f.setResizable(true); f.add(new PolySpiral(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
413Polyspiral
9java
f1ydv
bool polynomialfit(int obs, int degree, double *dx, double *dy, double *store);
417Polynomial regression
5c
ikno2
package main import ( "fmt" "container/heap" ) type Task struct { priority int name string } type TaskPQ []Task func (self TaskPQ) Len() int { return len(self) } func (self TaskPQ) Less(i, j int) bool { return self[i].priority < self[j].priority } func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] } func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) } func (self *TaskPQ) Pop() (popped interface{}) { popped = (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return } func main() { pq := &TaskPQ{{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}}
408Priority queue
0go
lohcw
from collections import namedtuple import math Circle = namedtuple('Circle', 'x, y, r') def solveApollonius(c1, c2, c3, s1, s2, s3): ''' >>> solveApollonius((0, 0, 1), (4, 0, 1), (2, 4, 2), 1,1,1) Circle(x=2.0, y=2.1, r=3.9) >>> solveApollonius((0, 0, 1), (4, 0, 1), (2, 4, 2), -1,-1,-1) Circle(x=2.0, y=0.8333333333333333, r=1.1666666666666667) ''' x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3 v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1 v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2 w12 = v12/v11 w13 = v13/v11 w14 = v14/v11 w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14 P = -w23/w22 Q = w24/w22 M = -w12*P-w13 N = w14 - w12*Q a = N*N + Q*Q - 1 b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1 D = b*b-4*a*c rs = (-b-math.sqrt(D))/(2*a) xs = M+N*rs ys = P+Q*rs return Circle(xs, ys, rs) if __name__ == '__main__': c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2) print(solveApollonius(c1, c2, c3, 1, 1, 1)) print(solveApollonius(c1, c2, c3, -1, -1, -1))
405Problem of Apollonius
3python
dpun1
object ScriptName extends App { println(s"Program of instantiated object: ${this.getClass.getName}")
401Program name
16scala
gzo4i
typedef uint32_t pint; typedef uint64_t xint; typedef unsigned int uint; uint8_t *pbits; pint next_prime(pint); int is_prime(xint); void sieve(pint); uint8_t bit_pos[30] = { 0, 1<<0, 0, 0, 0, 0, 0, 1<<1, 0, 0, 0, 1<<2, 0, 1<<3, 0, 0, 0, 1<<4, 0, 1<<5, 0, 0, 0, 1<<6, 0, 0, 0, 0, 0, 1<<7, }; uint8_t rem_num[] = { 1, 7, 11, 13, 17, 19, 23, 29 }; void init_primes() { FILE *fp; pint s, tgt = 4; if (!(pbits = malloc(PBITS))) { perror(); exit(1); } if ((fp = fopen(, ))) { fread(pbits, 1, PBITS, fp); fclose(fp); return; } memset(pbits, 255, PBITS); for (s = 7; s <= MAX_PRIME_SQ; s = next_prime(s)) { if (s > tgt) { tgt *= 2; fprintf(stderr, PRIuPINT, s); } sieve(s); } fp = fopen(, ); fwrite(pbits, 1, PBITS, fp); fclose(fp); } int is_prime(xint x) { pint p; if (x > 5) { if (x < MAX_PRIME) return pbits[x/30] & bit_pos[x % 30]; for (p = 2; p && (xint)p * p <= x; p = next_prime(p)) if (x % p == 0) return 0; return 1; } return x == 2 || x == 3 || x == 5; } void sieve(pint p) { unsigned char b[8]; off_t ofs[8]; int i, q; for (i = 0; i < 8; i++) { q = rem_num[i] * p; b[i] = ~bit_pos[q % 30]; ofs[i] = q / 30; } for (q = ofs[1], i = 7; i; i--) ofs[i] -= ofs[i-1]; for (ofs[0] = p, i = 1; i < 8; i++) ofs[0] -= ofs[i]; for (i = 1; q < PBITS; q += ofs[i = (i + 1) & 7]) pbits[q] &= b[i]; } pint next_prime(pint p) { off_t addr; uint8_t bits, rem; if (p > 5) { addr = p / 30; bits = bit_pos[ p % 30 ] << 1; for (rem = 0; (1 << rem) < bits; rem++); while (pbits[addr] < bits || !bits) { if (++addr >= PBITS) return 0; bits = 1; rem = 0; } if (addr >= PBITS) return 0; while (!(pbits[addr] & bits)) { rem++; bits <<= 1; } return p = addr * 30 + rem_num[rem]; } switch(p) { case 2: return 3; case 3: return 5; case 5: return 7; } return 2; } int decompose(xint n, xint *f) { pint p = 0; int i = 0; if (n <= MAX_PRIME && is_prime(n)) { f[0] = n; return 1; } while (n >= (xint)p * p) { if (!(p = next_prime(p))) break; while (n % p == 0) { n /= p; f[i++] = p; } } if (n > 1) f[i++] = n; return i; } int main() { int i, len; pint p = 0; xint f[MAX_FACTORS], po; init_primes(); for (p = 1; p < 64; p++) { po = (1LLU << p) - 1; printf(PRIuPINTPRIuXINT, p, po); fflush(stdout); if ((len = decompose(po, f)) > 1) for (i = 0; i < len; i++) printf(PRIuXINT, i?'x':'=', f[i]); putchar('\n'); } return 0; }
418Prime decomposition
5c
vnv2o
<!-- Polyspiral.html --> <html> <head><title>Polyspiral Generator</title></head> <script>
413Polyspiral
10javascript
yq26r
public class Prob{ static long TRIALS= 1000000; private static class Expv{ public String name; public int probcount; public double expect; public double mapping; public Expv(String name, int probcount, double expect, double mapping){ this.name= name; this.probcount= probcount; this.expect= expect; this.mapping= mapping; } } static Expv[] items= {new Expv("aleph", 0, 0.0, 0.0), new Expv("beth", 0, 0.0, 0.0), new Expv("gimel", 0, 0.0, 0.0), new Expv("daleth", 0, 0.0, 0.0), new Expv("he", 0, 0.0, 0.0), new Expv("waw", 0, 0.0, 0.0), new Expv("zayin", 0, 0.0, 0.0), new Expv("heth", 0, 0.0, 0.0)}; public static void main(String[] args){ int i, j; double rnum, tsum= 0.0; for(i= 0, rnum= 5.0;i < 7;i++, rnum+= 1.0){ items[i].expect= 1.0 / rnum; tsum+= items[i].expect; } items[7].expect= 1.0 - tsum; items[0].mapping= 1.0 / 5.0; for(i= 1;i < 7;i++){ items[i].mapping= items[i - 1].mapping + 1.0 / ((double)i + 5.0); } items[7].mapping= 1.0; for(i= 0;i < TRIALS;i++){ rnum= Math.random(); for(j= 0;j < 8;j++){ if(rnum < items[j].mapping){ items[j].probcount++; break; } } } System.out.printf("Trials:%d\n", TRIALS); System.out.printf("Items: "); for(i= 0;i < 8;i++) System.out.printf("%-8s ", items[i].name); System.out.printf("\nTarget prob.: "); for(i= 0;i < 8;i++) System.out.printf("%8.6f ", items[i].expect); System.out.printf("\nAttained prob.: "); for(i= 0;i < 8;i++) System.out.printf("%8.6f ", (double)(items[i].probcount) / (double)TRIALS); System.out.printf("\n"); } }
410Probabilistic choice
9java
talf9
import groovy.transform.Canonical @Canonical class Task implements Comparable<Task> { int priority String name int compareTo(Task o) { priority <=> o?.priority } } new PriorityQueue<Task>().with { add new Task(priority: 3, name: 'Clear drains') add new Task(priority: 4, name: 'Feed cat') add new Task(priority: 5, name: 'Make tea') add new Task(priority: 1, name: 'Solve RC tasks') add new Task(priority: 2, name: 'Tax return') while (!empty) { println remove() } }
408Priority queue
7groovy
6x43o
import sys if problem: sys.exit(1)
403Program termination
3python
pltbm
def isPrime(n): if n < 2: return False if n% 2 == 0: return n == 2 if n% 3 == 0: return n == 3 d = 5 while d * d <= n: if n% d == 0: return False d += 2 if n% d == 0: return False d += 4 return True def generatePrimes(): yield 2 yield 3 p = 5 while p > 0: if isPrime(p): yield p p += 2 if isPrime(p): yield p p += 4 g = generatePrimes() transMap = {} prev = None limit = 1000000 for _ in xrange(limit): prime = next(g) if prev: transition = (prev, prime%10) if transition in transMap: transMap[transition] += 1 else: transMap[transition] = 1 prev = prime% 10 print .format(limit) for trans in sorted(transMap): print .format(trans[0], trans[1], transMap[trans], 100.0 * transMap[trans] / limit)
407Prime conspiracy
3python
07ysq
null
413Polyspiral
11kotlin
8jf0q
(def values [10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100]) (defn price [v] (format "%.2f" (double (/ (values (int (/ (- (* v 100) 1) 5))) 100))))
415Price fraction
6clojure
12wpy
var probabilities = { aleph: 1/5.0, beth: 1/6.0, gimel: 1/7.0, daleth: 1/8.0, he: 1/9.0, waw: 1/10.0, zayin: 1/11.0, heth: 1759/27720 }; var sum = 0; var iterations = 1000000; var cumulative = {}; var randomly = {}; for (var name in probabilities) { sum += probabilities[name]; cumulative[name] = sum; randomly[name] = 0; } for (var i = 0; i < iterations; i++) { var r = Math.random(); for (var name in cumulative) { if (r <= cumulative[name]) { randomly[name]++; break; } } } for (var name in probabilities)
410Probabilistic choice
10javascript
ms4yv
import Data.PQueue.Prio.Min main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
408Priority queue
8haskell
12ips
if(problem) q(status=10)
403Program termination
13r
jyi78
use strict; use warnings; use feature 'say'; use ntheory qw(factorial); my($ends_in_7, $ends_in_3); sub is_wilson_prime { my($n) = @_; $n > 1 or return 0; (factorial($n-1) % $n) == ($n-1) ? 1 : 0; } for (0..50) { my $m = 3 + 10 * $_; $ends_in_3 .= "$m " if is_wilson_prime($m); my $n = 7 + 10 * $_; $ends_in_7 .= "$n " if is_wilson_prime($n); } say $ends_in_3; say $ends_in_7;
412Primality by Wilson's theorem
2perl
hmejl
suppressMessages(library(gmp)) limit <- 1e6 result <- vector('numeric', 99) prev_prime <- 2 count <- 0 getOutput <- function(transition) { if (result[transition] == 0) return() second <- transition %% 10 first <- (transition - second) / 10 cat(first,"->",second,"count:", sprintf("%6d",result[transition]), "frequency:", sprintf("%5.2f%%\n",result[transition]*100/limit)) } while (count <= limit) { count <- count + 1 next_prime <- nextprime(prev_prime) transition <- 10*(asNumeric(prev_prime) %% 10) + (asNumeric(next_prime) %% 10) prev_prime <- next_prime result[transition] <- result[transition] + 1 } cat(sprintf("%d",limit),"first primes. Transitions prime% 10 -> next-prime% 10\n") invisible(sapply(1:99,getOutput))
407Prime conspiracy
13r
w5te5
typedef int bool; typedef struct { int face; char suit; } card; card cards[5]; int compare_card(const void *a, const void *b) { card c1 = *(card *)a; card c2 = *(card *)b; return c1.face - c2.face; } bool equals_card(card c1, card c2) { if (c1.face == c2.face && c1.suit == c2.suit) return TRUE; return FALSE; } bool are_distinct() { int i, j; for (i = 0; i < 4; ++i) for (j = i + 1; j < 5; ++j) if (equals_card(cards[i], cards[j])) return FALSE; return TRUE; } bool is_straight() { int i; qsort(cards, 5, sizeof(card), compare_card); if (cards[0].face + 4 == cards[4].face) return TRUE; if (cards[4].face == 12 && cards[0].face == 0 && cards[3].face == 3) return TRUE; return FALSE; } bool is_flush() { int i; char suit = cards[0].suit; for (i = 1; i < 5; ++i) if (cards[i].suit != suit) return FALSE; return TRUE; } const char *analyze_hand(const char *hand) { int i, j, gs = 0; char suit, *cp; bool found, flush, straight; int groups[13]; if (strlen(hand) != 14) return ; for (i = 0; i < 14; i += 3) { cp = strchr(FACES, tolower(hand[i])); if (cp == NULL) return ; j = i / 3; cards[j].face = cp - FACES; suit = tolower(hand[i + 1]); cp = strchr(SUITS, suit); if (cp == NULL) return ; cards[j].suit = suit; } if (!are_distinct()) return ; for (i = 0; i < 13; ++i) groups[i] = 0; for (i = 0; i < 5; ++i) groups[cards[i].face]++; for (i = 0; i < 13; ++i) if (groups[i] > 0) gs++; switch(gs) { case 2: found = FALSE; for (i = 0; i < 13; ++i) if (groups[i] == 4) { found = TRUE; break; } if (found) return ; return ; case 3: found = FALSE; for (i = 0; i < 13; ++i) if (groups[i] == 3) { found = TRUE; break; } if (found) return ; return ; case 4: return ; default: flush = is_flush(); straight = is_straight(); if (flush && straight) return ; else if (flush) return ; else if (straight) return ; else return ; } } int main(){ int i; const char *type; const char *hands[10] = { , , , , , , , , , }; for (i = 0; i < 10; ++i) { type = analyze_hand(hands[i]); printf(, hands[i], type); } return 0; }
419Poker hand analyser
5c
9sym1
(defn grevlex [term1 term2] (let [grade1 (reduce +' term1) grade2 (reduce +' term2) comp (- grade2 grade1)] (if (not= 0 comp) comp (loop [term1 term1 term2 term2] (if (empty? term1) 0 (let [grade1 (last term1) grade2 (last term2) comp (- grade1 grade2)] (if (not= 0 comp) comp (recur (pop term1) (pop term2))))))))) (defn mul ([poly1] (fn ([] poly1) ([poly2] (mul poly1 poly2)) ([poly2 & more] (mul poly1 poly2 more)))) ([poly1 poly2] (let [product (atom (transient (sorted-map-by grevlex)))] (doall (for [term1 poly1 term2 poly2 :let [vars (mapv +' (key term1) (key term2)) coeff (* (val term1) (val term2))]] (if (contains? @product vars) (swap! product assoc! vars (+ (get @product vars) coeff)) (swap! product assoc! vars coeff)))) (->> product (deref) (persistent!) (denull)))) ([poly1 poly2 & more] (reduce mul (mul poly1 poly2) more))) (defn compl [term1 term2] (map (fn [x y] (cond (and (zero? x) (not= 0 y)) nil (< x y) nil (>= x y) (- x y))) term1 term2)) (defn s-poly [f g] (let [f-vars (first f) g-vars (first g) lcm (compl f-vars g-vars)] (if (not-any? nil? lcm) {(vec lcm) (/ (second f) (second g))}))) (defn divide [f g] (loop [f f g g result (transient {}) remainder {}] (if (empty? f) (list (persistent! result) (->> remainder (filter #(not (nil? %))) (into (sorted-map-by grevlex)))) (let [term1 (first f) term2 (first g) s-term (s-poly term1 term2)] (if (nil? s-term) (recur (dissoc f (first term1)) (dissoc g (first term2)) result (conj remainder term1)) (recur (sub f (mul g s-term)) g (conj! result s-term) remainder)))))) (deftest divide-tests (is (= (divide {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7}) '({[0 0] 1} {}))) (is (= (divide {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} {[0 0] 1}) '({[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} {}))) (is (= (divide {[1 1] 2, [1 0] 10, [0 1] 3, [0 0] 15} {[0 1] 1, [0 0] 5}) '({[1 0] 2, [0 0] 3} {}))) (is (= (divide {[1 1] 2, [1 0] 10, [0 1] 3, [0 0] 15} {[1 0] 2, [0 0] 3}) '({[0 1] 1, [0 0] 5} {}))))
416Polynomial long division
6clojure
sr8qr
function love.load () love.window.setTitle("Polyspiral") incr = 0 end function love.update (dt) incr = (incr + 0.05) % 360 x1 = love.graphics.getWidth() / 2 y1 = love.graphics.getHeight() / 2 length = 5 angle = incr end function love.draw () for i = 1, 150 do x2 = x1 + math.cos(angle) * length y2 = y1 + math.sin(angle) * length love.graphics.line(x1, y1, x2, y2) x1, y1 = x2, y2 length = length + 3 angle = (angle + incr) % 360 end end
413Polyspiral
1lua
oht8h
null
410Probabilistic choice
11kotlin
oh68z
class Circle def initialize(x, y, r) @x, @y, @r = [x, y, r].map(&:to_f) end attr_reader :x, :y, :r def self.apollonius(c1, c2, c3, s1=1, s2=1, s3=1) x1, y1, r1 = c1.x, c1.y, c1.r x2, y2, r2 = c2.x, c2.y, c2.r x3, y3, r3 = c3.x, c3.y, c3.r v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1**2 - x2**2 + y1**2 - y2**2 - r1**2 + r2**2 v14 = 2*s2*r2 - 2*s1*r1 v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2**2 - x3**2 + y2**2 - y3**2 - r2**2 + r3**2 v24 = 2*s3*r3 - 2*s2*r2 w12 = v12/v11 w13 = v13/v11 w14 = v14/v11 w22 = v22/v21 - w12 w23 = v23/v21 - w13 w24 = v24/v21 - w14 p = -w23/w22 q = w24/w22 m = -w12*p - w13 n = w14 - w12*q a = n**2 + q**2 - 1 b = 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1 c = x1**2 + m**2 - 2*m*x1 + p**2 + y1**2 - 2*p*y1 - r1**2 d = b**2 - 4*a*c rs = (-b - Math.sqrt(d)) / (2*a) xs = m + n*rs ys = p + q*rs self.new(xs, ys, rs) end def to_s end end puts c1 = Circle.new(0, 0, 1) puts c2 = Circle.new(2, 4, 2) puts c3 = Circle.new(4, 0, 1) puts Circle.apollonius(c1, c2, c3) puts Circle.apollonius(c1, c2, c3, -1, -1, -1)
405Problem of Apollonius
14ruby
ta4f2
(defn factors "Return a list of factors of N." ([n] (factors n 2 ())) ([n k acc] (if (= 1 n) acc (if (= 0 (rem n k)) (recur (quot n k) k (cons k acc)) (recur n (inc k) acc)))))
418Prime decomposition
6clojure
r3rg2
object ApolloniusSolver extends App { case class Circle(x: Double, y: Double, r: Double) object Tangent extends Enumeration { type Tangent = Value val intern = Value(-1) val extern = Value(1) } import Tangent._ import scala.Math._ val solveApollonius: (Circle, Circle, Circle, Triple[Tangent, Tangent, Tangent]) => Circle = (c1, c2, c3, tangents) => { val fv: (Circle, Circle, Int, Int) => Tuple4[Double, Double, Double, Double] = (c1, c2, s1, s2) => { val v11 = 2 * c2.x - 2 * c1.x val v12 = 2 * c2.y - 2 * c1.y val v13 = pow(c1.x, 2) - pow(c2.x, 2) + pow(c1.y, 2) - pow(c2.y, 2) - pow(c1.r, 2) + pow(c2.r, 2) val v14 = 2 * s2 * c2.r - 2 * s1 * c1.r Tuple4(v11, v12, v13, v14) } val (s1, s2, s3) = (tangents._1.id, tangents._2.id, tangents._3.id) val (v11, v12, v13, v14) = fv(c1, c2, s1, s2) val (v21, v22, v23, v24) = fv(c2, c3, s2, s3) val w12 = v12 / v11 val w13 = v13 / v11 val w14 = v14 / v11 val w22 = v22 / v21 - w12 val w23 = v23 / v21 - w13 val w24 = v24 / v21 - w14 val P = -w23 / w22 val Q = w24 / w22 val M = -w12 * P - w13 val N = w14 - w12 * Q val a = N*N + Q*Q - 1 val b = 2*M*N - 2*N*c1.x + 2*P*Q - 2*Q*c1.y + 2*s1*c1.r val c = pow(c1.x, 2) + M*M - 2*M*c1.x + P*P + pow(c1.y, 2) - 2*P*c1.y - pow(c1.r, 2)
405Problem of Apollonius
16scala
yqj63
class PythagoranTriplesCounter def initialize(limit) @limit = limit @total = 0 @primitives = 0 generate_triples(3, 4, 5) end attr_reader :total, :primitives private def generate_triples(a, b, c) perim = a + b + c return if perim > @limit @primitives += 1 @total += @limit / perim generate_triples( a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c) generate_triples( a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c) generate_triples(-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c) end end perim = 10 while perim <= 100_000_000 c = PythagoranTriplesCounter.new perim p [perim, c.total, c.primitives] perim *= 10 end
399Pythagorean triples
14ruby
r3dgs
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine(); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine(); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
420Polymorphism
5c
mq3ys
use strict; use warnings; use Tk; use List::Util qw( min ); my $size = 500; my ($width, $height, $x, $y, $dist); my $angleinc = 0; my $active = 0; my $wait = 1000 / 30; my $radian = 90 / atan2 1, 0; my $mw = MainWindow->new; $mw->title( 'Polyspiral' ); my $c = $mw->Canvas( -width => $size, -height => $size, -relief => 'raised', -borderwidth => 2, )->pack(-fill => 'both', -expand => 1); $mw->bind('<Configure>' => sub { $width = $c->width; $height = $c->height; $dist = min($width, $height) ** 2 / 4 } ); $mw->Button(-text => $_->[0], -command => $_->[1], )->pack(-side => 'right') for [ Exit => sub {$mw->destroy} ], [ 'Start / Pause' => sub { $active ^= 1; step() } ]; MainLoop; -M $0 < 0 and exec $0; sub step { $active or return; my @pts = ($x = $width >> 1, $y = $height >> 1); my $length = 5; my $angle = $angleinc; $angleinc += 0.05 / $radian; while( ($x - $width / 2)**2 + ($y - $height / 2)**2 < $dist && @pts < 300 ) { push @pts, $x, $y; $x += $length * cos($angle); $y += $length * sin($angle); $length += 3; $angle += $angleinc; } $c->delete('all'); $c->createLine( @pts ); $mw->after($wait => \&step); }
413Polyspiral
2perl
4th5d
struct node { char *s; struct node* prev; }; void powerset(char **v, int n, struct node *up) { struct node me; if (!n) { putchar('['); while (up) { printf(, up->s); up = up->prev; } puts(); } else { me.s = *v; me.prev = up; powerset(v + 1, n - 1, up); powerset(v + 1, n - 1, &me); } } int main(int argc, char **argv) { powerset(argv + 1, argc - 1, 0); return 0; }
421Power set
5c
4f25t
items = {} items["aleph"] = 1/5.0 items["beth"] = 1/6.0 items["gimel"] = 1/7.0 items["daleth"] = 1/8.0 items["he"] = 1/9.0 items["waw"] = 1/10.0 items["zayin"] = 1/11.0 items["heth"] = 1759/27720 num_trials = 1000000 samples = {} for item, _ in pairs( items ) do samples[item] = 0 end math.randomseed( os.time() ) for i = 1, num_trials do z = math.random() for item, _ in pairs( items ) do if z < items[item] then samples[item] = samples[item] + 1 break; else z = z - items[item] end end end for item, _ in pairs( items ) do print( item, samples[item]/num_trials, items[item] ) end
410Probabilistic choice
1lua
ikyot
import java.util.PriorityQueue; class Task implements Comparable<Task> { final int priority; final String name; public Task(int p, String n) { priority = p; name = n; } public String toString() { return priority + ", " + name; } public int compareTo(Task other) { return priority < other.priority ? -1 : priority > other.priority ? 1 : 0; } public static void main(String[] args) { PriorityQueue<Task> pq = new PriorityQueue<Task>(); pq.add(new Task(3, "Clear drains")); pq.add(new Task(4, "Feed cat")); pq.add(new Task(5, "Make tea")); pq.add(new Task(1, "Solve RC tasks")); pq.add(new Task(2, "Tax return")); while (!pq.isEmpty()) System.out.println(pq.remove()); } }
408Priority queue
9java
76xrj
use std::thread; fn f1 (a: u64, b: u64, c: u64, d: u64) -> u64 { let mut primitive_count = 0; for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() { let l = triangle[0] + triangle[1] + triangle[2]; if l > d { continue; } primitive_count += 1 + f1(triangle[0], triangle[1], triangle[2], d); } primitive_count } fn f2 (a: u64, b: u64, c: u64, d: u64) -> u64 { let mut triplet_count = 0; for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() { let l = triangle[0] + triangle[1] + triangle[2]; if l > d { continue; } triplet_count += (d/l) + f2(triangle[0], triangle[1], triangle[2], d); } triplet_count } fn main () { let new_th_1 = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || { let mut i = 100; while i <= 100_000_000_000 { println!(" Primitive triples below {}: {}", i, f1(3, 4, 5, i) + 1); i *= 10; } }).unwrap(); let new_th_2 =thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || { let mut i = 100; while i <= 100_000_000_000 { println!(" Triples below {}: {}", i, f2(3, 4, 5, i) + i/12); i *= 10; } }).unwrap(); new_th_1.join().unwrap(); new_th_2.join().unwrap(); }
399Pythagorean triples
15rust
76frc
if problem exit(1) end if problem abort end
403Program termination
14ruby
av31s
from math import factorial def is_wprime(n): return n == 2 or ( n > 1 and n% 2 != 0 and (factorial(n - 1) + 1)% n == 0 ) if __name__ == '__main__': c = int(input('Enter upper limit: ')) print(f'Primes under {c}:') print([n for n in range(c) if is_wprime(n)])
412Primality by Wilson's theorem
3python
k9whf
require def prime_conspiracy(m) conspiracy = Hash.new(0) Prime.take(m).map{|n| n%10}.each_cons(2){|a,b| conspiracy[[a,b]] += 1} puts conspiracy.sort.each do |(a,b),v| puts % [a, b, v, 100.0*v/m] end end prime_conspiracy(1_000_000)
407Prime conspiracy
14ruby
oh98v
null
407Prime conspiracy
15rust
ikcod
double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, int n) { int i; *minx = *maxx = x[0]; *miny = *maxy = y[0]; for(i=1; i < n; i++) { if ( x[i] < *minx ) *minx = x[i]; if ( x[i] > *maxx ) *maxx = x[i]; if ( y[i] < *miny ) *miny = y[i]; if ( y[i] > *maxy ) *maxy = y[i]; } } int main() { int plotter, i; double minx, miny, maxx, maxy; double lx, ly; double xticstep, yticstep, nx, ny; double sx, sy; char labs[MAXLABLEN+1]; plotter = pl_newpl(, NULL, stdout, NULL); if ( plotter < 0 ) exit(1); pl_selectpl(plotter); if ( pl_openpl() < 0 ) exit(1); minmax(x, y, &minx, &maxx, &miny, &maxy, NP); lx = maxx - minx; ly = maxy - miny; pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly, ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly); xticstep = (ceil(maxx) - floor(minx)) / XDIV; yticstep = (ceil(maxy) - floor(miny)) / YDIV; pl_flinewidth(0.25); if ( lx < ly ) { sx = lx/ly; sy = 1.0; } else { sx = 1.0; sy = ly/lx; } pl_erase(); pl_fbox(floor(minx), floor(miny), ceil(maxx), ceil(maxy)); pl_fontname(); for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) { pl_fline(floor(minx), ny, ceil(maxx), ny); snprintf(labs, MAXLABLEN, , ny); FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny); PUSHSCALE(sx,sy); pl_label(labs); POPSCALE(sx,sy); } for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) { pl_fline(nx, floor(miny), nx, ceil(maxy)); snprintf(labs, MAXLABLEN, , nx); FMOVESCALE(nx, floor(miny)); PUSHSCALE(sx,sy); pl_ftextangle(-90); pl_alabel('l', 'b', labs); POPSCALE(sx,sy); } pl_fillcolorname(); pl_filltype(1); for(i=0; i < NP; i++) { pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE, x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE); } pl_flushpl(); pl_closepl(); }
422Plot coordinate pairs
5c
5dcuk
(defn rank [card] (let [[fst _] card] (if (Character/isDigit fst) (Integer/valueOf (str fst)) ({\T 10, \J 11, \Q 12, \K 13, \A 14} fst)))) (defn suit [card] (let [[_ snd] card] (str snd))) (defn n-of-a-kind [hand n] (not (empty? (filter #(= true %) (map #(>= % n) (vals (frequencies (map rank hand)))))))) (defn ranks-with-ace [hand] (let [ranks (sort (map rank hand))] (if (some #(= 14 %) ranks) (cons 1 ranks) ranks))) (defn pair? [hand] (n-of-a-kind hand 2)) (defn three-of-a-kind? [hand] (n-of-a-kind hand 3)) (defn four-of-a-kind? [hand] (n-of-a-kind hand 4)) (defn flush? [hand] (not (empty? (filter #(= true %) (map #(>= % 5) (vals (frequencies (map suit hand)))))))) (defn full-house? [hand] (true? (and (some #(= 2 %) (vals (frequencies (map rank hand)))) (some #(= 3 %) (vals (frequencies (map rank hand))))))) (defn two-pairs? [hand] (or (full-house? hand) (four-of-a-kind? hand) (= 2 (count (filter #(= true %) (map #(>= % 2) (vals (frequencies (map rank hand))))))))) (defn straight? [hand] (let [hand-a (ranks-with-ace hand) fst (first hand-a) snd (second hand-a)] (or (= (take 5 hand-a) (range fst (+ fst 5))) (= (drop 1 hand-a) (range snd (+ snd 5)))))) (defn straight-flush? [hand] (and (straight? hand) (flush? hand))) (defn invalid? [hand] (not= 5 (count (set hand)))) (defn check-hand [hand] (cond (invalid? hand) "invalid" (straight-flush? hand) "straight-flush" (four-of-a-kind? hand) "four-of-a-kind" (full-house? hand) "full-house" (flush? hand) "flush" (straight? hand) "straight" (three-of-a-kind? hand) "three-of-a-kind" (two-pairs? hand) "two-pair" (pair? hand) "one-pair" :else "high-card")) (def hands [["2H" "2D" "2S" "KS" "QD"] ["2H" "5H" "7D" "8S" "9D"] ["AH" "2D" "3S" "4S" "5S"] ["2H" "3H" "2D" "3S" "3D"] ["2H" "7H" "2D" "3S" "3D"] ["2H" "7H" "7D" "7S" "7C"] ["TH" "JH" "QH" "KH" "AH"] ["4H" "4C" "KC" "5D" "TC"] ["QC" "TC" "7C" "6C" "4C"]]) (run! println (map #(str % ": " (check-hand %)) hands))
419Poker hand analyser
6clojure
un2vi
package main import ( "fmt" "reflect" )
414Polymorphic copy
0go
r3kgm
import Foundation struct Circle { let center:[Double]! let radius:Double! init(center:[Double], radius:Double) { self.center = center self.radius = radius } func toString() -> String { return "Circle[x=\(center[0]),y=\(center[1]),r=\(radius)]" } } func solveApollonius(c1:Circle, c2:Circle, c3:Circle, s1:Double, s2:Double, s3:Double) -> Circle { let x1 = c1.center[0] let y1 = c1.center[1] let r1 = c1.radius let x2 = c2.center[0] let y2 = c2.center[1] let r2 = c2.radius let x3 = c3.center[0] let y3 = c3.center[1] let r3 = c3.radius let v11 = 2*x2 - 2*x1 let v12 = 2*y2 - 2*y1 let v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 let v14 = 2*s2*r2 - 2*s1*r1 let v21 = 2*x3 - 2*x2 let v22 = 2*y3 - 2*y2 let v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 let v24 = 2*s3*r3 - 2*s2*r2 let w12 = v12/v11 let w13 = v13/v11 let w14 = v14/v11 let w22 = v22/v21-w12 let w23 = v23/v21-w13 let w24 = v24/v21-w14 let P = -w23/w22 let Q = w24/w22 let M = -w12*P-w13 let N = w14 - w12*Q let a = N*N + Q*Q - 1 let b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 let c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1 let D = b*b-4*a*c let rs = (-b - sqrt(D)) / (2*a) let xs = M + N * rs let ys = P + Q * rs return Circle(center: [xs,ys], radius: rs) } let c1 = Circle(center: [0,0], radius: 1) let c2 = Circle(center: [4,0], radius: 1) let c3 = Circle(center: [2,4], radius: 2) println(solveApollonius(c1,c2,c3,1,1,1).toString()) println(solveApollonius(c1,c2,c3,-1,-1,-1).toString())
405Problem of Apollonius
17swift
f15dk
object PythagoreanTriples extends App { println(" Limit Primatives All") for {e <- 2 to 7 limit = math.pow(10, e).longValue() } { var primCount, tripCount = 0 def parChild(a: BigInt, b: BigInt, c: BigInt): Unit = { val perim = a + b + c val (a2, b2, c2, c3) = (2 * a, 2 * b, 2 * c, 3 * c) if (limit >= perim) { primCount += 1 tripCount += (limit / perim).toInt parChild(a - b2 + c2, a2 - b + c2, a2 - b2 + c3) parChild(a + b2 + c2, a2 + b + c2, a2 + b2 + c3) parChild(-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3) } } parChild(BigInt(3), BigInt(4), BigInt(5)) println(f"a + b + c <= ${limit.toFloat}%3.1e $primCount%9d $tripCount%12d") } }
399Pythagorean triples
16scala
k93hk
fn main() { println!("The program is running"); return; println!("This line won't be printed"); }
403Program termination
15rust
eu6aj
import scala.annotation.tailrec import scala.collection.mutable object PrimeConspiracy extends App { val limit = 1000000 val sieveTop = 15485863 + 1 val buckets = Array.ofDim[Int](10, 10) var prevPrime = 2 def sieve(limit: Int) = { val composite = new mutable.BitSet(sieveTop) composite(0) = true composite(1) = true for (n <- 2 to math.sqrt(limit).toInt) if (!composite(n)) for (k <- n * n until limit by n) composite(k) = true composite } val notPrime = sieve(sieveTop) def isPrime(n: Long) = { @tailrec def inner(d: Int, end: Int): Boolean = { if (d > end) true else if (n % d != 0 && n % (d + 2) != 0) inner(d + 6, end) else false } n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) && inner(5, math.sqrt(n).toInt) } var primeCount = 1 var n = 3 while (primeCount < limit) { if (!notPrime(n)) { val prime = n buckets(prevPrime % 10)(prime % 10) += 1 prevPrime = prime primeCount += 1 } n += 1 } for {i <- buckets.indices j <- buckets.head.indices} { val nPrime = buckets(i)(j) if (nPrime != 0) println(f"$i%d -> $j%d: $nPrime%5d ${nPrime / (limit / 100.0)}%2f") } println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") }
407Prime conspiracy
16scala
f1vd4
class T implements Cloneable { String property String name() { 'T' } T copy() { try { super.clone() } catch(CloneNotSupportedException e) { null } } @Override boolean equals(that) { this.name() == that?.name() && this.property == that?.property } } class S extends T { @Override String name() { 'S' } }
414Polymorphic copy
7groovy
vng28
import math import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((1024, 600)) pygame.display.set_caption() incr = 0 running = True while running: pygame.time.Clock().tick(60) for event in pygame.event.get(): if event.type==QUIT: running = False break incr = (incr + 0.05)% 360 x1 = pygame.display.Info().current_w / 2 y1 = pygame.display.Info().current_h / 2 length = 5 angle = incr screen.fill((255,255,255)) for i in range(1,151): x2 = x1 + math.cos(angle) * length y2 = y1 + math.sin(angle) * length pygame.draw.line(screen, (255,0,0), (x1, y1), (x2, y2), 1) x1, y1 = x2, y2 length += 3 angle = (angle + incr)% 360 pygame.display.flip()
413Polyspiral
3python
gzk4h
if (problem) {
403Program termination
16scala
qg9xw
var p *int
423Pointers and references
0go
2o6l7
import Data.STRef example :: ST s () example = do p <- newSTRef 1 k <- readSTRef p writeSTRef p (k+1)
423Pointers and references
8haskell
a2j1g
(use '(incanter core stats charts)) (def x (range 0 10)) (def y '(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0)) (view (xy-plot x y))
422Plot coordinate pairs
6clojure
j657m
(use '[clojure.math.combinatorics:only [subsets] ]) (def S #{1 2 3 4}) user> (subsets S) (() (1) (2) (3) (4) (1 2) (1 3) (1 4) (2 3) (2 4) (3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4) (1 2 3 4))
421Power set
6clojure
hygjr
package main import ( "fmt" "strconv" ) func listProperDivisors(limit int) { if limit < 1 { return } width := len(strconv.Itoa(limit)) for i := 1; i <= limit; i++ { fmt.Printf("%*d -> ", width, i) if i == 1 { fmt.Println("(None)") continue } for j := 1; j <= i/2; j++ { if i%j == 0 { fmt.Printf("%d", j) } } fmt.Println() } } func countProperDivisors(n int) int { if n < 2 { return 0 } count := 0 for i := 1; i <= n/2; i++ { if n%i == 0 { count++ } } return count } func main() { fmt.Println("The proper divisors of the following numbers are:\n") listProperDivisors(10) fmt.Println() maxCount := 0 most := []int{1} for n := 2; n <= 20000; n++ { count := countProperDivisors(n) if count == maxCount { most = append(most, n) } else if count > maxCount { maxCount = count most = most[0:1] most[0] = n } } fmt.Print("The following number(s) <= 20000 have the most proper divisors, ") fmt.Println("namely", maxCount, "\b\n") for _, n := range most { fmt.Println(n) } }
411Proper divisors
0go
07tsk
import java.util.PriorityQueue internal data class Task(val priority: Int, val name: String) : Comparable<Task> { override fun compareTo(other: Task) = when { priority < other.priority -> -1 priority > other.priority -> 1 else -> 0 } } private infix fun String.priority(priority: Int) = Task(priority, this) fun main(args: Array<String>) { val q = PriorityQueue(listOf("Clear drains" priority 3, "Feed cat" priority 4, "Make tea" priority 5, "Solve RC tasks" priority 1, "Tax return" priority 2)) while (q.any()) println(q.remove()) }
408Priority queue
11kotlin
udpvc
def w_prime?(i) return false if i < 2 ((1..i-1).inject(&:*) + 1) % i == 0 end p (1..100).select{|n| w_prime?(n) }
412Primality by Wilson's theorem
14ruby
plqbh
(defprotocol Printable (print-it [this] "Prints out the Printable.")) (deftype Point [x y] Printable (print-it [this] (println (str "Point: " x " " y)))) (defn create-point "Redundant constructor function." [x y] (Point. x y)) (deftype Circle [x y r] Printable (print-it [this] (println (str "Circle: " x " " y " " r)))) (defn create-circle "Redundant consturctor function." [x y r] (Circle. x y r))
420Polymorphism
6clojure
vic2f
class T implements Cloneable { public String name() { return "T"; } public T copy() { try { return (T)super.clone(); } catch (CloneNotSupportedException e) { return null; } } } class S extends T { public String name() { return "S"; } } public class PolymorphicCopy { public static T copier(T x) { return x.copy(); } public static void main(String[] args) { T obj1 = new T(); S obj2 = new S(); System.out.println(copier(obj1).name());
414Polymorphic copy
9java
avq1y
import java.awt._ import java.awt.event.ActionEvent import javax.swing._ object PolySpiral extends App { SwingUtilities.invokeLater(() => new JFrame("PolySpiral") { class PolySpiral extends JPanel { private var inc = 0.0 override def paintComponent(gg: Graphics): Unit = { val g = gg.asInstanceOf[Graphics2D] def drawSpiral(g: Graphics2D, l: Int, angleIncrement: Double): Unit = { var len = l var (x1, y1) = (getWidth / 2d, getHeight / 2d) var angle = angleIncrement for (i <- 0 until 150) { g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f)) val x2 = x1 + math.cos(angle) * len val y2 = y1 - math.sin(angle) * len g.drawLine(x1.toInt, y1.toInt, x2.toInt, y2.toInt) x1 = x2 y1 = y2 len += 3 angle = (angle + angleIncrement) % (math.Pi * 2) } } super.paintComponent(gg) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawSpiral(g, 5, math.toRadians(inc)) } setBackground(Color.white) setPreferredSize(new Dimension(640, 640)) new Timer(40, (_: ActionEvent) => { inc = (inc + 0.05) % 360 repaint() }).start() } add(new PolySpiral, BorderLayout.CENTER) pack() setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setLocationRelativeTo(null) setResizable(true) setVisible(true) } ) }
413Polyspiral
16scala
bcwk6
import Data.Ord import Data.List divisors :: (Integral a) => a -> [a] divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)] main :: IO () main = do putStrLn "divisors of 1 to 10:" mapM_ (print . divisors) [1 .. 10] putStrLn "a number with the most divisors within 1 to 20000 (number, count):" print $ maximumBy (comparing snd) [(n, length $ divisors n) | n <- [1 .. 20000]]
411Proper divisors
8haskell
c8g94
use List::Util qw(first sum); use constant TRIALS => 1e6; sub prob_choice_picker { my %options = @_; my ($n, @a) = 0; while (my ($k,$v) = each %options) { $n += $v; push @a, [$n, $k]; } return sub { my $r = rand; ( first {$r <= $_->[0]} @a )->[1]; }; } my %ps = (aleph => 1/5, beth => 1/6, gimel => 1/7, daleth => 1/8, he => 1/9, waw => 1/10, zayin => 1/11); $ps{heth} = 1 - sum values %ps; my $picker = prob_choice_picker %ps; my %results; for (my $n = 0 ; $n < TRIALS ; ++$n) { ++$results{$picker->()}; } print "Event Occurred Expected Difference\n"; foreach (sort {$results{$b} <=> $results{$a}} keys %results) { printf "%-6s %f %f %f\n", $_, $results{$_}/TRIALS, $ps{$_}, abs($results{$_}/TRIALS - $ps{$_}); }
410Probabilistic choice
2perl
gz14e
fn factorial_mod(mut n: u32, p: u32) -> u32 { let mut f = 1; while n!= 0 && f!= 0 { f = (f * n)% p; n -= 1; } f } fn is_prime(p: u32) -> bool { p > 1 && factorial_mod(p - 1, p) == p - 1 } fn main() { println!(" n | prime?\n------------"); for p in vec![2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659] { println!("{:>3} | {}", p, is_prime(p)); } println!("\nFirst 120 primes by Wilson's theorem:"); let mut n = 0; let mut p = 1; while n < 120 { if is_prime(p) { n += 1; print!("{:>3}{}", p, if n% 20 == 0 { '\n' } else { ' ' }); } p += 1; } println!("\n1000th through 1015th primes:"); let mut i = 0; while n < 1015 { if is_prime(p) { n += 1; if n >= 1000 { i += 1; print!("{:>3}{}", p, if i% 16 == 0 { '\n' } else { ' ' }); } } p += 1; } }
412Primality by Wilson's theorem
15rust
12spu
public class Foo { public int x = 0; } void somefunction() { Foo a;
423Pointers and references
9java
j6u7c