code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import Control.Monad.Random import Control.Applicative import Text.Printf import Control.Monad import Data.Bits data OneRun = OutRun | InRun deriving (Eq, Show) randomList :: Int -> Double -> Rand StdGen [Int] randomList n p = take n . map f <$> getRandomRs (0,1) where f n = if (n > p) then 0 else 1 countRuns xs = fromIntegral . sum $ zipWith (\x y -> x .&. xor y 1) xs (tail xs ++ [0]) calcK :: Int -> Double -> Rand StdGen Double calcK n p = (/ fromIntegral n) . countRuns <$> randomList n p printKs :: StdGen -> Double -> IO () printKs g p = do printf "p=%.1f, K(p)=%.3f\n" p (p * (1 - p)) forM_ [1..5] $ \n -> do let est = evalRand (calcK (10^n) p) g printf "n=%7d, estimated K(p)=%5.3f\n" (10^n::Int) est main = do x <- newStdGen forM_ [0.1,0.3,0.5,0.7,0.9] $ printKs x
447Percolation/Mean run density
8haskell
c0494
null
448Percolation/Site percolation
11kotlin
fpydo
(defn perfect-shuffle [deck] (let [half (split-at (/ (count deck) 2) deck)] (interleave (first half) (last half)))) (defn solve [deck-size] (let [original (range deck-size) trials (drop 1 (iterate perfect-shuffle original)) predicate #(= original %)] (println (format "%5s:%s" deck-size (inc (some identity (map-indexed (fn [i x] (when (predicate x) i)) trials))))))) (map solve [8 24 52 100 1020 1024 10000])
452Perfect shuffle
6clojure
sg0qr
perfectTotients :: [Int] perfectTotients = filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate )) [2 ..] :: Int -> Int = memoize (\n -> length (filter ((1 ==) . gcd n) [1 .. n])) memoize :: (Int -> a) -> (Int -> a) memoize f = (!!) (f <$> [0 ..]) main :: IO () main = print $ take 20 perfectTotients
450Perfect totient numbers
8haskell
0ris7
import java.util.Random; ... int[] array = {1,2,3}; return array[new Random().nextInt(array.length)];
436Pick random element
9java
q4lxa
var array = [1,2,3]; return array[Math.floor(Math.random() * array.length)];
436Pick random element
10javascript
ih4ol
(function (p) { return [ p.split('').reverse().join(''), p.split(' ').map(function (x) { return x.split('').reverse().join(''); }).join(' '), p.split(' ').reverse().join(' ') ].join('\n'); })('rosetta code phrase reversal');
437Phrase reversals
10javascript
dbgnu
package main import ( "fmt" "math/big" )
444Permutations/Derangements
0go
l8jcw
package pentominotiling; import java.util.*; public class PentominoTiling { static final char[] symbols = "FILNPTUVWXYZ-".toCharArray(); static final Random rand = new Random(); static final int nRows = 8; static final int nCols = 8; static final int blank = 12; static int[][] grid = new int[nRows][nCols]; static boolean[] placed = new boolean[symbols.length - 1]; public static void main(String[] args) { shuffleShapes(); for (int r = 0; r < nRows; r++) Arrays.fill(grid[r], -1); for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.nextInt(nRows); randCol = rand.nextInt(nCols); } while (grid[randRow][randCol] == blank); grid[randRow][randCol] = blank; } if (solve(0, 0)) { printResult(); } else { System.out.println("no solution"); } } static void shuffleShapes() { int n = shapes.length; while (n > 1) { int r = rand.nextInt(n--); int[][] tmp = shapes[r]; shapes[r] = shapes[n]; shapes[n] = tmp; char tmpSymbol = symbols[r]; symbols[r] = symbols[n]; symbols[n] = tmpSymbol; } } static void printResult() { for (int[] r : grid) { for (int i : r) System.out.printf("%c ", symbols[i]); System.out.println(); } } static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) { for (int i = 0; i < o.length; i += 2) { int x = c + o[i + 1]; int y = r + o[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; } grid[r][c] = shapeIndex; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex; return true; } static void removeOrientation(int[] o, int r, int c) { grid[r][c] = -1; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = -1; } static boolean solve(int pos, int numPlaced) { if (numPlaced == shapes.length) return true; int row = pos / nCols; int col = pos % nCols; if (grid[row][col] != -1) return solve(pos + 1, numPlaced); for (int i = 0; i < shapes.length; i++) { if (!placed[i]) { for (int[] orientation : shapes[i]) { if (!tryPlaceOrientation(orientation, row, col, i)) continue; placed[i] = true; if (solve(pos + 1, numPlaced + 1)) return true; removeOrientation(orientation, row, col); placed[i] = false; } } } return false; } static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}}; static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}; static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}}; static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}}; static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}}; static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}}; static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}}; static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}}; static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}}; static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}}; static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}}; static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}}; static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z}; }
454Pentomino tiling
9java
tpdf9
$fill = 'x'; $D{$_} = $i++ for qw<DeadEnd Up Right Down Left>; sub deq { defined $_[0] && $_[0] eq $_[1] } sub perctest { my($grid) = @_; generate($grid); my $block = 1; for my $y (0..$grid-1) { for my $x (0..$grid-1) { fill($x, $y, $block++) if $perc[$y][$x] eq $fill } } ($block - 1) / $grid**2; } sub generate { my($grid) = @_; for my $y (0..$grid-1) { for my $x (0..$grid-1) { $perc[$y][$x] = rand() < .5 ? '.' : $fill; } } } sub fill { my($x, $y, $block) = @_; $perc[$y][$x] = $block; my @stack; while (1) { if (my $dir = direction( $x, $y )) { push @stack, [$x, $y]; ($x,$y) = move($dir, $x, $y, $block) } else { return unless @stack; ($x,$y) = @{pop @stack}; } } } sub direction { my($x, $y) = @_; return $D{Down} if deq($perc[$y+1][$x ], $fill); return $D{Left} if deq($perc[$y ][$x-1], $fill); return $D{Right} if deq($perc[$y ][$x+1], $fill); return $D{Up} if deq($perc[$y-1][$x ], $fill); return $D{DeadEnd}; } sub move { my($dir,$x,$y,$block) = @_; $perc[--$y][ $x] = $block if $dir == $D{Up}; $perc[++$y][ $x] = $block if $dir == $D{Down}; $perc[ $y][ --$x] = $block if $dir == $D{Left}; $perc[ $y][ ++$x] = $block if $dir == $D{Right}; ($x, $y) } my $K = perctest(15); for my $row (@perc) { printf "%3s", $_ for @$row; print "\n"; } printf " = 0.5, = 15, =%.4f\n\n", $K; $trials = 5; for $N (10, 30, 100, 300, 1000) { my $total = 0; $total += perctest($N) for 1..$trials; printf " = 0.5, trials = $trials, =%4d, =%.4f\n", $N, $total / $trials; }
449Percolation/Mean cluster density
2perl
4fj5d
null
451Percolation/Bond percolation
11kotlin
3eyz5
my $block = ''; my $water = '+'; my $pore = ' '; my $grid = 15; my @site; $D{$_} = $i++ for qw<DeadEnd Up Right Down Left>; sub deq { defined $_[0] && $_[0] eq $_[1] } sub percolate { my($prob) = shift || 0.6; $site[0] = [($pore) x $grid]; for my $y (1..$grid) { for my $x (0..$grid-1) { $site[$y][$x] = rand() < $prob ? $pore : $block; } } $site[$grid + 1] = [($pore) x $grid]; $site[0][0] = $water; my $x = 0; my $y = 0; my @stack; while () { if (my $dir = direction($x,$y)) { push @stack, [$x,$y]; ($x,$y) = move($dir, $x, $y) } else { return 0 unless @stack; ($x,$y) = @{pop @stack} } return 1 if $y > $grid; } } sub direction { my($x, $y) = @_; return $D{Down} if deq($site[$y+1][$x ], $pore); return $D{Right} if deq($site[$y ][$x+1], $pore); return $D{Left} if deq($site[$y ][$x-1], $pore); return $D{Up} if deq($site[$y-1][$x ], $pore); return $D{DeadEnd}; } sub move { my($dir,$x,$y) = @_; $site[--$y][ $x] = $water if $dir == $D{Up}; $site[++$y][ $x] = $water if $dir == $D{Down}; $site[ $y][ --$x] = $water if $dir == $D{Left}; $site[ $y][ ++$x] = $water if $dir == $D{Right}; $x, $y } my $prob = 0.65; percolate($prob); print "Sample percolation at $prob\n"; print join '', @$_, "\n" for @site; print "\n"; my $tests = 100; print "Doing $tests trials at each porosity:\n"; my @table; for my $p (1 .. 10) { $p = $p/10; my $total = 0; $total += percolate($p) for 1..$tests; push @table, sprintf "p =%0.1f:%0.2f", $p, $total / $tests } print "$_\n" for @table;
448Percolation/Site percolation
2perl
hyajl
null
445Perlin noise
9java
87306
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first%d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Integer> perfectTotient(int n) { int test = 2; List<Integer> results = new ArrayList<Integer>(); for ( int i = 0 ; i < n ; test++ ) { int phiLoop = test; int sum = 0; do { phiLoop = phi[phiLoop]; sum += phiLoop; } while ( phiLoop > 1); if ( sum == test ) { i++; results.add(test); } } return results; } private static final int max = 100000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
450Perfect totient numbers
9java
a2x1y
import BigInt import Foundation public func pierpoint(n: Int) -> (first: [BigInt], second: [BigInt]) { var primes = (first: [BigInt](repeating: 0, count: n), second: [BigInt](repeating: 0, count: n)) primes.first[0] = 2 var count1 = 1, count2 = 0 var s = [BigInt(1)] var i2 = 0, i3 = 0, k = 1 var n2 = BigInt(0), n3 = BigInt(0), t = BigInt(0) while min(count1, count2) < n { n2 = s[i2] * 2 n3 = s[i3] * 3 if n2 < n3 { t = n2 i2 += 1 } else { t = n3 i3 += 1 } if t <= s[k - 1] { continue } s.append(t) k += 1 t += 1 if count1 < n && t.isPrime(rounds: 10) { primes.first[count1] = t count1 += 1 } t -= 2 if count2 < n && t.isPrime(rounds: 10) { primes.second[count2] = t count2 += 1 } } return primes } let primes = pierpoint(n: 250) print("First 50 Pierpoint primes of the first kind: \(Array(primes.first.prefix(50)))\n") print("First 50 Pierpoint primes of the second kind: \(Array(primes.second.prefix(50)))") print() print("250th Pierpoint prime of the first kind: \(primes.first[249])") print("250th Pierpoint prime of the second kind: \(primes.second[249])")
433Pierpont primes
17swift
ojr8k
def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() } def subfact subfact = { BigInteger n -> (n == 0) ? 1: (n == 1) ? 0: ((n-1) * (subfact(n-1) + subfact(n-2))) } def derangement = { List l -> def d = [] if (l) l.eachPermutation { p -> if ([p,l].transpose().every{ pp, ll -> pp != ll }) d << p } d }
444Permutations/Derangements
7groovy
6w53o
null
442Permutations by swapping
11kotlin
km8h3
from itertools import combinations as comb def statistic(ab, a): sumab, suma = sum(ab), sum(a) return ( suma / len(a) - (sumab -suma) / (len(ab) - len(a)) ) def permutationTest(a, b): ab = a + b Tobs = statistic(ab, a) under = 0 for count, perm in enumerate(comb(ab, len(a)), 1): if statistic(ab, perm) <= Tobs: under += 1 return under * 100. / count treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] under = permutationTest(treatmentGroup, controlGroup) print(% (under, 100. - under))
440Permutation test
3python
yxj6q
null
454Pentomino tiling
11kotlin
o708z
my @bond; my $grid = 10; my $water = ''; $D{$_} = $i++ for qw<DeadEnd Up Right Down Left>; sub percolate { generate(shift || 0.6); fill(my $x = 1,my $y = 0); my @stack; while () { if (my $dir = direction($x,$y)) { push @stack, [$x,$y]; ($x,$y) = move($dir, $x, $y) } else { return 0 unless @stack; ($x,$y) = @{pop @stack} } return 1 if $y == $ } } sub direction { my($x, $y) = @_; return $D{Down} if $bond[$y+1][$x ] =~ / /; return $D{Left} if $bond[$y ][$x-1] =~ / /; return $D{Right} if $bond[$y ][$x+1] =~ / /; return $D{Up} if defined $bond[$y-1][$x ] && $bond[$y-1][$x] =~ / /; return $D{DeadEnd} } sub move { my($dir,$x,$y) = @_; fill( $x,--$y), fill( $x,--$y) if $dir == $D{Up}; fill( $x,++$y), fill( $x,++$y) if $dir == $D{Down}; fill(--$x, $y), fill(--$x, $y) if $dir == $D{Left}; fill(++$x, $y), fill(++$x, $y) if $dir == $D{Right}; $x, $y } sub fill { my($x, $y) = @_; $bond[$y][$x] =~ s/ /$water/g } sub generate { our($prob) = shift || 0.5; @bond = (); our $sp = ' '; push @bond, ['', ($sp, ' ') x ($grid-1), $sp, ''], ['', hx(''), h(), '']; push @bond, ['', vx( ), $sp, ''], ['', hx(''), h(), ''] for 1..$grid-1; push @bond, ['', vx( ), $sp, ''], ['', hx(''), h(), ''], ['', ($sp, ' ') x ($grid-1), $sp, '']; sub hx { my($c)=@_; my @l; push @l, (h(),$c) for 1..$grid-1; return @l; } sub vx { my @l; push @l, $sp, v() for 1..$grid-1; return @l; } sub h { rand() < $prob ? $sp : '' } sub v { rand() < $prob ? ' ' : '' } } print "Sample percolation at .6\n"; percolate(.6); for my $row (@bond) { my $line = ''; $line .= join '', $_ for @$row; print "$line\n"; } my $tests = 100; print "Doing $tests trials at each porosity:\n"; my @table; for my $p (1 .. 10) { $p = $p/10; my $total = 0; $total += percolate($p) for 1..$tests; printf "p =%0.1f:%0.2f\n", $p, $total / $tests }
451Percolation/Bond percolation
2perl
pcab0
null
445Perlin noise
11kotlin
wunek
(() => { 'use strict';
450Perfect totient numbers
10javascript
sgoqz
null
436Pick random element
11kotlin
1l6pd
import Control.Monad (forM_) import Data.List (permutations) derangements :: Eq a => [a] -> [[a]] derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations subfactorial :: (Eq a, Num a) => a -> a subfactorial 0 = 1 subfactorial 1 = 0 subfactorial n = (n - 1) * (subfactorial (n - 1) + subfactorial (n - 2)) main :: IO () main = do print $ derangements [1 .. 4] putStrLn "" forM_ [1 .. 9] $ \i -> putStrLn $ mconcat [show (length (derangements [1 .. i])), " ", show (subfactorial i)] putStrLn "" print $ subfactorial 20
444Permutations/Derangements
8haskell
1lops
_JT={} function JT(dim) local n={ values={}, positions={}, directions={}, sign=1 } setmetatable(n,{__index=_JT}) for i=1,dim do n.values[i]=i n.positions[i]=i n.directions[i]=-1 end return n end function _JT:largestMobile() for i=#self.values,1,-1 do local loc=self.positions[i]+self.directions[i] if loc >= 1 and loc <= #self.values and self.values[loc] < i then return i end end return 0 end function _JT:next() local r=self:largestMobile() if r==0 then return false end local rloc=self.positions[r] local lloc=rloc+self.directions[r] local l=self.values[lloc] self.values[lloc],self.values[rloc] = self.values[rloc],self.values[lloc] self.positions[l],self.positions[r] = self.positions[r],self.positions[l] self.sign=-self.sign for i=r+1,#self.directions do self.directions[i]=-self.directions[i] end return true end
442Permutations by swapping
1lua
b9oka
permutation.test <- function(treatment, control) { perms <- combinations(length(treatment)+length(control), length(treatment), c(treatment, control), set=FALSE) p <- mean(rowMeans(perms) <= mean(treatment)) c(under=p, over=(1-p)) }
440Permutation test
13r
t14fz
use strict; use warnings; my $size = shift // 8; sub rotate { local $_ = shift; my $ans = ''; $ans .= "\n" while s/.$/$ans .= $&; ''/gem; $ans; } sub topattern { local $_ = shift; s/.+/ $& . ' ' x ($size - length $&)/ge; s/^\s+|\s+\z//g; [ tr/ \nA-Z/.. /r, lc tr/ \n/\0/r, substr $_, 0, 1 ]; } my %all; @all{ " FF\nFF \n F \n", "IIIII\n", "LLLL\nL \n", "NNN \n NN\n", "PPP\nPP \n", "TTT\n T \n T \n", "UUU\nU U\n", "VVV\nV \nV \n", "WW \n WW\n W\n", " X \nXXX\n X \n", "YYYY\n Y \n", "ZZ \n Z \n ZZ\n", } = (); @all{map rotate($_), keys %all} = () for 1 .. 3; @all{map s/.+/reverse $&/ger, keys %all} = (); my @all = map topattern($_), keys %all; my $grid = ( ' ' x $size . "\n" ) x $size; my %used; find( $grid ); sub find { my $grid = shift; %used >= 12 and exit not print $grid; for ( grep ! $used{ $_->[2] }, @all ) { my ($pattern, $pentomino, $letter) = @$_; local $used{$letter} = 1; $grid =~ /^[^ ]*\K$pattern/s and find( $grid ^ "\0" x $-[0] . $pentomino ); } }
454Pentomino tiling
2perl
gf54e
from __future__ import division from random import random import string from math import fsum n_range, p, t = (2**n2 for n2 in range(4, 14, 2)), 0.5, 5 N = M = 15 NOT_CLUSTERED = 1 cell2char = ' def newgrid(n, p): return [[int(random() < p) for x in range(n)] for y in range(n)] def pgrid(cell): for n in range(N): print( '%i) '% (n% 10) + ' '.join(cell2char[cell[n][m]] for m in range(M))) def cluster_density(n, p): cc = clustercount(newgrid(n, p)) return cc / n / n def clustercount(cell): walk_index = 1 for n in range(N): for m in range(M): if cell[n][m] == NOT_CLUSTERED: walk_index += 1 walk_maze(m, n, cell, walk_index) return walk_index - 1 def walk_maze(m, n, cell, indx): cell[n][m] = indx if n < N - 1 and cell[n+1][m] == NOT_CLUSTERED: walk_maze(m, n+1, cell, indx) if m < M - 1 and cell[n][m + 1] == NOT_CLUSTERED: walk_maze(m+1, n, cell, indx) if m and cell[n][m - 1] == NOT_CLUSTERED: walk_maze(m-1, n, cell, indx) if n and cell[n-1][m] == NOT_CLUSTERED: walk_maze(m, n-1, cell, indx) if __name__ == '__main__': cell = newgrid(n=N, p=0.5) print('Found%i clusters in this%i by%i grid\n' % (clustercount(cell), N, N)) pgrid(cell) print('') for n in n_range: N = M = n sim = fsum(cluster_density(n, p) for i in range(t)) / t print('t=%3i p=%4.2f n=%5i sim=%7.5f' % (t, p, n, sim))
449Percolation/Mean cluster density
3python
gth4h
null
447Percolation/Mean run density
11kotlin
ih3o4
from random import random import string from pprint import pprint as pp M, N, t = 15, 15, 100 cell2char = ' NOT_VISITED = 1 class PercolatedException(Exception): pass def newgrid(p): return [[int(random() < p) for m in range(M)] for n in range(N)] def pgrid(cell, percolated=None): for n in range(N): print( '%i) '% (n% 10) + ' '.join(cell2char[cell[n][m]] for m in range(M))) if percolated: where = percolated.args[0][0] print('!) ' + ' ' * where + cell2char[cell[n][where]]) def check_from_top(cell): n, walk_index = 0, 1 try: for m in range(M): if cell[n][m] == NOT_VISITED: walk_index += 1 walk_maze(m, n, cell, walk_index) except PercolatedException as ex: return ex return None def walk_maze(m, n, cell, indx): cell[n][m] = indx if n < N - 1 and cell[n+1][m] == NOT_VISITED: walk_maze(m, n+1, cell, indx) elif n == N - 1: raise PercolatedException((m, indx)) if m and cell[n][m - 1] == NOT_VISITED: walk_maze(m-1, n, cell, indx) if m < M - 1 and cell[n][m + 1] == NOT_VISITED: walk_maze(m+1, n, cell, indx) if n and cell[n-1][m] == NOT_VISITED: walk_maze(m, n-1, cell, indx) if __name__ == '__main__': sample_printed = False pcount = {} for p10 in range(11): p = p10 / 10.0 pcount[p] = 0 for tries in range(t): cell = newgrid(p) percolated = check_from_top(cell) if percolated: pcount[p] += 1 if not sample_printed: print('\nSample percolating%i x%i, p =%5.2f grid\n'% (M, N, p)) pgrid(cell, percolated) sample_printed = True print('\n p: Fraction of%i tries that percolate through\n'% t ) pp({p:c/float(t) for p, c in pcount.items()})
448Percolation/Site percolation
3python
kmehf
local p = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 }
445Perlin noise
1lua
x5dwz
package cards import ( "math/rand" )
438Playing cards
0go
x5mwf
package main import "fmt" func pernicious(w uint32) bool { const ( ff = 1<<32 - 1 mask1 = ff / 3 mask3 = ff / 5 maskf = ff / 17 maskp = ff / 255 ) w -= w >> 1 & mask1 w = w&mask3 + w>>2&mask3 w = (w + w>>4) & maskf return 0xa08a28ac>>(w*maskp>>24)&1 != 0 } func main() { for i, n := 0, uint32(1); i < 25; n++ { if pernicious(n) { fmt.Printf("%d ", n) i++ } } fmt.Println() for n := uint32(888888877); n <= 888888888; n++ { if pernicious(n) { fmt.Printf("%d ", n) } } fmt.Println() }
441Pernicious numbers
0go
unavt
null
437Phrase reversals
11kotlin
evya4
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d %-7d%-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 =%20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
444Permutations/Derangements
9java
73wrj
from collections import namedtuple from random import random from pprint import pprint as pp Grid = namedtuple('Grid', 'cell, hwall, vwall') M, N, t = 10, 10, 100 class PercolatedException(Exception): pass HVF = [(' .', ' _'), (':', '|'), (' ', ' def newgrid(p): hwall = [[int(random() < p) for m in range(M)] for n in range(N+1)] vwall = [[(1 if m in (0, M) else int(random() < p)) for m in range(M+1)] for n in range(N)] cell = [[0 for m in range(M)] for n in range(N)] return Grid(cell, hwall, vwall) def pgrid(grid, percolated=None): cell, hwall, vwall = grid h, v, f = HVF for n in range(N): print(' ' + ''.join(h[hwall[n][m]] for m in range(M))) print('%i) '% (n% 10) + ''.join(v[vwall[n][m]] + f[cell[n][m] if m < M else 0] for m in range(M+1))[:-1]) n = N print(' ' + ''.join(h[hwall[n][m]] for m in range(M))) if percolated: where = percolated.args[0][0] print('!) ' + ' ' * where + ' ' + f[1]) def pour_on_top(grid): cell, hwall, vwall = grid n = 0 try: for m in range(M): if not hwall[n][m]: flood_fill(m, n, cell, hwall, vwall) except PercolatedException as ex: return ex return None def flood_fill(m, n, cell, hwall, vwall): cell[n][m] = 1 if n < N - 1 and not hwall[n + 1][m] and not cell[n+1][m]: flood_fill(m, n+1, cell, hwall, vwall) elif n == N - 1 and not hwall[n + 1][m]: raise PercolatedException((m, n+1)) if m and not vwall[n][m] and not cell[n][m - 1]: flood_fill(m-1, n, cell, hwall, vwall) if m < M - 1 and not vwall[n][m + 1] and not cell[n][m + 1]: flood_fill(m+1, n, cell, hwall, vwall) if n and not hwall[n][m] and not cell[n-1][m]: flood_fill(m, n-1, cell, hwall, vwall) if __name__ == '__main__': sample_printed = False pcount = {} for p10 in range(11): p = (10 - p10) / 10.0 pcount[p] = 0 for tries in range(t): grid = newgrid(p) percolated = pour_on_top(grid) if percolated: pcount[p] += 1 if not sample_printed: print('\nSample percolating%i x%i grid'% (M, N)) pgrid(grid, percolated) sample_printed = True print('\n p: Fraction of%i tries that percolate through'% t ) pp({p:c/float(t) for p, c in pcount.items()})
451Percolation/Bond percolation
3python
1lepc
null
450Perfect totient numbers
11kotlin
hypj3
import groovy.transform.TupleConstructor enum Pip { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } enum Suit { DIAMONDS, SPADES, HEARTS, CLUBS } @TupleConstructor class Card { final Pip pip final Suit suit String toString() { "$pip of $suit" } } class Deck { private LinkedList cards = [] Deck() { reset() } void reset() { cards = [] Suit.values().each { suit -> Pip.values().each { pip -> cards << new Card(pip, suit) } } } Card deal() { cards.poll() } void shuffle() { Collections.shuffle cards } String toString() { cards.isEmpty() ? "Empty Deck": "Deck $cards" } }
438Playing cards
7groovy
pctbo
class example{ static void main(String[] args){ def n=0; def counter=0; while(counter<25){ if(print(n)){ counter++;} n=n+1; } println(); def x=888888877; while(x<888888889){ print(x); x++;} } static def print(def a){ def primes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]; def c=Integer.toBinaryString(a); String d=c; def e=0; for(i in d){if(i=='1'){e++;}} if(e in primes){printf(a+" ");return 1;} } }
441Pernicious numbers
7groovy
9shm4
null
437Phrase reversals
1lua
wumea
package main import ( "fmt" "image/jpeg" "os" "log" "image" ) func loadJpeg(filename string) (image.Image, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() img, err := jpeg.Decode(f) if err != nil { return nil, err } return img, nil } func diff(a, b uint32) int64 { if a > b { return int64(a - b) } return int64(b - a) } func main() { i50, err := loadJpeg("Lenna50.jpg") if err != nil { log.Fatal(err) } i100, err := loadJpeg("Lenna100.jpg") if err != nil { log.Fatal(err) } if i50.ColorModel() != i100.ColorModel() { log.Fatal("different color models") } b := i50.Bounds() if !b.Eq(i100.Bounds()) { log.Fatal("different image sizes") } var sum int64 for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { r1, g1, b1, _ := i50.At(x, y).RGBA() r2, g2, b2, _ := i100.At(x, y).RGBA() sum += diff(r1, r2) sum += diff(g1, g2) sum += diff(b1, b2) } } nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) fmt.Printf("Image difference:%f%%\n", float64(sum*100)/(float64(nPixels)*0xffff*3)) }
453Percentage difference between images
0go
gtg4n
import System.Random data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Ord, Enum, Bounded, Eq, Show) data Suit = Diamonds | Spades | Hearts | Clubs deriving (Ord, Enum, Bounded, Eq, Show) type Card = (Pip, Suit) fullRange :: (Bounded a, Enum a) => [a] fullRange = [minBound..maxBound] fullDeck :: [Card] fullDeck = [(pip, suit) | pip <- fullRange, suit <- fullRange] insertAt :: Int -> a -> [a] -> [a] insertAt 0 x ys = x:ys insertAt n _ [] = error "insertAt: list too short" insertAt n x (y:ys) = y: insertAt (n-1) x ys shuffle :: RandomGen g => g -> [a] -> [a] shuffle g xs = shuffle' g xs 0 [] where shuffle' g [] _ ys = ys shuffle' g (x:xs) n ys = shuffle' g' xs (n+1) (insertAt k x ys) where (k,g') = randomR (0,n) g
438Playing cards
8haskell
yxk66
module Pernicious where isPernicious :: Integer -> Bool isPernicious num = isPrime $ toInteger $ length $ filter ( == 1 ) $ toBinary num isPrime :: Integer -> Bool isPrime number = divisors number == [1, number] where divisors :: Integer -> [Integer] divisors number = [ m | m <- [1 .. number] , number `mod` m == 0 ] toBinary :: Integer -> [Integer] toBinary num = reverse $ map ( `mod` 2 ) ( takeWhile ( /= 0 ) $ iterate ( `div` 2 ) num ) solution1 = take 25 $ filter isPernicious [1 ..] solution2 = filter isPernicious [888888877 .. 888888888]
441Pernicious numbers
8haskell
wuzed
math.randomseed(os.time()) local a = {1,2,3} print(a[math.random(1,#a)])
436Pick random element
1lua
a2y1v
use strict; use warnings; sub perms(&@) { my $callback = shift; my @perm = map [$_, -1], @_; $perm[0][1] = 0; my $sign = 1; while( ) { $callback->($sign, map $_->[0], @perm); $sign *= -1; my ($chosen, $index) = (-1, -1); for my $i ( 0 .. $ ($chosen, $index) = ($perm[$i][0], $i) if $perm[$i][1] and $perm[$i][0] > $chosen; } return if $index == -1; my $direction = $perm[$index][1]; my $next = $index + $direction; @perm[ $index, $next ] = @perm[ $next, $index ]; if( $next <= 0 or $next >= $ $perm[$next][1] = 0; } elsif( $perm[$next + $direction][0] > $chosen ) { $perm[$next][1] = 0; } for my $i ( 0 .. $next - 1 ) { $perm[$i][1] = +1 if $perm[$i][0] > $chosen; } for my $i ( $next + 1 .. $ $perm[$i][1] = -1 if $perm[$i][0] > $chosen; } } } my $n = shift(@ARGV) || 4; perms { my ($sign, @perm) = @_; print "[", join(", ", @perm), "]"; print $sign < 0 ? " => -1\n" : " => +1\n"; } 1 .. $n;
442Permutations by swapping
2perl
3e4zs
def statistic(ab, a) sumab, suma = ab.inject(:+).to_f, a.inject(:+).to_f suma / a.size - (sumab - suma) / (ab.size - a.size) end def permutationTest(a, b) ab = a + b tobs = statistic(ab, a) under = count = 0 ab.combination(a.size) do |perm| under += 1 if statistic(ab, perm) <= tobs count += 1 end under * 100.0 / count end treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] under = permutationTest(treatmentGroup, controlGroup) puts % [under, 100 - under]
440Permutation test
14ruby
9skmz
import Bitmap import Bitmap.Netpbm import Bitmap.RGB import Control.Monad import Control.Monad.ST import System.Environment (getArgs) main = do [path1, path2] <- getArgs image1 <- readNetpbm path1 image2 <- readNetpbm path2 diff <- stToIO $ imageDiff image1 image2 putStrLn $ "Difference: " ++ show (100 * diff) ++ "%" imageDiff :: Image s RGB -> Image s RGB -> ST s Double imageDiff image1 image2 = do i1 <- getPixels image1 i2 <- getPixels image2 unless (length i1 == length i2) $ fail "imageDiff: Images are of different sizes" return $ toEnum (sum $ zipWith minus i1 i2) / toEnum (3 * 255 * length i1) where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) = abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
453Percentage difference between images
8haskell
sgsqk
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) tiles = [] for row in minos: tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[-1]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i vert = ([' |'[row[i] != row[i+1]] for i in range(9)] for row in b) hori = ([' _'[b[i+1][j] != b[i][j]] for j in range(1, 10)] for i in range(9)) return '\n'.join([''.join(a + b for a, b in zip(v, h)) for v, h in zip(vert, hori)]) def tile(board, i, seq=tuple()): if not i: yield img(seq) else: for c in [c for c in tiles[i - 1] if not board & c]: yield from tile(board|c, i - 1, (c,) + seq) for i in tile(0, len(tiles)): print(i)
454Pentomino tiling
3python
rt4gq
let randMax = 32767.0 let filled = 1 let rightWall = 2 let bottomWall = 4 final class Percolate { let height: Int let width: Int private var grid: [Int] private var end: Int init(height: Int, width: Int) { self.height = height self.width = width self.end = width self.grid = [Int](repeating: 0, count: width * (height + 2)) } private func fill(at p: Int) -> Bool { guard grid[p] & filled == 0 else { return false } grid[p] |= filled guard p < end else { return true } return (((grid[p + 0] & bottomWall) == 0) && fill(at: p + width)) || (((grid[p + 0] & rightWall) == 0) && fill(at: p + 1)) || (((grid[p - 1] & rightWall) == 0) && fill(at: p - 1)) || (((grid[p - width] & bottomWall) == 0) && fill(at: p - width)) } func makeGrid(porosity p: Double) { grid = [Int](repeating: 0, count: width * (height + 2)) end = width let thresh = Int(randMax * p) for i in 0..<width { grid[i] = bottomWall | rightWall } for _ in 0..<height { for _ in stride(from: width - 1, through: 1, by: -1) { let r1 = Int.random(in: 0..<Int(randMax)+1) let r2 = Int.random(in: 0..<Int(randMax)+1) grid[end] = (r1 < thresh? bottomWall: 0) | (r2 < thresh? rightWall: 0) end += 1 } let r3 = Int.random(in: 0..<Int(randMax)+1) grid[end] = rightWall | (r3 < thresh? bottomWall: 0) end += 1 } } @discardableResult func percolate() -> Bool { var i = 0 while i < width &&!fill(at: width + i) { i += 1 } return i < width } func showGrid() { for _ in 0..<width { print("+--", terminator: "") } print("+") for i in 0..<height { print(i == height? " ": "|", terminator: "") for j in 0..<width { print(grid[i * width + j + width] & filled!= 0? "[]": " ", terminator: "") print(grid[i * width + j + width] & rightWall!= 0? "|": " ", terminator: "") } print() guard i!= height else { return } for j in 0..<width { print(grid[i * width + j + width] & bottomWall!= 0? "+--": "+ ", terminator: "") } print("+") } } } let p = Percolate(height: 10, width: 10) p.makeGrid(porosity: 0.5) p.percolate() p.showGrid() print("Running \(p.height) x \(p.width) grid 10,000 times for each porosity") for factor in 1...10 { var count = 0 let porosity = Double(factor) / 10.0 for _ in 0..<10_000 { p.makeGrid(porosity: porosity) if p.percolate() { count += 1 } } print("p = \(porosity): \(Double(count) / 10_000.0)") }
451Percolation/Bond percolation
17swift
a2w1i
sub R { my ($n, $p) = @_; my $r = join '', map { rand() < $p ? 1 : 0 } 1 .. $n; 0+ $r =~ s/1+//g; } use constant t => 100; printf "t=%d\n", t; for my $p (qw(.1 .3 .5 .7 .9)) { printf "p=%f, K(p)=%f\n", $p, $p*(1-$p); for my $n (qw(10 100 1000)) { my $r; $r += R($n, $p) for 1 .. t; $r /= $n; printf " R(n, p)=%f\n", $r / t; } }
447Percolation/Mean run density
2perl
rzpgd
package main import ( "fmt" "math/big" ) type lft struct { q,r,s,t big.Int } func (t *lft) extr(x *big.Int) *big.Rat { var n, d big.Int var r big.Rat return r.SetFrac( n.Add(n.Mul(&t.q, x), &t.r), d.Add(d.Mul(&t.s, x), &t.t)) } var three = big.NewInt(3) var four = big.NewInt(4) func (t *lft) next() *big.Int { r := t.extr(three) var f big.Int return f.Div(r.Num(), r.Denom()) } func (t *lft) safe(n *big.Int) bool { r := t.extr(four) var f big.Int if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 { return true } return false } func (t *lft) comp(u *lft) *lft { var r lft var a, b big.Int r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s)) r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t)) r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s)) r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t)) return &r } func (t *lft) prod(n *big.Int) *lft { var r lft r.q.SetInt64(10) r.r.Mul(r.r.SetInt64(-10), n) r.t.SetInt64(1) return r.comp(t) } func main() {
443Pi
0go
9s7mt
use strict; use warnings; my @players = @ARGV; @players = qw(Joe Mike); my @scores = (0) x @players; while( 1 ) { PLAYER: for my $i ( 0 .. $ my $name = $players[$i]; my $score = $scores[$i]; my $roundscore = 1 + int rand 6; print "$name, your score so far is $score.\n"; print "You rolled a $roundscore.\n"; next PLAYER if $roundscore == 1; while($score + $roundscore < 100) { print "Roll again, or hold [r/h]: "; my $answer = <>; $answer = 'h' unless defined $answer; if( $answer =~ /^h/i ) { $score += $roundscore; $scores[$i] = $score; print "Your score is now $score.\n"; next PLAYER; } elsif( $answer =~ /^r/ ) { my $die = 1 + int rand 6; print "$name, you rolled a $die.\n"; next PLAYER if $die == 1; $roundscore += $die; print "Your score for the round is now $roundscore.\n"; } else { print "I did not understand that.\n"; } } $score += $roundscore; print "With that, your score became $score.\n"; print "You won!\n"; exit; } } __END__
434Pig the dice game
2perl
un8vr
null
444Permutations/Derangements
11kotlin
unbvc
fn main() { let treatment = vec![85, 88, 75, 66, 25, 29, 83, 39, 97]; let control = vec![68, 41, 10, 49, 16, 65, 32, 92, 28, 98]; let mut data_set = control.clone(); data_set.extend_from_slice(&treatment); let greater = combinations(treatment.iter().sum(), treatment.len() as i64, &data_set) as f64; let lesser = combinations(control.iter().sum(), control.len() as i64, &data_set) as f64; let total = binomial(data_set.len() as i64, treatment.len() as i64) as f64; println!("<=: {}%", (lesser / total * 100.0)); println!(" >: {}%", (greater / total * 100.0)); } fn factorial(x: i64) -> i64 { let mut product = 1; for a in 1..(x + 1) { product *= a; } product } fn binomial(n: i64, k: i64) -> i64 { let numerator = factorial(n); let denominator = factorial(k) * factorial(n - k); numerator / denominator } fn combinations(total: i64, number: i64, data: &[i64]) -> i64 { if total < 0 { return binomial(data.len() as i64, number); } if number == 0 { return 0; } if number > data.len() as i64 { return 0; } if number == data.len() as i64 { if total < data.iter().sum() { return 1; } else { return 0; } } let tail = &data[1..]; combinations(total - data[0], number - 1, &tail) + combinations(total, number, &tail) }
440Permutation test
15rust
c0b9z
object PermutationTest extends App { private val data = Array(85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98) private var (total, treat) = (1.0, 0) private def pick(at: Int, remain: Int, accu: Int, treat: Int): Int = { if (remain == 0) return if (accu > treat) 1 else 0 pick(at - 1, remain - 1, accu + data(at - 1), treat) + (if (at > remain) pick(at - 1, remain, accu, treat) else 0) } for (i <- 0 to 8) treat += data(i) for (j <- 19 to 11 by -1) total *= j for (g <- 9 to 1 by -1) total /= g private val gt = pick(19, 9, 0, treat) private val le = (total - gt).toInt println(f"<=: ${100.0 * le / total}%f%% ${le}%d") println(f" >: ${100.0 * gt / total}%f%% ${gt}%d") }
440Permutation test
16scala
via2s
package main import "fmt" type Deck struct { Cards []int length int } func NewDeck(deckSize int) (res *Deck){ if deckSize % 2 != 0{ panic("Deck size must be even") } res = new(Deck) res.Cards = make([]int, deckSize) res.length = deckSize for i,_ := range res.Cards{ res.Cards[i] = i } return } func (d *Deck)shuffleDeck(){ tmp := make([]int,d.length) for i := 0;i <d.length/2;i++ { tmp[i*2] = d.Cards[i] tmp[i*2+1] = d.Cards[d.length / 2 + i] } d.Cards = tmp } func (d *Deck) isEqualTo(c Deck) (res bool) { if d.length != c.length { panic("Decks aren't equally sized") } res = true for i, v := range d.Cards{ if v != c.Cards[i] { res = false } } return } func main(){ for _,v := range []int{8,24,52,100,1020,1024,10000} { fmt.Printf("Cards count:%d, shuffles required:%d\n",v,ShufflesRequired(v)) } } func ShufflesRequired(deckSize int)(res int){ deck := NewDeck(deckSize) Ref := *deck deck.shuffleDeck() res++ for ;!deck.isEqualTo(Ref);deck.shuffleDeck(){ res++ } return }
452Perfect shuffle
0go
mq9yi
use strict; use warnings; use experimental 'signatures'; use constant permutation => qw{ 151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180}; use constant p => permutation, permutation; sub floor ($x) { my $xi = int($x); return $x < $xi ? $xi - 1 : $xi } sub fade ($t) { $t**3 * ($t * ($t * 6 - 15) + 10) } sub lerp ($t, $a, $b) { $a + $t * ($b - $a) } sub grad ($h, $x, $y, $z) { $h &= 15; my $u = $h < 8 ? $x : $y; my $v = $h < 4 ? $y : ($h == 12 or $h == 14) ? $x : $z; (($h & 1) == 0 ? $u : -$u) + (($h & 2) == 0 ? $v : -$v); } sub noise ($x, $y, $z) { my ($X, $Y, $Z) = map { 255 & floor $_ } $x, $y, $z; my ($u, $v, $w) = map { fade $_ } $x -= $X, $y -= $Y, $z -= $Z; my $A = (p)[$X] + $Y; my ($AA, $AB) = ( (p)[$A] + $Z, (p)[$A + 1] + $Z ); my $B = (p)[$X + 1] + $Y; my ($BA, $BB) = ( (p)[$B] + $Z, (p)[$B + 1] + $Z ); lerp($w, lerp($v, lerp($u, grad((p)[$AA ], $x , $y , $z ), grad((p)[$BA ], $x - 1, $y , $z )), lerp($u, grad((p)[$AB ], $x , $y - 1, $z ), grad((p)[$BB ], $x - 1, $y - 1, $z ))), lerp($v, lerp($u, grad((p)[$AA + 1], $x , $y , $z - 1 ), grad((p)[$BA + 1], $x - 1, $y , $z - 1 )), lerp($u, grad((p)[$AB + 1], $x , $y - 1, $z - 1 ), grad((p)[$BB + 1], $x - 1, $y - 1, $z - 1 )))); } print noise 3.14, 42, 7;
445Perlin noise
2perl
l87c5
use ntheory qw(euler_phi); sub phi_iter { my($p) = @_; euler_phi($p) + ($p == 2 ? 0 : phi_iter(euler_phi($p))); } my @perfect; for (my $p = 2; @perfect < 20 ; ++$p) { push @perfect, $p if $p == phi_iter($p); } printf "The first twenty perfect totient numbers:\n%s\n", join ' ', @perfect;
450Perfect totient numbers
2perl
zaytb
BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3 String nn boolean first = true while (true) { (nn, first, q, r, t, k, n, l) = (4*q + r - t < n*t) \ ? ["${n}${first?'.':''}", false, 10*q, 10*(r - n*t), t , k , 10*(3*q + r)/t - 10*n , l ] \ : ['' , first, q*k , (2*q + r)*l , t*l, k + 1, (q*(7*k + 2) + r*l)/(t*l), l + 2] print nn }
443Pi
7groovy
zaut5
public class Pernicious{
441Pernicious numbers
9java
kmohm
null
444Permutations/Derangements
1lua
5dpu6
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public enum ImgDiffPercent { ; public static void main(String[] args) throws IOException {
453Percentage difference between images
9java
1l1p2
from __future__ import division from random import random from math import fsum n, p, t = 100, 0.5, 500 def newv(n, p): return [int(random() < p) for i in range(n)] def runs(v): return sum((a & ~b) for a, b in zip(v, v[1:] + [0])) def mean_run_density(n, p): return runs(newv(n, p)) / n for p10 in range(1, 10, 2): p = p10 / 10 limit = p * (1 - p) print('') for n2 in range(10, 16, 2): n = 2**n2 sim = fsum(mean_run_density(n, p) for i in range(t)) / t print('t=%3i p=%4.2f n=%5i p(1-p)=%5.3f sim=%5.3f delta=%3.1f%%' % (t, p, n, limit, sim, abs(sim - limit) / limit * 100 if limit else sim * 100))
447Percolation/Mean run density
3python
731rm
shuffle :: [a] -> [a] shuffle lst = let (a,b) = splitAt (length lst `div` 2) lst in foldMap (\(x,y) -> [x,y]) $ zip a b findCycle :: Eq a => (a -> a) -> a -> [a] findCycle f x = takeWhile (/= x) $ iterate f (f x) main = mapM_ report [ 8, 24, 52, 100, 1020, 1024, 10000 ] where report n = putStrLn ("deck of " ++ show n ++ " cards: " ++ show (countSuffles n) ++ " shuffles!") countSuffles n = 1 + length (findCycle shuffle [1..n])
452Perfect shuffle
8haskell
kmbh0
pi_ = g (1, 0, 1, 1, 3, 3) where g (q, r, t, k, n, l) = if 4 * q + r - t < n * t then n: g ( 10 * q , 10 * (r - n * t) , t , k , div (10 * (3 * q + r)) t - 10 * n , l) else g ( q * k , (2 * q + r) * l , t * l , k + 1 , div (q * (7 * k + 2) + r * l) (t * l) , l + 2)
443Pi
8haskell
b98k2
error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING )); define('MAXSCORE', 100); define('PLAYERCOUNT', 2); $confirm = array('Y', 'y', ''); while (true) { printf(' Player%d: (%d,%d) Rolling? (Yn) ', $player, $safeScore[$player], $score); if ($safeScore[$player] + $score < MAXSCORE && in_array(trim(fgets(STDIN)), $confirm)) { $rolled = rand(1, 6); echo ; if ($rolled == 1) { printf(' Bust! You lose%d but keep%d \n\n', $score, $safeScore[$player]); } else { $score += $rolled; continue; } } else { $safeScore[$player] += $score; if ($safeScore[$player] >= MAXSCORE) break; echo ' Sticking with ', $safeScore[$player], '\n\n'; } $score = 0; $player = ($player + 1) % PLAYERCOUNT; } printf('\n\nPlayer%d wins with a score of%d ', $player, $safeScore[$player]);
434Pig the dice game
12php
8740m
use feature 'say'; my $s = "rosetta code phrase reversal"; say "0. Input : ", $s; say "1. String reversed : ", scalar reverse $s; say "2. Each word reversed : ", join " ", reverse split / /, reverse $s; say "3. Word-order reversed: ", join " ", reverse split / /,$s; say "2. Each word reversed : ", $s =~ s/[^ ]+/reverse $&/gre;
437Phrase reversals
2perl
c0a9a
from operator import itemgetter DEBUG = False def spermutations(n): sign = 1 p = [[i, 0 if i == 0 else -1] for i in range(n)] if DEBUG: print ' yield tuple(pp[0] for pp in p), sign while any(pp[1] for pp in p): i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]), key=itemgetter(1)) sign *= -1 if d1 == -1: i2 = i1 - 1 p[i1], p[i2] = p[i2], p[i1] if i2 == 0 or p[i2 - 1][0] > n1: p[i2][1] = 0 elif d1 == 1: i2 = i1 + 1 p[i1], p[i2] = p[i2], p[i1] if i2 == n - 1 or p[i2 + 1][0] > n1: p[i2][1] = 0 if DEBUG: print ' yield tuple(pp[0] for pp in p), sign for i3, pp in enumerate(p): n3, d3 = pp if n3 > n1: pp[1] = 1 if i3 < i2 else -1 if DEBUG: print ' if __name__ == '__main__': from itertools import permutations for n in (3, 4): print '\nPermutations and sign of%i items'% n sp = set() for i in spermutations(n): sp.add(i[0]) print('Perm:%r Sign:%2i'% i) p = set(permutations(range(n))) assert sp == p, 'Two methods of generating permutations do not agree'
442Permutations by swapping
3python
6wg3w
function getImageData(url, callback) { var img = document.createElement('img'); var canvas = document.createElement('canvas'); img.onload = function () { canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); callback(ctx.getImageData(0, 0, img.width, img.height)); }; img.src = url; } function compare(firstImage, secondImage, callback) { getImageData(firstImage, function (img1) { getImageData(secondImage, function (img2) { if (img1.width !== img2.width || img1.height != img2.height) { callback(NaN); return; } var diff = 0; for (var i = 0; i < img1.data.length / 4; i++) { diff += Math.abs(img1.data[4 * i + 0] - img2.data[4 * i + 0]) / 255; diff += Math.abs(img1.data[4 * i + 1] - img2.data[4 * i + 1]) / 255; diff += Math.abs(img1.data[4 * i + 2] - img2.data[4 * i + 2]) / 255; } callback(100 * diff / (img1.width * img1.height * 3)); }); }); } compare('Lenna50.jpg', 'Lenna100.jpg', function (result) { console.log(result); });
453Percentage difference between images
10javascript
q4qx8
import java.util.Arrays; import java.util.stream.IntStream; public class PerfectShuffle { public static void main(String[] args) { int[] sizes = {8, 24, 52, 100, 1020, 1024, 10_000}; for (int size : sizes) System.out.printf("%5d:%5d%n", size, perfectShuffle(size)); } static int perfectShuffle(int size) { if (size % 2 != 0) throw new IllegalArgumentException("size must be even"); int half = size / 2; int[] a = IntStream.range(0, size).toArray(); int[] original = a.clone(); int[] aa = new int[size]; for (int count = 1; true; count++) { System.arraycopy(a, 0, aa, 0, size); for (int i = 0; i < half; i++) { a[2 * i] = aa[i]; a[2 * i + 1] = aa[i + half]; } if (Arrays.equals(a, original)) return count; } } }
452Perfect shuffle
9java
4fg58
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
438Playing cards
9java
db4n9
''' See: http: This program scores and throws the dice for a two player game of Pig ''' from random import randint playercount = 2 maxscore = 100 safescore = [0] * playercount player = 0 score=0 while max(safescore) < maxscore: rolling = input( % (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''} if rolling: rolled = randint(1, 6) print(' Rolled%i'% rolled) if rolled == 1: print(' Bust! you lose%i but still keep your previous%i' % (score, safescore[player])) score, player = 0, (player + 1)% playercount else: score += rolled else: safescore[player] += score if safescore[player] >= maxscore: break print(' Sticking with%i'% safescore[player]) score, player = 0, (player + 1)% playercount print('\nPlayer%i wins with a score of%i'%(player, safescore[player]))
434Pig the dice game
3python
5doux
null
441Pernicious numbers
11kotlin
gtx4d
null
453Percentage difference between images
11kotlin
j6j7r
int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf(, n); return 0; }
455Perfect numbers
5c
9q6m1
(() => { 'use strict';
452Perfect shuffle
10javascript
hykjh
def perlin_noise(x, y, z): X = int(x) & 255 Y = int(y) & 255 Z = int(z) & 255 x -= int(x) y -= int(y) z -= int(z) u = fade(x) v = fade(y) w = fade(z) A = p[X ]+Y; AA = p[A]+Z; AB = p[A+1]+Z B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))) def fade(t): return t ** 3 * (t * (t * 6 - 15) + 10) def lerp(t, a, b): return a + t * (b - a) def grad(hash, x, y, z): h = hash & 15 u = x if h<8 else y v = y if h<4 else (x if h in (12, 14) else z) return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v) p = [None] * 512 permutation = [151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180] for i in range(256): p[256+i] = p[i] = permutation[i] if __name__ == '__main__': print(% perlin_noise(3.14, 42, 7))
445Perlin noise
3python
2ojlz
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def (n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = (n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
450Perfect totient numbers
3python
3emzc
function Card(pip, suit) { this.pip = pip; this.suit = suit; this.toString = function () { return this.pip + ' ' + this.suit; }; } function Deck() { var pips = '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' '); var suits = 'Clubs Hearts Spades Diamonds'.split(' '); this.deck = []; for (var i = 0; i < suits.length; i++) for (var j = 0; j < pips.length; j++) this.deck.push(new Card(pips[j], suits[i])); this.toString = function () { return '[' + this.deck.join(', ') + ']'; }; this.shuffle = function () { for (var i = 0; i < this.deck.length; i++) this.deck[i] = this.deck.splice( parseInt(this.deck.length * Math.random()), 1, this.deck[i])[0]; }; this.deal = function () { return this.deck.shift(); }; }
438Playing cards
10javascript
6wh38
<?php $strin = ; echo .$strin.; echo .strrev($strin).; $str_words_reversed = ; $temp = explode(, $strin); foreach($temp as $word) $str_words_reversed .= strrev($word).; echo .$str_words_reversed.; $str_word_order_reversed = ; $temp = explode(, $strin); for($i=(count($temp)-1); $i>=0; $i--) $str_word_order_reversed .= $temp[$i].; echo .$str_word_order_reversed.;
437Phrase reversals
12php
x59w5
Bitmap.loadPPM = function(self, filename) local fp = io.open( filename, "rb" ) if fp == nil then return false end local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line") self.width, self.height = width, height self:alloc() self:clear( {0,0,0} ) for y = 1, self.height do for x = 1, self.width do self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) } end end fp:close() return true end Bitmap.percentageDifference = function(self, other) if self.width ~= other.width or self.height ~= other.height then return end local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels for y = 1, self.height do for x = 1, self.width do local sp, op = spx[y][x], opx[y][x] dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3]) end end return dif/255/self.width/self.height/3*100 end local bm50 = Bitmap(0,0) bm50:loadPPM("Lenna50.ppm") local bm100 = Bitmap(0,0) bm100:loadPPM("Lenna100.ppm") print("%diff:", bm100:percentageDifference(bm50))
453Percentage difference between images
1lua
hyhj8
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
443Pi
9java
gte4m
null
441Pernicious numbers
1lua
rzqga
sub d { $ grep { $_[$_] != @{$_[0]} } 1 .. $ : $_[0] } sub deranged { my ($result, @avail) = @_; return $result if !@avail; my @list; for my $i (0 .. $ next if $avail[$i] == @$result; my $e = splice @avail, $i, 1; push @list, deranged([ @$result, $e ], @avail); splice @avail, $i, 0, $e; } return @list; } sub choose { my ($n, $k) = @_; factorial($n) / factorial($k) / factorial($n - $k) } my @fact = (1); sub factorial { $fact[ $_[0] ] //= $_[0] * factorial($_[0] - 1) } my @subfact; sub sub_factorial { my $n = shift; $subfact[$n] //= do { my $total = factorial($n); for my $k (1 .. $n) { $total -= choose($n, $k) * sub_factorial($n - $k) } $total } } print "Derangements for 4 elements:\n"; my @deranged = d([], 0 .. 3); for (1 .. @deranged) { print "$_: @{$deranged[$_-1]}\n" } print "\nCompare list length and calculated table\n"; for (0 .. 9) { my @x = d([], 0 .. $_-1); print $_, "\t", scalar(@x), "\t", sub_factorial($_), "\n" } print "\nNumber of derangements:\n"; print "$_:\t", sub_factorial($_), "\n" for 1 .. 20;
444Permutations/Derangements
2perl
8760w
def perms(n) p = Array.new(n+1){|i| -i} s = 1 loop do yield p[1..-1].map(&:abs), s k = 0 for i in 2..n k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs end for i in 1...n k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs end break if k.zero? for i in 1..n p[i] *= -1 if p[i].abs > p[k].abs end i = k + (p[k] <=> 0) p[k], p[i] = p[i], p[k] s = -s end end for i in 3..4 perms(i){|perm, sign| puts } puts end
442Permutations by swapping
14ruby
mq7yj
int main (int argc, char *argv[]) { if (argc < 2) { printf(); return 0; } int x; for (x = 0; argv[1][x] != '\0'; x++); int f, v, m; for(f=0; f < x; f++) { for(v = x-1; v > f; v-- ) { if (argv[1][v-1] > argv[1][v]) { m=argv[1][v-1]; argv[1][v-1]=argv[1][v]; argv[1][v]=m; } } } char a[x]; int k=0; int fact=k+1; while (k!=x) { a[k]=argv[1][k]; k++; fact = k*fact; } a[k]='\0'; int i, j; int y=0; char c; while (y != fact) { printf(, a); i=x-2; while(a[i] > a[i+1] ) i--; j=x-1; while(a[j] < a[i] ) j--; c=a[j]; a[j]=a[i]; a[i]=c; i++; for (j = x-1; j > i; i++, j--) { c = a[i]; a[i] = a[j]; a[j] = c; } y++; } }
456Permutations
5c
mxzys
null
452Perfect shuffle
11kotlin
l82cp
let q = 1n, r = 180n, t = 60n, i = 2n; for (;;) { let y = (q*(27n*i-12n)+5n*r)/(5n*t); let u = 3n*(3n*i+1n)*(3n*i+2n); r = 10n*u*(q*(5n*i-2n)+r-y*t); q = 10n*q*i*(2n*i-1n); t = t*u; i = i+1n; process.stdout.write(y.toString()); if (i === 3n) { process.stdout.write('.'); } }
443Pi
10javascript
km0hq
null
442Permutations by swapping
15rust
9sjmm
object JohnsonTrotter extends App { private def perm(n: Int): Unit = { val p = new Array[Int](n)
442Permutations by swapping
16scala
2oblb
(defn proper-divisors [n] (if (< n 4) [1] (->> (range 2 (inc (quot n 2))) (filter #(zero? (rem n %))) (cons 1)))) (defn perfect? [n] (= (reduce + (proper-divisors n)) n))
455Perfect numbers
6clojure
uilvi
null
452Perfect shuffle
1lua
2ovl3
require class Integer def prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end def perfect_totient? f, sum = self, 0 until f == 1 do f = f. sum += f end self == sum end end puts (1..).lazy.select(&:perfect_totient?).first(20).join()
450Perfect totient numbers
14ruby
yxc6n
const val FACES = "23456789TJQKA" const val SUITS = "shdc" fun createDeck(): List<String> { val cards = mutableListOf<String>() FACES.forEach { face -> SUITS.forEach { suit -> cards.add("$face$suit") } } return cards } fun dealTopDeck(deck: List<String>, n: Int) = deck.take(n) fun dealBottomDeck(deck: List<String>, n: Int) = deck.takeLast(n).reversed() fun printDeck(deck: List<String>) { for (i in deck.indices) { print("${deck[i]} ") if ((i + 1) % 13 == 0 || i == deck.size - 1) println() } } fun main(args: Array<String>) { var deck = createDeck() println("After creation, deck consists of:") printDeck(deck) deck = deck.shuffled() println("\nAfter shuffling, deck consists of:") printDeck(deck) val dealtTop = dealTopDeck(deck, 10) println("\nThe 10 cards dealt from the top of the deck are:") printDeck(dealtTop) val dealtBottom = dealBottomDeck(deck, 10) println("\nThe 10 cards dealt from the bottom of the deck are:") printDeck(dealtBottom) }
438Playing cards
11kotlin
0rlsf
my @array = qw(a b c); print $array[ rand @array ];
436Pick random element
2perl
mq1yz
fn main() { println!("{}", noise(3.14, 42.0, 7.0)); } fn noise(x: f64, y: f64, z: f64) -> f64 { let x0 = x.floor() as usize & 255; let y0 = y.floor() as usize & 255; let z0 = z.floor() as usize & 255; let x = x - x.floor(); let y = y - y.floor(); let z = z - z.floor(); let u = fade(x); let v = fade(y); let w = fade(z); let a = P[x0] + y0; let aa = P[a] + z0; let ab = P[a + 1] + z0; let b = P[x0 + 1] + y0; let ba = P[b] + z0; let bb = P[b + 1] + z0; return lerp(w, lerp(v, lerp(u, grad(P[aa], x , y , z), grad(P[ba], x-1.0, y , z)), lerp(u, grad(P[ab], x , y-1.0, z), grad(P[bb], x-1.0, y-1.0, z))), lerp(v, lerp(u, grad(P[aa+1], x , y , z-1.0), grad(P[ba+1], x-1.0, y , z-1.0)), lerp(u, grad(P[ab+1], x , y-1.0, z-1.0), grad(P[bb+1], x-1.0, y-1.0, z-1.0)))); } fn fade(t: f64) -> f64 { t * t * t * ( t * (t * 6.0 - 15.0) + 10.0) } fn lerp(t: f64, a: f64, b: f64) -> f64 { a + t * (b - a) } fn grad(hash: usize, x: f64, y: f64, z: f64) -> f64 { let h = hash & 15; let u = if h < 8 { x } else { y }; let v = if h < 4 { y } else { if h == 12 || h == 14 { x } else { z } }; return if h&1 == 0 { u } else { -u } + if h&2 == 0 { v } else { -v }; } static P: [usize; 512] = [151,160,137,91,90,15,131,13,201,95,96,53,194,233, 7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190, 6,148,247,120,234, 75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87, 174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,77,146,158, 231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102, 143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124, 123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189, 28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218, 246,97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249, 14,239,107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156, 180,151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69 ,142,8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219, 203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175, 74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230, 220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161, 1,216,80,73,209, 76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198, 173,186, 3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212, 207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152, 2, 44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108, 110,79,113,224,232,178,185, 112,104,218,246,97,228,251,34,242,193,238, 210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31, 181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205, 93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];
445Perlin noise
15rust
5dbuq
null
450Perfect totient numbers
16scala
l8ucq
class PigGame Player = Struct.new(:name, :safescore, :score) do def bust!() self.score = safescore end def stay!() self.safescore = score end def to_s() end end def initialize(names, maxscore=100, die_sides=6) rotation = names.map {|name| Player.new(name,0,0) } rotation.cycle do |player| loop do if wants_to_roll?(player) puts if bust?(roll) puts ,'' player.bust! break else player.score += roll if player.score >= maxscore puts player.name + return end end else player.stay! puts , '' break end end end end def roll_dice(die_sides) rand(1..die_sides) end def bust?(roll) roll==1 end def wants_to_roll?(player) print ['Y','y',''].include?(gets.chomp) end end PigGame.new( %w|Samuel Elizabeth| )
434Pig the dice game
14ruby
gtn4q
$arr = array('foo', 'bar', 'baz'); $x = $arr[array_rand($arr)];
436Pick random element
12php
evma9
>>> phrase = >>> phrase[::-1] 'lasrever esarhp edoc attesor' >>> ' '.join(word[::-1] for word in phrase.split()) 'attesor edoc esarhp lasrever' >>> ' '.join(phrase.split()[::-1]) 'reversal phrase code rosetta' >>>
437Phrase reversals
3python
l8ecv