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/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.
#C
C
#include "stdio.h" #include "math.h"   int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i;   for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; }   return tot == n; }   int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf("%d\n", n);   return 0; }
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.
#Raku
Raku
sub R($n, $p) { [+] ((rand < $p) xx $n).squish }   say 't= ', constant t = 100;   for .1, .3 ... .9 -> $p { say "p= $p, K(p)= {$p*(1-$p)}"; for 10, 100, 1000 -> $n { printf " R(%6d, p)= %f\n", $n, t R/ [+] R($n, $p)/$n xx t } }
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.
#Sidef
Sidef
func R(n,p) { n.of { 1.rand < p ? 1 : 0}.sum; }   const t = 100; say ('t=', t);   range(.1, .9, .2).each { |p| printf("p= %f, K(p)= %f\n", p, p*(1-p)); [10, 100, 1000].each { |n| printf (" R(n, p)= %f\n", t.of { R(n, p) }.sum/n / t); } }
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
#BBC_BASIC
BBC BASIC
DIM List%(3) List%() = 1, 2, 3, 4 FOR perm% = 1 TO 24 FOR i% = 0 TO DIM(List%(),1) PRINT List%(i%); NEXT PRINT PROC_NextPermutation(List%()) NEXT END   DEF PROC_NextPermutation(A%()) LOCAL first, last, elementcount, pos elementcount = DIM(A%(),1) IF elementcount < 1 THEN ENDPROC pos = elementcount-1 WHILE A%(pos) >= A%(pos+1) pos -= 1 IF pos < 0 THEN PROC_Permutation_Reverse(A%(), 0, elementcount) ENDPROC ENDIF ENDWHILE last = elementcount WHILE A%(last) <= A%(pos) last -= 1 ENDWHILE SWAP A%(pos), A%(last) PROC_Permutation_Reverse(A%(), pos+1, elementcount) ENDPROC   DEF PROC_Permutation_Reverse(A%(), first, last) WHILE first < last SWAP A%(first), A%(last) first += 1 last -= 1 ENDWHILE ENDPROC
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
#JavaScript
JavaScript
(() => { 'use strict';   // shuffleCycleLength :: Int -> Int const shuffleCycleLength = deckSize => firstCycle(shuffle, range(1, deckSize)) .all.length;   // shuffle :: [a] -> [a] const shuffle = xs => concat(zip.apply(null, splitAt(div(length(xs), 2), xs)));   // firstycle :: Eq a => (a -> a) -> a -> [a] const firstCycle = (f, x) => until( m => EqArray(x, m.current), m => { const fx = f(m.current); return { current: fx, all: m.all.concat([fx]) }; }, { current: f(x), all: [x] } );   // Two arrays equal ? // EqArray :: [a] -> [b] -> Bool const EqArray = (xs, ys) => { const [nx, ny] = [xs.length, ys.length]; return nx === ny ? ( nx > 0 ? ( xs[0] === ys[0] && EqArray(xs.slice(1), ys.slice(1)) ) : true ) : false; };   // GENERIC FUNCTIONS   // zip :: [a] -> [b] -> [(a,b)] const zip = (xs, ys) => xs.slice(0, Math.min(xs.length, ys.length)) .map((x, i) => [x, ys[i]]);   // concat :: [[a]] -> [a] const concat = xs => [].concat.apply([], xs);   // splitAt :: Int -> [a] -> ([a],[a]) const splitAt = (n, xs) => [xs.slice(0, n), xs.slice(n)];   // div :: Num -> Num -> Int const div = (x, y) => Math.floor(x / y);   // until :: (a -> Bool) -> (a -> a) -> a -> a const until = (p, f, x) => { const go = x => p(x) ? x : go(f(x)); return go(x); }   // range :: Int -> Int -> [Int] const range = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i);   // length :: [a] -> Int // length :: Text -> Int const length = xs => xs.length;   // maximumBy :: (a -> a -> Ordering) -> [a] -> a const maximumBy = (f, xs) => xs.reduce((a, x) => a === undefined ? x : ( f(x, a) > 0 ? x : a ), undefined);   // transpose :: [[a]] -> [[a]] const transpose = xs => xs[0].map((_, iCol) => xs.map((row) => row[iCol]));   // show :: a -> String const show = x => JSON.stringify(x, null, 2);   // replicateS :: Int -> String -> String const replicateS = (n, s) => { let v = s, o = ''; if (n < 1) return o; while (n > 1) { if (n & 1) o = o.concat(v); n >>= 1; v = v.concat(v); } return o.concat(v); };   // justifyRight :: Int -> Char -> Text -> Text const justifyRight = (n, cFiller, strText) => n > strText.length ? ( (replicateS(n, cFiller) + strText) .slice(-n) ) : strText;   // TEST return transpose(transpose([ ['Deck', 'Shuffles'] ].concat( [8, 24, 52, 100, 1020, 1024, 10000] .map(n => [n.toString(), shuffleCycleLength(n) .toString() ]))) .map(col => { // Right-justified number columns const width = length( maximumBy((a, b) => length(a) - length(b), col) ) + 2;   return col.map(x => justifyRight(width, ' ', x)); })) .map(row => row.join('')) .join('\n'); })();
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.
#Python
Python
def perlin_noise(x, y, z): X = int(x) & 255 # FIND UNIT CUBE THAT Y = int(y) & 255 # CONTAINS POINT. Z = int(z) & 255 x -= int(x) # FIND RELATIVE X,Y,Z y -= int(y) # OF POINT IN CUBE. z -= int(z) u = fade(x) # COMPUTE FADE CURVES v = fade(y) # FOR EACH OF X,Y,Z. w = fade(z) 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 ))))   def fade(t): return t ** 3 * (t * (t * 6 - 15) + 10)   def lerp(t, a, b): return a + t * (b - a)   def grad(hash, x, y, z): h = hash & 15 # CONVERT LO 4 BITS OF HASH CODE u = x if h<8 else y # INTO 12 GRADIENT DIRECTIONS. v = y if h<4 else (x if h in (12, 14) else z) return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)   p = [None] * 512 permutation = [151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180] for i in range(256): p[256+i] = p[i] = permutation[i]   if __name__ == '__main__': print("%1.17f" % perlin_noise(3.14, 42, 7))
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
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (7) BYTE INITIAL ('..... $'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = .S(5); DIGIT: P = P - 1; C = N MOD 10 + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL PRINT(P); END PRINT$NUMBER;   GCD: PROCEDURE (A, B) ADDRESS; DECLARE (A, B, C) ADDRESS; DO WHILE B <> 0; C = A; A = B; B = C MOD B; END; RETURN A; END GCD;   TOTIENT: PROCEDURE (N) ADDRESS; DECLARE (I, N, S) ADDRESS; S = 0; DO I=1 TO N-1; IF GCD(N,I) = 1 THEN S = S+1; END; RETURN S; END TOTIENT;   PERFECT: PROCEDURE (N) BYTE; DECLARE (N, X, SUM) ADDRESS; X = N; SUM = 0; DO WHILE X > 1; X = TOTIENT(X); SUM = SUM + X; END; RETURN SUM = N; END PERFECT;   DECLARE N ADDRESS, SEEN BYTE; SEEN = 0; N = 3; DO WHILE SEEN < 20; IF PERFECT(N) THEN DO; CALL PRINT$NUMBER(N); SEEN = SEEN+1; END; N = N+2; END; CALL EXIT; EOF
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
#Python
Python
from math import gcd from functools import lru_cache from itertools import islice, count   @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)   def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0     if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
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
#JavaScript
JavaScript
function Card(pip, suit) { this.pip = pip; this.suit = suit;   this.toString = function () { return this.pip + ' ' + this.suit; }; }   function Deck() { var pips = '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' '); var suits = 'Clubs Hearts Spades Diamonds'.split(' '); this.deck = []; for (var i = 0; i < suits.length; i++) for (var j = 0; j < pips.length; j++) this.deck.push(new Card(pips[j], suits[i]));   this.toString = function () { return '[' + this.deck.join(', ') + ']'; };   this.shuffle = function () { for (var i = 0; i < this.deck.length; i++) this.deck[i] = this.deck.splice( parseInt(this.deck.length * Math.random()), 1, this.deck[i])[0]; };   this.deal = function () { return this.deck.shift(); }; }
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
#J
J
pi=: 3 :0 echo"0 '3.1' i=. 0 while. i=. i + 1 do. echo -/ 1 10 * <.@o. 10x ^ 1 0 + i 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
#Racket
Racket
  #lang racket   (define (pig-the-dice #:print? [print? #t] . players) (define prn (if print? (λ xs (apply printf xs) (flush-output)) void)) (define names (for/list ([p players] [n (in-naturals 1)]) n)) (define points (for/list ([p players]) (box 0))) (with-handlers ([(negate exn?) identity]) (for ([nm (in-cycle names)] [tp (in-cycle points)] [pl (in-cycle players)]) (prn (string-join (for/list ([n names] [p points]) (format "Player ~a, ~a points" n (unbox p))) "; " #:before-first "Status: " #:after-last ".\n")) (let turn ([p 0] [n 0]) (prn "Player ~a, round #~a, [R]oll or [P]ass? " nm (+ 1 n)) (define roll? (pl (unbox tp) p n)) (unless (eq? pl human) (prn "~a\n" (if roll? 'R 'P))) (if (not roll?) (set-box! tp (+ (unbox tp) p)) (let ([r (+ 1 (random 6))]) (prn " Dice roll: ~s => " r) (if (= r 1) (prn "turn lost\n") (let ([p (+ p r)]) (prn "~a points\n" p) (turn p (+ 1 n))))))) (prn "--------------------\n") (when (<= 100 (unbox tp)) (prn "Player ~a wins!\n" nm) (raise nm)))))   (define (human total-points turn-points round#) (case (string->symbol (car (regexp-match #px"[A-Za-z]?" (read-line)))) [(R r) #t] [(P p) #f] [else (human total-points turn-points round#)]))   (pig-the-dice #:print? #t human human)  
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.
#Ksh
Ksh
  #!/bin/ksh   # Positive integer whose population count is a prime   # # Variables: # integer PNUM=25 MINN=888888877 MAXN=888888888   # # Functions: # # # Function _dec2bin(n) - return binary representation of decimal n # function _dec2bin { typeset _n ; integer _n=$1 typeset _base ; integer _base=2 typeset _q _r _buff ; integer _q _r typeset -a _arr _barr   (( _q = _n / _base )) (( _r = _n % _base )) _arr+=( ${_r} ) until (( _q == 0 )); do _n=${_q} (( _q = _n / _base )) (( _r = _n % _base )) _arr+=( ${_r} ) done _revarr _arr _barr _buff=${_barr[@]} echo ${_buff// /} }   # # Function _revarr(arr, barr) - reverse arr into barr # function _revarr { typeset _arr ; nameref _arr="$1" typeset _barr ; nameref _barr="$2" typeset _i ; integer _i   for ((_i=${#_arr[*]}-1; _i>=0; _i--)); do _barr+=( ${_arr[_i]} ) done }   # # Function _isprime(n) return 1 for prime, 0 for not prime # function _isprime { typeset _n ; integer _n=$1 typeset _i ; integer _i   (( _n < 2 )) && return 0 for (( _i=2 ; _i*_i<=_n ; _i++ )); do (( ! ( _n % _i ) )) && return 0 done return 1 }   # # Function _sumdigits(n) return sum of n's digits # function _sumdigits { typeset _n ; _n=$1 typeset _i _sum ; integer _i _sum=0   for ((_i=0; _i<${#_n}; _i++)); do (( _sum+=${_n:${_i}:1} )) done echo ${_sum} }   ###### # main # ######   integer i sbi n=3 cnt=0   printf "First $PNUM Pernicious numbers:\n" for ((n = cnt = 0; cnt < PNUM; n++)); do bi=$(_dec2bin ${n}) # $n as Binary sbi=${bi//0/} # Strip zeros (i.e. count ones) _isprime ${#sbi} # One count prime? (( $? )) && { printf "%4d " ${n} ; ((++cnt)) } done   printf "\n\nPernicious numbers between %11,d and %11,d inclusive:\n" $MINN $MAXN for ((i=MINN; i<=MAXN; i++)); do bi=$(_dec2bin ${i}) sbi=${bi//0/} _isprime ${#sbi} (( $? )) && printf "%12,d " ${i} done echo  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Objeck
Objeck
values := [1, 2, 3]; value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#OCaml
OCaml
let list_rand lst = let len = List.length lst in List.nth lst (Random.int len)
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   "Rosetta Code Phrase Reversal" dup print nl dup reverse print nl split dup reverse len for . pop swap print " " print endfor . nl len for . pop swap reverse print " " print endfor .
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
#PHP
PHP
<?php // Initialize a variable with the input desired $strin = "rosetta code phrase reversal";   // Show user what original input was echo "Input: ".$strin."\n";   // Show the full input reversed echo "Reversed: ".strrev($strin)."\n";   // reverse the word letters in place $str_words_reversed = ""; $temp = explode(" ", $strin); foreach($temp as $word) $str_words_reversed .= strrev($word)." ";   // Show the reversed words in place echo "Words reversed: ".$str_words_reversed."\n";     // reverse the word order while leaving the words in order $str_word_order_reversed = ""; $temp = explode(" ", $strin); for($i=(count($temp)-1); $i>=0; $i--) $str_word_order_reversed .= $temp[$i]." ";   // Show the reversal of the word order while leaving the words in order echo "Word order reversed: ".$str_word_order_reversed."\n";  
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
#PARI.2FGP
PARI/GP
derangements(n)=if(n,round(n!/exp(1)),1); derange(n)={ my(v=[[]],tmp); for(level=1,n, tmp=List(); for(i=1,#v, for(k=1,n, if(k==level, next); for(j=1,level-1,if(v[i][j]==k, next(2))); listput(tmp, concat(v[i],k)) ) ); v=Vec(tmp) ); v }; derange(4) for(n=0,9,print("!"n" = "#derange(n)" = "derangements(n))) derangements(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
#REXX
REXX
/*REXX program generates all permutations of N different objects by swapping. */ parse arg things bunch . /*obtain optional arguments from the CL*/ if things=='' | things=="," then things=4 /*Not specified? Then use the default.*/ if bunch =='' | bunch =="," then bunch =things /* " " " " " " */ call permSets things, bunch /*invoke permutations by swapping sub. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ !: procedure;  !=1; do j=2 to arg(1);  !=!*j; end; return ! /*──────────────────────────────────────────────────────────────────────────────────────*/ permSets: procedure; parse arg x,y /*take X things Y at a time. */  !.=0; pad=left('', x*y) /*X can't be > length of below str (62)*/ z=left('123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', x); q=z #=1 /*the number of permutations (so far).*/  !.z=1; s=1; times=!(x) % !(x-y) /*calculate (#) TIMES using factorial.*/ w=max(length(z), length('permute') ) /*maximum width of Z and also PERMUTE.*/ say center('permutations for ' x ' things taken ' y " at a time",60,'═') say say pad 'permutation' center("permute", w, '─') "sign" say pad '───────────' center("───────", w, '─') "────" say pad center(#, 11) center(z , w) right(s, 4-1)   do $=1 until #==times /*perform permutation until # of times.*/ do k=1 for x-1 /*step thru things for things-1 times.*/ do m=k+1 to x;  ?= /*this method doesn't use adjacency. */ do n=1 for x /*build the new permutation by swapping*/ if n\==k & n\==m then  ? =  ? || substr(z, n, 1) else if n==k then ? =  ? || substr(z, m, 1) else ? =  ? || substr(z, k, 1) end /*n*/ z=? /*save this permutation for next swap. */ if !.? then iterate m /*if defined before, then try next one.*/ _=0 /* [↓] count number of swapped symbols*/ do d=1 for x while $\==1; _= _ + (substr(?,d,1)\==substr(prev,d,1)) end /*d*/ if _>2 then do; _=z a=$//x+1; q=q + _ /* [← ↓] this swapping tries adjacency*/ b=q//x+1; if b==a then b=a + 1; if b>x then b=a - 1 z=overlay( substr(z,b,1), overlay( substr(z,a,1), _, b), a) iterate $ /*now, try this particular permutation.*/ end #=#+1; s= -s; say pad center(#, 11) center(?, w) right(s, 4-1)  !.?=1; prev=?; iterate $ /*now, try another swapped permutation.*/ end /*m*/ end /*k*/ end /*$*/ return /*we're all finished with permutating. */
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.
#zkl
zkl
fcn permutationTest(a,b){ ab  := a.extend(b); tObs  := a.sum(0); combs := Utils.Helpers.pickNFrom(a.len(),ab); // 92,378 under := combs.reduce('wrap(sum,perm){ sum+(perm.sum(0) <= tObs) },0); 100.0 * under / combs.len(); }   treatmentGroup := T(85, 88, 75, 66, 25, 29, 83, 39, 97); controlGroup  := T(68, 41, 10, 49, 16, 65, 32, 92, 28, 98); under  := permutationTest(treatmentGroup, controlGroup); println("Under =%6.2f%%\nOver =%6.2f%%".fmt(under, 100.0 - 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%
#Lua
Lua
Bitmap.loadPPM = function(self, filename) local fp = io.open( filename, "rb" ) if fp == nil then return false end local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line") self.width, self.height = width, height self:alloc() self:clear( {0,0,0} ) for y = 1, self.height do for x = 1, self.width do self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) } end end fp:close() return true end   Bitmap.percentageDifference = function(self, other) if self.width ~= other.width or self.height ~= other.height then return end local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels for y = 1, self.height do for x = 1, self.width do local sp, op = spx[y][x], opx[y][x] dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3]) end end return dif/255/self.width/self.height/3*100 end   local bm50 = Bitmap(0,0) bm50:loadPPM("Lenna50.ppm")   local bm100 = Bitmap(0,0) bm100:loadPPM("Lenna100.ppm")   print("%diff:", bm100:percentageDifference(bm50))
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.
#C.23
C#
static void Main(string[] args) { Console.WriteLine("Perfect numbers from 1 to 33550337:");   for (int x = 0; x < 33550337; x++) { if (IsPerfect(x)) Console.WriteLine(x + " is perfect."); }   Console.ReadLine(); }   static bool IsPerfect(int num) { int sum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) sum += i; }   return sum == num ; }
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.
#Tcl
Tcl
proc randomString {length probability} { for {set s ""} {[string length $s] < $length} {} { append s [expr {rand() < $probability}] } return $s }   # By default, [regexp -all] gives the number of times that the RE matches proc runs {str} { regexp -all {1+} $str }   # Compute the mean run density proc mrd {t p n} { for {set i 0;set total 0.0} {$i < $t} {incr i} { set run [randomString $n $p] set total [expr {$total + double([runs $run])/$n}] } return [expr {$total / $t}] }   # Parameter sweep with nested [foreach] set runs 500 foreach p {0.10 0.30 0.50 0.70 0.90} { foreach n {1024 4096 16384} { set theory [expr {$p * (1 - $p)}] set sim [mrd $runs $p $n] set diffpc [expr {abs($theory-$sim)*100/$theory}] puts [format "t=%d, p=%.2f, n=%5d, p(1-p)=%.3f, sim=%.3f, delta=%.2f%%" \ $runs $p $n $theory $sim $diffpc] } puts "" }
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
#Bracmat
Bracmat
( perm = prefix List result original A Z .  !arg:(?.) |  !arg:(?prefix.?List:?original) & :?result & whl ' ( !List:%?A ?Z & !result perm$(!prefix !A.!Z):?result & !Z !A:~!original:?List ) & !result ) & out$(perm$(.a 2 "]" u+z);
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
#jq
jq
def perfect_shuffle: . as $a | if (length % 2) == 1 then "cannot perform perfect shuffle on odd-length array" | error else (length / 2) as $mid | reduce range(0; $mid) as $i (null; .[2*$i] = $a[$i] | .[2*$i + 1] = $a[$mid+$i] ) end;   # How many iterations of f are required to get back to . ? def recurrence(f): def r: # input: [$init, $current, $count] (.[1]|f) as $next | if .[0] == $next then .[-1] + 1 else [.[0], $next, .[-1]+1] | r end; [., ., 0] | r;   def count_perfect_shuffles: [range(0;.)] | recurrence(perfect_shuffle);   (8, 24, 52, 100, 1020, 1024, 10000, 100000) | [., count_perfect_shuffles]
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
#Julia
Julia
using Printf   function perfect_shuffle(a::Array)::Array if isodd(length(a)) error("cannot perform perfect shuffle on odd-length array") end   rst = zeros(a) mid = div(length(a), 2) for i in 1:mid rst[2i-1], rst[2i] = a[i], a[mid+i] end return rst end   function count_perfect_shuffles(decksize::Int)::Int a = collect(1:decksize) b, c = perfect_shuffle(a), 1 while a != b b = perfect_shuffle(b) c += 1 end return c end   println(" Deck n.Shuffles") for i in (8, 24, 52, 100, 1020, 1024, 10000, 100000) count = count_perfect_shuffles(i) @printf("%7i%7i\n", i, count) 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.
#Racket
Racket
#lang racket (define (floor-to-255 x) (bitwise-and (exact-floor x) #xFF))   (define (fade t) (* t t t (+ 10 (* t (- (* t 6) 15)))))   (define (lerp t a b) (+ a (* t (- b a))))   ;; CONVERT LO 4 BITS OF HASH CODE INTO 12 GRADIENT DIRECTIONS. (define (grad hsh x y z) (define h (bitwise-and hsh #x0F)) (define u (if (< h 8) x y)) (define v (cond [(< h 4) y] [(or (= h 12) (= h 14)) x] [else z])) (+ (if (bitwise-bit-set? h 0) (- u) u) (if (bitwise-bit-set? h 1) (- v) v)))   (define permutation (vector 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))   (define p (make-vector 512)) (for ((offset (in-list '(0 256)))) (vector-copy! p offset permutation))   (define-syntax-rule (p-ref n) (vector-ref p n))   (define (noise x y z) (let* (  ;; FIND UNIT CUBE THAT CONTAINS POINT. (X (floor-to-255 x)) (Y (floor-to-255 y)) (Z (floor-to-255 z))  ; FIND RELATIVE X,Y,Z OF POINT IN CUBE. (x (- x (floor x))) (y (- y (floor y))) (z (- z (floor z)))  ;; COMPUTE FADE CURVES FOR EACH OF X,Y,Z. (u (fade x)) (v (fade y)) (w (fade z))  ;; HASH COORDINATES OF THE 8 CUBE CORNERS... (A (+ (p-ref X) Y)) (AA (+ (p-ref A) Z)) (AB (+ (p-ref (add1 A)) Z)) (B (+ (p-ref (add1 X)) Y)) (BA (+ (p-ref B) Z)) (BB (+ (p-ref (add1 B)) Z)))  ;; .. AND ADD BLENDED RESULTS FROM 8 CORNERS OF CUBE (lerp w (lerp v (lerp u (grad (p-ref AA) x y z) (grad (p-ref BA) (sub1 x) y z)) (lerp u (grad (p-ref AB) x (sub1 y) z) (grad (p-ref BB) (sub1 x) (sub1 y) z))) (lerp v (lerp u (grad (p-ref (add1 AA)) x y (sub1 z)) (grad (p-ref (add1 BA)) (sub1 x) y (sub1 z))) (lerp u (grad (vector-ref p (add1 AB)) x (sub1 y) (sub1 z)) (grad (vector-ref p (add1 BB)) (sub1 x) (sub1 y) (sub1 z)))))))   (module+ test (noise 3.14 42 7))
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
#Quackery
Quackery
[ 0 over [ dup 1 != while totient dup dip + again ] drop = ] is perfecttotient ( n --> b )   [ [] 1 [ dup perfecttotient if [ dup dip join ] 2 + over size 20 = until ] drop ] is task ( --> )  
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
#Racket
Racket
  #lang racket (require math/number-theory)   (define (tot n) (match n [1 0] [n (define t (totient n)) (+ t (tot t))]))   (define (perfect? n) (= n (tot n)))   (define-values (ns i) (for/fold ([ns '()] [i 0]) ([n (in-naturals 1)] #:break (= i 20) #:when (perfect? n)) (values (cons n ns) (+ i 1))))   (reverse ns)  
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
#Julia
Julia
  type DeckDesign{T<:Integer,U<:String} rlen::T slen::T ranks::Array{U,1} suits::Array{U,1} hlen::T end   type Deck{T<:Integer} cards::Array{T,1} design::DeckDesign end   Deck(n::Integer, des::DeckDesign) = Deck([n], des)   function pokerlayout() r = [map(string, 2:10), "J", "Q", "K", "A"] r = map(utf8, r) s = ["\u2663", "\u2666", "\u2665", "\u2660"] DeckDesign(13, 4, r, s, 5) end   function fresh(des::DeckDesign) Deck(collect(1:des.rlen*des.slen), des) end  
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
#Java
Java
import java.math.BigInteger ;   public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ;   BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ;   public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } }   public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
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
#Raku
Raku
constant DIE = 1..6;   sub MAIN (Int :$players = 2, Int :$goal = 100) { my @safe = 0 xx $players; for |^$players xx * -> $player { say "\nOK, player #$player is up now."; my $safe = @safe[$player]; my $ante = 0; until $safe + $ante >= $goal or prompt("#$player, you have $safe + $ante = {$safe+$ante}. Roll? [Yn] ") ~~ /:i ^n/ { given DIE.roll { say " You rolled a $_."; when 1 { say " Bust! You lose $ante but keep your previous $safe."; $ante = 0; last; } when 2..* { $ante += $_; } } } $safe += $ante; if $safe >= $goal { say "\nPlayer #$player wins with a score of $safe!"; last; } @safe[$player] = $safe; say " Sticking with $safe." if $ante; } }
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.
#Lua
Lua
-- Test primality by trial division function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end   -- Take decimal number, return binary string function dec2bin (n) local bin, bit = "" while n > 0 do bit = n % 2 n = math.floor(n / 2) bin = bit .. bin end return bin end   -- Take decimal number, return population count as number function popCount (n) local bin, count = dec2bin(n), 0 for pos = 1, bin:len() do if bin:sub(pos, pos) == "1" then count = count + 1 end end return count end   -- Print pernicious numbers in range if two arguments provided, or function pernicious (x, y) -- the first 'x' if only one argument. if y then for n = x, y do if isPrime(popCount(n)) then io.write(n .. " ") end end else local n, count = 0, 0 while count < x do if isPrime(popCount(n)) then io.write(n .. " ") count = count + 1 end n = n + 1 end end print() end   -- Main procedure pernicious(25) pernicious(888888877, 888888888)
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Oforth
Oforth
: pickRand(l) l size rand l at ;
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Ol
Ol
  (import (otus random!))   (define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday")) (print (list-ref x (rand! (length x))))  
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
#Picat
Picat
import util.   go => S = "rosetta code phrase reversal", println(S), println(reverse(S)), println([reverse(W) : W in S.split()].join(' ')), println(reverse(S.split()).join(' ')), nl.
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
#PicoLisp
PicoLisp
(let (S (chop "rosetta code phrase reversal") L (split S " ")) (prinl (reverse S)) (prinl (glue " " (mapcar reverse L))) (prinl (glue " " (reverse L))) )
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
#Perl
Perl
sub d { # compare this with the deranged() sub to see how to turn procedural # code into functional one ('functional' as not in 'understandable') $#_ ? map d([ @{$_[0]}, $_[$_] ], @_[1 .. $_-1, $_+1 .. $#_ ]), grep { $_[$_] != @{$_[0]} } 1 .. $#_ : $_[0] }   sub deranged { # same as sub d above, just a readable version to explain method my ($result, @avail) = @_; return $result if !@avail; # no more elements to pick from, done   my @list; # list of permutations to return for my $i (0 .. $#avail) { # try to add each element to result in turn next if $avail[$i] == @$result; # element n at n-th position, no-no my $e = splice @avail, $i, 1; # move the n-th element from available to result push @list, deranged([ @$result, $e ], @avail); # and recurse down, keep what's returned splice @avail, $i, 0, $e; # put that element back, try next } return @list; }   sub choose { # choose k among n, i.e. n! / k! (n-k)! my ($n, $k) = @_; factorial($n) / factorial($k) / factorial($n - $k) }   my @fact = (1); sub factorial { # //= : standard caching technique. If cached value available, # return it; else compute, cache and return. # For this specific task not really necessary. $fact[ $_[0] ] //= $_[0] * factorial($_[0] - 1) }   my @subfact; sub sub_factorial { my $n = shift; $subfact[$n] //= do # same caching stuff, try comment out this line { # computes deranged without formula, using recursion my $total = factorial($n); # total permutations for my $k (1 .. $n) { # minus the permutations where k items are fixed # to original location, and the rest deranged $total -= choose($n, $k) * sub_factorial($n - $k) } $total } }   print "Derangements for 4 elements:\n"; my @deranged = d([], 0 .. 3); for (1 .. @deranged) { print "$_: @{$deranged[$_-1]}\n" }   print "\nCompare list length and calculated table\n"; for (0 .. 9) { my @x = d([], 0 .. $_-1); print $_, "\t", scalar(@x), "\t", sub_factorial($_), "\n" }   print "\nNumber of derangements:\n"; print "$_:\t", sub_factorial($_), "\n" for 1 .. 20;
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
#Ruby
Ruby
def perms(n) p = Array.new(n+1){|i| -i} s = 1 loop do yield p[1..-1].map(&:abs), s k = 0 for i in 2..n k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs end for i in 1...n k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs end break if k.zero? for i in 1..n p[i] *= -1 if p[i].abs > p[k].abs end i = k + (p[k] <=> 0) p[k], p[i] = p[i], p[k] s = -s end end   for i in 3..4 perms(i){|perm, sign| puts "Perm: #{perm} Sign: #{sign}"} puts end
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%
#Liberty_BASIC
Liberty BASIC
  now =time$( "seconds") nomainwin   WindowWidth = 1620 WindowHeight = 660   open "jpeg.dll" for dll as #j ' "JPEG.DLL copyright Alyce Watson, 2003. "   open "RC Image Comparison- difference shown as 20 times abs( pixel_difference." for graphics_nf_nsb as #1 #1 "trapclose [quit]" #1 "down ; fill black"   hW =hwnd( #1) calldll #user32,"GetDC", hW as ulong, hdc as ulong   jname1$ ="Lenna50.jpg" hPic1 =LoadImageFile( hW, jname1$) if hPic1 =0 then notice "Function failed.": wait loadbmp "demo1", hPic1 hDemo1 =hbmp( "demo1") #1 "drawbmp demo1 10 10 ; flush"   jname2$ ="Lenna100.jpg" hPic2 =LoadImageFile( hW, jname2$) if hPic2 =0 then notice "Function failed.": wait loadbmp "demo2", hPic2 hDemo1 =hbmp( "demo2") #1 "drawbmp demo2 550 10 ; flush"   c1 =16777216 c2 = 65536 c3 = 256 x1 =10 y1 =10 x2 =550 y2 =10   for y =0 to 511 for x =0 to 511 pixel1 =( GetPixel( hdc, x1 +x, y1 +y) + c1) mod c1 b1 = int( pixel1 /c2) g1 = int(( pixel1 -b1 *c2) /c3) r1 = int( pixel1 -b1 *c2 -g1 *c3)   pixel2 =( GetPixel( hdc, x2 +x, y2 +y) + c1) mod c1 b2 = int( pixel2 /c2) g2 = int(( pixel2 -b2 *c2) /c3) r2 = int( pixel2 -b2 *c2 -g2 *c3)   totalDiff =totalDiff +abs( r1 -r2) +abs( g1 -g2)+ abs( b1 -b2)   #1 "color "; 20 *abs( r2 -r1); " "; 20 *abs( g2 -g1); " "; 20 *abs( b2 -b1) #1 "set "; 1090 +x; " "; 10 +y scan next x next y   #1 "place 90 575 ; color white ; backcolor black" #1 "font courier 9 bold" #1 "\"; " Difference between images ="; using( "#.#####", 100.0 *totalDiff / 512 /512 /3 /255); "%." #1 "\"; " Rosetta Code for these two images =1.62125%."; " Time taken ="; time$( "seconds") -now; " seconds." #1 "flush"   wait   function LoadImageFile( hWnd, file$) calldll #j, "LoadImageFile", hWnd as ulong, file$ as ptr, LoadImageFile as ulong end function   function GetPixel( hDC, x, y) calldll #gdi32, "GetPixel", hDC As uLong, x As long, y As long, GetPixel As long end function   [quit] if hPic1 <>0 then calldll #gdi32, "DeleteObject", hPic1 as long, re as long if hPic2 <>0 then calldll #gdi32, "DeleteObject", hPic2 as long, re as long if hDemo1 <>0 then unloadbmp "demo1" if hDemo2 <>0 then unloadbmp "demo2" close #1 close #j 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.
#C.2B.2B
C++
#include <iostream> using namespace std ;   int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; }   int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }  
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.
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new() var RAND_MAX = 32767   // just generate 0s and 1s without storing them var runTest = Fn.new { |p, len, runs| var cnt = 0 var thresh = (p * RAND_MAX).truncate for (r in 0...runs) { var x = 0 var i = len while (i > 0) { i = i - 1 var y = (rand.int(RAND_MAX + 1) < thresh) ? 1 : 0 if (x < y) cnt = cnt + 1 x = y } } return cnt / runs / len }   System.print("Running 1000 tests each:") System.print(" p\t n\tK\tp(1-p)\t diff") System.print("------------------------------------------------") var fmt = "$.1f\t$6d\t$.4f\t$.4f\t$+.4f ($+.2f\%)" for (ip in [1, 3, 5, 7, 9]) { var p = ip / 10 var p1p = p * (1 - p) var n = 100 while (n <= 1e5) { var k = runTest.call(p, n, 1000) Fmt.lprint(fmt, [p, n, k, p1p, k - p1p, (k - p1p) /p1p * 100]) n = n * 10 } System.print() }
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
#C
C
  #include <stdio.h> int main (int argc, char *argv[]) { //here we check arguments if (argc < 2) { printf("Enter an argument. Example 1234 or dcba:\n"); return 0; } //it calculates an array's length int x; for (x = 0; argv[1][x] != '\0'; x++); //buble sort the array int f, v, m; for(f=0; f < x; f++) { for(v = x-1; v > f; v-- ) { if (argv[1][v-1] > argv[1][v]) { m=argv[1][v-1]; argv[1][v-1]=argv[1][v]; argv[1][v]=m; } } }   //it calculates a factorial to stop the algorithm char a[x]; int k=0; int fact=k+1; while (k!=x) { a[k]=argv[1][k]; k++; fact = k*fact; } a[k]='\0'; //Main part: here we permutate int i, j; int y=0; char c; while (y != fact) { printf("%s\n", a); i=x-2; while(a[i] > a[i+1] ) i--; j=x-1; while(a[j] < a[i] ) j--; c=a[j]; a[j]=a[i]; a[i]=c; i++; for (j = x-1; j > i; i++, j--) { c = a[i]; a[i] = a[j]; a[j] = c; } y++; } }  
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
#Kotlin
Kotlin
// version 1.1.2   fun areSame(a: IntArray, b: IntArray): Boolean { for (i in 0 until a.size) if (a[i] != b[i]) return false return true }   fun perfectShuffle(a: IntArray): IntArray { var b = IntArray(a.size) val hSize = a.size / 2 for (i in 0 until hSize) b[i * 2] = a[i] var j = 1 for (i in hSize until a.size) { b[j] = a[i] j += 2 } return b }   fun countShuffles(a: IntArray): Int { require(a.size >= 2 && a.size % 2 == 0) var b = a var count = 0 while (true) { val c = perfectShuffle(b) count++ if (areSame(a, c)) return count b = c } }   fun main(args: Array<String>) { println("Deck size Num shuffles") println("--------- ------------") val sizes = intArrayOf(8, 24, 52, 100, 1020, 1024, 10000) for (size in sizes) { val a = IntArray(size) { it } val count = countShuffles(a) println("${"%-9d".format(size)} $count") } }
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.
#Raku
Raku
constant @p = map {:36($_)}, flat < 47 4G 3T 2J 2I F 3N D 5L 2N 2O 1H 5E 6H 7 69 3W 10 2V U 1X 3Y 8 2R 11 6O L A N 5A 6 44 6V 3C 6I 23 0 Q 5H 1Q 2M 70 63 5N 39 Z B W 1L 4X X 2G 6L 45 1K 2F 4U K 3H 3S 4R 4O 1W 4V 22 4L 1Z 3Q 3V 1C R 4M 25 42 4E 6F 2B 33 6D 3E 1O 5V 3P 6E 64 2X 2K 15 1J 1A 6T 14 6S 2U 3Z 1I 1T P 1R 4H 1 60 28 21 5T 24 3O 57 5S 2H I 4P 5K 5G 3R 3M 38 58 4F 2E 4K 2S 31 5I 4T 56 3 1S 1G 61 6A 6Y 3G 3F 5 5M 12 43 3A 3I 73 2A 2D 5W 5R 5Q 1N 6B 1B G 1M H 52 59 S 16 67 53 4Q 5X 3B 6W 48 2 18 4A 4J 1Y 65 49 2T 4B 4N 17 4S 9 3L M 13 71 J 2Q 30 32 27 35 68 6G 4Y 55 34 2W 62 6U 2P 6C 6Z Y 6Q 5D 6M 5U 40 C 5B 4Z 4I 6P 29 1F 41 6J 6X E 6N 2Z 1D 5C 5Y V 51 5J 2Y 4D 54 2C 5O 4W 37 3D 1E 19 3J 4 46 72 3U 6K 5P 2L 66 36 1V T O 20 6R 3X 3K 5F 26 1U 5Z 1P 4C 50 > xx 2;   sub fade($_) { $_ * $_ * $_ * ($_ * ($_ * 6 - 15) + 10) } sub lerp($t, $a, $b) { $a + $t * ($b - $a) } sub grad($h is copy, $x, $y, $z) { $h +&= 15; my $u = $h < 8 ?? $x !! $y; my $v = $h < 4 ?? $y !! $h == 12|14 ?? $x !! $z; ($h +& 1 ?? -$u !! $u) + ($h +& 2 ?? -$v !! $v); }   sub noise($x is copy, $y is copy, $z is copy) is export { my ($X, $Y, $Z) = ($x, $y, $z)».floor »+&» 255; my ($u, $v, $w) = map &fade, $x -= $X, $y -= $Y, $z -= $Z; my ($AA, $AB) = @p[$_] + $Z, @p[$_ + 1] + $Z given @p[$X] + $Y; my ($BA, $BB) = @p[$_] + $Z, @p[$_ + 1] + $Z given @p[$X + 1] + $Y; 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 )))); }   say noise 3.14, 42, 7;
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
#Raku
Raku
use Prime::Factor;   my \𝜑 = lazy 0, |(1..*).hyper.map: -> \t { t * [*] t.&prime-factors.squish.map: 1 - 1/* } my \𝜑𝜑 = Nil, |(3, *+2 … *).grep: -> \p { p == sum 𝜑[p], { 𝜑[$_] } … 1 };   put "The first twenty Perfect totient numbers:\n", 𝜑𝜑[1..20];
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
#REXX
REXX
/*REXX program calculates and displays the first N perfect totient numbers. */ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/ @.= . /*memoization array of totient numbers.*/ p= 0 /*the count of perfect " " */ $= /*list of the " " " */ do j=3 by 2 until p==N; s= phi(j) /*obtain totient number for a number. */ a= s /* [↓] search for a perfect totient #.*/ do until a==1; a= phi(a); s= s + a end /*until*/ if s\==j then iterate /*Is J not a perfect totient number? */ p= p + 1 /*bump count of perfect totient numbers*/ $= $ j /*add to perfect totient numbers list. */ end /*j*/   say 'The first ' N " perfect totient numbers:" /*display the header to the terminal. */ say strip($) /* " " list. " " " */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x /*──────────────────────────────────────────────────────────────────────────────────────*/ phi: procedure expose @.; parse arg z; if @.z\==. then return @.z /*was found before?*/ #= z==1; do m=1 for z-1; if gcd(m, z)==1 then #= # + 1; end /*m*/ @.z= #; return # /*use memoization. */
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
#K
K
v:"A23456789TJQK" / values s:"SHCD" / suites   / create a new deck newdeck:{deck::,/s,'\:v} newdeck();
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
#JavaScript
JavaScript
let q = 1n, r = 180n, t = 60n, i = 2n; for (;;) { let y = (q*(27n*i-12n)+5n*r)/(5n*t); let u = 3n*(3n*i+1n)*(3n*i+2n); r = 10n*u*(q*(5n*i-2n)+r-y*t); q = 10n*q*i*(2n*i-1n); t = t*u; i = i+1n; process.stdout.write(y.toString()); if (i === 3n) { process.stdout.write('.'); } }
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
#REXX
REXX
/*REXX program plays "pig the dice game" (any number of CBLFs and/or silicons or HALs).*/ sw= linesize() - 1 /*get the width of the terminal screen,*/ parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments from the CL*/ /*names with blanks should use an _ */ if _\=='' then call err 'too many arguments were specified: ' _ @nhp = 'number of human players'  ; hp = scrutinize( hp, @nhp , 0, 0, 0) @ncp = 'number of computer players'  ; cp = scrutinize( cp, @ncp , 0, 0, 2) @sn2w = 'score needed to win'  ; win= scrutinize(win, @sn2w, 1, 1e6, 60) @nsid = 'number of sides in die'  ; die= scrutinize(die, @nsid, 2, 999, 6) if hp==0 & cp==0 then cp= 2 /*if both counts are zero, two HALs. */ if hp==1 & cp==0 then cp= 1 /*if one human, then use one HAL. */ name.= /*nullify all names (to a blank). */ L= 0 /*maximum length of a player name. */ do i=1 for hp+cp /*get the player's names, ... maybe. */ if i>hp then @= 'HAL_'i"_the_computer" /*use this for default name. */ else @= 'player_'i /* " " " " " */ name.i = translate( word( strip( word( names, i) ) @, 1), , '_') L= max(L, length( name.i) ) /*use L for nice name formatting. */ end /*i*/ /*underscores are changed ──► blanks. */   hpn=hp; if hpn==0 then hpn= 'no' /*use normal English for the display. */ cpn=cp; if cpn==0 then cpn= 'no' /* " " " " " " */   say 'Pig (the dice game) is being played with:' /*the introduction to pig-the-dice-game*/   if cpn\==0 then say right(cpn, 9) 'computer player's(cp) if hpn\==0 then say right(hpn, 9) 'human player's(hp) !.= say 'and the' @sn2w "is: " win ' (or greater).' dieNames= 'ace deuce trey square nickle boxcar' /*some slangy vernacular die─face names*/ !w= 0 /*note: snake eyes is for two aces. */ do i=1 for die /*assign the vernacular die─face names.*/  !.i= ' ['word(dieNames,i)"]" /*pick a word from die─face name lists.*/  !w= max(!w, length(!.i) ) /*!w ──► maximum length die─face name. */ end /*i*/ s.= 0 /*set all player's scores to zero. */ !w= !w + length(die) + 3 /*pad the die number and die names. */ @= copies('─', 9) /*eyecatcher (for the prompting text). */ @jra= 'just rolled a ' /*a nice literal to have laying 'round.*/ @ati= 'and the inning' /*" " " " " " " */ /*═══════════════════════════════════════════════════let's play some pig.*/ do game=1; in.= 0; call score /*set each inning's score to 0; display*/   do j=1 for hp+cp; say /*let each player roll their dice. */ say copies('─', sw) /*display a fence for da ole eyeballs. */ it= name.j say it', your total score (so far) in this pig game is: ' s.j"."   do until stopped /*keep prompting/rolling 'til stopped. */ r= random(1, die) /*get a random die face (number). */  != left(space(r !.r','),  !w) /*for color, use a die─face name. */ in.j= in.j + r /*add die─face number to the inning. */   if r==1 then do; say it @jra  ! || @ati "is a bust."; leave; end say it @jra  ! || @ati "total is: " in.j   stopped= what2do(j) /*determine or ask to stop rolling. */ if j>hp & stopped then say ' and' name.j "elected to stop rolling." end /*until stopped*/   if r\==1 then s.j= s.j + in.j /*if not a bust, then add to the inning*/ if s.j>=win then leave game /*we have a winner, so the game ends. */ end /*j*/ /*that's the end of the players. */ end /*game*/   call score; say; say; say; say; say center(''name.j "won! ", sw, '═') say; say; exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ score: say; say copies('█', sw) /*display a fence for da ole eyeballs. */   do k=1 for hp+cp /*display the scores (as a recap). */ say 'The score for ' left(name.k, L) " is " right(s.k, length(win) ). end /*k*/   say copies('█', sw); return /*display a fence for da ole eyeballs. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ scrutinize: parse arg ?,what,min,max /*? is the number, ... or maybe not. */ if ?=='' |  ?==',' then return arg(5) if \datatype(?, 'N') then call err what "isn't numeric: "  ?;  ?= ?/1 if \datatype(?, 'W') then call err what "isn't an integer: " ? if ?==0 & min>0 then call err what "can't be zero." if ?<min then call err what "can't be less than" min': '  ? if ?==0 & max>0 then call err what "can't be zero." if ?>max & max\==0 then call err what "can't be greater than" max': '  ? return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ what2do: parse arg who /*"who" is a human or a computer.*/ if j>hp & s.j+in.j>=win then return 1 /*an easy choice for HAL. */ if j>hp & in.j>=win%4 then return 1 /*a simple strategy for HAL. */ if j>hp then return 0 /*HAL says, keep truckin'! */ say @ name.who', what do you want to do? (a QUIT will stop the game),' say @ 'press ENTER to roll again, or anything else to STOP rolling.' pull action; action= space(action) /*remove any superfluous blanks. */ if \abbrev('QUIT', action, 1) then return action\=='' say; say; say center(' quitting. ', sw, '─'); say; say; exit /*──────────────────────────────────────────────────────────────────────────────────────*/ err: say; say; say center(' error! ', max(40, linesize() % 2), "*"); say do j=1 for arg(); say arg(j); say; end; say; exit 13
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.
#Maple
Maple
ispernicious := proc(n::posint) return evalb(isprime(rhs(Statistics:-Tally(StringTools:-Explode(convert(convert(n, binary), string)))[-1]))); end proc;   print_pernicious := proc(n::posint) local k, count, list_num; count := 0; list_num := []; for k while count < n do if ispernicious(k) then count := count + 1; list_num := [op(list_num), k]; end if; end do; return list_num; end proc:   range_pernicious := proc(n::posint, m::posint) local k, list_num; list_num := []; for k from n to m do if ispernicious(k) then list_num := [op(list_num), k]; end if; end do; return list_num; end proc:
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#PARI.2FGP
PARI/GP
pick(v)=v[random(#v)+1]
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Pascal_.2F_Delphi_.2F_Free_Pascal
Pascal / Delphi / Free Pascal
Program PickRandomElement (output);   const s: array [1..5] of string = ('1234', 'ABCDE', 'Charlie', 'XB56ds', 'lala');   begin randomize; writeln(s[low(s) + random(length(s))]); end.
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
#PL.2FI
PL/I
  reverser: procedure options (main); /* 19 August 2015 */ declare (phrase, r, word) character (100) varying; declare (start, end) fixed binary;   phrase = 'rosetta code phrase reversal'; put ('The original phrase is: ' || phrase);   put skip list ( '1. ' || reverse(phrase) );   start = 1; r = ''; put skip edit ('2. ') (a); do until ( end > length(phrase) ); end = index(phrase, ' ', start); /* Find end of the next word.*/ if end = 0 then end = length(phrase) + 1; /* We're at the last word. */ word = substr(phrase, start, end-start); put edit ( reverse(word), ' ' ) (a); /* Append reversed word. */ r = word || ' ' || r; /* Prepend normal word. */ start = end+1; end; put skip list ('3. ' || r);   end reverser;  
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
#Plain_TeX
Plain TeX
\def\afterfi#1#2\fi{#2\fi#1} \def\RevSingleWord#1{\RevSingleWordi{}#1\RSWA\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWA} \def\RevSingleWordi#1#2#3#4#5#6#7#8#9{\RSWgobtoB#9\RSWend\RSWB\RevSingleWordi{#9#8#7#6#5#4#3#2#1}} \def\RSWend\RSWB\RevSingleWordi#1#2\RSWA{\RSWgobtoA#1} \def\RSWgobtoA#1\RSWA{} \def\RSWgobtoB#1\RSWB{} %--- \def\firstchartonil#1#2\nil{#1} \def\RevOrderSameWords#1{\RevOrderSameWordsi{}#1 \. \* \* \* \* \* \* \* \* \.} \def\RevOrderSameWordsi#1#2 #3 #4 #5 #6 #7 #8 #9 {% \expandafter\ifx\expandafter\*\firstchartonil#9\nil \expandafter\ROSWend\else\expandafter\RevOrderSameWordsi\fi{#9 #8 #7 #6 #5 #4 #3 #2#1}% } \def\ROSWend#1#2\.{\ROSWendi#1} \def\ROSWendi#1\.{\romannumeral-`\-} %--- \def\ROWquark{\ROWquark} \def\RevOnlyWords#1{\edef\ROWtemp{\noexpand\RevOnlyWordsi{}#1 \noexpand\ROWquark\space}\ROWtemp} \def\RevOnlyWordsi#1#2 {% \ifx\ROWquark#2\afterfi{\ROWgoblastspace#1\nil}% \else\afterfi{\RevOnlyWordsi{#1\RevSingleWord{#2} }}% \fi } \def\ROWgoblastspace#1 \nil{#1} %--- \def\RevAll#1{\RevAlli{}#1 \. \* \* \* \* \* \* \* \* \.\:} \def\RevAlli#1#2 #3 #4 #5 #6 #7 #8 #9 {% \expandafter\ifx\expandafter\*\firstchartonil#9\nil \expandafter\RAWend\else\expandafter\RevAlli\fi{#9 #8 #7 #6 #5 #4 #3 #2#1}% } \def\RAWend#1#2\.{\RAWendi#1} \def\RAWendi#1\.{\expandafter\RAWendii\romannumeral-`\-} \def\RAWendii#1\:{\RevOnlyWords{#1}} %-- \halign{#\hfil: &#\cr Initial&rosetta code phrase reversal\cr Reverse all&\RevAll{rosetta code phrase reversal}\cr Reverse order, same words&\RevOrderSameWords{rosetta code phrase reversal}\cr Reverse only words&\RevOnlyWords{rosetta code phrase reversal}\cr\crcr} \bye
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
#Phix
Phix
with javascript_semantics function deranged(sequence s1, sequence s2) for i=1 to length(s1) do if s1[i]==s2[i] then return 0 end if end for return 1 end function function derangements(integer n) sequence ts = tagset(n) sequence res = {} for i=1 to factorial(n) do sequence s = permute(i,ts) if deranged(s,ts) then res = append(res,s) end if end for return res end function function subfactorial(integer n) if n<2 then return 1-n end if return (n-1)*(subfactorial(n-1)+subfactorial(n-2)) end function ?derangements(4) for n=0 to 9 do printf(1,"%d: counted:%d, calculated:%d\n",{n,length(derangements(n)),subfactorial(n)}) end for string msg = iff(machine_bits()=32?" (incorrect on 32-bit!)":"") -- (fine on 64-bit) printf(1,"!20=%d%s\n",{subfactorial(20),msg}) include mpfr.e function mpz_sub_factorial(integer n) -- probably not the most efficient way to do this! if n<2 then return sprintf("%d",{1-n}) end if mpz f = mpz_init(mpz_sub_factorial(n-1)), g = mpz_init(mpz_sub_factorial(n-2)) mpz_add(f,f,g) mpz_mul_si(f,f,n-1) string res = mpz_get_str(f) {f,g} = mpz_free({f,g}) return res end function printf(1,"!20=%s (mpfr)\n",{mpz_sub_factorial(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
#Rust
Rust
// Implementation of Heap's algorithm. // See https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm fn generate<T, F>(a: &mut [T], output: F) where F: Fn(&[T], isize), { let n = a.len(); let mut c = vec![0; n]; let mut i = 1; let mut sign = 1; output(a, sign); while i < n { if c[i] < i { if (i & 1) == 0 { a.swap(0, i); } else { a.swap(c[i], i); } sign = -sign; output(a, sign); c[i] += 1; i = 1; } else { c[i] = 0; i += 1; } } }   fn print_permutation<T: std::fmt::Debug>(a: &[T], sign: isize) { println!("{:?} {}", a, sign); }   fn main() { println!("Permutations and signs for three items:"); let mut a = vec![0, 1, 2]; generate(&mut a, print_permutation);   println!("\nPermutations and signs for four items:"); let mut b = vec![0, 1, 2, 3]; generate(&mut b, print_permutation); }
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
#Scala
Scala
object JohnsonTrotter extends App {   private def perm(n: Int): Unit = { val p = new Array[Int](n) // permutation val pi = new Array[Int](n) // inverse permutation val dir = new Array[Int](n) // direction = +1 or -1   def perm(n: Int, p: Array[Int], pi: Array[Int], dir: Array[Int]): Unit = { if (n >= p.length) for (aP <- p) print(aP) else { perm(n + 1, p, pi, dir) for (i <- 0 until n) { // swap printf(" (%d %d)\n", pi(n), pi(n) + dir(n)) val z = p(pi(n) + dir(n)) p(pi(n)) = z p(pi(n) + dir(n)) = n pi(z) = pi(n) pi(n) = pi(n) + dir(n) perm(n + 1, p, pi, dir) } dir(n) = -dir(n) } }   for (i <- 0 until n) { dir(i) = -1 p(i) = i pi(i) = i } perm(0, p, pi, dir) print(" (0 1)\n") }   perm(4)   }
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%
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"]; img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"]; diff = img50 - img100; Print["Total Difference between both Lenas = ", Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]
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%
#MATLAB
MATLAB
  % Percentage difference between images function p = PercentageDifferenceBetweenImages(im1,im2)   if numel(im1)~=numel(im2), error('Error: images have to be the same size'); end   d = abs(single(im1) - single(im2))./255; p = sum(d(:))./numel(im1)*100;   disp(['Percentage difference between images is: ', num2str(p), '%'])
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.
#Clojure
Clojure
(defn proper-divisors [n] (if (< n 4) [1] (->> (range 2 (inc (quot n 2))) (filter #(zero? (rem n %))) (cons 1))))   (defn perfect? [n] (= (reduce + (proper-divisors n)) n))
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.
#zkl
zkl
fcn run_test(p,len,runs){ cnt:=0; do(runs){ pv:=0; do(len){ v:=0 + ((0.0).random(1.0)<p); // 0 or 1, value of V[n] cnt += (pv<v); // if v is 1 & prev v was zero, inc cnt pv = v; } } return(cnt.toFloat() / runs / len); }
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
#C.23
C#
public static class Extension { public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values) where T : IComparable<T> { if (values.Count() == 1) return new[] { values }; return values.SelectMany(v => Permutations(values.Where(x => x.CompareTo(v) != 0)), (v, p) => p.Prepend(v)); } }
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
#Lua
Lua
-- Perform weave shuffle function shuffle (cards) local pile1, pile2 = {}, {} for card = 1, #cards / 2 do table.insert(pile1, cards[card]) end for card = (#cards / 2) + 1, #cards do table.insert(pile2, cards[card]) end cards = {} for card = 1, #pile1 do table.insert(cards, pile1[card]) table.insert(cards, pile2[card]) end return cards end   -- Return boolean indicating whether or not the cards are in order function inOrder (cards) for k, v in pairs(cards) do if k ~= v then return false end end return true end   -- Count the number of shuffles needed before the cards are in order again function countShuffles (deckSize) local deck, count = {}, 0 for i = 1, deckSize do deck[i] = i end repeat deck = shuffle(deck) count = count + 1 until inOrder(deck) return count end   -- Main procedure local testCases = {8, 24, 52, 100, 1020, 1024, 10000} print("Input", "Output") for _, case in pairs(testCases) do print(case, countShuffles(case)) 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.
#REXX
REXX
/*REXX program implements a Perlin noise algorithm of a point in 3D─space. */ _= 97a0895b5a0f830dc95f6035c2e907e18c24671e458e086325f0150a17be0694f778ea4b001ac53e5efcdbcb75230b2039b12158ed953857ae147d88aba844af, ||4aa547868b301ba64d929ee7536fe57a3cd385e6dc695c29372ef528f4668f3641193fa101d85049d14c84bbd05912a9c8c4878274bc9f56a4646dc6adba0340, ||34d9e2fa7c7b05ca2693767eff5255d4cfce3be32f103a11b6bd1c2adfb7aad577f898022c9aa346dd99659ba72bac09811627fd13626c6e4f71e0e8b2b97068, ||daf661e4fb22f2c1eed2900cbfb3a2f1513391ebf90eef6b31c0d61fb5c76a9db854ccb07379322d7f0496fe8aeccd5dde72431d1848f38d80c34e42d73d9cb4 do j=0 for length(_)%2; @.j= x2d( substr(_, 2 * j + 1, 2) ) end /*j*/ /* [↑] assign an indexed array. */ parse arg x y z d . /*obtain optional arguments from the CL*/ if x=='' | x=="," then x= 3.14 /*Not specified? Then use the default.*/ if y=='' | y=="," then y= 42 /* " " " " " " */ if z=='' | z=="," then z= 7 /* " " " " " " */ if d=='' | d=="," then d= 100 /* " " " " " " */ numeric digits d /*use D decimal digits for precision.*/ say 'Perlin noise for the 3D point ['space(x y z, 3)"] ───► " PerlinNoise(x, y, z) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fade: procedure; parse arg t; return t**3 * (t * (t * 6 - 15) + 10) floor: procedure; parse arg x; _= x % 1; return _ - (x < 0) * (x \= _) lerp: procedure; parse arg t,a,b; return a + t * (b - a) pick: _= abs( arg(1) ) // 256; return @._ /*──────────────────────────────────────────────────────────────────────────────────────*/ grad: procedure; parse arg hash,x,y,z; _= abs(hash) // 16 /*force positive remainder*/ select when _== 0 | _==12 then return x+y; when _== 1 | _==14 then return y-x when _== 2 then return x-y; when _== 3 then return -x-y when _== 4 then return x+z; when _== 5 then return z-x when _== 6 then return x-z; when _== 7 then return -x-z when _== 8 then return y+z; when _== 9 | _==13 then return z-y when _==10 then return y-z otherwise return -y-z /*for cases 11 or 15. */ end /*select*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ PerlinNoise: procedure expose @.; parse arg x,y,z x$= floor(x) // 256; x = x - floor(x); xm= x-1; u= fade(x) y$= floor(y) // 256; y = y - floor(y); ym= y-1; v= fade(y) z$= floor(z) // 256; z = z - floor(z); zm= z-1; w= fade(z) a = pick(x$ ) + y$; aa= pick(a) + z$; ab= pick(a +1) + z$ b = pick(x$ +1) + y$; ba= pick(b) + z$; bb= pick(b +1) + z$ return lerp(w, lerp(v, lerp(u, grad( pick(aa ), x , y , z ), , grad( pick(ba ), xm, y , z )), , lerp(u, grad( pick(ab ), x , ym, z ), , grad( pick(bb ), xm, ym, z ))), , lerp(v, lerp(u, grad( pick(aa+1), x , y , zm ), , grad( pick(ba+1), xm, y , zm )), , lerp(u, grad( pick(ab+1), x , ym, zm ), , grad( pick(bb+1), xm, ym, zm )))) /1
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
#Ring
Ring
  perfect = [] n = 1 while len(perfect)<20 totnt = n tsum = 0 while totnt!=1 totnt = totient(totnt) tsum = tsum + totnt end if tsum=n add(perfect,n) ok n = n + 2 end see "The first 20 perfect totient numbers are:" + nl showarray(perfect)   func totient n totnt = n i = 2 while i*i <= n if n%i=0 while true n = n/i if n%i!=0 exit ok end totnt = totnt - totnt/i ok if i=2 i = i + 1 else i = i + 2 ok end if n>1 totnt = totnt - totnt/n ok return totnt   func showArray array txt = "" see "[" for n = 1 to len(array) txt = txt + array[n] + "," next txt = left(txt,len(txt)-1) txt = txt + "]" see txt  
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
#Ruby
Ruby
require "prime"   class Integer   def φ prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end   def perfect_totient? f, sum = self, 0 until f == 1 do f = f.φ sum += f end self == sum end   end   puts (1..).lazy.select(&:perfect_totient?).first(20).join(", ")  
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
#Kotlin
Kotlin
const val FACES = "23456789TJQKA" const val SUITS = "shdc"   fun createDeck(): List<String> { val cards = mutableListOf<String>() FACES.forEach { face -> SUITS.forEach { suit -> cards.add("$face$suit") } } return cards }   fun dealTopDeck(deck: List<String>, n: Int) = deck.take(n)   fun dealBottomDeck(deck: List<String>, n: Int) = deck.takeLast(n).reversed()   fun printDeck(deck: List<String>) { for (i in deck.indices) { print("${deck[i]} ") if ((i + 1) % 13 == 0 || i == deck.size - 1) println() } }   fun main(args: Array<String>) { var deck = createDeck() println("After creation, deck consists of:") printDeck(deck) deck = deck.shuffled() println("\nAfter shuffling, deck consists of:") printDeck(deck) val dealtTop = dealTopDeck(deck, 10) println("\nThe 10 cards dealt from the top of the deck are:") printDeck(dealtTop) val dealtBottom = dealBottomDeck(deck, 10) println("\nThe 10 cards dealt from the bottom of the deck are:") printDeck(dealtBottom) }
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
#jq
jq
# The Gibbons spigot, in the mold of the [[#Groovy]] and [[#Python]] programs shown on this page. # The "bigint" functions needed are: # long_minus long_add long_multiply long_div   def pi_spigot:   # S is the sixtuple: # q r t k n l # 0 1 2 3 4 5   def long_lt(x;y): if x == y then false else lessOrEqual(x;y) end;   def check: long_lt(long_minus(long_add(long_multiply("4"; .[0]); .[1]) ; .[2]); long_multiply(.[4]; .[2]));   # state: [d, S] where digit is null or a digit ready to be printed def next: .[1] as $S | $S[0] as $q | $S[1] as $r | $S[2] as $t | $S[3] as $k | $S[4] as $n | $S[5] as $l | if $S|check then [$n, [long_multiply("10"; $q), long_multiply("10"; long_minus($r; long_multiply($n;$t))), $t, $k, long_minus( long_div(long_multiply("10";long_add(long_multiply("3"; $q); $r)); $t ); long_multiply("10";$n)), $l ]] else [null, [long_multiply($q;$k), long_multiply( long_add(long_multiply("2";$q); $r); $l), long_multiply($t;$l), long_add($k; "1"), long_div( long_add(long_multiply($q; long_add(long_multiply("7";$k); "2")) ; long_multiply($r;$l)); long_multiply($t;$l) ), long_add($l; "2") ]] end;   # Input: input to the filter "nextstate" # Output: [count, space, digit] for successive digits produced by "nextstate" def decorate( nextstate ):   # For efficiency it is important that the recursive # function have arity 0 and be tail-recursive: def count: .[0] as $count | .[1] as $state | $state[0] as $value | ($state[1] | map(length) | add) as $space | (if $value then [$count, $space, $value] else empty end), ( [if $value then $count+1 else $count end, ($state | nextstate)] | count); [0, .] | count;   # q=1, r=0, t=1, k=1, n=3, l=3 [null, ["1", "0", "1", "1", "3", "3"]] | decorate(next) ;   pi_spigot
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
#Ring
Ring
  # Project : Pig the dice game   numPlayers = 2 maxScore = 100 safescore = list(numPlayers)   while true rolling = "" for player = 1 to numPlayers score = 0 while safeScore[player] < maxScore see "Player " + player + " Rolling? (Y) " give rolling if upper(rolling) = "Y" rolled = random(5) + 1 see "Player " + player + " rolled " + rolled + nl if rolled = 1 see "Bust! you lose player " + player + " but still keep your previous score of " + safeScore[player] + nl exit ok score = score + rolled else safeScore[player] = safeScore[player] + score ok end next end see "Player " + player + " wins with a score of " + safeScore[player]  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
popcount[n_Integer] := IntegerDigits[n, 2] // Total perniciousQ[n_Integer] := popcount[n] // PrimeQ perniciouscount = 0; perniciouslist = {}; i = 0; While[perniciouscount < 25, If[perniciousQ[i], AppendTo[perniciouslist, i]; perniciouscount++]; i++] Print["first 25 pernicious numbers"] perniciouslist (*******) perniciouslist2 = {}; Do[ If[perniciousQ[i], AppendTo[perniciouslist2, i]] , {i, 888888877, 888888888}] Print["Pernicious numbers between 888,888,877 and 888,888,888 (inclusive)"] perniciouslist2
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Perl
Perl
my @array = qw(a b c); print $array[ rand @array ];
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Phix
Phix
with javascript_semantics constant s = {1,2.5,"three",{4,{"4 as well"}}} pp(s[rand(length(s))])
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
#PowerShell
PowerShell
  function reverse($a, $sep = "") { if($a.Length -gt 0) { $a = $a[($a.Length -1)..0] -join $sep } $a } $line = "rosetta code phrase reversal" $task1 = reverse $line $task2 = ($line -split " " | foreach{ reverse $_ }) -join " " $task3 = reverse ($line -split " ") " " $task1 $task2 $task3  
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
#PureBasic
PureBasic
#TEXT="rosetta code phrase reversal"   If OpenConsole("rosetta code phrase reversal") Define idx.i=1, txt.s=""   Print(~"Original:\t\t") PrintN(#TEXT)   Print(~"Reversed:\t\t") PrintN(ReverseString(#TEXT))   Print(~"Reversed words:\t\t") txt=StringField(#TEXT,idx," ") While Len(txt) Print(ReverseString(txt)+" ") idx+1 txt=StringField(#TEXT,idx," ") Wend PrintN("")   Print(~"Reversed order:\t\t") idx-1 txt=StringField(#TEXT,idx," ") While Len(txt) Print(txt+" ") If idx>1 : idx-1 : Else : Break : EndIf txt=StringField(#TEXT,idx," ") Wend   Input() EndIf
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
#Picat
Picat
import util.   go => foreach(N in 0..9) println([N,num_derangements=num_derangements(N), subfactorial=subfactorial(N), subfactorial2=subfactorial2(N)]) end, println(["!20", subfactorial(20)]), println(["!20 approx", subfactorial2(20)]), println("subfactorial0..30"=[subfactorial(N) : N in 0..30 ]), println("subfactorial2_0..30"=[subfactorial2(N) : N in 0..30 ]), println(["!200", subfactorial(200)]), nl, println("Syntax sugar:"), println("'!'(20)"='!'(20)), println("200.'!'()"=200.'!'()), println("'!!'(20)"='!!'(20)), println("'!-!!'(10)"='!-!!'(10)), nl.   num_derangements(N) = derangements(N).length.   derangements(N) = D => D = [P : P in permutations(1..N), nofixpoint(P)].   % subfactorial: tabled recursive function table subfactorial(0) = 1. subfactorial(1) = 0. subfactorial(N) = (N-1)*(subfactorial(N-1)+subfactorial(N-2)).   % approximate version of subfactorial subfactorial2(0) = 1. subfactorial2(N) = floor(1.0*floor(factorial(N)/2.71828 + 1/2.0)).   % Factorial fact(N) = F => F1 = 1, foreach(I in 1..N) F1 := F1 * I end, F = F1.   % No fixpoint in L nofixpoint(L) => foreach(I in 1..L.length) L[I] != I end.   % Some syntax sugar. Note: the function must be an atom. '!'(N) = fact(N). '!!'(N) = subfactorial(N).   '!-!!'(N) = fact(N) - subfactorial(N).
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
#Sidef
Sidef
func perms(n) { var perms = [[+1]] for x in (1..n) { var sign = -1 perms = gather { for s,*p in perms { var r = (0 .. p.len) take((s < 0 ? r : r.flip).map {|i| [sign *= -1, p[^i], x, p[i..p.end]] }...) } } } perms }   var n = 4 for p in perms(n) { var s = p.shift s > 0 && (s = '+1') say "#{p} => #{s}" }
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%
#MAXScript
MAXScript
fn diffImages = ( local img1 = selectBitmap caption:"Select Image 1" local img2 = selectBitmap caption:"Select Image 2" local totalDiff = 0 for i in 0 to (img1.height-1) do ( local img1Row = getPixels img1 [0, i] img1.width local img2Row = getPixels img2 [0, i] img2.width   for j in 1 to img1.width do ( totalDiff += (abs (img1Row[j].r - img2Row[j].r)) / 255.0 totalDiff += (abs (img1Row[j].g - img2Row[j].g)) / 255.0 totalDiff += (abs (img1Row[j].b - img2Row[j].b)) / 255.0 ) ) format "Diff: %\%\n" (totalDiff / ((img1.width * img1.height * 3) as float) * 100) )
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%
#Nim
Nim
import strformat import imageman   var img50, img100: Image[ColorRGBU] try: img50 = loadImage[ColorRGBU]("Lenna50.jpg") img100 = loadImage[ColorRGBU]("Lenna100.jpg") except IOError: echo getCurrentExceptionMsg() quit QuitFailure   let width = img50.width let height = img50.height if img100.width != width or img100.height != height: quit "Images have different sizes.", QuitFailure   var sum = 0 for x in 0..<height: for y in 0..<width: let color1 = img50[x, y] let color2 = img100[x, y] for i in 0..2: sum += abs(color1[i].int - color2[i].int)   echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"
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.
#COBOL
COBOL
$set REPOSITORY "UPDATE ON"   IDENTIFICATION DIVISION. PROGRAM-ID. perfect-main.   ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION perfect . DATA DIVISION. WORKING-STORAGE SECTION. 01 i PIC 9(8).   PROCEDURE DIVISION. PERFORM VARYING i FROM 2 BY 1 UNTIL 33550337 = i IF FUNCTION perfect(i) = 0 DISPLAY i END-IF END-PERFORM   GOBACK . END PROGRAM perfect-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
#C.2B.2B
C++
#include <algorithm> #include <string> #include <vector> #include <iostream>   template<class T> void print(const std::vector<T> &vec) { for (typename std::vector<T>::const_iterator i = vec.begin(); i != vec.end(); ++i) { std::cout << *i; if ((i + 1) != vec.end()) std::cout << ","; } std::cout << std::endl; }   int main() { //Permutations for strings std::string example("Hello"); std::sort(example.begin(), example.end()); do { std::cout << example << '\n'; } while (std::next_permutation(example.begin(), example.end()));   // And for vectors std::vector<int> another; another.push_back(1234); another.push_back(4321); another.push_back(1234); another.push_back(9999);   std::sort(another.begin(), another.end()); do { print(another); } while (std::next_permutation(another.begin(), another.end()));   return 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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
shuffle[deck_] := Apply[Riffle, TakeDrop[deck, Length[deck]/2]]; shuffleCount[n_] := Block[{count=0}, NestWhile[shuffle, shuffle[Range[n]], (count++; OrderedQ[#] )&];count]; Map[shuffleCount, {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
#MATLAB
MATLAB
function [New]=PerfectShuffle(Nitems, Nturns) if mod(Nitems,2)==0 %only if even number X=1:Nitems; %define deck for c=1:Nturns %defines one shuffle X=reshape(X,Nitems/2,2)'; %split the deck in two and stack halves X=X(:)'; %mix the halves end New=X; %result of multiple shufflings 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.
#Rust
Rust
fn main() { println!("{}", noise(3.14, 42.0, 7.0)); }   fn noise(x: f64, y: f64, z: f64) -> f64 { let x0 = x.floor() as usize & 255; let y0 = y.floor() as usize & 255; let z0 = z.floor() as usize & 255;   let x = x - x.floor(); let y = y - y.floor(); let z = z - z.floor();   let u = fade(x); let v = fade(y); let w = fade(z);   let a = P[x0] + y0; let aa = P[a] + z0; let ab = P[a + 1] + z0; let b = P[x0 + 1] + y0; let ba = P[b] + z0; let bb = P[b + 1] + z0;   return lerp(w, lerp(v, lerp(u, grad(P[aa], x , y , z), grad(P[ba], x-1.0, y , z)), lerp(u, grad(P[ab], x , y-1.0, z), grad(P[bb], x-1.0, y-1.0, z))), lerp(v, lerp(u, grad(P[aa+1], x , y , z-1.0), grad(P[ba+1], x-1.0, y , z-1.0)), lerp(u, grad(P[ab+1], x , y-1.0, z-1.0), grad(P[bb+1], x-1.0, y-1.0, z-1.0)))); }   fn fade(t: f64) -> f64 { t * t * t * ( t * (t * 6.0 - 15.0) + 10.0) }   fn lerp(t: f64, a: f64, b: f64) -> f64 { a + t * (b - a) }   fn grad(hash: usize, x: f64, y: f64, z: f64) -> f64 { let h = hash & 15; let u = if h < 8 { x } else { y }; let v = if h < 4 { y } else { if h == 12 || h == 14 { x } else { z } };   return if h&1 == 0 { u } else { -u } + if h&2 == 0 { v } else { -v }; }   static P: [usize; 512] = [151,160,137,91,90,15,131,13,201,95,96,53,194,233, 7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190, 6,148,247,120,234, 75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87, 174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,77,146,158, 231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102, 143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124, 123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189, 28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218, 246,97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249, 14,239,107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156, 180,151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69 ,142,8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219, 203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175, 74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230, 220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161, 1,216,80,73,209, 76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198, 173,186, 3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212, 207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152, 2, 44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108, 110,79,113,224,232,178,185, 112,104,218,246,97,228,251,34,242,193,238, 210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31, 181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205, 93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];
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
#Scala
Scala
//List of perfect totients def isPerfectTotient(num: Int): Boolean = LazyList.iterate(totient(num))(totient).takeWhile(_ != 1).foldLeft(0L)(_+_) + 1 == num def perfectTotients: LazyList[Int] = LazyList.from(3).filter(isPerfectTotient)   //Totient Function @tailrec def scrub(f: Long, num: Long): Long = if(num%f == 0) scrub(f, num/f) else num def totient(num: Long): Long = LazyList.iterate((num, 2: Long, num)){case (ac, i, n) => if(n%i == 0) (ac*(i - 1)/i, i + 1, scrub(i, n)) else (ac, i + 1, n)}.dropWhile(_._3 != 1).head._1
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
#Liberty_BASIC
Liberty BASIC
Dim deckCards(52) Dim holdCards(1, 1) Print "The Sorted Deck" Call sortDeck Call dealDeck Print: Print Print "The Shuffled Deck" Call shuffleDeck Call dealDeck Print: Print nPlayers = 4 nCards = 5 ct = 0 Redim holdCards(nPlayers, nCards) Print "Dealing ";nCards;" cards to ";nPlayers;" players" For i = 1 to nPlayers Print "Player #";i,, Next i Print For i = 1 to nCards For j = 1 to nPlayers ct = ct + 1 holdCards(j, i) = deckCards(ct) card = deckCards(ct) value = value(card) suit$ = suit$(card) pip$ = pip$(value) Print card;": ";pip$;" of ";suit$, Next j Print Next i Print: Print Print "The cards in memory / array" For i = 1 to nPlayers Print "Player #";i;" is holding" For j = 1 to nCards card = holdCards(i, j) value = value(card) suit$ = suit$(card) pip$ = pip$(value) Print card;": ";pip$;" of ";suit$ Next j Print Next i   End   Sub dealDeck For i = 1 to 52 card = deckCards(i) value = value(card) suit$ = suit$(card) pip$ = pip$(value) Print i, card, value, pip$;" of ";suit$ Next i End Sub   Sub sortDeck For i = 1 to 52 deckCards(i) = i Next i End Sub   Sub shuffleDeck For i = 52 to 1 Step -1 x = Int(Rnd(1) * i) + 1 temp = deckCards(x) deckCards(x) = deckCards(i) deckCards(i) = temp Next i End Sub   Function suit$(deckValue) cardSuit$ = "Spades Hearts Clubs Diamonds" suit = Int(deckValue / 13) If deckValue Mod 13 = 0 Then suit = suit - 1 End If suit$ = Word$(cardSuit$, suit + 1) End Function   Function value(deckValue) value = deckValue Mod 13 If value = 0 Then value = 13 End If End Function   Function pip$(faceValue) pipLabel$ = "Ace Deuce Three Four Five Six Seven Eight Nine Ten Jack Queen King" pip$ = Word$(pipLabel$, faceValue) End Function
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
#Julia
Julia
let prec = precision(BigFloat), spi = "", digit = 1 while true if digit > lastindex(spi) prec *= 2 setprecision(prec) spi = string(big(π)) end print(spi[digit]) digit += 1 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
#Ruby
Ruby
class PigGame Player = Struct.new(:name, :safescore, :score) do def bust!() self.score = safescore end def stay!() self.safescore = score end def to_s() "#{name} (#{safescore}, #{score})" end end   def initialize(names, maxscore=100, die_sides=6) rotation = names.map {|name| Player.new(name,0,0) }   rotation.cycle do |player| loop do if wants_to_roll?(player) puts "Rolled: #{roll=roll_dice(die_sides)}" if bust?(roll) puts "Busted!",'' player.bust! break else player.score += roll if player.score >= maxscore puts player.name + " wins!" return end end else player.stay! puts "Staying with #{player.safescore}!", '' break end end end end   def roll_dice(die_sides) rand(1..die_sides) end def bust?(roll) roll==1 end def wants_to_roll?(player) print "#{player}: Roll? (Y) " ['Y','y',''].include?(gets.chomp) end end   PigGame.new( %w|Samuel Elizabeth| )
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.
#Modula-2
Modula-2
MODULE Pernicious; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE IsPrime(x : LONGINT) : BOOLEAN; VAR i : LONGINT; BEGIN IF x<2 THEN RETURN FALSE END; FOR i:=2 TO x-1 DO IF x MOD i = 0 THEN RETURN FALSE END END; RETURN TRUE END IsPrime;   PROCEDURE BitCount(x : LONGINT) : LONGINT; VAR count : LONGINT; BEGIN count := 0; WHILE x>0 DO x := x BAND (x-1); INC(count) END; RETURN count END BitCount;   VAR buf : ARRAY[0..63] OF CHAR; i,n : LONGINT; BEGIN i := 1; n := 0; WHILE n<25 DO IF IsPrime(BitCount(i)) THEN FormatString("%l ", buf, i); WriteString(buf); INC(n) END; INC(i) END; WriteLn;   FOR i:=888888877 TO 888888888 DO IF IsPrime(BitCount(i)) THEN FormatString("%l ", buf, i); WriteString(buf) END; END;   ReadChar END Pernicious.
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#PHP
PHP
$arr = array('foo', 'bar', 'baz'); $x = $arr[array_rand($arr)];
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
#Python
Python
>>> phrase = "rosetta code phrase reversal" >>> phrase[::-1] # Reversed. 'lasrever esarhp edoc attesor' >>> ' '.join(word[::-1] for word in phrase.split()) # Words reversed. 'attesor edoc esarhp lasrever' >>> ' '.join(phrase.split()[::-1]) # Word order reversed. 'reversal phrase code rosetta' >>>
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
#Quackery
Quackery
$ "rosetta code phrase reversal"   3 times dup   say "0. " echo$ cr say "1. " reverse echo$ cr say "2. " nest$ witheach [ reverse echo$ sp ] cr say "3. " nest$ reverse witheach [ echo$ sp ] cr
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
#PicoLisp
PicoLisp
(load "@lib/simul.l") # For 'permute'   (de derangements (Lst) (filter '((L) (not (find = L Lst))) (permute Lst) ) )   (de subfact (N) (if (>= 2 N) (if (= 1 N) 0 1) (* (dec N) (+ (subfact (dec N)) (subfact (- N 2))) ) ) )
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
#Swift
Swift
// Implementation of Heap's algorithm. // See https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm func generate<T>(array: inout [T], output: (_: [T], _: Int) -> Void) { let n = array.count var c = Array(repeating: 0, count: n) var i = 1 var sign = 1 output(array, sign) while i < n { if c[i] < i { if (i & 1) == 0 { array.swapAt(0, i) } else { array.swapAt(c[i], i) } sign = -sign output(array, sign) c[i] += 1 i = 1 } else { c[i] = 0 i += 1 } } }   func printPermutation<T>(array: [T], sign: Int) { print("\(array) \(sign)") }   print("Permutations and signs for three items:") var a = [0, 1, 2] generate(array: &a, output: printPermutation)   print("\nPermutations and signs for four items:") var b = [0, 1, 2, 3] generate(array: &b, output: printPermutation)
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
#Tcl
Tcl
# A simple swap operation proc swap {listvar i1 i2} { upvar 1 $listvar l set tmp [lindex $l $i1] lset l $i1 [lindex $l $i2] lset l $i2 $tmp }   proc permswap {n v1 v2 body} { upvar 1 $v1 perm $v2 sign   # Initialize set sign -1 for {set i 0} {$i < $n} {incr i} { lappend items $i lappend dirs -1 }   while 1 { # Report via callback set perm $items set sign [expr {-$sign}] uplevel 1 $body   # Find the largest mobile integer (lmi) and its index (idx) set i [set idx -1] foreach item $items dir $dirs { set j [expr {[incr i] + $dir}] if {$j < 0 || $j >= [llength $items]} continue if {$item > [lindex $items $j] && ($idx == -1 || $item > $lmi)} { set lmi $item set idx $i } }   # If none, we're done if {$idx == -1} break   # Swap the largest mobile integer with "what it is looking at" set nextIdx [expr {$idx + [lindex $dirs $idx]}] swap items $idx $nextIdx swap dirs $idx $nextIdx   # Reverse directions on larger integers set i -1 foreach item $items dir $dirs { lset dirs [incr i] [expr {$item > $lmi ? -$dir : $dir}] } } }
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%
#OCaml
OCaml
#! /usr/bin/env ocaml #directory "+glMLite/" #load "jpeg_loader.cma" #load "bigarray.cma" open Jpeg_loader   let () = let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1)) and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in   assert(width1 = width2); assert(height1 = height2); assert(col_comp1 = col_comp2); (* number of color components *) assert(color_space1 = color_space2);   let img1 = Bigarray.array3_of_genarray img1 and img2 = Bigarray.array3_of_genarray img2 in   let sum = ref 0.0 and num = ref 0 in   for x=0 to pred width1 do for y=0 to pred height1 do for c=0 to pred col_comp1 do let v1 = float img1.{x,y,c} and v2 = float img2.{x,y,c} in let diff = (abs_float (v1 -. v2)) /. 255. in sum := diff +. !sum; incr num; done; done; done;   let diff_percent = !sum /. float !num in Printf.printf " diff: %f percent\n" diff_percent; ;;
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.
#CoffeeScript
CoffeeScript
is_perfect_number = (n) -> do_factors_add_up_to n, 2*n   do_factors_add_up_to = (n, desired_sum) -> # We mildly optimize here, by taking advantage of # the fact that the sum_of_factors( (p^m) * x) # is (1 + ... + p^m-1 + p^m) * sum_factors(x) when # x is not itself a multiple of p.   p = smallest_prime_factor(n) if p == n return desired_sum == p + 1   # ok, now sum up all powers of p that # divide n sum_powers = 1 curr_power = 1 while n % p == 0 curr_power *= p sum_powers += curr_power n /= p   # if desired_sum does not divide sum_powers, we # can short circuit quickly return false unless desired_sum % sum_powers == 0   # otherwise, recurse do_factors_add_up_to n, desired_sum / sum_powers   smallest_prime_factor = (n) -> for i in [2..n] return n if i*i > n return i if n % i == 0   # tests do -> # This is pretty fast... for n in [2..100000] console.log n if is_perfect_number n   # For big numbers, let's just sanity check the known ones. known_perfects = [ 33550336 8589869056 137438691328 ] for n in known_perfects throw Error("fail") unless is_perfect_number(n) throw Error("fail") if is_perfect_number(n+1)
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
#Clojure
Clojure
  user=> (require 'clojure.contrib.combinatorics) nil user=> (clojure.contrib.combinatorics/permutations [1 2 3]) ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))
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
#Modula-2
Modula-2
MODULE PerfectShuffle; FROM FormatString IMPORT FormatString; FROM Storage IMPORT ALLOCATE,DEALLOCATE; FROM SYSTEM IMPORT ADDRESS,TSIZE; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteCard(c : CARDINAL); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%c", buf, c); WriteString(buf) END WriteCard;   PROCEDURE Init(VAR arr : ARRAY OF INTEGER); VAR i : CARDINAL; BEGIN FOR i:=0 TO HIGH(arr) DO arr[i] := i + 1 END END Init;   PROCEDURE PerfectShuffle(VAR arr : ARRAY OF INTEGER); PROCEDURE Inner(ti : CARDINAL); VAR tv : INTEGER; tp,tn,n : CARDINAL; BEGIN n := HIGH(arr); tn := ti; tv := arr[ti]; REPEAT tp := tn; IF tp MOD 2 = 0 THEN tn := tp / 2 ELSE tn := (n+1)/2+tp/2 END; arr[tp] := arr[tn]; UNTIL tn = ti; arr[tp] := tv END Inner; VAR done : BOOLEAN; i,c : CARDINAL; BEGIN c := 0; Init(arr);   REPEAT i := 1; WHILE i <= (HIGH(arr)/2) DO Inner(i); INC(i,2) END; INC(c);   done := TRUE; FOR i:=0 TO HIGH(arr) DO IF arr[i] # INT(i+1) THEN done := FALSE; BREAK END END UNTIL done;   WriteCard(HIGH(arr)+1); WriteString(": "); WriteCard(c); WriteLn END PerfectShuffle;   (* Main *) VAR v8 : ARRAY[1..8] OF INTEGER; v24 : ARRAY[1..24] OF INTEGER; v52 : ARRAY[1..52] OF INTEGER; v100 : ARRAY[1..100] OF INTEGER; v1020 : ARRAY[1..1020] OF INTEGER; v1024 : ARRAY[1..1024] OF INTEGER; v10000 : ARRAY[1..10000] OF INTEGER; BEGIN PerfectShuffle(v8); PerfectShuffle(v24); PerfectShuffle(v52); PerfectShuffle(v100); PerfectShuffle(v1020); PerfectShuffle(v1024); PerfectShuffle(v10000);   ReadChar END PerfectShuffle.
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.
#Sidef
Sidef
const p = (%w'47 4G 3T 2J 2I F 3N D 5L 2N 2O 1H 5E 6H 7 69 3W 10 2V U 1X 3Y 8 2R 11 6O L A N 5A 6 44 6V 3C 6I 23 0 Q 5H 1Q 2M 70 63 5N 39 Z B W 1L 4X X 2G 6L 45 1K 2F 4U K 3H 3S 4R 4O 1W 4V 22 4L 1Z 3Q 3V 1C R 4M 25 42 4E 6F 2B 33 6D 3E 1O 5V 3P 6E 64 2X 2K 15 1J 1A 6T 14 6S 2U 3Z 1I 1T P 1R 4H 1 60 28 21 5T 24 3O 57 5S 2H I 4P 5K 5G 3R 3M 38 58 4F 2E 4K 2S 31 5I 4T 56 3 1S 1G 61 6A 6Y 3G 3F 5 5M 12 43 3A 3I 73 2A 2D 5W 5R 5Q 1N 6B 1B G 1M H 52 59 S 16 67 53 4Q 5X 3B 6W 48 2 18 4A 4J 1Y 65 49 2T 4B 4N 17 4S 9 3L M 13 71 J 2Q 30 32 27 35 68 6G 4Y 55 34 2W 62 6U 2P 6C 6Z Y 6Q 5D 6M 5U 40 C 5B 4Z 4I 6P 29 1F 41 6J 6X E 6N 2Z 1D 5C 5Y V 51 5J 2Y 4D 54 2C 5O 4W 37 3D 1E 19 3J 4 46 72 3U 6K 5P 2L 66 36 1V T O 20 6R 3X 3K 5F 26 1U 5Z 1P 4C 50' * 2 -> map {|n| Num(n, 36) })   func fade(n) { n * n * n * (n * (n * 6 - 15) + 10) } func lerp(t, a, b) { a + t*(b-a) }   func grad(h, x, y, z) { h &= 15 var u = (h < 8 ? x : y) var v = (h < 4 ? y : (h ~~ [12,14] ? x : z)) (h&1 ? -u : u) + (h&2 ? -v : v) }   func noise(x, y, z) { var(X, Y, Z) = [x, y, z].map { .floor & 255 }... var (u, v, w) = [x-=X, y-=Y, z-=Z].map { fade(_) }... var (AA, AB) = with(p[X] + Y) {|i| (p[i] + Z, p[i+1] + Z) } var (BA, BB) = with(p[X+1] + Y) {|i| (p[i] + Z, p[i+1] + Z) } lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1), grad(p[BA+1], x-1, y , z-1)), lerp(u, grad(p[AB+1], x , y-1, z-1), grad(p[BB+1], x-1, y-1, z-1)))) }   say noise(3.14, 42, 7)
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
#Sidef
Sidef
func perfect_totient({.<=1}, sum=0) { sum } func perfect_totient( n, sum=0) { __FUNC__(var(t = n.euler_phi), sum + t) }   say (1..Inf -> lazy.grep {|n| perfect_totient(n) == n }.first(20))