task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#C.23
C#
using System; using System.Drawing;   class Program { static void Main() { Bitmap img1 = new Bitmap("Lenna50.jpg"); Bitmap img2 = new Bitmap("Lenna100.jpg");   if (img1.Size != img2.Size) { Console.Error.WriteLine("Images are of different sizes"); return; }   float diff = 0;   for (int y = 0; y < img1.Height; y++) { for (int x = 0; x < img1.Width; x++) { Color pixel1 = img1.GetPixel(x, y); Color pixel2 = img2.GetPixel(x, y);   diff += Math.Abs(pixel1.R - pixel2.R); diff += Math.Abs(pixel1.G - pixel2.G); diff += Math.Abs(pixel1.B - pixel2.B); } }   Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3)); } }
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#C.23
C#
using System; using System.Linq;   namespace PentominoTiling { class Program { static readonly char[] symbols = "FILNPTUVWXYZ-".ToCharArray();   static readonly int nRows = 8; static readonly int nCols = 8; static readonly int target = 12; static readonly int blank = 12;   static int[][] grid = new int[nRows][]; static bool[] placed = new bool[target];   static void Main(string[] args) { var rand = new Random();   for (int r = 0; r < nRows; r++) grid[r] = Enumerable.Repeat(-1, nCols).ToArray();   for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.Next(nRows); randCol = rand.Next(nCols); } while (grid[randRow][randCol] == blank);   grid[randRow][randCol] = blank; }   if (Solve(0, 0)) { PrintResult(); } else { Console.WriteLine("no solution"); }   Console.ReadKey(); }   private static void PrintResult() { foreach (int[] r in grid) { foreach (int i in r) Console.Write("{0} ", symbols[i]); Console.WriteLine(); } }   private static bool Solve(int pos, int numPlaced) { if (numPlaced == target) 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]) { foreach (int[] orientation in 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; }   private static void RemoveOrientation(int[] orientation, int row, int col) { grid[row][col] = -1; for (int i = 0; i < orientation.Length; i += 2) grid[row + orientation[i]][col + orientation[i + 1]] = -1; }   private static bool TryPlaceOrientation(int[] orientation, int row, int col, int shapeIndex) { for (int i = 0; i < orientation.Length; i += 2) { int x = col + orientation[i + 1]; int y = row + orientation[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; }   grid[row][col] = shapeIndex; for (int i = 0; i < orientation.Length; i += 2) grid[row + orientation[i]][col + orientation[i + 1]] = shapeIndex;   return true; }   // four (x, y) pairs are listed, (0,0) not included static readonly int[][] F = { new int[] {1, -1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 1}, new int[] {1, 0, 1, 1, 2, -1, 2, 0}, new int[] {1, -2, 1, -1, 1, 0, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 1}, new int[] {1, -1, 1, 0, 1, 1, 2, -1}, new int[] {1, -1, 1, 0, 2, 0, 2, 1}};   static readonly int[][] I = { new int[] { 0, 1, 0, 2, 0, 3, 0, 4 }, new int[] { 1, 0, 2, 0, 3, 0, 4, 0 } };   static readonly int[][] L = { new int[] {1, 0, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, 0, 3, -1, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 3}, new int[] {0, 1, 1, 0, 2, 0, 3, 0}, new int[] {0, 1, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 0, 3, 1, 0}, new int[] {1, 0, 2, 0, 3, 0, 3, 1}, new int[] {1, -3, 1, -2, 1, -1, 1, 0}};   static readonly int[][] N = { new int[] {0, 1, 1, -2, 1, -1, 1, 0}, new int[] {1, 0, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 1, -1, 1, 0}, new int[] {1, 0, 2, 0, 2, 1, 3, 1}, new int[] {0, 1, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, -1, 2, 0, 3, -1}, new int[] {0, 1, 0, 2, 1, 2, 1, 3}, new int[] {1, -1, 1, 0, 2, -1, 3, -1}};   static readonly int[][] P = { new int[] {0, 1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 0, 2, 1, 0, 1, 1}, new int[] {1, 0, 1, 1, 2, 0, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 1, 1}, new int[] {0, 1, 1, 0, 1, 1, 1, 2}, new int[] {1, -1, 1, 0, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 1, 1, 2, 0}};   static readonly int[][] T = { new int[] {0, 1, 0, 2, 1, 1, 2, 1}, new int[] {1, -2, 1, -1, 1, 0, 2, 0}, new int[] {1, 0, 2, -1, 2, 0, 2, 1}, new int[] {1, 0, 1, 1, 1, 2, 2, 0}};   static readonly int[][] U = { new int[] {0, 1, 0, 2, 1, 0, 1, 2}, new int[] {0, 1, 1, 1, 2, 0, 2, 1}, new int[] {0, 2, 1, 0, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 2, 0, 2, 1}};   static readonly int[][] V = { new int[] {1, 0, 2, 0, 2, 1, 2, 2}, new int[] {0, 1, 0, 2, 1, 0, 2, 0}, new int[] {1, 0, 2, -2, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 2, 2, 2}};   static readonly int[][] W = { new int[] {1, 0, 1, 1, 2, 1, 2, 2}, new int[] {1, -1, 1, 0, 2, -2, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, -1, 1, 0, 2, -1}};   static readonly int[][] X = { new int[] { 1, -1, 1, 0, 1, 1, 2, 0 } };   static readonly int[][] Y = { new int[] {1, -2, 1, -1, 1, 0, 1, 1}, new int[] {1, -1, 1, 0, 2, 0, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 1}, new int[] {1, 0, 2, 0, 2, 1, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 2}, new int[] {1, 0, 1, 1, 2, 0, 3, 0}, new int[] {1, -1, 1, 0, 1, 1, 1, 2}, new int[] {1, 0, 2, -1, 2, 0, 3, 0}};   static readonly int[][] Z = { new int[] {0, 1, 1, 0, 2, -1, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, 1, 2, 1, 2, 2}, new int[] {1, -2, 1, -1, 1, 0, 2, -2}};   static readonly int[][][] shapes = { F, I, L, N, P, T, U, V, W, X, Y, Z }; } }
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Haskell
Haskell
{-# language FlexibleContexts #-} import Data.List import Data.Maybe import System.Random import Control.Monad.State import Text.Printf import Data.Set (Set) import qualified Data.Set as S   type Matrix = [[Bool]] type Cell = (Int, Int) type Cluster = Set (Int, Int)   clusters :: Matrix -> [Cluster] clusters m = unfoldr findCuster cells where cells = S.fromList [ (i,j) | (r, i) <- zip m [0..] , (x, j) <- zip r [0..], x]   findCuster s = do (p, ps) <- S.minView s return $ runState (expand p) ps   expand p = do ns <- state $ extract (neigbours p) xs <- mapM expand $ S.elems ns return $ S.insert p $ mconcat xs   extract s1 s2 = (s2 `S.intersection` s1, s2 S.\\ s1) neigbours (i,j) = S.fromList [(i-1,j),(i+1,j),(i,j-1),(i,j+1)] n = length m   showClusters :: Matrix -> String showClusters m = unlines [ unwords [ mark (i,j) | j <- [0..n-1] ] | i <- [0..n-1] ] where cls = clusters m n = length m mark c = maybe "." snd $ find (S.member c . fst) $ zip cls syms syms = sequence [['a'..'z'] ++ ['A'..'Z']] ------------------------------------------------------------   randomMatrices :: Int -> StdGen -> [Matrix] randomMatrices n = clipBy n . clipBy n . randoms where clipBy n = unfoldr (Just . splitAt n)   randomMatrix n = head . randomMatrices n   tests :: Int -> StdGen -> [Int] tests n = map (length . clusters) . randomMatrices n   task :: Int -> StdGen -> (Int, Double) task n g = (n, result) where result = mean $ take 10 $ map density $ tests n g density c = fromIntegral c / fromIntegral n**2 mean lst = sum lst / genericLength lst   main = newStdGen >>= mapM_ (uncurry (printf "%d\t%.5f\n")) . res where res = mapM task [10,50,100,500]
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Lucas-Lehmer test   is used to find primes of the form   2n-1,   all known perfect numbers can be derived from these primes using the formula   (2n - 1) × 2n - 1. It is not known if there are any odd perfect numbers (any that exist are larger than 102000). The number of   known   perfect numbers is   51   (as of December, 2018),   and the largest known perfect number contains  49,724,095  decimal digits. See also   Rational Arithmetic   Perfect numbers on OEIS   Odd Perfect showing the current status of bounds on odd perfect numbers.
#Ada
Ada
function Is_Perfect(N : Positive) return Boolean is Sum : Natural := 0; begin for I in 1..N - 1 loop if N mod I = 0 then Sum := Sum + I; end if; end loop; return Sum = N; end Is_Perfect;
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Go
Go
package main   import ( "fmt" "math/rand" "strings" "time" )   func main() { const ( m, n = 10, 10 t = 1000 minp, maxp, Δp = 0.1, 0.99, 0.1 )   // Purposely don't seed for a repeatable example grid: g := NewGrid(.5, m, n) g.Percolate() fmt.Println(g)   rand.Seed(time.Now().UnixNano()) // could pick a better seed for p := float64(minp); p < maxp; p += Δp { count := 0 for i := 0; i < t; i++ { g := NewGrid(p, m, n) if g.Percolate() { count++ } } fmt.Printf("p=%.2f, %.3f\n", p, float64(count)/t) } }   type cell struct { full bool right, down bool // true if open to the right (x+1) or down (y+1) }   type grid struct { cell [][]cell // row first, i.e. [y][x] }   func NewGrid(p float64, xsize, ysize int) *grid { g := &grid{cell: make([][]cell, ysize)} for y := range g.cell { g.cell[y] = make([]cell, xsize) for x := 0; x < xsize-1; x++ { if rand.Float64() > p { g.cell[y][x].right = true } if rand.Float64() > p { g.cell[y][x].down = true } } if rand.Float64() > p { g.cell[y][xsize-1].down = true } } return g }   var ( full = map[bool]string{false: " ", true: "**"} hopen = map[bool]string{false: "--", true: " "} vopen = map[bool]string{false: "|", true: " "} )   func (g *grid) String() string { var buf strings.Builder // Don't really need to call Grow but it helps avoid multiple // reallocations if the size is large. buf.Grow((len(g.cell) + 1) * len(g.cell[0]) * 7)   for _ = range g.cell[0] { buf.WriteString("+") buf.WriteString(hopen[false]) } buf.WriteString("+\n") for y := range g.cell { buf.WriteString(vopen[false]) for x := range g.cell[y] { buf.WriteString(full[g.cell[y][x].full]) buf.WriteString(vopen[g.cell[y][x].right]) } buf.WriteByte('\n') for x := range g.cell[y] { buf.WriteString("+") buf.WriteString(hopen[g.cell[y][x].down]) } buf.WriteString("+\n") } ly := len(g.cell) - 1 for x := range g.cell[ly] { buf.WriteByte(' ') buf.WriteString(full[g.cell[ly][x].down && g.cell[ly][x].full]) } return buf.String() }   func (g *grid) Percolate() bool { for x := range g.cell[0] { if g.fill(x, 0) { return true } } return false }   func (g *grid) fill(x, y int) bool { if y >= len(g.cell) { return true // Out the bottom } if g.cell[y][x].full { return false // Allready filled } g.cell[y][x].full = true   if g.cell[y][x].down && g.fill(x, y+1) { return true } if g.cell[y][x].right && g.fill(x+1, y) { return true } if x > 0 && g.cell[y][x-1].right && g.fill(x-1, y) { return true } if y > 0 && g.cell[y-1][x].down && g.fill(x, y-1) { return true } return false }
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\displaystyle v} be a vector of n {\displaystyle n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} ; the probability of a value being 0 is therefore 1 − p {\displaystyle 1-p} . Define a run of 1s as being a group of consecutive 1s in the vector bounded either by the limits of the vector or by a 0. Let the number of such runs in a given vector of length n {\displaystyle n} be R n {\displaystyle R_{n}} . For example, the following vector has R 10 = 3 {\displaystyle R_{10}=3} [1 1 0 0 0 1 0 1 1 1] ^^^ ^ ^^^^^ Percolation theory states that K ( p ) = lim n → ∞ R n / n = p ( 1 − p ) {\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)} Task Any calculation of R n / n {\displaystyle R_{n}/n} for finite n {\displaystyle n} is subject to randomness so should be computed as the average of t {\displaystyle t} runs, where t ≥ 100 {\displaystyle t\geq 100} . For values of p {\displaystyle p} of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} . Show your output here. See also s-Run on Wolfram mathworld.
#Go
Go
package main   import ( "fmt" "math/rand" )   var ( pList = []float64{.1, .3, .5, .7, .9} nList = []int{1e2, 1e3, 1e4, 1e5} t = 100 )   func main() { for _, p := range pList { theory := p * (1 - p) fmt.Printf("\np: %.4f theory: %.4f t: %d\n", p, theory, t) fmt.Println(" n sim sim-theory") for _, n := range nList { sum := 0 for i := 0; i < t; i++ { run := false for j := 0; j < n; j++ { one := rand.Float64() < p if one && !run { sum++ } run = one } } K := float64(sum) / float64(t) / float64(n) fmt.Printf("%9d %15.4f %9.6f\n", n, K, K-theory) } } }
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#J
J
groups=:[: +/\ 2 </\ 0 , * ooze=: [ >. [ +&* [ * [: ; groups@[ <@(* * 2 < >./)/. + percolate=: ooze/\.@|.^:2^:_@(* (1 + # {. 1:))   trial=: percolate@([ >: ]?@$0:) simulate=: %@[ * [: +/ (2 e. {:)@trial&15 15"0@#
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Julia
Julia
using Printf, Distributions   newgrid(p::Float64, M::Int=15, N::Int=15) = rand(Bernoulli(p), M, N)   function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int) NOT_VISITED = 1 # const N, M = size(grid) dirs = [[1, 0], [-1, 0], [0, 1], [1, 0]] # fill cell grid[r, c] = indx   # is the bottom line? rst = r == N   # for each direction, if has not reached the bottom yet and can continue go to that direction for d in dirs rr, cc = (r, c) .+ d if !rst && checkbounds(Bool, grid, rr, cc) && grid[rr, cc] == NOT_VISITED rst = walkmaze!(grid, rr, cc, indx) end end return rst end   function checkpath!(grid::Matrix{Int}) NOT_VISITED = 1 # const N, M = size(grid) walkind = 1 for m in 1:M if grid[1, m] == NOT_VISITED walkind += 1 if walkmaze!(grid, 1, m, walkind) return true end end end return false end   function printgrid(G::Matrix{Int}) LETTERS = vcat(' ', '#', 'A':'Z') for r in 1:size(G, 1) println(r % 10, ") ", join(LETTERS[G[r, :] .+ 1], ' ')) end if any(G[end, :] .> 1) println("!) ", join((ifelse(c > 1, LETTERS[c+1], ' ') for c in G[end, :]), ' ')) end end   const nrep = 1000 # const sampleprinted = false   p = collect(0.0:0.1:1.0) f = similar(p) for i in linearindices(f) c = 0 for _ in 1:nrep G = newgrid(p[i]) perc = checkpath!(G) if perc c += 1 if !sampleprinted @printf("Sample percolation, %i×%i grid, p = %.2f\n\n", size(G, 1), size(G, 2), p[i]) printgrid(G) sampleprinted = true end end end f[i] = c / nrep end   println("\nFrequencies for $nrep tries that percolate through\n") for (pi, fi) in zip(p, f) @printf("p = %.1f ⇛ f = %.3f\n", pi, fi) end
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Aime
Aime
void f1(record r, ...) { if (~r) { for (text s in r) { r.delete(s); rcall(f1, -2, 0, -1, s); r[s] = 0; } } else { ocall(o_, -2, 1, -1, " ", ","); o_newline(); } }   main(...) { record r;   ocall(r_put, -2, 1, -1, r, 0); f1(r);   0; }
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#C.2B.2B
C++
  #include <iostream> #include <algorithm> #include <vector>   int pShuffle( int t ) { std::vector<int> v, o, r;   for( int x = 0; x < t; x++ ) { o.push_back( x + 1 ); }   r = o; int t2 = t / 2 - 1, c = 1;   while( true ) { v = r; r.clear();   for( int x = t2; x > -1; x-- ) { r.push_back( v[x + t2 + 1] ); r.push_back( v[x] ); }   std::reverse( r.begin(), r.end() );   if( std::equal( o.begin(), o.end(), r.begin() ) ) return c; c++; } }   int main() { int s[] = { 8, 24, 52, 100, 1020, 1024, 10000 }; for( int x = 0; x < 7; x++ ) { std::cout << "Cards count: " << s[x] << ", shuffles required: "; std::cout << pShuffle( s[x] ) << ".\n"; } return 0; }  
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Go
Go
package main   import ( "fmt" "math" )   func main() { fmt.Println(noise(3.14, 42, 7)) }   func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(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)))) } func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) } func lerp(t, a, b float64) float64 { return a + t*(b-a) } func grad(hash int, x, y, z float64) float64 { // Go doesn't have a ternary. Ternaries can be translated directly // with if statements, but chains of if statements are often better // expressed with switch statements. switch hash & 15 { case 0, 12: return x + y case 1, 14: return y - x case 2: return x - y case 3: return -x - y case 4: return x + z case 5: return z - x case 6: return x - z case 7: return -x - z case 8: return y + z case 9, 13: return z - y case 10: return y - z } // case 11, 16: return -y - z }   var permutation = []int{ 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, } var p = append(permutation, permutation...)
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#FreeBASIC
FreeBASIC
#include"totient.bas"   dim as uinteger found = 0, curr = 3, sum, toti   while found < 20 sum = totient(curr) toti = sum do toti = totient(toti) sum += toti loop while toti <> 1 if sum = curr then print sum found += 1 end if curr += 1 wend
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Go
Go
package main   import "fmt"   func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") }   s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 }   t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { t >>= 1 } if t > 0 { n = t } else { k = -t } t = n - k } return n * s }   func totient(n int) int { tot := 0 for k := 1; k <= n; k++ { if gcd(n, k) == 1 { tot++ } } return tot }   func main() { var perfect []int for n := 1; len(perfect) < 20; n += 2 { tot := n sum := 0 for tot != 1 { tot = totient(tot) sum += tot } if sum == n { perfect = append(perfect, n) } } fmt.Println("The first 20 perfect totient numbers are:") fmt.Println(perfect) }
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card must have a pip value and a suit value which constitute the unique value of the card. Related tasks: Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser Go Fish
#Fantom
Fantom
  enum class Suit { clubs, diamonds, hearts, spades } enum class Pips { ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king }   class Card { readonly Suit suit readonly Pips pips   new make (Suit suit, Pips pips) { this.suit = suit this.pips = pips }   override Str toStr () { "card: $pips of $suit" } }   class Deck { Card[] deck := [,]   new make () { Suit.vals.each |val| { Pips.vals.each |pip| { deck.add (Card(val, pip)) } } }   Void shuffle (Int swaps := 50) { swaps.times { deck.swap(Int.random(0..deck.size-1), Int.random(0..deck.size-1)) } }   Card[] deal (Int cards := 1) { if (cards > deck.size) throw ArgErr("$cards is larger than ${deck.size}") Card[] result := [,] cards.times { result.push (deck.removeAt (0)) } return result }   Void show () { deck.each |card| { echo (card.toStr) } } }   class PlayingCards { public static Void main () { deck := Deck() deck.shuffle Card[] hand := deck.deal (7) echo ("Dealt hand is:") hand.each |card| { echo (card.toStr) } echo ("Remaining deck is:") deck.show } }  
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ... Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions. Related Task Arithmetic-geometric mean/Calculate Pi
#Erlang
Erlang
% Implemented by Arjun Sunel -module(pi_calculation). -export([main/0]).   main() -> pi(1,0,1,1,3,3,0).   pi(Q,R,T,K,N,L,C) ->   if C=:=50 -> io:format("\n"), pi(Q,R,T,K,N,L,0) ;   true ->   if (4*Q + R-T) < (N*T) -> io:format("~p",[N]), P = 10*(R-N*T), pi(Q*10 , P, T , K , ((10*(3*Q+R)) div T)-10*N , L,C+1);   true -> P = (2*Q+R)*L, M = (Q*(7*K)+2+(R*L)) div (T*L), H = L+2, J =K+ 1, pi(Q*K, P , T*L ,J,M,H,C) end end.  
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   1   loses the player's total points   for that turn   and their turn finishes with play passing to the next player. Holding:   the player's score for that round is added to their total and becomes safe from the effects of throwing a   1   (one).   The player's turn finishes with play passing to the next player. Task Create a program to score for, and simulate dice throws for, a two-person game. Related task   Pig the dice game/Player
#Maple
Maple
pig := proc() local Points, pointsThisTurn, answer, rollNum, i, win; randomize(); Points := [0, 0]; win := [false, 0]; while not win[1] do for i to 2 do if not win[1] then printf("Player %a's turn.\n", i); answer := ""; pointsThisTurn := 0; while not answer = "HOLD" do while not answer = "ROLL" and not answer = "HOLD" do printf("Would you like to ROLL or HOLD?\n"); answer := StringTools:-UpperCase(readline()); if not answer = "ROLL" and not answer = "HOLD" then printf("Invalid answer.\n\n"); end if; end do; if answer = "ROLL" then rollNum := rand(1..6)(); printf("You rolled a %a!\n", rollNum); if rollNum = 1 then pointsThisTurn := 0; answer := "HOLD"; else pointsThisTurn := pointsThisTurn + rollNum; answer := ""; printf("Your points so far this turn: %a.\n\n", pointsThisTurn); end if; end if; end do; printf("This turn is over! Player %a gained %a points this turn.\n\n", i, pointsThisTurn); Points[i] := Points[i] + pointsThisTurn; if Points[i] >= 100 then win := [true, i]; end if; printf("Player 1 has %a points. Player 2 has %a points.\n\n", Points[1], Points[2]); end if; end do; end do; printf("Player %a won with %a points!\n", win[2], Points[win[2]]); end proc;   pig();
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pernicious number. Task display the first   25   pernicious numbers   (in decimal). display all pernicious numbers between   888,888,877   and   888,888,888   (inclusive). display each list of integers on one line   (which may or may not include a title). See also Sequence   A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences. Rosetta Code entry   population count, evil numbers, odious numbers.
#Forth
Forth
: popcount { n -- u } 0 begin n 0<> while n n 1- and to n 1+ repeat ;   \ primality test for 0 <= n <= 63 : prime? ( n -- ? ) 1 swap lshift 0x28208a20a08a28ac and 0<> ;   : pernicious? ( n -- ? ) popcount prime? ;   : first_n_pernicious_numbers { n -- } ." First " n . ." pernicious numbers:" cr 1 begin n 0 > while dup pernicious? if dup . n 1- to n then 1+ repeat drop cr ;   : pernicious_numbers_between { m n -- } ." Pernicious numbers between " m . ." and " n 1 .r ." :" cr n 1+ m do i pernicious? if i . then loop cr ;   25 first_n_pernicious_numbers 888888877 888888888 pernicious_numbers_between   bye
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them. Task Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind. See also Wikipedia - Pierpont primes OEIS:A005109 - Class 1 -, or Pierpont primes OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl   pierpont = [] limit1 = 18 limit2 = 8505000 limit3 = 50 limit4 = 21 limit5 = 30500000   for n = 0 to limit1 for m = 0 to limit1 num = pow(2,n)*pow(3,m) + 1 if isprime(num) and num < limit2 add(pierpont,num) ok if num > limit2 exit ok next next   pierpont = sort(pierpont)   see "First 50 Pierpont primes of the first kind:" + nl + nl   for n = 1 to limit3 see "" + n + ". " + pierpont[n] + nl next   see "done1..." + nl   pierpont = []   for n = 0 to limit4 for m = 0 to limit4 num = pow(2,n)*pow(3,m) - 1 if isprime(num) and num < limit5 add(pierpont,num) ok if num > limit5 exit ok next next   pierpont = sort(pierpont)   see "First 50 Pierpont primes of the second kind:" + nl + nl   for n = 1 to limit3 see "" + n + ". " + pierpont[n] + nl next   see "done2..." + nl  
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them. Task Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind. See also Wikipedia - Pierpont primes OEIS:A005109 - Class 1 -, or Pierpont primes OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
#Ruby
Ruby
require 'gmp'   def smooth_generator(ar) return to_enum(__method__, ar) unless block_given? next_smooth = 1 queues = ar.map{|num| [num, []] } loop do yield next_smooth queues.each {|m, queue| queue << next_smooth * m} next_smooth = queues.collect{|m, queue| queue.first}.min queues.each{|m, queue| queue.shift if queue.first == next_smooth } end end   def pierpont(num = 1) return to_enum(__method__, num) unless block_given? smooth_generator([2,3]).each{|smooth| yield smooth+num if GMP::Z(smooth + num).probab_prime? > 0} end   def puts_cols(ar, n=10) ar.each_slice(n).map{|slice|puts slice.map{|n| n.to_s.rjust(10)}.join } end   n, m = 50, 250 puts "First #{n} Pierpont primes of the first kind:" puts_cols(pierpont.take(n)) puts "#{m}th Pierpont prime of the first kind: #{pierpont.take(250).last}","" puts "First #{n} Pierpont primes of the second kind:" puts_cols(pierpont(-1).take(n)) puts "#{m}th Pierpont prime of the second kind: #{pierpont(-1).take(250).last}"  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Icon_and_Unicon
Icon and Unicon
procedure main() L := [1,2,3] # a list x := ?L # random element end
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#J
J
({~ ?@#) 'abcdef' b
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#zkl
zkl
fcn isPrime(n){ if(n.isEven or n<2) return(n==2); (not [3..n.toFloat().sqrt().toInt(),2].filter1('wrap(m){n%m==0})) }
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Java
Java
import java.util.Arrays;   public class PhraseRev{ private static String reverse(String x){ return new StringBuilder(x).reverse().toString(); }   private static <T> T[] reverse(T[] x){ T[] rev = Arrays.copyOf(x, x.length); for(int i = x.length - 1; i >= 0; i--){ rev[x.length - 1 - i] = x[i]; } return rev; }   private static String join(String[] arr, String joinStr){ StringBuilder joined = new StringBuilder(); for(int i = 0; i < arr.length; i++){ joined.append(arr[i]); if(i < arr.length - 1) joined.append(joinStr); } return joined.toString(); }   public static void main(String[] args){ String str = "rosetta code phrase reversal";   System.out.println("Straight-up reversed: " + reverse(str)); String[] words = str.split(" "); for(int i = 0; i < words.length; i++){ words[i] = reverse(words[i]); } System.out.println("Reversed words: " + join(words, " ")); System.out.println("Reversed word order: " + join(reverse(str.split(" ")), " ")); } }
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n. Task Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer). Generate and show all the derangements of 4 integers using the above routine. Create a function that calculates the subfactorial of n, !n. Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive. Optional stretch goal   Calculate    !20 Related tasks   Anagrams/Deranged anagrams   Best shuffle   Left_factorials Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#GAP
GAP
# All of this is built-in Derangements([1 .. 4]); # [ [ 2, 1, 4, 3 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 3, 1, 4, 2 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ], # [ 4, 1, 2, 3 ], [ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ] ] Size(last); # 9   NrDerangements([1 .. 4]); # 9   # An implementation using formula D(n + 1) = n*(D(n) + D(n - 1)) NrDerangementsAlt_memo := [1, 0]; NrDerangementsAlt := function(n) if not IsBound(NrDerangementsAlt_memo[n + 1]) then NrDerangementsAlt_memo[n + 1] := (n - 1)*(NrDerangementsAlt(n - 1) + NrDerangementsAlt(n - 2)); fi; return NrDerangementsAlt_memo[n + 1]; end;   L := List([0 .. 9]);   PrintArray(TransposedMat([L, List(L, n -> Size(Derangements([1 .. n]))), List(L, n -> NrDerangements([1 .. n])), List(L, NrDerangementsAlt)])); # [ [ 0, 1, 1, 1 ], # [ 1, 0, 0, 0 ], # [ 2, 1, 1, 1 ], # [ 3, 2, 2, 2 ], # [ 4, 9, 9, 9 ], # [ 5, 44, 44, 44 ], # [ 6, 265, 265, 265 ], # [ 7, 1854, 1854, 1854 ], # [ 8, 14833, 14833, 14833 ], # [ 9, 133496, 133496, 133496 ] ]
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#J
J
bfsjt0=: _1 - i. lookingat=: 0 >. <:@# <. i.@# + * next=: | >./@:* | > | {~ lookingat bfsjtn=: (((] <@, ] + *@{~) | i. next) C. ] * _1 ^ next < |)^:(*@next)
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#Java
Java
package org.rosettacode.java;   import java.util.Arrays; import java.util.stream.IntStream;   public class HeapsAlgorithm {   public static void main(String[] args) { Object[] array = IntStream.range(0, 4) .boxed() .toArray(); HeapsAlgorithm algorithm = new HeapsAlgorithm(); algorithm.recursive(array); System.out.println(); algorithm.loop(array); }   void recursive(Object[] array) { recursive(array, array.length, true); }   void recursive(Object[] array, int n, boolean plus) { if (n == 1) { output(array, plus); } else { for (int i = 0; i < n; i++) { recursive(array, n - 1, i == 0); swap(array, n % 2 == 0 ? i : 0, n - 1); } } }   void output(Object[] array, boolean plus) { System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1")); }   void swap(Object[] array, int a, int b) { Object o = array[a]; array[a] = array[b]; array[b] = o; }   void loop(Object[] array) { loop(array, array.length); }   void loop(Object[] array, int n) { int[] c = new int[n]; output(array, true); boolean plus = false; for (int i = 0; i < n; ) { if (c[i] < i) { if (i % 2 == 0) { swap(array, 0, i); } else { swap(array, c[i], i); } output(array, plus); plus = !plus; c[i]++; i = 0; } else { c[i] = 0; i++; } } } }
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment subjects, or to a group of m {\displaystyle m} control subjects. Members of the treatment group were given the treatment, and members of the control group were given a placebo. The effect of the treatment or placebo on each volunteer was measured and reported in this table. Table of experimental results Treatment group Control group 85 68 88 41 75 10 66 49 25 16 29 65 83 32 39 92 97 28 98 Write a program that performs a permutation test to judge whether the treatment had a significantly stronger effect than the placebo. Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size n {\displaystyle n} and a control group of size m {\displaystyle m} (i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless. Note that the number of alternatives will be the binomial coefficient ( n + m n ) {\displaystyle {\tbinom {n+m}{n}}} . Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group. Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater. Note that they should sum to 100%. Extremely dissimilar values are evidence of an effect not entirely due to chance, but your program need not draw any conclusions. You may assume the experimental data are known at compile time if that's easier than loading them at run time. Test your solution on the data given above.
#Phix
Phix
constant data = {85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 } function pick(int at, int remain, int accu, int treat) if remain=0 then return iff(accu>treat?1:0) end if return pick(at-1, remain-1, accu+data[at], treat) + iff(at>remain?pick(at-1, remain, accu, treat):0) end function int treat = 0, le, gt atom total = 1; for i=1 to 9 do treat += data[i] end for for i=19 to 11 by -1 do total *= i end for for i=9 to 1 by -1 do total /= i end for gt = pick(19, 9, 0, treat) le = total - gt; printf(1,"<= : %f%%  %d\n > : %f%%  %d\n", {100*le/total, le, 100*gt/total, gt})
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#C.2B.2B
C++
#include <QImage> #include <cstdlib> #include <QColor> #include <iostream>   int main( int argc , char *argv[ ] ) { if ( argc != 3 ) { std::cout << "Call this with imagecompare <file of image 1>" << " <file of image 2>\n" ; return 1 ; } QImage firstImage ( argv[ 1 ] ) ; QImage secondImage ( argv[ 2 ] ) ; double totaldiff = 0.0 ; //holds the number of different pixels int h = firstImage.height( ) ; int w = firstImage.width( ) ; int hsecond = secondImage.height( ) ; int wsecond = secondImage.width( ) ; if ( w != wsecond || h != hsecond ) { std::cerr << "Error, pictures must have identical dimensions!\n" ; return 2 ; } for ( int y = 0 ; y < h ; y++ ) { uint *firstLine = ( uint* )firstImage.scanLine( y ) ; uint *secondLine = ( uint* )secondImage.scanLine( y ) ; for ( int x = 0 ; x < w ; x++ ) { uint pixelFirst = firstLine[ x ] ; int rFirst = qRed( pixelFirst ) ; int gFirst = qGreen( pixelFirst ) ; int bFirst = qBlue( pixelFirst ) ; uint pixelSecond = secondLine[ x ] ; int rSecond = qRed( pixelSecond ) ; int gSecond = qGreen( pixelSecond ) ; int bSecond = qBlue( pixelSecond ) ; totaldiff += std::abs( rFirst - rSecond ) / 255.0 ; totaldiff += std::abs( gFirst - gSecond ) / 255.0 ; totaldiff += std::abs( bFirst -bSecond ) / 255.0 ; } } std::cout << "The difference of the two pictures is " << (totaldiff * 100) / (w * h * 3) << " % !\n" ; return 0 ; }
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   var F = [][]int{ {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}, }   var I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}   var L = [][]int{ {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}, }   var N = [][]int{ {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}, }   var P = [][]int{ {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}, }   var T = [][]int{ {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}, }   var U = [][]int{ {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}, }   var V = [][]int{ {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}, }   var W = [][]int{ {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}, }   var X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}   var Y = [][]int{ {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}, }   var Z = [][]int{ {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}, }   var shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}   var symbols = []byte("FILNPTUVWXYZ-")   const ( nRows = 8 nCols = 8 blank = 12 )   var grid [nRows][nCols]int var placed [12]bool   func tryPlaceOrientation(o []int, r, c, shapeIndex int) bool { for i := 0; i < len(o); i += 2 { x := c + o[i+1] y := r + o[i] if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 { return false } } grid[r][c] = shapeIndex for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = shapeIndex } return true }   func removeOrientation(o []int, r, c int) { grid[r][c] = -1 for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = -1 } }   func solve(pos, numPlaced int) bool { if numPlaced == len(shapes) { return true } row := pos / nCols col := pos % nCols if grid[row][col] != -1 { return solve(pos+1, numPlaced) }   for i := range shapes { if !placed[i] { for _, orientation := range 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 }   func shuffleShapes() { rand.Shuffle(len(shapes), func(i, j int) { shapes[i], shapes[j] = shapes[j], shapes[i] symbols[i], symbols[j] = symbols[j], symbols[i] }) }   func printResult() { for _, r := range grid { for _, i := range r { fmt.Printf("%c ", symbols[i]) } fmt.Println() } }   func main() { rand.Seed(time.Now().UnixNano()) shuffleShapes() for r := 0; r < nRows; r++ { for i := range grid[r] { grid[r][i] = -1 } } for i := 0; i < 4; i++ { var randRow, randCol int for { randRow = rand.Intn(nRows) randCol = rand.Intn(nCols) if grid[randRow][randCol] != blank { break } } grid[randRow][randCol] = blank } if solve(0, 0) { printResult() } else { fmt.Println("No solution") } }
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#J
J
congeal=: |.@|:@((*@[*>.)/\.)^:4^:_
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Julia
Julia
using Printf, Distributions   newgrid(p::Float64, r::Int, c::Int=r) = rand(Bernoulli(p), r, c)   function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int) NOT_CLUSTERED = 1 # const N, M = size(grid) dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]] # fill cell grid[r, c] = indx # check for each direction for d in dirs rr, cc = (r, c) .+ d if checkbounds(Bool, grid, rr, cc) && grid[rr, cc] == NOT_CLUSTERED walkmaze!(grid, rr, cc, indx) end end end   function clustercount!(grid::Matrix{Int}) NOT_CLUSTERED = 1 # const walkind = 1 for r in 1:size(grid, 1), c in 1:size(grid, 2) if grid[r, c] == NOT_CLUSTERED walkind += 1 walkmaze!(grid, r, c, walkind) end end return walkind - 1 end clusterdensity(p::Float64, n::Int) = clustercount!(newgrid(p, n)) / n ^ 2   function printgrid(G::Matrix{Int}) LETTERS = vcat(' ', '#', 'A':'Z', 'a':'z') for r in 1:size(G, 1) println(r % 10, ") ", join(LETTERS[G[r, :] .+ 1], ' ')) end end   G = newgrid(0.5, 15) @printf("Found %i clusters in this %i×%i grid\n\n", clustercount!(G), size(G, 1), size(G, 2)) printgrid(G) println()   const nrange = 2 .^ (4:2:12) const p = 0.5 const nrep = 5 for n in nrange sim = mean(clusterdensity(p, n) for _ in 1:nrep) @printf("nrep = %2i p = %.2f dim = %-13s sim = %.5f\n", nrep, p, "$n × $n", sim) end
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random() const val RAND_MAX = 32767   lateinit var map: IntArray var w = 0 var ww = 0   const val ALPHA = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" const val ALEN = ALPHA.length - 3   fun makeMap(p: Double) { val thresh = (p * RAND_MAX).toInt() ww = w * w var i = ww map = IntArray(i) while (i-- != 0) { val r = rand.nextInt(RAND_MAX + 1) if (r < thresh) map[i] = -1 } }   fun showCluster() { var k = 0 for (i in 0 until w) { for (j in 0 until w) { val s = map[k++] val c = if (s < ALEN) ALPHA[1 + s] else '?' print(" $c") } println() } }   fun recur(x: Int, v: Int) { if ((x in 0 until ww) && map[x] == -1) { map[x] = v recur(x - w, v) recur(x - 1, v) recur(x + 1, v) recur(x + w, v) } }   fun countClusters(): Int { var cls = 0 for (i in 0 until ww) { if (map[i] != -1) continue recur(i, ++cls) } return cls }   fun tests(n: Int, p: Double): Double { var k = 0.0 for (i in 0 until n) { makeMap(p) k += countClusters().toDouble() / ww } return k / n }   fun main(args: Array<String>) { w = 15 makeMap(0.5) val cls = countClusters() println("width = 15, p = 0.5, $cls clusters:") showCluster()   println("\np = 0.5, iter = 5:") w = 1 shl 2 while (w <= 1 shl 13) { val t = tests(5, 0.5) println("%5d %9.6f".format(w, t)) w = w shl 1 } }
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Lucas-Lehmer test   is used to find primes of the form   2n-1,   all known perfect numbers can be derived from these primes using the formula   (2n - 1) × 2n - 1. It is not known if there are any odd perfect numbers (any that exist are larger than 102000). The number of   known   perfect numbers is   51   (as of December, 2018),   and the largest known perfect number contains  49,724,095  decimal digits. See also   Rational Arithmetic   Perfect numbers on OEIS   Odd Perfect showing the current status of bounds on odd perfect numbers.
#ALGOL_60
ALGOL 60
  begin   comment - return p mod q; integer procedure mod(p, q); value p, q; integer p, q; begin mod := p - q * entier(p / q); end;   comment - return true if n is perfect, otherwise false; boolean procedure isperfect(n); value n; integer n; begin integer sum, f1, f2; sum := 1; f1 := 1; for f1 := f1 + 1 while (f1 * f1) <= n do begin if mod(n, f1) = 0 then begin sum := sum + f1; f2 := n / f1; if f2 > f1 then sum := sum + f2; end; end; isperfect := (sum = n); end;   comment - exercise the procedure; integer i, found; outstring(1,"Searching up to 10000 for perfect numbers\n"); found := 0; for i := 2 step 1 until 10000 do if isperfect(i) then begin outinteger(1,i); found := found + 1; end; outstring(1,"\n"); outinteger(1,found); outstring(1,"perfect numbers were found");   end  
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Lucas-Lehmer test   is used to find primes of the form   2n-1,   all known perfect numbers can be derived from these primes using the formula   (2n - 1) × 2n - 1. It is not known if there are any odd perfect numbers (any that exist are larger than 102000). The number of   known   perfect numbers is   51   (as of December, 2018),   and the largest known perfect number contains  49,724,095  decimal digits. See also   Rational Arithmetic   Perfect numbers on OEIS   Odd Perfect showing the current status of bounds on odd perfect numbers.
#ALGOL_68
ALGOL 68
PROC is perfect = (INT candidate)BOOL: ( INT sum :=1; FOR f1 FROM 2 TO ENTIER ( sqrt(candidate)*(1+2*small real) ) WHILE IF candidate MOD f1 = 0 THEN sum +:= f1; INT f2 = candidate OVER f1; IF f2 > f1 THEN sum +:= f2 FI FI; # WHILE # sum <= candidate DO SKIP OD; sum=candidate );   test:( FOR i FROM 2 TO 33550336 DO IF is perfect(i) THEN print((i, new line)) FI OD )
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Monad.Random import Data.Array.Unboxed import Data.List import Formatting   data Field = Field { f :: UArray (Int, Int) Char , hWall :: UArray (Int, Int) Bool , vWall :: UArray (Int, Int) Bool }   -- Start percolating some seepage through a field. -- Recurse to continue percolation with new seepage. percolateR :: [(Int, Int)] -> Field -> (Field, [(Int,Int)]) percolateR [] (Field f h v) = (Field f h v, []) percolateR seep (Field f h v) = let ((xLo,yLo),(xHi,yHi)) = bounds f validSeep = filter (\p@(x,y) -> x >= xLo && x <= xHi && y >= yLo && y <= yHi && f!p == ' ') $ nub $ sort seep   north (x,y) = if v ! (x ,y ) then [] else [(x ,y-1)] south (x,y) = if v ! (x ,y+1) then [] else [(x ,y+1)] west (x,y) = if h ! (x ,y ) then [] else [(x-1,y )] east (x,y) = if h ! (x+1,y ) then [] else [(x+1,y )] neighbors (x,y) = north(x,y) ++ south(x,y) ++ west(x,y) ++ east(x,y)   in percolateR (concatMap neighbors validSeep) (Field (f // map (\p -> (p,'.')) validSeep) h v)   -- Percolate a field; Return the percolated field. percolate :: Field -> Field percolate start@(Field f _ _) = let ((_,_),(xHi,_)) = bounds f (final, _) = percolateR [(x,0) | x <- [0..xHi]] start in final   -- Generate a random field. initField :: Int -> Int -> Double -> Rand StdGen Field initField width height threshold = do let f = listArray ((0,0), (width-1, height-1)) $ repeat ' '   hrnd <- fmap (<threshold) <$> getRandoms let h0 = listArray ((0,0),(width, height-1)) hrnd h1 = h0 // [((0,y), True) | y <- [0..height-1]] -- close left h2 = h1 // [((width,y), True) | y <- [0..height-1]] -- close right   vrnd <- fmap (<threshold) <$> getRandoms let v0 = listArray ((0,0),(width-1, height)) vrnd v1 = v0 // [((x,0), True) | x <- [0..width-1]] -- close top   return $ Field f h2 v1   -- Assess whether or not percolation reached bottom of field. leaks :: Field -> [Bool] leaks (Field f _ v) = let ((xLo,_),(xHi,yHi)) = bounds f in [f!(x,yHi)=='.' && not (v!(x,yHi+1)) | x <- [xLo..xHi]]   -- Run test once; Return bool indicating success or failure. oneTest :: Int -> Int -> Double -> Rand StdGen Bool oneTest width height threshold = or.leaks.percolate <$> initField width height threshold   -- Run test multple times; Return the number of tests that pass. multiTest :: Int -> Int -> Int -> Double -> Rand StdGen Double multiTest testCount width height threshold = do results <- replicateM testCount $ oneTest width height threshold let leakyCount = length $ filter id results return $ fromIntegral leakyCount / fromIntegral testCount   -- Helper function for display alternate :: [a] -> [a] -> [a] alternate [] _ = [] alternate (a:as) bs = a : alternate bs as   -- Display a field with walls and leaks. showField :: Field -> IO () showField field@(Field a h v) = do let ((xLo,yLo),(xHi,yHi)) = bounds a fLines = [ [ a!(x,y) | x <- [xLo..xHi]] | y <- [yLo..yHi]] hLines = [ [ if h!(x,y) then '|' else ' ' | x <- [xLo..xHi+1]] | y <- [yLo..yHi]] vLines = [ [ if v!(x,y) then '-' else ' ' | x <- [xLo..xHi]] | y <- [yLo..yHi+1]] lattice = [ [ '+' | x <- [xLo..xHi+1]] | y <- [yLo..yHi+1]]   hDrawn = zipWith alternate hLines fLines vDrawn = zipWith alternate lattice vLines mapM_ putStrLn $ alternate vDrawn hDrawn   let leakLine = [ if l then '.' else ' ' | l <- leaks field] putStrLn $ alternate (repeat ' ') leakLine   main :: IO () main = do g <- getStdGen let threshold = 0.45 (startField, g2) = runRand (initField 10 10 threshold) g   putStrLn ("Unpercolated field with " ++ show threshold ++ " threshold.") putStrLn "" showField startField   putStrLn "" putStrLn "Same field after percolation." putStrLn "" showField $ percolate startField   let testCount = 10000 densityCount = 10 putStrLn "" putStrLn ("Results of running percolation test " ++ show testCount ++ " times with thresholds ranging from 0/" ++ show densityCount ++ " to " ++ show densityCount ++ "/" ++ show densityCount ++ " .") let densities = [0..densityCount] let tests = sequence [multiTest testCount 10 10 v | density <- densities, let v = fromIntegral density / fromIntegral densityCount ] let results = zip densities (evalRand tests g2) mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) density densityCount x | (density,x) <- results]
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\displaystyle v} be a vector of n {\displaystyle n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} ; the probability of a value being 0 is therefore 1 − p {\displaystyle 1-p} . Define a run of 1s as being a group of consecutive 1s in the vector bounded either by the limits of the vector or by a 0. Let the number of such runs in a given vector of length n {\displaystyle n} be R n {\displaystyle R_{n}} . For example, the following vector has R 10 = 3 {\displaystyle R_{10}=3} [1 1 0 0 0 1 0 1 1 1] ^^^ ^ ^^^^^ Percolation theory states that K ( p ) = lim n → ∞ R n / n = p ( 1 − p ) {\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)} Task Any calculation of R n / n {\displaystyle R_{n}/n} for finite n {\displaystyle n} is subject to randomness so should be computed as the average of t {\displaystyle t} runs, where t ≥ 100 {\displaystyle t\geq 100} . For values of p {\displaystyle p} of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} . Show your output here. See also s-Run on Wolfram mathworld.
#Haskell
Haskell
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  
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random() const val RAND_MAX = 32767 const val NUL = '\u0000'   val x = 15 val y = 15 var grid = StringBuilder((x + 1) * (y + 1) + 1) var cell = 0 var end = 0 var m = 0 var n = 0   fun makeGrid(p: Double) { val thresh = (p * RAND_MAX).toInt() m = x n = y grid.setLength(0) // clears grid grid.setLength(m + 1) // sets first (m + 1) chars to NUL end = m + 1 cell = m + 1 for (i in 0 until n) { for (j in 0 until m) { val r = rand.nextInt(RAND_MAX + 1) grid.append(if (r < thresh) '+' else '.') end++ } grid.append('\n') end++ } grid[end - 1] = NUL end -= ++m // end is the index of the first cell of bottom row }   fun ff(p: Int): Boolean { // flood fill if (grid[p] != '+') return false grid[p] = '#' return p >= end || ff(p + m) || ff(p + 1) || ff(p - 1) || ff(p - m) }   fun percolate(): Boolean { var i = 0 while (i < m && !ff(cell + i)) i++ return i < m }   fun main(args: Array<String>) { makeGrid(0.5) percolate()   println("$x x $y grid:") println(grid)   println("\nrunning 10,000 tests for each case:") for (ip in 0..10) { val p = ip / 10.0 var cnt = 0 for (i in 0 until 10_000) { makeGrid(p) if (percolate()) cnt++ } println("p = %.1f:  %.4f".format(p, cnt / 10000.0)) } }
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRED BY "prelude_permutations.a68" MODE PERMDATA = ~; PROVIDES: # PERMDATA*=~* # # perm*=~ list* # END COMMENT   MODE PERMDATALIST = REF[]PERMDATA; MODE PERMDATALISTYIELD = PROC(PERMDATALIST)VOID;   # Generate permutations of the input data list of data list # PROC perm gen permutations = (PERMDATALIST data list, PERMDATALISTYIELD yield)VOID: ( # Warning: this routine does not correctly handle duplicate elements # IF LWB data list = UPB data list THEN yield(data list) ELSE FOR elem FROM LWB data list TO UPB data list DO PERMDATA first = data list[elem]; data list[LWB data list+1:elem] := data list[:elem-1]; data list[LWB data list] := first; # FOR PERMDATALIST next data list IN # perm gen permutations(data list[LWB data list+1:] # ) DO #, ## (PERMDATALIST next)VOID:( yield(data list) # OD #)); data list[:elem-1] := data list[LWB data list+1:elem]; data list[elem] := first OD FI );   SKIP
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#Clojure
Clojure
(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])
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#Common_Lisp
Common Lisp
(defun perfect-shuffle (deck) (let* ((half (floor (length deck) 2)) (left (subseq deck 0 half)) (right (nthcdr half deck))) (mapcan #'list left right)))   (defun solve (deck-size) (loop with original = (loop for n from 1 to deck-size collect n) for trials from 1 for deck = original then shuffled for shuffled = (perfect-shuffle deck) until (equal shuffled original) finally (format t "~5D: ~4D~%" deck-size trials)))   (solve 8) (solve 24) (solve 52) (solve 100) (solve 1020) (solve 1024) (solve 10000)
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#J
J
band=:17 b. ImprovedNoise=:3 :0 'x y z'=. y X=. (<. x) band 255 Y=. (<. y) band 255 Z=. (<. z) band 255 x=. x-<.!.0 x y=. y-<.!.0 y z=. z-<.!.0 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   t1=. (grad(p{~BB+1),(x-1),(y-1),z-1) t2=. (lerp u,(grad(p{~AB+1),x,(y-1),z-1),t1) t3=. (grad(p{~BA+1),(x-1),y,z-1) t4=. (lerp v,(lerp u,(grad(p{~AA+1),x,y,z-1),t3),t2) t5=. (grad(p{~BB),(x-1),(y-1),z) t6=. (lerp u,(grad(p{~AB),x,(y-1),z),t5) t7=. (grad(p{~BA),(x-1),y,z) (lerp w,(lerp v,(lerp u,(grad(p{~AA),x,y,z),t7),t6),t4) )   fade=:3 :0 t=.y t * t * t * ((t * ((t * 6) - 15)) + 10) )   lerp=:3 :0 't a b'=. y a + t * (b - a) )   grad=:3 :0 'hash x y z'=. y h =. hash band 15 NB. CONVERT LO 4 BITS OF HASH CODE u =. x [^:(h<8) y NB. INTO 12 GRADIENT DIRECTIONS. v =. y [^:(h<4) x [^:((h=12)+.(h=14)) z (u [^:((h band 1) = 0) -u) + v [^:((h band 2) = 0) -v )     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   fade=: 0 0 0 10 _15 6&p.   ImprovedNoise=:3 :0 'XYZ xyz'=. |:256 1 #:y uvw=. fade xyz hash=. 0 1+/(+ p{~0 1+/])/|. XYZ   t1=. (grad(p{~BB+1),(x-1),(y-1),z-1) t2=. (lerp u,(grad(p{~AB+1), x, (y-1),z-1),t1) t3=. (grad(p{~BA+1),(x-1), y, z-1) t4=. (lerp v,(lerp u,(grad(p{~AA+1), x, y, z-1),t3),t2) t5=. (grad(p{~BB), (x-1),(y-1),z) t6=. (lerp u,(grad(p{~AB), x, (y-1),z), t5) t7=. (grad(p{~BA), (x-1), y, z) (lerp w,(lerp v,(lerp u,(grad(p{~AA),x, y, z), t7),t6),t4) )  
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Haskell
Haskell
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
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card must have a pip value and a suit value which constitute the unique value of the card. Related tasks: Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser Go Fish
#Forth
Forth
require random.fs \ RANDOM ( n -- 0..n-1 ) is called CHOOSE in other Forths   create pips s" A23456789TJQK" mem, create suits s" DHCS" mem, \ diamonds, hearts, clubs, spades : .card ( c -- ) 13 /mod swap pips + c@ emit suits + c@ emit ;   create deck 52 allot variable dealt   : new-deck 52 0 do i deck i + c! loop 0 dealt ! ; : .deck 52 dealt @ ?do deck i + c@ .card space loop cr ; : shuffle 51 0 do 52 i - random i + ( rand-index ) deck + deck i + c@ over c@ deck i + c! swap c! loop ; : cards-left ( -- n ) 52 dealt @ - ; : deal-card ( -- c ) cards-left 0= abort" Deck empty!" deck dealt @ + c@ 1 dealt +! ; : .hand ( n -- ) 0 do deal-card .card space loop cr ;   new-deck shuffle .deck 5 .hand cards-left . \ 47
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ... Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions. Related Task Arithmetic-geometric mean/Calculate Pi
#F.23
F#
let rec g q r t k n l = seq { if 4I*q+r-t < n*t then yield n yield! (g (10I*q) (10I*(r-n*t)) t k ((10I*(3I*q+r))/t - 10I*n) l) else yield! (g (q*k) ((2I*q+r)*l) (t*l) (k+1I) ((q*(7I*k+2I)+r*l)/(t*l)) (l+2I)) }   let π = (g 1I 0I 1I 1I 3I 3I)   Seq.take 1 π |> Seq.iter (printf "%A.") // 6 digits beginning at position 762 of π are '9' Seq.take 767 (Seq.skip 1 π) |> Seq.iter (printf "%A")
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   1   loses the player's total points   for that turn   and their turn finishes with play passing to the next player. Holding:   the player's score for that round is added to their total and becomes safe from the effects of throwing a   1   (one).   The player's turn finishes with play passing to the next player. Task Create a program to score for, and simulate dice throws for, a two-person game. Related task   Pig the dice game/Player
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DynamicModule[{score, players = {1, 2}, roundscore = 0, roll}, (score@# = 0) & /@ players; Panel@Dynamic@ Column@{Grid[ Prepend[{#, score@#} & /@ players, {"Player", "Score"}], Background -> {None, 2 -> Gray}], roundscore, If[ValueQ@roll, Row@{"Rolled ", roll}, ""], If[IntegerQ@roundscore, Row@{Button["Roll", roll = RandomInteger[{1, 6}]; If[roll == 1, roundscore = 0; players = RotateLeft@players, roundscore += roll]], Button["Hold", score[players[[1]]] += roundscore; roundscore = 0; If[score[players[[1]]] >= 100, roll =.; roundscore = Row@{players[[1]], " wins."}, players = RotateLeft@players]]}, Button["Play again.", roundscore = 0; (score@# = 0) & /@ players]]}]
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pernicious number. Task display the first   25   pernicious numbers   (in decimal). display all pernicious numbers between   888,888,877   and   888,888,888   (inclusive). display each list of integers on one line   (which may or may not include a title). See also Sequence   A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences. Rosetta Code entry   population count, evil numbers, odious numbers.
#Fortran
Fortran
program pernicious implicit none   integer :: i, n   i = 1 n = 0 do if(isprime(popcnt(i))) then write(*, "(i0, 1x)", advance = "no") i n = n + 1 if(n == 25) exit end if i = i + 1 end do   write(*,*) do i = 888888877, 888888888 if(isprime(popcnt(i))) write(*, "(i0, 1x)", advance = "no") i end do   contains   function popcnt(x) integer :: popcnt integer, intent(in) :: x integer :: i   popcnt = 0 do i = 0, 31 if(btest(x, i)) popcnt = popcnt + 1 end do   end function   function isprime(number) logical :: isprime integer, intent(in) :: number integer :: i   if(number == 2) then isprime = .true. else if(number < 2 .or. mod(number,2) == 0) then isprime = .false. else isprime = .true. do i = 3, int(sqrt(real(number))), 2 if(mod(number,i) == 0) then isprime = .false. exit end if end do end if end function end program
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them. Task Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind. See also Wikipedia - Pierpont primes OEIS:A005109 - Class 1 -, or Pierpont primes OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
#Sidef
Sidef
func smooth_generator(primes) { var s = primes.len.of { [1] } { var n = s.map { .first }.min { |i| s[i].shift if (s[i][0] == n) s[i] << (n * primes[i]) } * primes.len n } }   func pierpont_primes(n, k = 1) { var g = smooth_generator([2,3]) 1..Inf -> lazy.map { g.run + k }.grep { .is_prime }.first(n) }   say "First 50 Pierpont primes of the 1st kind: " say pierpont_primes(50, +1).join(' ')   say "\nFirst 50 Pierpont primes of the 2nd kind: " say pierpont_primes(50, -1).join(' ')   for n in (250, 500, 1000) { var p = pierpont_primes(n, +1).last var q = pierpont_primes(n, -1).last say "\n#{n}th Pierpont prime of the 1st kind: #{p}" say "#{n}th Pierpont prime of the 2nd kind: #{q}" }
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Java
Java
import java.util.Random; ... int[] array = {1,2,3}; return array[new Random().nextInt(array.length)]; // if done multiple times, the Random object should be re-used
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#JavaScript
JavaScript
var array = [1,2,3]; return array[Math.floor(Math.random() * array.length)];
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#JavaScript
JavaScript
(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');
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n. Task Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer). Generate and show all the derangements of 4 integers using the above routine. Create a function that calculates the subfactorial of n, !n. Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive. Optional stretch goal   Calculate    !20 Related tasks   Anagrams/Deranged anagrams   Best shuffle   Left_factorials Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Go
Go
package main   import ( "fmt" "math/big" )   // task 1: function returns list of derangements of n integers func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } // recursive closure permutes a var recurse func(last int) recurse = func(last int) { if last == 0 { // bottom of recursion. you get here once for each permutation. // test if permutation is deranged. for j, v := range a { if j == v { return // no, ignore it } } // yes, save a copy r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return }   // task 3: function computes subfactorial of n func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 }   func main() { // task 2: fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) }   // task 4: fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) }   // stretch (sic) fmt.Println("\n!20 =", subFact(20)) }
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#jq
jq
# The helper function, _recurse, is tail-recursive and therefore in # versions of jq with TCO (tail call optimization) there is no # overhead associated with the recursion.   def permutations: def abs: if . < 0 then -. else . end; def sign: if . < 0 then -1 elif . == 0 then 0 else 1 end; def swap(i;j): .[i] as $i | .[i] = .[j] | .[j] = $i;   # input: [ parity, extendedPermutation] def _recurse: .[0] as $s | .[1] as $p | (($p | length) -1) as $n | [ $s, ($p[1:] | map(abs)) ], (reduce range(2; $n+1) as $i (0; if $p[$i] < 0 and -($p[$i]) > ($p[$i-1]|abs) and -($p[$i]) > ($p[.]|abs) then $i else . end)) as $k | (reduce range(1; $n) as $i ($k; if $p[$i] > 0 and $p[$i] > ($p[$i+1]|abs) and $p[$i] > ($p[.]|abs) then $i else . end)) as $k | if $k == 0 then empty else (reduce range(1; $n) as $i ($p; if (.[$i]|abs) > (.[$k]|abs) then .[$i] *= -1 else . end )) as $p | ($k + ($p[$k]|sign)) as $i | ($p | swap($i; $k)) as $p | [ -($s), $p ] | _recurse end ;   . as $in | length as $n | (reduce range(0; $n+1) as $i ([]; . + [ -$i ])) as $p # recurse state: [$s, $p] | [ 1, $p] | _recurse | .[1] as $p | .[1] = reduce range(0; $n) as $i ([]; . + [$in[$p[$i] - 1]]) ;   def count(stream): reduce stream as $x (0; .+1);
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#Julia
Julia
  function johnsontrottermove!(ints, isleft) len = length(ints) function ismobile(pos) if isleft[pos] && (pos > 1) && (ints[pos-1] < ints[pos]) return true elseif !isleft[pos] && (pos < len) && (ints[pos+1] < ints[pos]) return true end false end function maxmobile() arr = [ints[pos] for pos in 1:len if ismobile(pos)] if isempty(arr) 0, 0 else maxmob = maximum(arr) maxmob, findfirst(x -> x == maxmob, ints) end end function directedswap(pos) tmp = ints[pos] tmpisleft = isleft[pos] if isleft[pos] ints[pos] = ints[pos-1]; ints[pos-1] = tmp isleft[pos] = isleft[pos-1]; isleft[pos-1] = tmpisleft else ints[pos] = ints[pos+1]; ints[pos+1] = tmp isleft[pos] = isleft[pos+1]; isleft[pos+1] = tmpisleft end end (moveint, movepos) = maxmobile() if movepos > 0 directedswap(movepos) for (i, val) in enumerate(ints) if val > moveint isleft[i] = !isleft[i] end end ints, isleft, true else ints, isleft, false end end function johnsontrotter(low, high) ints = collect(low:high) isleft = [true for i in ints] firstconfig = copy(ints) iters = 0 while true iters += 1 println("$ints $(iters & 1 == 1 ? "+1" : "-1")") if johnsontrottermove!(ints, isleft)[3] == false break end end println("There were $iters iterations.") end johnsontrotter(1,4)  
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment subjects, or to a group of m {\displaystyle m} control subjects. Members of the treatment group were given the treatment, and members of the control group were given a placebo. The effect of the treatment or placebo on each volunteer was measured and reported in this table. Table of experimental results Treatment group Control group 85 68 88 41 75 10 66 49 25 16 29 65 83 32 39 92 97 28 98 Write a program that performs a permutation test to judge whether the treatment had a significantly stronger effect than the placebo. Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size n {\displaystyle n} and a control group of size m {\displaystyle m} (i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless. Note that the number of alternatives will be the binomial coefficient ( n + m n ) {\displaystyle {\tbinom {n+m}{n}}} . Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group. Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater. Note that they should sum to 100%. Extremely dissimilar values are evidence of an effect not entirely due to chance, but your program need not draw any conclusions. You may assume the experimental data are known at compile time if that's easier than loading them at run time. Test your solution on the data given above.
#PicoLisp
PicoLisp
(load "@lib/simul.l") # For 'subsets'   (scl 2)   (de _stat (A) (let (LenA (length A) SumA (apply + A)) (- (*/ SumA LenA) (*/ (- SumAB SumA) (- LenAB LenA)) ) ) )   (de permutationTest (A B) (let (AB (append A B) SumAB (apply + AB) LenAB (length AB) Tobs (_stat A) Count 0 ) (*/ (sum '((Perm) (inc 'Count) (and (>= Tobs (_stat Perm)) 1) ) (subsets (length A) AB) ) 100.0 Count ) ) )   (setq *TreatmentGroup (0.85 0.88 0.75 0.66 0.25 0.29 0.83 0.39 0.97) *ControlGroup (0.68 0.41 0.10 0.49 0.16 0.65 0.32 0.92 0.28 0.98) )   (let N (permutationTest *TreatmentGroup *ControlGroup) (prinl "under = " (round N) "%, over = " (round (- 100.0 N)) "%") )
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment subjects, or to a group of m {\displaystyle m} control subjects. Members of the treatment group were given the treatment, and members of the control group were given a placebo. The effect of the treatment or placebo on each volunteer was measured and reported in this table. Table of experimental results Treatment group Control group 85 68 88 41 75 10 66 49 25 16 29 65 83 32 39 92 97 28 98 Write a program that performs a permutation test to judge whether the treatment had a significantly stronger effect than the placebo. Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size n {\displaystyle n} and a control group of size m {\displaystyle m} (i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless. Note that the number of alternatives will be the binomial coefficient ( n + m n ) {\displaystyle {\tbinom {n+m}{n}}} . Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group. Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater. Note that they should sum to 100%. Extremely dissimilar values are evidence of an effect not entirely due to chance, but your program need not draw any conclusions. You may assume the experimental data are known at compile time if that's easier than loading them at run time. Test your solution on the data given above.
#PureBasic
PureBasic
    Define.f meanTreated,meanControl,diffInMeans Define.f actualmeanTreated,actualmeanControl,actualdiffInMeans   Dim poolA(19)   poolA(1) =85 ; first 9 the treated poolA(2) =88 poolA(3) =75 poolA(4) =66 poolA(5) =25 poolA(6) =29 poolA(7) =83 poolA(8) =39 poolA(9) =97   poolA(10) =68 ; last 10 the control poolA(11) =41 poolA(12) =10 poolA(13) =49 poolA(14) =16 poolA(15) =65 poolA(16) =32 poolA(17) =92 poolA(18) =28 poolA(19) =98   Procedure.i IsValidBitString(x,pool,treated) Protected c,i For i=1 to pool mask=1<<(i-1) If mask&x:c+1:EndIf Next If c=treated :ProcedureReturn x Else  :ProcedureReturn 0 EndIf EndProcedure   treated=9 control=10   pool =treated+control   ; actual Experimentally observed difference in means   For i=1 to Treated sumTreated+poolA(i) Next For i=Treated+1 to Treated+Control sumControl+poolA(i) Next   actualmeanTreated=sumTreated /Treated actualmeanControl=sumControl /Control actualdiffInMeans=actualmeanTreated-actualmeanControl   ; exhaust the possibilites For x=1 to 1<<pool   ; Valid? i.e. are there 9 "1's" ? If IsValidBitString(x,pool,treated) TotalComBinations+1:sumTreated=0:sumControl=0   ; separate the groups For i=pool to 1 Step -1 mask=1<<(i-1):idx=pool-i+1 If mask&x sumTreated+poolA(idx) Else sumControl+poolA(idx) EndIf Next   meanTreated=sumTreated /Treated meanControl=sumControl /Control diffInMeans=meanTreated-meanControl ; gather the statistics If (diffInMeans)<=(actualdiffInMeans) diffLessOrEqual+1 Else diffGreater+1 EndIf   EndIf Next ; show our results ; cw(StrF(100*diffLessOrEqual/TotalComBinations,2)+" "+Str(diffLessOrEqual)) ; cw(StrF(100*diffGreater /TotalComBinations,2)+" "+Str(diffGreater))   Debug StrF(100*diffLessOrEqual/TotalComBinations,2)+" "+Str(diffLessOrEqual) Debug StrF(100*diffGreater /TotalComBinations,2)+" "+Str(diffGreater)  
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#Common_Lisp
Common Lisp
(require 'cl-jpeg) ;;; the JPEG library uses simple-vectors to store data. this is insane! (defun compare-images (file1 file2) (declare (optimize (speed 3) (safety 0) (debug 0))) (multiple-value-bind (image1 height width) (jpeg:decode-image file1) (let ((image2 (jpeg:decode-image file2))) (loop for i of-type (unsigned-byte 8) across (the simple-vector image1) for j of-type (unsigned-byte 8) across (the simple-vector image2) sum (the fixnum (abs (- i j))) into difference of-type fixnum finally (return (coerce (/ difference width height #.(* 3 255)) 'double-float))))))   CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg")) 1.774856467652165d0
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Java
Java
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}; }
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(*Calculate C_n / n^2 for n=1000, 2000, ..., 10 000*) In[1]:= Table[N[Max@MorphologicalComponents[ RandomVariate[BernoulliDistribution[.5], {n, n}], CornerNeighbors -> False]/n^2], {n, 10^3, 10^4, 10^3}]   (*Find the average*) In[2]:= % // MeanAround   (*Show a 15x15 matrix with each cluster given an incrementally higher number, Colorize instead of MatrixForm creates an image*) In[3]:= MorphologicalComponents[RandomChoice[{0, 1}, {15, 15}], CornerNeighbors -> False] // MatrixForm
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Nim
Nim
import random, sequtils, strformat   const N = 15 T = 5 P = 0.5 NotClustered = 1 Cell2Char = " #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" NRange = [4, 64, 256, 1024, 4096]   type Grid = seq[seq[int]]     proc newGrid(n: Positive; p: float): Grid = result = newSeqWith(n, newSeq[int](n)) for row in result.mitems: for cell in row.mitems: if rand(1.0) < p: cell = 1     func walkMaze(grid: var Grid; m, n, idx: int) = grid[n][m] = idx if n < grid.high and grid[n + 1][m] == NotClustered: grid.walkMaze(m, n + 1, idx) if m < grid[0].high and grid[n][m + 1] == NotClustered: grid.walkMaze(m + 1, n, idx) if m > 0 and grid[n][m - 1] == NotClustered: grid.walkMaze(m - 1, n, idx) if n > 0 and grid[n - 1][m] == NotClustered: grid.walkMaze(m, n - 1, idx)     func clusterCount(grid: var Grid): int = var walkIndex = 1 for n in 0..grid.high: for m in 0..grid[0].high: if grid[n][m] == NotClustered: inc walkIndex grid.walkMaze(m, n, walkIndex) result = walkIndex - 1     proc clusterDensity(n: int; p: float): float = var grid = newGrid(n, p) result = grid.clusterCount() / (n * n)     proc print(grid: Grid) = for n, row in grid: stdout.write n mod 10, ") " for cell in row: stdout.write ' ', Cell2Char[cell] stdout.write '\n'     when isMainModule:   randomize()   var grid = newGrid(N, 0.5) echo &"Found {grid.clusterCount()} clusters in this {N} by {N} grid\n" grid.print() echo ""   for n in NRange: var sum = 0.0 for _ in 1..T: sum += clusterDensity(n, P) let sim = sum / T echo &"t = {T} p = {P:4.2f} n = {n:4} sim = {sim:7.5f}"
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Perl
Perl
$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; }
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Lucas-Lehmer test   is used to find primes of the form   2n-1,   all known perfect numbers can be derived from these primes using the formula   (2n - 1) × 2n - 1. It is not known if there are any odd perfect numbers (any that exist are larger than 102000). The number of   known   perfect numbers is   51   (as of December, 2018),   and the largest known perfect number contains  49,724,095  decimal digits. See also   Rational Arithmetic   Perfect numbers on OEIS   Odd Perfect showing the current status of bounds on odd perfect numbers.
#ALGOL_W
ALGOL W
begin  % returns true if n is perfect, false otherwise  %  % n must be > 0  % logical procedure isPerfect ( integer value candidate ) ; begin integer sum; sum  := 1; for f1 := 2 until round( sqrt( candidate ) ) do begin if candidate rem f1 = 0 then begin integer f2; sum := sum + f1; f2  := candidate div f1;  % avoid e.g. counting 2 twice as a factor of 4 % if f2 > f1 then sum := sum + f2 end if_candidate_rem_f1_eq_0 ; end for_f1 ; sum = candidate end isPerfect ;    % test isPerfect  % for n := 2 until 10000 do if isPerfect( n ) then write( n ); end.
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Julia
Julia
using Printf, Distributions   struct Grid cells::BitArray{2} hwall::BitArray{2} vwall::BitArray{2} end function Grid(p::AbstractFloat, m::Integer=10, n::Integer=10) cells = fill(false, m, n) hwall = rand(Bernoulli(p), m + 1, n) vwall = rand(Bernoulli(p), m, n + 1) vwall[:, 1] = true vwall[:, end] = true return Grid(cells, hwall, vwall) end   function Base.show(io::IO, g::Grid) H = (" .", " _") V = (":", "|") C = (" ", "#") ind = findfirst(g.cells[end, :] .& .!g.hwall[end, :]) percolated = !iszero(ind) println(io, "$(size(g.cells, 1))×$(size(g.cells, 2)) $(percolated ? "Percolated" : "Not percolated") grid") for r in 1:size(g.cells, 1) println(io, " ", join(H[w+1] for w in g.hwall[r, :])) println(io, " $(r % 10)) ", join(V[w+1] * C[c+1] for (w, c) in zip(g.vwall[r, :], g.cells[r, :]))) end println(io, " ", join(H[w+1] for w in g.hwall[end, :])) if percolated println(io, " !) ", " " ^ (ind - 1), '#') end end   function floodfill!(m::Integer, n::Integer, cells::AbstractMatrix{<:Integer}, hwall::AbstractMatrix{<:Integer}, vwall::AbstractMatrix{<:Integer}) # fill cells cells[m, n] = true percolated = false # bottom if m < size(cells, 1) && !hwall[m+1, n] && !cells[m+1, n] percolated = percolated || floodfill!(m + 1, n, cells, hwall, vwall) # The Bottom elseif m == size(cells, 1) && !hwall[m+1, n] return true end # left if n > 1 && !vwall[m, n] && !cells[m, n-1] percolated = percolated || floodfill!(m, n - 1, cells, hwall, vwall) end # right if n < size(cells, 2) && !vwall[m, n+1] && !cells[m, n+1] percolated = percolated || floodfill!(m, n + 1, cells, hwall, vwall) end # top if m > 1 && !hwall[m, n] && !cells[m-1, n] percolated = percolated || floodfill!(m - 1, n, cells, hwall, vwall) end return percolated end function pourontop!(g::Grid) m, n = 1, 1 percolated = false while !percolated && n ≤ size(g.cells, 2) percolated = !g.hwall[m, n] && floodfill!(m, n, g.cells, g.hwall, g.vwall) n += 1 end return percolated end   function main(probs, nrep::Integer=1000) sampleprinted = false pcount = zeros(Int, size(probs)) for (i, p) in enumerate(probs), _ in 1:nrep g = Grid(p) percolated = pourontop!(g) if percolated pcount[i] += 1 if !sampleprinted println(g) sampleprinted = true end end end return pcount ./ nrep end   probs = collect(10:-1:0) ./ 10 percprobs = main(probs)   println("Fraction of 1000 tries that percolate through:") for (pr, pp) in zip(probs, percprobs) @printf("\tp = %.3f ⇒ freq. = %5.3f\n", pr, pp) end
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random() const val RAND_MAX = 32767   // cell states const val FILL = 1 const val RWALL = 2 // right wall const val BWALL = 4 // bottom wall   val x = 10 val y = 10 var grid = IntArray(x * (y + 2)) var cells = 0 var end = 0 var m = 0 var n = 0   fun makeGrid(p: Double) { val thresh = (p * RAND_MAX).toInt() m = x n = y grid.fill(0) // clears grid for (i in 0 until m) grid[i] = BWALL or RWALL cells = m end = m for (i in 0 until y) { for (j in x - 1 downTo 1) { val r1 = rand.nextInt(RAND_MAX + 1) val r2 = rand.nextInt(RAND_MAX + 1) grid[end++] = (if (r1 < thresh) BWALL else 0) or (if (r2 < thresh) RWALL else 0) } val r3 = rand.nextInt(RAND_MAX + 1) grid[end++] = RWALL or (if (r3 < thresh) BWALL else 0) } }   fun showGrid() { for (j in 0 until m) print("+--") println("+")   for (i in 0..n) { print(if (i == n) " " else "|") for (j in 0 until m) { print(if ((grid[i * m + j + cells] and FILL) != 0) "[]" else " ") print(if ((grid[i * m + j + cells] and RWALL) != 0) "|" else " ") } println() if (i == n) return for (j in 0 until m) { print(if ((grid[i * m + j + cells] and BWALL) != 0) "+--" else "+ ") } println("+") } }   fun fill(p: Int): Boolean { if ((grid[p] and FILL) != 0) return false grid[p] = grid[p] or FILL if (p >= end) return true // success: reached bottom row return (((grid[p + 0] and BWALL) == 0) && fill(p + m)) || (((grid[p + 0] and RWALL) == 0) && fill(p + 1)) || (((grid[p - 1] and RWALL) == 0) && fill(p - 1)) || (((grid[p - m] and BWALL) == 0) && fill(p - m)) }   fun percolate(): Boolean { var i = 0 while (i < m && !fill(cells + i)) i++ return i < m }   fun main(args: Array<String>) { makeGrid(0.5) percolate() showGrid()   println("\nrunning $x x $y grids 10,000 times for each p:") for (p in 1..9) { var cnt = 0 val pp = p / 10.0 for (i in 0 until 10_000) { makeGrid(pp) if (percolate()) cnt++ } println("p = %3g: %.4f".format(pp, cnt.toDouble() / 10_000)) } }
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\displaystyle v} be a vector of n {\displaystyle n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} ; the probability of a value being 0 is therefore 1 − p {\displaystyle 1-p} . Define a run of 1s as being a group of consecutive 1s in the vector bounded either by the limits of the vector or by a 0. Let the number of such runs in a given vector of length n {\displaystyle n} be R n {\displaystyle R_{n}} . For example, the following vector has R 10 = 3 {\displaystyle R_{10}=3} [1 1 0 0 0 1 0 1 1 1] ^^^ ^ ^^^^^ Percolation theory states that K ( p ) = lim n → ∞ R n / n = p ( 1 − p ) {\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)} Task Any calculation of R n / n {\displaystyle R_{n}/n} for finite n {\displaystyle n} is subject to randomness so should be computed as the average of t {\displaystyle t} runs, where t ≥ 100 {\displaystyle t\geq 100} . For values of p {\displaystyle p} of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} . Show your output here. See also s-Run on Wolfram mathworld.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) t := integer(A[2]) | 500   write(left("p",8)," ",left("n",8)," ",left("p(1-p)",10)," ",left("SimK(p)",10)) every (p := 0.1 | 0.3 | 0.5 | 0.7 | 0.9, n := 1000 | 2000 | 3000) do { Ka := 0.0 every !t do { every (v := "", !n) do v ||:= |((?0.1 > p,"0")|"1") R := 0 v ? while tab(upto('1')) do R +:= (tab(many('1')), 1) Ka +:= real(R)/n } write(left(p,8)," ",left(n,8)," ",left(p*(1-p),10)," ",left(Ka/t, 10)) } end
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Nim
Nim
import random, sequtils, strformat, strutils   type Grid = seq[string] # Row first, i.e. [y][x].   const Full = '.' Used = '#' Empty = ' '     proc newGrid(p: float; xsize, ysize: Positive): Grid =   result = newSeqWith(ysize, newString(xsize)) for row in result.mitems: for cell in row.mitems: cell = if rand(1.0) < p: Full else: Empty     proc `$`(grid: Grid): string =   # Preallocate result to avoid multiple reallocations. result = newStringOfCap((grid.len + 2) * (grid[0].len + 3))   result.add '+' result.add repeat('-', grid[0].len) result.add "+\n"   for row in grid: result.add '|' result.add row result.add "|\n"   result.add '+' for cell in grid[^1]: result.add if cell == Used: Used else: '-' result.add '+'     proc use(grid: var Grid; x, y: int): bool = if y < 0 or x < 0 or x >= grid[0].len or grid[y][x] != Full: return false # Off the edges, empty, or used. grid[y][x] = Used if y == grid.high: return true # On the bottom.   # Try down, right, left, up in that order. result = grid.use(x, y + 1) or grid.use(x + 1, y) or grid.use(x - 1, y) or grid.use(x, y - 1)     proc percolate(grid: var Grid): bool = for x in 0..grid[0].high: if grid.use(x, 0): return true     const M = 15 N = 15   T = 1000 MinP = 0.0 MaxP = 1.0 ΔP = 0.1     randomize() var grid = newGrid(0.5, M, N) discard grid.percolate() echo grid echo ""   var p = MinP while p < MaxP: var count = 0 for _ in 1..T: var grid = newGrid(p, M, N) if grid.percolate(): inc count echo &"p = {p:.2f}: {count / T:.4f}" p += ΔP
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Perl
Perl
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;
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Amazing_Hopper
Amazing Hopper
  /* hopper-JAMBO - a flavour of Amazing Hopper! */   #include <jambo.h> Main leng=0 Void(lista) Set("la realidad","escapa","a los sentidos"), Apnd list(lista) Length(lista), Move to(leng) Toksep(" ") Printnl( lista ) Set(1) Gosub(Permutar) End-Return   Subrutines   Define( Permutar, pos ) If ( Sub(leng, pos) Isgeq(1) ) i=pos Loop if( Less( i, leng ) ) Plusone(pos), Gosub(Permutar) Set( pos ), Gosub(Rotate) Printnl( lista ) ++i Back Plusone(pos), Gosub(Permutar) Set( pos ), Gosub(Rotate) End If Return   Define ( Rotate, pos ) c=0, [pos] Get(lista), Move to(c) [ Plusone(pos): leng ] Cget(lista) [ pos: Minusone(leng) ] Cput(lista) Set(c), [ leng ] Cput(lista) Return  
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#D
D
import std.stdio;   void main() { auto sizes = [8, 24, 52, 100, 1020, 1024, 10_000]; foreach(s; sizes) { writefln("%5s : %5s", s, perfectShuffle(s)); } }   int perfectShuffle(int size) { import std.exception : enforce; enforce(size%2==0);   import std.algorithm : copy, equal; import std.range; int[] orig = iota(0, size).array;   int[] process; process.length = size; copy(orig, process);   for(int count=1; true; count++) { process = roundRobin(process[0..$/2], process[$/2..$]).array;   if (equal(orig, process)) { return count; } }   assert(false, "How did this get here?"); }
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Java
Java
// JAVA REFERENCE IMPLEMENTATION OF IMPROVED NOISE - COPYRIGHT 2002 KEN PERLIN.   public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, // FIND UNIT CUBE THAT Y = (int)Math.floor(y) & 255, // CONTAINS POINT. Z = (int)Math.floor(z) & 255; x -= Math.floor(x); // FIND RELATIVE X,Y,Z y -= Math.floor(y); // OF POINT IN CUBE. z -= Math.floor(z); double u = fade(x), // COMPUTE FADE CURVES v = fade(y), // FOR EACH OF X,Y,Z. w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, // HASH COORDINATES OF B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; // THE 8 CUBE CORNERS,   return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD grad(p[BA ], x-1, y , z )), // BLENDED lerp(u, grad(p[AB ], x , y-1, z ), // RESULTS grad(p[BB ], x-1, y-1, z ))),// FROM 8 lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), // CORNERS grad(p[BA+1], x-1, y , z-1 )), // OF CUBE lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } static double lerp(double t, double a, double b) { return a + t * (b - a); } static double grad(int hash, double x, double y, double z) { int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE double u = h<8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } static final int p[] = new int[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 }; static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } }
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#J
J
  Until =: conjunction def 'u^:(0 -: v)^:_' Filter =: (#~`)(`:6) totient =: 5&p: totient_chain =: [: }. (, totient@{:)Until(1={:) ptnQ =: (= ([: +/ totient_chain))&>  
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Java
Java
  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; } } }   }  
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card must have a pip value and a suit value which constitute the unique value of the card. Related tasks: Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser Go Fish
#Fortran
Fortran
MODULE Cards   IMPLICIT NONE   TYPE Card CHARACTER(5) :: value CHARACTER(8) :: suit END TYPE Card   TYPE(Card) :: deck(52), hand(52) TYPE(Card) :: temp   CHARACTER(5) :: pip(13) = (/"Two ", "Three", "Four ", "Five ", "Six ", "Seven", "Eight", "Nine ", "Ten ", & "Jack ", "Queen", "King ", "Ace "/) CHARACTER(8) :: suits(4) = (/"Clubs ", "Diamonds", "Hearts ", "Spades "/) INTEGER :: i, j, n, rand, dealt = 0 REAL :: x   CONTAINS   SUBROUTINE Init_deck ! Create deck DO i = 1, 4 DO j = 1, 13 deck((i-1)*13+j) = Card(pip(j), suits(i)) END DO END DO END SUBROUTINE Init_deck   SUBROUTINE Shuffle_deck ! Shuffle deck using Fisher-Yates algorithm DO i = 52-dealt, 1, -1 CALL RANDOM_NUMBER(x) rand = INT(x * i) + 1 temp = deck(rand) deck(rand) = deck(i) deck(i) = temp END DO END SUBROUTINE Shuffle_deck   SUBROUTINE Deal_hand(number) ! Deal from deck to hand INTEGER :: number DO i = 1, number hand(i) = deck(dealt+1) dealt = dealt + 1 END DO END SUBROUTINE   SUBROUTINE Print_hand ! Print cards in hand DO i = 1, dealt WRITE (*, "(3A)") TRIM(deck(i)%value), " of ", TRIM(deck(i)%suit) END DO WRITE(*,*) END SUBROUTINE Print_hand   SUBROUTINE Print_deck ! Print cards in deck DO i = dealt+1, 52 WRITE (*, "(3A)") TRIM(deck(i)%value), " of ", TRIM(deck(i)%suit) END DO WRITE(*,*) END SUBROUTINE Print_deck   END MODULE Cards
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ... Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions. Related Task Arithmetic-geometric mean/Calculate Pi
#Factor
Factor
USING: combinators.extras io kernel locals math prettyprint ; IN: rosetta-code.pi   :: calc-pi-digits ( -- ) 1 0 1 1 3 3 :> ( q! r! t! k! n! l! ) [ 4 q * r + t - n t * < [ n pprint flush r n t * - 10 * 3 q * r + 10 * t /i n 10 * - n! r! q 10 * q! ] [ 2 q * r + l * 7 k * q * 2 + r l * + t l * /i n! r! k q * q! t l * t! l 2 + l! k 1 + k! ] if ] forever ;   MAIN: calc-pi-digits
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   1   loses the player's total points   for that turn   and their turn finishes with play passing to the next player. Holding:   the player's score for that round is added to their total and becomes safe from the effects of throwing a   1   (one).   The player's turn finishes with play passing to the next player. Task Create a program to score for, and simulate dice throws for, a two-person game. Related task   Pig the dice game/Player
#MiniScript
MiniScript
// Pig the Dice for two players. Player = {} Player.score = 0 Player.doTurn = function() rolls = 0 pot = 0 print self.name + "'s Turn!" while true if self.score + pot >= goal then print " " + self.name.upper + " WINS WITH " + (self.score + pot) + "!" inp = "H" else inp = input(self.name + ", you have " + pot + " in the pot. [R]oll or Hold? ") end if if inp == "" or inp[0].upper == "R" then die = ceil(rnd*6) if die == 1 then print " You roll a 1. Busted!" return else print " You roll a " + die + "." pot = pot + die end if else self.score = self.score + pot return end if end while end function   p1 = new Player p1.name = "Alice" p2 = new Player p2.name = "Bob" goal = 100   while p1.score < goal and p2.score < goal for player in [p1, p2] print print p1.name + ": " + p1.score + " | " + p2.name + ": " + p2.score player.doTurn if player.score >= goal then break end for end while
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pernicious number. Task display the first   25   pernicious numbers   (in decimal). display all pernicious numbers between   888,888,877   and   888,888,888   (inclusive). display each list of integers on one line   (which may or may not include a title). See also Sequence   A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences. Rosetta Code entry   population count, evil numbers, odious numbers.
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64   Function SumBinaryDigits(number As Integer) As Integer If number < 0 Then number = -number ' convert negative numbers to positive Var sum = 0 While number > 0 sum += number Mod 2 number \= 2 Wend Return sum End Function   Function IsPrime(number As Integer) As Boolean If number <= 1 Then Return false ElseIf number <= 3 Then Return true ElseIf number Mod 2 = 0 OrElse number Mod 3 = 0 Then Return false End If Var i = 5 While i * i <= number If number Mod i = 0 OrElse number Mod (i + 2) = 0 Then Return false End If i += 6 Wend Return True End Function   Function IsPernicious(number As Integer) As Boolean Dim popCount As Integer = SumBinaryDigits(number) Return IsPrime(popCount) End Function   Dim As Integer n = 1, count = 0 Print "The following are the first 25 pernicious numbers :" Print   Do If IsPernicious(n) Then Print Using "###"; n; count += 1 End If n += 1 Loop Until count = 25   Print : Print Print "The pernicious numbers between 888,888,877 and 888,888,888 inclusive are :" Print For n = 888888877 To 888888888 If IsPernicious(n) Then Print Using "##########"; n; Next Print : Print Print "Press any key to exit the program" Sleep End  
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them. Task Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind. See also Wikipedia - Pierpont primes OEIS:A005109 - Class 1 -, or Pierpont primes OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
#Swift
Swift
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])")
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them. Task Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind. See also Wikipedia - Pierpont primes OEIS:A005109 - Class 1 -, or Pierpont primes OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var pierpont = Fn.new { |n, first| var p = [ List.filled(n, null), List.filled(n, null) ] for (i in 0...n) { p[0][i] = BigInt.zero p[1][i] = BigInt.zero } p[0][0] = BigInt.two var count = 0 var count1 = 1 var count2 = 0 var s = [BigInt.one] var i2 = 0 var i3 = 0 var k = 1 while (count < n) { var n2 = s[i2] * 2 var n3 = s[i3] * 3 var t if (n2 < n3) { t = n2 i2 = i2 + 1 } else { t = n3 i3 = i3 + 1 } if (t > s[k-1]) { s.add(t.copy()) k = k + 1 t = t.inc if (count1 < n && t.isProbablePrime(5)) { p[0][count1] = t.copy() count1 = count1 + 1 } t = t - 2 if (count2 < n && t.isProbablePrime(5)) { p[1][count2] = t.copy() count2 = count2 + 1 } count = count1.min(count2) } } return p }   var p = pierpont.call(250, true) System.print("First 50 Pierpont primes of the first kind:") for (i in 0...50) { Fmt.write("$8i ", p[0][i]) if ((i-9)%10 == 0) System.print() } System.print("\nFirst 50 Pierpont primes of the second kind:") for (i in 0...50) { Fmt.write("$8i ", p[1][i]) if ((i-9)%10 == 0) System.print() }   System.print("\n250th Pierpont prime of the first kind: %(p[0][249])") System.print("\n250th Pierpont prime of the second kind: %(p[1][249])")
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#jq
jq
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Julia
Julia
array = [1,2,3] rand(array)
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#K
K
1?"abcdefg" ,"e"
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#jq
jq
def reverse_string: explode | reverse | implode;   "rosetta code phrase reversal" | split(" ") as $words | "0. input: \(.)", "1. string reversed: \(reverse_string)", "2. each word reversed: \($words | map(reverse_string) | join(" "))", "3. word-order reversed: \($words | reverse | join(" "))"
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Julia
Julia
  s = "rosetta code phrase reversal"   println("The original phrase.") println(" ", s)   println("Reverse the string.") t = reverse(s) println(" ", t)   println("Reverse each individual word in the string.") t = join(map(reverse, split(s, " ")), " ") println(" ", t)   println("Reverse the order of each word of the phrase.") t = join(reverse(split(s, " ")), " ") println(" ", t)  
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n. Task Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer). Generate and show all the derangements of 4 integers using the above routine. Create a function that calculates the subfactorial of n, !n. Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive. Optional stretch goal   Calculate    !20 Related tasks   Anagrams/Deranged anagrams   Best shuffle   Left_factorials Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Groovy
Groovy
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 }
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#Kotlin
Kotlin
// version 1.1.2   fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } // permutation val q = IntArray(n) { it } // inverse permutation val d = IntArray(n) { -1 } // direction = 1 or -1 var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>()   fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 }   permute(0) return perms to signs }   fun printPermsAndSigns(perms: List<IntArray>, signs: List<Int>) { for ((i, perm) in perms.withIndex()) { println("${perm.contentToString()} -> sign = ${signs[i]}") } }   fun main(args: Array<String>) { val (perms, signs) = johnsonTrotter(3) printPermsAndSigns(perms, signs) println() val (perms2, signs2) = johnsonTrotter(4) printPermsAndSigns(perms2, signs2) }
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment subjects, or to a group of m {\displaystyle m} control subjects. Members of the treatment group were given the treatment, and members of the control group were given a placebo. The effect of the treatment or placebo on each volunteer was measured and reported in this table. Table of experimental results Treatment group Control group 85 68 88 41 75 10 66 49 25 16 29 65 83 32 39 92 97 28 98 Write a program that performs a permutation test to judge whether the treatment had a significantly stronger effect than the placebo. Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size n {\displaystyle n} and a control group of size m {\displaystyle m} (i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless. Note that the number of alternatives will be the binomial coefficient ( n + m n ) {\displaystyle {\tbinom {n+m}{n}}} . Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group. Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater. Note that they should sum to 100%. Extremely dissimilar values are evidence of an effect not entirely due to chance, but your program need not draw any conclusions. You may assume the experimental data are known at compile time if that's easier than loading them at run time. Test your solution on the data given above.
#Python
Python
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=%.2f%%, over=%.2f%%" % (under, 100. - under))
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#D
D
import std.stdio, std.exception, std.range, std.math, bitmap;   void main() { Image!RGB i1, i2; i1 = i1.loadPPM6("Lenna50.ppm"); i2 = i2.loadPPM6("Lenna100.ppm");   enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");   real dif = 0.0; foreach (p, q; zip(i1.image, i2.image)) dif += abs(p.r - q.r) + abs(p.g - q.g) + abs(p.b - q.b);   immutable nData = i1.nx * i1.ny * 3; writeln("Difference (percentage): ", (dif / 255.0 * 100) / nData); }
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#E
E
def imageDifference(a, b) { require(a.width() == b.width()) require(a.height() == b.height()) def X := 0..!(a.width()) def Y := 0..!(a.height())   var sumByteDiff := 0 for y in Y { for x in X { def ca := a[x, y] def cb := b[x, y] sumByteDiff += (ca.rb() - cb.rb()).abs() \ + (ca.gb() - cb.gb()).abs() \ + (ca.bb() - cb.bb()).abs() } println(y) } return sumByteDiff / (255 * 3 * a.width() * a.height()) }   def imageDifferenceTask() { println("Read 1...") def a := readPPM(<import:java.io.makeFileInputStream>(<file:Lenna50.ppm>)) println("Read 2...") def b := readPPM(<import:java.io.makeFileInputStream>(<file:Lenna100.ppm>)) println("Compare...") def d := imageDifference(a, b) println(`${d * 100}% different.`) }
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Julia
Julia
using Random   struct GridPoint x::Int; y::Int end   const nrows, ncols, target = 8, 8, 12 const grid = fill('*', nrows, ncols) const shapeletters = ['F', 'I', 'L', 'N', 'P', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] const shapevec = [ [(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)], [(0,1, 0,2, 0,3, 0,4), (1,0, 2,0, 3,0, 4,0)], [(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)], [(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)], [(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)], [(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)], [(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)], [(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)], [(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)], [(1,-1, 1,0, 1,1, 2,0)], [(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)], [(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)]] const shapes = Dict{Char,Vector{Vector{GridPoint}}}() const placed = Dict{Char,Bool}()   for (ltr, vec) in zip(shapeletters, shapevec) shapes[ltr] = [[GridPoint(v[i], v[i + 1]) for i in 1:2:7] for v in vec] placed[ltr] = false end   printgrid(m, w, h) = for x in 1:w for y in 1:h print(m[x, y], " ") end; println() end   function tryplaceorientation(o, R, C, shapeindex) for p in o r, c = R + p.x, C + p.y if r < 1 || r > nrows || c < 1 || c > ncols || grid[r, c] != '*' return false end end grid[R, C] = shapeindex for p in o grid[R + p.x, C + p.y] = shapeindex end true end   function removeorientation(o, r, c) grid[r, c] = '*' for p in o grid[r + p.x, c + p.y] = '*' end end   function solve(pos, nplaced) if nplaced == target return true end row, col = divrem(pos, ncols) .+ 1 if grid[row, col] != '*' return solve(pos + 1, nplaced) end for i in keys((shapes)) if !placed[i] for orientation in shapes[i] if tryplaceorientation(orientation, row, col, i) placed[i] = true if solve(pos + 1, nplaced + 1) return true else removeorientation(orientation, row, col) placed[i] = false end end end end end false end   function placepentominoes() for p in zip(shuffle(collect(1:nrows))[1:4], shuffle(collect(1:ncols))[1:4]) grid[p[1], p[2]] = ' ' end if solve(0, 0) printgrid(grid, nrows, ncols) else println("No solution found.") end end   placepentominoes()  
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Kotlin
Kotlin
// Version 1.1.4-3   import java.util.Random   val F = arrayOf( intArrayOf(1, -1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 2, 0), intArrayOf(1, 0, 1, 1, 1, 2, 2, 1), intArrayOf(1, 0, 1, 1, 2, -1, 2, 0), intArrayOf(1, -2, 1, -1, 1, 0, 2, -1), intArrayOf(0, 1, 1, 1, 1, 2, 2, 1), intArrayOf(1, -1, 1, 0, 1, 1, 2, -1), intArrayOf(1, -1, 1, 0, 2, 0, 2, 1) )   val I = arrayOf( intArrayOf(0, 1, 0, 2, 0, 3, 0, 4), intArrayOf(1, 0, 2, 0, 3, 0, 4, 0) )   val L = arrayOf( intArrayOf(1, 0, 1, 1, 1, 2, 1, 3), intArrayOf(1, 0, 2, 0, 3, -1, 3, 0), intArrayOf(0, 1, 0, 2, 0, 3, 1, 3), intArrayOf(0, 1, 1, 0, 2, 0, 3, 0), intArrayOf(0, 1, 1, 1, 2, 1, 3, 1), intArrayOf(0, 1, 0, 2, 0, 3, 1, 0), intArrayOf(1, 0, 2, 0, 3, 0, 3, 1), intArrayOf(1, -3, 1, -2, 1, -1, 1, 0) )   val N = arrayOf( intArrayOf(0, 1, 1, -2, 1, -1, 1, 0), intArrayOf(1, 0, 1, 1, 2, 1, 3, 1), intArrayOf(0, 1, 0, 2, 1, -1, 1, 0), intArrayOf(1, 0, 2, 0, 2, 1, 3, 1), intArrayOf(0, 1, 1, 1, 1, 2, 1, 3), intArrayOf(1, 0, 2, -1, 2, 0, 3, -1), intArrayOf(0, 1, 0, 2, 1, 2, 1, 3), intArrayOf(1, -1, 1, 0, 2, -1, 3, -1) )   val P = arrayOf( intArrayOf(0, 1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 0, 2, 1, 0, 1, 1), intArrayOf(1, 0, 1, 1, 2, 0, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 1, 1), intArrayOf(0, 1, 1, 0, 1, 1, 1, 2), intArrayOf(1, -1, 1, 0, 2, -1, 2, 0), intArrayOf(0, 1, 0, 2, 1, 1, 1, 2), intArrayOf(0, 1, 1, 0, 1, 1, 2, 0) )   val T = arrayOf( intArrayOf(0, 1, 0, 2, 1, 1, 2, 1), intArrayOf(1, -2, 1, -1, 1, 0, 2, 0), intArrayOf(1, 0, 2, -1, 2, 0, 2, 1), intArrayOf(1, 0, 1, 1, 1, 2, 2, 0) )   val U = arrayOf( intArrayOf(0, 1, 0, 2, 1, 0, 1, 2), intArrayOf(0, 1, 1, 1, 2, 0, 2, 1), intArrayOf(0, 2, 1, 0, 1, 1, 1, 2), intArrayOf(0, 1, 1, 0, 2, 0, 2, 1) )   val V = arrayOf( intArrayOf(1, 0, 2, 0, 2, 1, 2, 2), intArrayOf(0, 1, 0, 2, 1, 0, 2, 0), intArrayOf(1, 0, 2, -2, 2, -1, 2, 0), intArrayOf(0, 1, 0, 2, 1, 2, 2, 2) )   val W = arrayOf( intArrayOf(1, 0, 1, 1, 2, 1, 2, 2), intArrayOf(1, -1, 1, 0, 2, -2, 2, -1), intArrayOf(0, 1, 1, 1, 1, 2, 2, 2), intArrayOf(0, 1, 1, -1, 1, 0, 2, -1) )   val X = arrayOf(intArrayOf(1, -1, 1, 0, 1, 1, 2, 0))   val Y = arrayOf( intArrayOf(1, -2, 1, -1, 1, 0, 1, 1), intArrayOf(1, -1, 1, 0, 2, 0, 3, 0), intArrayOf(0, 1, 0, 2, 0, 3, 1, 1), intArrayOf(1, 0, 2, 0, 2, 1, 3, 0), intArrayOf(0, 1, 0, 2, 0, 3, 1, 2), intArrayOf(1, 0, 1, 1, 2, 0, 3, 0), intArrayOf(1, -1, 1, 0, 1, 1, 1, 2), intArrayOf(1, 0, 2, -1, 2, 0, 3, 0) )   val Z = arrayOf( intArrayOf(0, 1, 1, 0, 2, -1, 2, 0), intArrayOf(1, 0, 1, 1, 1, 2, 2, 2), intArrayOf(0, 1, 1, 1, 2, 1, 2, 2), intArrayOf(1, -2, 1, -1, 1, 0, 2, -2) )   val shapes = arrayOf(F, I, L, N, P, T, U, V, W, X, Y, Z) val rand = Random()   val symbols = "FILNPTUVWXYZ-".toCharArray()   val nRows = 8 val nCols = 8 val blank = 12   val grid = Array(nRows) { IntArray(nCols) } val placed = BooleanArray(symbols.size - 1)   fun tryPlaceOrientation(o: IntArray, r: Int, c: Int, shapeIndex: Int): Boolean { for (i in 0 until o.size step 2) { val x = c + o[i + 1] val y = r + o[i] if (x !in (0 until nCols) || y !in (0 until nRows) || grid[y][x] != - 1) return false } grid[r][c] = shapeIndex for (i in 0 until o.size step 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex return true }   fun removeOrientation(o: IntArray, r: Int, c: Int) { grid[r][c] = -1 for (i in 0 until o.size step 2) grid[r + o[i]][c + o[i + 1]] = -1 }   fun solve(pos: Int, numPlaced: Int): Boolean { if (numPlaced == shapes.size) return true val row = pos / nCols val col = pos % nCols if (grid[row][col] != -1) return solve(pos + 1, numPlaced)   for (i in 0 until shapes.size) { if (!placed[i]) { for (orientation in 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 }   fun shuffleShapes() { var n = shapes.size while (n > 1) { val r = rand.nextInt(n--) val tmp = shapes[r] shapes[r] = shapes[n] shapes[n] = tmp val tmpSymbol= symbols[r] symbols[r] = symbols[n] symbols[n] = tmpSymbol } }   fun printResult() { for (r in grid) { for (i in r) print("${symbols[i]} ") println() } }   fun main(args: Array<String>) { shuffleShapes() for (r in 0 until nRows) grid[r].fill(-1) for (i in 0..3) { var randRow: Int var randCol: Int do { randRow = rand.nextInt(nRows) randCol = rand.nextInt(nCols) } while (grid[randRow][randCol] == blank) grid[randRow][randCol] = blank } if (solve(0, 0)) printResult() else println("No solution") }
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Phix
Phix
with javascript_semantics sequence grid integer w, ww procedure make_grid(atom p) ww = w*w grid = repeat(0,ww) for i=1 to ww do grid[i] = -(rnd()<p) end for end procedure constant alpha = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZ"& "abcdefghijklmnopqrstuvwxyz" procedure show_cluster() for i=1 to ww do integer gi = grid[i]+2 grid[i] = iff(gi<=length(alpha)?alpha[gi]:'?') end for puts(1,join_by(grid,w,w,"")) end procedure procedure recur(integer x, v) if x>=1 and x<=ww and grid[x]==-1 then grid[x] = v recur(x-w, v) recur(x-1, v) recur(x+1, v) recur(x+w, v) end if end procedure function count_clusters() integer cls = 0 for i=1 to ww do if grid[i]=-1 then cls += 1 recur(i, cls) end if end for return cls end function function tests(int n, atom p) atom k = 0 for i=1 to n do make_grid(p) k += count_clusters()/ww end for return k / n end function procedure main() w = 15 make_grid(0.5) printf(1,"width=15, p=0.5, %d clusters:\n", count_clusters()) show_cluster() printf(1,"\np=0.5, iter=5:\n") w = 4 while w<=4096 do printf(1,"%5d %9.6f\n", {w, tests(5,0.5)}) w *= 4 end while end procedure main()
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Lucas-Lehmer test   is used to find primes of the form   2n-1,   all known perfect numbers can be derived from these primes using the formula   (2n - 1) × 2n - 1. It is not known if there are any odd perfect numbers (any that exist are larger than 102000). The number of   known   perfect numbers is   51   (as of December, 2018),   and the largest known perfect number contains  49,724,095  decimal digits. See also   Rational Arithmetic   Perfect numbers on OEIS   Odd Perfect showing the current status of bounds on odd perfect numbers.
#AppleScript
AppleScript
-- PERFECT NUMBERS -----------------------------------------------------------   -- perfect :: integer -> bool on perfect(n)   -- isFactor :: integer -> bool script isFactor on |λ|(x) n mod x = 0 end |λ| end script   -- quotient :: number -> number script quotient on |λ|(x) n / x end |λ| end script   -- sum :: number -> number -> number script sum on |λ|(a, b) a + b end |λ| end script   -- Integer factors of n below the square root set lows to filter(isFactor, enumFromTo(1, (n ^ (1 / 2)) as integer))   -- low and high factors (quotients of low factors) tested for perfection (n > 1) and (foldl(sum, 0, (lows & map(quotient, lows))) / 2 = n) end perfect     -- TEST ---------------------------------------------------------------------- on run   filter(perfect, enumFromTo(1, 10000))   --> {6, 28, 496, 8128}   end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m > n then set d to -1 else set d to 1 end if set lst to {} repeat with i from m to n by d set end of lst to i end repeat return lst end enumFromTo   -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Nim
Nim
import random, sequtils, strformat, tables   type   Cell = object full: bool right, down: bool # True if open to the right (x+1) or down (y+1).   Grid = seq[seq[Cell]] # Row first, i.e. [y][x].     proc newGrid(p: float; xsize, ysize: Positive): Grid =   result = newSeqWith(ysize, newSeq[Cell](xsize)) for row in result.mitems: for x in 0..(xsize - 2): if rand(1.0) > p: row[x].right = true if rand(1.0) > p: row[x].down = true if rand(1.0) > p: row[xsize - 1].down = true     const Full = {false: " ", true: "()"}.toTable HOpen = {false: "--", true: " "}.toTable VOpen = {false: "|", true: " "}.toTable   proc `$`(grid: Grid): string =   # Preallocate result to avoid multiple reallocations. result = newStringOfCap((grid.len + 1) * grid[0].len * 7)   for _ in 0..grid[0].high: result.add '+' result.add HOpen[false] result.add "+\n"   for row in grid: result.add VOpen[false] for cell in row: result.add Full[cell.full] result.add VOpen[cell.right] result.add '\n' for cell in row: result.add '+' result.add HOpen[cell.down] result.add "+\n"   for cell in grid[^1]: result.add ' ' result.add Full[cell.down and cell.full]     proc fill(grid: var Grid; x, y: Natural): bool =   if y >= grid.len: return true # Out the bottom. if grid[y][x].full: return false # Already filled. grid[y][x].full = true   if grid[y][x].down and grid.fill(x, y + 1): return true if grid[y][x].right and grid.fill(x + 1, y): return true if x > 0 and grid[y][x - 1].right and grid.fill(x - 1, y): return true if y > 0 and grid[y - 1][x].down and grid.fill(x, y - 1): return true     proc percolate(grid: var Grid): bool = for x in 0..grid[0].high: if grid.fill(x, 0): return true     const M = 10 N = 10 T = 1000 MinP = 0.1 MaxP = 0.99 ΔP = 0.1   # Purposely don't seed for a repeatable example grid. var grid = newGrid(0.4, M, N) discard grid.percolate() echo grid echo ""   randomize() var p = MinP while p < MaxP: var count = 0 for _ in 1..T: var grid = newGrid(p, M, N) if grid.percolate(): inc count echo &"p = {p:.2f}: {count / T:.3f}" p += ΔP
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Perl
Perl
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 == $#bond; } }   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 }
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\displaystyle v} be a vector of n {\displaystyle n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} ; the probability of a value being 0 is therefore 1 − p {\displaystyle 1-p} . Define a run of 1s as being a group of consecutive 1s in the vector bounded either by the limits of the vector or by a 0. Let the number of such runs in a given vector of length n {\displaystyle n} be R n {\displaystyle R_{n}} . For example, the following vector has R 10 = 3 {\displaystyle R_{10}=3} [1 1 0 0 0 1 0 1 1 1] ^^^ ^ ^^^^^ Percolation theory states that K ( p ) = lim n → ∞ R n / n = p ( 1 − p ) {\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)} Task Any calculation of R n / n {\displaystyle R_{n}/n} for finite n {\displaystyle n} is subject to randomness so should be computed as the average of t {\displaystyle t} runs, where t ≥ 100 {\displaystyle t\geq 100} . For values of p {\displaystyle p} of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} . Show your output here. See also s-Run on Wolfram mathworld.
#J
J
  NB. translation of python   NB. 'N P T' =: 100 0.5 500 NB. hypothetical example values, to aid comprehension...   newv =: (> ?@(#&0))~ NB. generate a random binary vector. Use: N newv P runs =: {: + [: +/ 1 0&E. NB. add the tail to the sum of 1 0 occurrences Use: runs V mean_run_density =: [ %~ [: runs newv NB. perform experiment. Use: N mean_run_density P   main =: 3 : 0 NB.Usage: main T T =. y smoutput' T P N P(1-P) SIM DELTA%' for_P. 10 %~ >: +: i. 5 do. LIMIT =. (* -.) P smoutput '' for_N. 2 ^ 10 + +: i. 3 do. SIM =. T %~ +/ (N mean_run_density P"_)^:(<T) 0 smoutput 4 5j2 6 6j3 6j3 4j1 ": T, P, N, LIMIT, SIM, SIM (100 * [`(|@:(- % ]))@.(0 ~: ])) LIMIT end. end. EMPTY )  
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Phix
Phix
with javascript_semantics string grid integer m, n, last, lastrow enum SOLID = '#', EMPTY=' ', WET = 'v' procedure make_grid(integer x, y, atom p) m = x n = y grid = repeat('\n',x*(y+1)+1) last = length(grid) lastrow = last-n for i=0 to x-1 do for j=1 to y do grid[1+i*(y+1)+j] = iff(rnd()<p?EMPTY:SOLID) end for end for end procedure function ff(integer i) -- flood_fill if i<=0 or i>=last or grid[i]!=EMPTY then return 0 end if grid[i] = WET return i>=lastrow or ff(i+m+1) or ff(i+1) or ff(i-1) or ff(i-m-1) end function function percolate() for i=2 to m+1 do if ff(i) then return true end if end for return false end function procedure main() make_grid(15,15,0.55) {} = percolate() printf(1,"%dx%d grid:%s",{15,15,grid}) puts(1,"\nrunning 10,000 tests for each case:\n") for ip=0 to 10 do atom p = ip/10 integer count = 0 for i=1 to 10000 do make_grid(15, 15, p) count += percolate() end for printf(1,"p=%.1f:  %6.4f\n", {p, count/10000}) end for end procedure main()
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#APL
APL
  ⍝ Builtin version, takes a vector: ⎕CY'dfns' perms←{↓⍵[pmat ≢⍵]} ⍝ pmat always gives lexicographically ordered permutations.   ⍝ Recursive fast implementation, courtesy of dzaima from The APL Orchard: dpmat←{1=⍵:,⊂,0 ⋄ (⊃,/)¨(⍳⍵)⌽¨⊂(⊂(!⍵-1)⍴⍵-1),⍨∇⍵-1} perms2←{↓⍵[1+⍉↑dpmat ≢⍵]}  
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#Delphi
Delphi
  program Perfect_shuffle;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TDeck = record Cards: TArray<Integer>; Len: Integer; constructor Create(deckSize: Integer); overload; constructor Create(deck: TDeck); overload; procedure shuffleDeck(); class operator Equal(a, b: TDeck): boolean; function ShufflesRequired: Integer; procedure Assign(a: TDeck); end;   { TDeck }   procedure TDeck.Assign(a: TDeck); begin Len := a.Len; Cards := copy(a.Cards, 0, len); end;   constructor TDeck.Create(deckSize: Integer); begin if deckSize < 1 then raise Exception.Create('Error: Deck size must have above zero');   if Odd(deckSize) then raise Exception.Create('Error: Deck size must be even');   SetLength(Cards, deckSize); Len := deckSize;   for var i := 0 to High(Cards) do Cards[i] := i; end;   constructor TDeck.Create(deck: TDeck); begin Assign(deck); end;   class operator TDeck.Equal(a, b: TDeck): boolean; begin if a.len <> b.len then raise Exception.Create('Error: Decks aren''t equally sized');   if a.Len = 0 then exit(True);   for var i := 0 to a.Len - 1 do if a.Cards[i] <> b.Cards[i] then exit(False);   Result := True; end;   procedure TDeck.shuffleDeck; var tmp: TArray<Integer>; begin SetLength(tmp, len); for var i := 0 to len div 2 - 1 do begin tmp[i * 2] := Cards[i]; tmp[i * 2 + 1] := Cards[len div 2 + i]; end; Cards := copy(tmp, 0, len); end;   function TDeck.ShufflesRequired: Integer; var ref: TDeck; begin Result := 1; ref := TDeck.Create(self); shuffleDeck; while not (self = ref) do begin shuffleDeck; inc(Result); end; end;   const cases: TArray<Integer> = [8, 24, 52, 100, 1020, 1024, 10000];   begin for var size in cases do begin var deck := TDeck.Create(size); writeln(format('Cards count: %d, shuffles required: %d', [size, deck.ShufflesRequired])); end; readln; end.
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Julia
Julia
const permutation = UInt8[ 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]   function grad(h::Integer, x, y, z) h &= 15 # CONVERT LO 4 BITS OF HASH CODE u = h < 8 ? x : y # INTO 12 GRADIENT DIRECTIONS. v = h < 4 ? y : h == 12 || h == 14 ? x : z (h & 1 == 0 ? u : -u) + (h & 2 == 0 ? v : -v) end   function perlinsnoise(x, y, z) p = vcat(permutation, permutation) fade(t) = t * t * t * (t * (t * 6 - 15) + 10) lerp(t, a, b) = a + t * (b - a) floorb(x) = Int(floor(x)) & 0xff X, Y, Z = floorb(x), floorb(y), floorb(z) # FIND UNIT CUBE THAT CONTAINS POINT. x, y, z = x - floor(x), y - floor(y), z - floor(z) # FIND RELATIVE X,Y,Z OF POINT IN CUBE. u, v, w = fade(x), fade(y), fade(z) # COMPUTE FADE CURVES FOR EACH OF X,Y,Z. A = p[X + 1] + Y; AA = p[A + 1] + Z; AB = p[A + 2] + Z B = p[X + 2] + Y; BA = p[B + 1] + Z; BB = p[B + 2] + Z # HASH COORDINATES OF THE 8 CUBE CORNERS   return lerp(w, lerp(v, lerp(u, grad(p[AA + 1], x , y , z ), # AND ADD grad(p[BA + 1], x - 1, y , z )), # BLENDED lerp(u, grad(p[AB + 1], x , y - 1, z ), # RESULTS grad(p[BB + 1], x - 1, y - 1, z ))), # FROM 8 lerp(v, lerp(u, grad(p[AA + 2], x , y , z - 1 ), # CORNERS grad(p[BA + 2], x - 1, y , z - 1)), # OF CUBE. lerp(u, grad(p[AB + 2], x , y - 1, z - 1 ), grad(p[BB + 2], x - 1, y - 1, z - 1)))) end   println("Perlin noise applied to (3.14, 42.0, 7.0) gives ", perlinsnoise(3.14, 42.0, 7.0))  
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Kotlin
Kotlin
// version 1.1.3   object Perlin {   private val permutation = intArrayOf( 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 )   private val p = IntArray(512) { if (it < 256) permutation[it] else permutation[it - 256] }   fun noise(x: Double, y: Double, z: Double): Double { // Find unit cube that contains point val xi = Math.floor(x).toInt() and 255 val yi = Math.floor(y).toInt() and 255 val zi = Math.floor(z).toInt() and 255   // Find relative x, y, z of point in cube val xx = x - Math.floor(x) val yy = y - Math.floor(y) val zz = z - Math.floor(z)   // Compute fade curves for each of xx, yy, zz val u = fade(xx) val v = fade(yy) val w = fade(zz)   // Hash co-ordinates of the 8 cube corners // and add blended results from 8 corners of cube   val a = p[xi] + yi val aa = p[a] + zi val ab = p[a + 1] + zi val b = p[xi + 1] + yi val ba = p[b] + zi val bb = p[b + 1] + zi   return lerp(w, lerp(v, lerp(u, grad(p[aa], xx, yy, zz), grad(p[ba], xx - 1, yy, zz)), lerp(u, grad(p[ab], xx, yy - 1, zz), grad(p[bb], xx - 1, yy - 1, zz))), lerp(v, lerp(u, grad(p[aa + 1], xx, yy, zz - 1), grad(p[ba + 1], xx - 1, yy, zz - 1)), lerp(u, grad(p[ab + 1], xx, yy - 1, zz - 1), grad(p[bb + 1], xx - 1, yy - 1, zz - 1)))) }   private fun fade(t: Double) = t * t * t * (t * (t * 6 - 15) + 10)   private fun lerp(t: Double, a: Double, b: Double) = a + t * (b - a)   private fun grad(hash: Int, x: Double, y: Double, z: Double): Double { // Convert low 4 bits of hash code into 12 gradient directions val h = hash and 15 val u = if (h < 8) x else y val v = if (h < 4) y else if (h == 12 || h == 14) x else z return (if ((h and 1) == 0) u else -u) + (if ((h and 2) == 0) v else -v) } }   fun main(args: Array<String>) { println(Perlin.noise(3.14, 42.0, 7.0)) }
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => showLog( take(20, perfectTotients()) );   // perfectTotients :: Generator [Int] function* perfectTotients() { const phi = memoized( n => length( filter( k => 1 === gcd(n, k), enumFromTo(1, n) ) ) ), imperfect = n => n !== sum( tail(iterateUntil( x => 1 === x, phi, n )) ); let ys = dropWhileGen(imperfect, enumFrom(1)) while (true) { yield ys.next().value - 1; ys = dropWhileGen(imperfect, ys) } }   // GENERIC FUNCTIONS ----------------------------   // abs :: Num -> Num const abs = Math.abs;   // dropWhileGen :: (a -> Bool) -> Gen [a] -> [a] const dropWhileGen = (p, xs) => { let nxt = xs.next(), v = nxt.value; while (!nxt.done && p(v)) { nxt = xs.next(); v = nxt.value; } return xs; };   // enumFrom :: Int -> [Int] function* enumFrom(x) { let v = x; while (true) { yield v; v = 1 + v; } }   // enumFromTo :: Int -> Int -> [Int] const enumFromTo = (m, n) => m <= n ? iterateUntil( x => n <= x, x => 1 + x, m ) : [];   // filter :: (a -> Bool) -> [a] -> [a] const filter = (f, xs) => xs.filter(f);   // gcd :: Int -> Int -> Int const gcd = (x, y) => { const _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)), abs = Math.abs; return _gcd(abs(x), abs(y)); };   // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] const iterateUntil = (p, f, x) => { const vs = [x]; let h = x; while (!p(h))(h = f(h), vs.push(h)); return vs; };   // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc   // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // memoized :: (a -> b) -> (a -> b) const memoized = f => { const dctMemo = {}; return x => { const v = dctMemo[x]; return undefined !== v ? v : (dctMemo[x] = f(x)); }; };   // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') );   // sum :: [Num] -> Num const sum = xs => xs.reduce((a, x) => a + x, 0);   // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : [];   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));   // MAIN --- main(); })();