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/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
#FreeBASIC
FreeBASIC
#define NSWAPS 100   type card suit : 2 as ubyte face : 4 as ubyte 'the remaining 2 bits are unused end type   dim shared as string*8 Suits(0 to 3) = {"Spades", "Clubs", "Hearts", "Diamonds"} dim shared as string*8 Faces(0 to 12) = {"Ace", "Two", "Three", "Four", "Five",_ "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}   sub newdeck( deck() as card ) 'produces an unshuffled deck of 52 cards redim preserve deck(0 to 51) as card for s as ubyte = 0 to 3 for f as ubyte = 0 to 12 deck(13*s + f).suit = s deck(13*s + f).face = f next f next s end sub   function deal( deck() as card ) as card 'deals one card from the top of the deck, returning that 'card and removing it from the deck dim as card dealt = deck(ubound(deck)) redim preserve deck(0 to ubound(deck) - 1) return dealt end function   function card_name( c as card ) as string 'returns the name of a single given card return Faces(c.face) + " of " + Suits(c.suit) end function   sub print_deck( deck() as card ) 'displays the contents of the deck, 'with the top card (next to be dealt) first for i as byte = ubound(deck) to 0 step -1 print card_name( deck(i) ) next i end sub   sub shuffle_deck( deck() as card ) dim as integer n = ubound(deck)+1 for i as integer = 1 to NSWAPS swap deck( int(rnd*n) ), deck( int(rnd*n) ) next i end sub   redim as card deck(0 to 0) 'allocate a new deck newdeck(deck()) 'set up the new deck print "Dealing a card: ", card_name( deal( deck() ) ) for j as integer = 1 to 41 'deal another 41 cards and discard them deal(deck()) next j shuffle_deck(deck()) 'shuffle the remaining cards print_deck(deck()) 'display the last ten cards
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ... Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions. Related Task Arithmetic-geometric mean/Calculate Pi
#Fortran
Fortran
  program pi implicit none integer,dimension(3350) :: vect integer,dimension(201) :: buffer integer :: more,karray,num,k,l,n more = 0 vect = 2 do n = 1,201 karray = 0 do l = 3350,1,-1 num = 100000*vect(l) + karray*l karray = num/(2*l - 1) vect(l) = num - karray*(2*l - 1) end do k = karray/100000 buffer(n) = more + k more = karray - k*100000 end do write (*,'(i2,"."/(1x,10i5.5))') buffer end program pi  
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
#Nim
Nim
import random, strformat, strutils   randomize()   stdout.write "Player 1 - Enter your name : " let name1 = block: let n = stdin.readLine().strip() if n.len == 0: "PLAYER 1" else: n.toUpper stdout.write "Player 2 - Enter your name : " let name2 = block: let n = stdin.readLine().strip() if n.len == 0: "PLAYER 2" else: n.toUpper   let names = [name1, name2] var totals: array[2, Natural] var player = 0   while true: echo &"\n{names[player]}" echo &" Your total score is currently {totals[player]}" var score = 0   while true: stdout.write " Roll or Hold r/h : " let rh = stdin.readLine().toLowerAscii() case rh   of "h": inc totals[player], score echo &" Your total score is now {totals[player]}" if totals[player] >= 100: echo &" So, {names[player]}, YOU'VE WON!" quit QuitSuccess player = 1 - player break   of "r": let dice = rand(1..6) echo &" You have thrown a {dice}" if dice == 1: echo " Sorry, your score for this round is now 0" echo &" Your total score remains at {totals[player]}" player = 1 - player break inc score, dice echo &" Your score for the round is now {score}"   else: echo " Must be 'r' or 'h', try again"
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func pernicious(w uint32) bool { const ( ff = 1<<32 - 1 mask1 = ff / 3 mask3 = ff / 5 maskf = ff / 17 maskp = ff / 255 ) w -= w >> 1 & mask1 w = w&mask3 + w>>2&mask3 w = (w + w>>4) & maskf return 0xa08a28ac>>(w*maskp>>24)&1 != 0 }   func main() { for i, n := 0, uint32(1); i < 25; n++ { if pernicious(n) { fmt.Printf("%d ", n) i++ } } fmt.Println() for n := uint32(888888877); n <= 888888888; n++ { if pernicious(n) { fmt.Printf("%d ", n) } } fmt.Println() }
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them. Task Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind. Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind. See also Wikipedia - Pierpont primes OEIS:A005109 - Class 1 -, or Pierpont primes OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP var [const] one=BI(1), two=BI(2), three=BI(3);   fcn pierPonts(n){ //-->((bigInt first kind primes) (bigInt second)) pps1,pps2 := List(BI(2)), List(); count1, count2, s := 1, 0, List(BI(1)); // n==2_000, s-->266_379 elements i2,i3,k := 0, 0, 1; n2,n3,t := BI(0),BI(0),BI(0); while(count1.min(count2) < n){ n2.set(s[i2]).mul(two); // .mul, .add, .sub are in-place n3.set(s[i3]).mul(three); if(n2<n3){ t.set(n2); i2+=1; } else { t.set(n3); i3+=1; } if(t > s[k-1]){ s.append(t.copy()); k+=1; t.add(one); if(count1<n and t.probablyPrime()){ pps1.append(t.copy()); count1+=1; } if(count2<n and t.sub(two).probablyPrime()){ pps2.append(t.copy()); count2+=1; } } } return(pps1,pps2) }
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Klingphix
Klingphix
include ..\Utilitys.tlhy   :pickran len rand * 1 + get ;   ( 1 3.1415 "Hello world" ( "nest" "list" ) )   10 [drop pickran ?] for   " " input
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   /** * Extension function on any list that will return a random element from index 0 * to the last index */ fun <E> List<E>.getRandomElement() = this[Random().nextInt(this.size)]   /** * Extension function on any list that will return a list of unique random picks * from the list. If the specified number of elements you want is larger than the * number of elements in the list it returns null */ fun <E> List<E>.getRandomElements(numberOfElements: Int): List<E>? { if (numberOfElements > this.size) { return null } return this.shuffled().take(numberOfElements) }   fun main(args: Array<String>) { val list = listOf(1, 16, 3, 7, 17, 24, 34, 23, 11, 2) println("The list consists of the following numbers:\n${list}")   // notice we can call our extension functions as if they were regular member functions of List println("\nA randomly selected element from the list is ${list.getRandomElement()}") println("\nA random sequence of 5 elements from the list is ${list.getRandomElements(5)}") }
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
#K
K
  / Rosetta code phrase reversal / phraserev.k   reversestr: {|x} getnxtwd: {c:(&" "~'x); if[c~!0;w::x;:""];w::c[0]#x; x: ((1+c[0]) _ x)} revwords: {rw:""; while[~(x~""); x: getnxtwd x;rw,:|w;rw,:" "];:-1 _ rw} revwordorder: {rw:""; while[~(x~""); x: getnxtwd x;rw:" ",rw;rw:w,rw];:-1 _ rw}    
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
#Klingphix
Klingphix
include ..\Utilitys.tlhy   "Rosetta Code Phrase Reversal" dup ? dup reverse ? split dup reverse len [drop pop swap print " " print] for drop nl len [drop pop swap reverse print " " print] for drop nl nl   "End " input
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
#Haskell
Haskell
import Control.Monad (forM_)   import Data.List (permutations)   -- Compute all derangements of a list derangements :: Eq a => [a] -> [[a]] derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations   -- Compute the number of derangements of n elements subfactorial :: (Eq a, Num a) => a -> a subfactorial 0 = 1 subfactorial 1 = 0 subfactorial n = (n - 1) * (subfactorial (n - 1) + subfactorial (n - 2))   main :: IO () main -- Generate and show all the derangements of four integers = do print $ derangements [1 .. 4] putStrLn "" -- Print the count of derangements vs subfactorial forM_ [1 .. 9] $ \i -> putStrLn $ mconcat [show (length (derangements [1 .. i])), " ", show (subfactorial i)] putStrLn "" -- Print the number of derangements in a list of 20 items print $ subfactorial 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
#Lua
Lua
_JT={} function JT(dim) local n={ values={}, positions={}, directions={}, sign=1 } setmetatable(n,{__index=_JT}) for i=1,dim do n.values[i]=i n.positions[i]=i n.directions[i]=-1 end return n end   function _JT:largestMobile() for i=#self.values,1,-1 do local loc=self.positions[i]+self.directions[i] if loc >= 1 and loc <= #self.values and self.values[loc] < i then return i end end return 0 end   function _JT:next() local r=self:largestMobile() if r==0 then return false end local rloc=self.positions[r] local lloc=rloc+self.directions[r] local l=self.values[lloc] self.values[lloc],self.values[rloc] = self.values[rloc],self.values[lloc] self.positions[l],self.positions[r] = self.positions[r],self.positions[l] self.sign=-self.sign for i=r+1,#self.directions do self.directions[i]=-self.directions[i] end return true end   -- test   perm=JT(4) repeat print(unpack(perm.values)) until not perm:next()
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.
#R
R
permutation.test <- function(treatment, control) { perms <- combinations(length(treatment)+length(control), length(treatment), c(treatment, control), set=FALSE) p <- mean(rowMeans(perms) <= mean(treatment)) c(under=p, over=(1-p)) }
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.
#Racket
Racket
#lang racket/base   (define-syntax-rule (inc! x) (set! x (add1 x)))   (define (permutation-test control-gr treatment-gr) (let ([both-gr (append control-gr treatment-gr)] [threshold (apply + control-gr)] [more 0] [leq 0]) (let loop ([data both-gr] [sum 0] [needed (length control-gr)] [available (length both-gr)]) (cond [(zero? needed) (if (>= sum threshold) (inc! more) (inc! leq))] [(>= available needed) (loop (cdr data) sum needed (sub1 available)) (loop (cdr data) (+ sum (car data)) (sub1 needed) (sub1 available))] [else (void)])) (values more leq)))   (let-values ([(more leq) (permutation-test '(68 41 10 49 16 65 32 92 28 98) '(85 88 75 66 25 29 83 39 97))]) (let ([sum (+ more leq)]) (printf "<=: ~a ~a%~n>: ~a ~a%~n" more (real->decimal-string (* 100. (/ more sum)) 2) leq (real->decimal-string (* 100. (/ leq sum)) 2))))  
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%
#F.23
F#
  //Percentage difference between 2 images. Nigel Galloway April 18th., 2018 let img50 = new System.Drawing.Bitmap("Lenna50.jpg") let img100 = new System.Drawing.Bitmap("Lenna100.jpg") let diff=Seq.cast<System.Drawing.Color*System.Drawing.Color>(Array2D.init img50.Width img50.Height (fun n g->(img50.GetPixel(n,g),img100.GetPixel(n,g))))|>Seq.fold(fun i (e,l)->i+abs(int(e.R)-int(l.R))+abs(int(e.B)-int(l.B))+abs(int(e.G)-int(l.G))) 0 printfn "%f" ((float diff)*100.00/(float(img50.Height*img50.Width)*255.0*3.0))
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%
#Forth
Forth
: pixel-diff ( pixel1 pixel2 -- n ) over 255 and over 255 and - abs >r 8 rshift swap 8 rshift over 255 and over 255 and - abs >r 8 rshift swap 8 rshift - abs r> + r> + ; : bdiff ( bmp1 bmp2 -- fdiff ) 2dup bdim rot bdim d<> abort" images not comparable" 0e ( F: total diff ) dup bdim * >r ( R: total pixels ) bdata swap bdata r@ 0 do over @ over @ pixel-diff 0 d>f f+ cell+ swap cell+ loop 2drop r> 3 * 255 * 0 d>f f/ ;   : .bdiff ( bmp1 bmp2 -- ) cr bdiff 100e f* f. ." percent different" ;
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Nim
Nim
import random, sequtils, strutils   const   F = @[[1, -1, 1, 0, 1, 1, 2, 1], [0, 1, 1, -1, 1, 0, 2, 0], [1, 0, 1, 1, 1, 2, 2, 1], [1, 0, 1, 1, 2, -1, 2, 0], [1, -2, 1, -1, 1, 0, 2, -1], [0, 1, 1, 1, 1, 2, 2, 1], [1, -1, 1, 0, 1, 1, 2, -1], [1, -1, 1, 0, 2, 0, 2, 1]]   I = @[[0, 1, 0, 2, 0, 3, 0, 4], [1, 0, 2, 0, 3, 0, 4, 0]]   L = @[[1, 0, 1, 1, 1, 2, 1, 3], [1, 0, 2, 0, 3, -1, 3, 0], [0, 1, 0, 2, 0, 3, 1, 3], [0, 1, 1, 0, 2, 0, 3, 0], [0, 1, 1, 1, 2, 1, 3, 1], [0, 1, 0, 2, 0, 3, 1, 0], [1, 0, 2, 0, 3, 0, 3, 1], [1, -3, 1, -2, 1, -1, 1, 0]]   N = @[[0, 1, 1, -2, 1, -1, 1, 0], [1, 0, 1, 1, 2, 1, 3, 1], [0, 1, 0, 2, 1, -1, 1, 0], [1, 0, 2, 0, 2, 1, 3, 1], [0, 1, 1, 1, 1, 2, 1, 3], [1, 0, 2, -1, 2, 0, 3, -1], [0, 1, 0, 2, 1, 2, 1, 3], [1, -1, 1, 0, 2, -1, 3, -1]]   P = @[[0, 1, 1, 0, 1, 1, 2, 1], [0, 1, 0, 2, 1, 0, 1, 1], [1, 0, 1, 1, 2, 0, 2, 1], [0, 1, 1, -1, 1, 0, 1, 1], [0, 1, 1, 0, 1, 1, 1, 2], [1, -1, 1, 0, 2, -1, 2, 0], [0, 1, 0, 2, 1, 1, 1, 2], [0, 1, 1, 0, 1, 1, 2, 0]]   T = @[[0, 1, 0, 2, 1, 1, 2, 1], [1, -2, 1, -1, 1, 0, 2, 0], [1, 0, 2, -1, 2, 0, 2, 1], [1, 0, 1, 1, 1, 2, 2, 0]]     U = @[[0, 1, 0, 2, 1, 0, 1, 2], [0, 1, 1, 1, 2, 0, 2, 1], [0, 2, 1, 0, 1, 1, 1, 2], [0, 1, 1, 0, 2, 0, 2, 1]]   V = @[[1, 0, 2, 0, 2, 1, 2, 2], [0, 1, 0, 2, 1, 0, 2, 0], [1, 0, 2, -2, 2, -1, 2, 0], [0, 1, 0, 2, 1, 2, 2, 2]]   W = @[[1, 0, 1, 1, 2, 1, 2, 2], [1, -1, 1, 0, 2, -2, 2, -1], [0, 1, 1, 1, 1, 2, 2, 2], [0, 1, 1, -1, 1, 0, 2, -1]]   X = @[[1, -1, 1, 0, 1, 1, 2, 0]]   Y = @[[1, -2, 1, -1, 1, 0, 1, 1], [1, -1, 1, 0, 2, 0, 3, 0], [0, 1, 0, 2, 0, 3, 1, 1], [1, 0, 2, 0, 2, 1, 3, 0], [0, 1, 0, 2, 0, 3, 1, 2], [1, 0, 1, 1, 2, 0, 3, 0], [1, -1, 1, 0, 1, 1, 1, 2], [1, 0, 2, -1, 2, 0, 3, 0]]   Z = @[[0, 1, 1, 0, 2, -1, 2, 0], [1, 0, 1, 1, 1, 2, 2, 2], [0, 1, 1, 1, 2, 1, 2, 2], [1, -2, 1, -1, 1, 0, 2, -2]]   Shapes = [F, I, L, N, P, T, U, V, W, X, Y, Z] Symbols = @"FILNPTUVWXYZ-"   NRows = 8 NCols = 8 Blank = Shapes.len     type Tiling = object shapes: array[Shapes.len, seq[array[8, int]]] # Shuffled shapes. symbols: array[Symbols.len, char] # Associated symbols. grid: array[NRows, array[NCols, int]] placed: array[Shapes.len, bool]     proc initTiling(): Tiling =   # Build list of shapes and symbols. var indexes = toSeq(0..11) indexes.shuffle() for i, index in indexes: result.shapes[i] = Shapes[index] result.symbols[i] = Symbols[index] result.symbols[^1] = Symbols[^1]   # Fill grid. for r in result.grid.mitems: for c in r.mitems: c = -1 for i in 0..3: while true: let randRow = rand(NRows - 1) let randCol = rand(NCols - 1) if result.grid[randRow][randCol] != Blank: result.grid[randRow][randCol] = Blank break     func tryPlaceOrientation(t: var Tiling; o: openArray[int]; r, c, shapeIndex: int): bool = for i in countup(0, o.len - 2, 2): let x = c + o[i + 1] let y = r + o[i] if x notin 0..<NCols or y notin 0..<NRows or t.grid[y][x] != - 1: return false t.grid[r][c] = shapeIndex for i in countup(0, o.len - 2, 2): t.grid[r + o[i]][c + o[i + 1]] = shapeIndex result = true     func removeOrientation(t: var Tiling; o: openArray[int]; r, c: int) = t.grid[r][c] = -1 for i in countup(0, o.len - 2, 2): t.grid[r + o[i]][c + o[i + 1]] = -1     func solve(t: var Tiling; pos, numPlaced: int): bool = if numPlaced == t.shapes.len: return true let row = pos div NCols let col = pos mod NCols if t.grid[row][col] != -1: return t.solve(pos + 1, numPlaced)   for i in 0..<t.shapes.len: if not t.placed[i]: for orientation in t.shapes[i]: if not t.tryPlaceOrientation(orientation, row, col, i): continue t.placed[i] = true if t.solve(pos + 1, numPlaced + 1): return true t.removeOrientation(orientation, row, col) t.placed[i] = false     proc printResult(t: Tiling) = for r in t.grid: echo r.mapIt(t.symbols[it]).join(" ")     when isMainModule: randomize() var tiling = initTiling() if tiling.solve(0, 0): tiling.printResult else: echo "No solution"
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Perl
Perl
#!/usr/bin/perl   use strict; # first open space version use warnings;   my $size = shift // 8;   sub rotate { local $_ = shift; my $ans = ''; $ans .= "\n" while s/.$/$ans .= $&; ''/gem; $ans; }   sub topattern { local $_ = shift; s/.+/ $& . ' ' x ($size - length $&)/ge; s/^\s+|\s+\z//g; [ tr/ \nA-Z/.. /r, lc tr/ \n/\0/r, substr $_, 0, 1 ]; # pattern, xor-update }   my %all; @all{ " FF\nFF \n F \n", "IIIII\n", "LLLL\nL \n", "NNN \n NN\n", "PPP\nPP \n", "TTT\n T \n T \n", "UUU\nU U\n", "VVV\nV \nV \n", "WW \n WW\n W\n", " X \nXXX\n X \n", "YYYY\n Y \n", "ZZ \n Z \n ZZ\n", } = (); @all{map rotate($_), keys %all} = () for 1 .. 3; # all four rotations @all{map s/.+/reverse $&/ger, keys %all} = (); # mirror my @all = map topattern($_), keys %all; my $grid = ( ' ' x $size . "\n" ) x $size; my %used; find( $grid );   sub find { my $grid = shift; %used >= 12 and exit not print $grid; for ( grep ! $used{ $_->[2] }, @all ) { my ($pattern, $pentomino, $letter) = @$_; local $used{$letter} = 1; $grid =~ /^[^ ]*\K$pattern/s and find( $grid ^ "\0" x $-[0] . $pentomino ); } }
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Python
Python
from __future__ import division from random import random import string from math import fsum   n_range, p, t = (2**n2 for n2 in range(4, 14, 2)), 0.5, 5 N = M = 15   NOT_CLUSTERED = 1 # filled but not clustered cell cell2char = ' #' + string.ascii_letters   def newgrid(n, p): return [[int(random() < p) for x in range(n)] for y in range(n)]   def pgrid(cell): for n in range(N): print( '%i) ' % (n % 10) + ' '.join(cell2char[cell[n][m]] for m in range(M)))     def cluster_density(n, p): cc = clustercount(newgrid(n, p)) return cc / n / n   def clustercount(cell): walk_index = 1 for n in range(N): for m in range(M): if cell[n][m] == NOT_CLUSTERED: walk_index += 1 walk_maze(m, n, cell, walk_index) return walk_index - 1     def walk_maze(m, n, cell, indx): # fill cell cell[n][m] = indx # down if n < N - 1 and cell[n+1][m] == NOT_CLUSTERED: walk_maze(m, n+1, cell, indx) # right if m < M - 1 and cell[n][m + 1] == NOT_CLUSTERED: walk_maze(m+1, n, cell, indx) # left if m and cell[n][m - 1] == NOT_CLUSTERED: walk_maze(m-1, n, cell, indx) # up if n and cell[n-1][m] == NOT_CLUSTERED: walk_maze(m, n-1, cell, indx)     if __name__ == '__main__': cell = newgrid(n=N, p=0.5) print('Found %i clusters in this %i by %i grid\n'  % (clustercount(cell), N, N)) pgrid(cell) print('')   for n in n_range: N = M = n sim = fsum(cluster_density(n, p) for i in range(t)) / t print('t=%3i p=%4.2f n=%5i sim=%7.5f'  % (t, p, n, sim))
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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program perfectNumber.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   .equ MAXI, 1<<31   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResultPerf: .asciz "Perfect  : @ \n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program mov r2,#2 @ begin first number 1: @ begin loop mov r5,#1 @ sum mov r4,#2 @ first divisor 1 2: udiv r0,r2,r4 @ compute divisor 2 mls r3,r0,r4,r2 @ remainder cmp r3,#0 bne 3f @ remainder = 0 ? add r5,r5,r0 @ add divisor 2 add r5,r5,r4 @ add divisor 1 3: add r4,r4,#1 @ increment divisor cmp r4,r0 @ divisor 1 < divisor 2 blt 2b @ yes -> loop cmp r2,r5 @ compare number and divisors sum bne 4f @ not equal mov r0,r2 @ equal -> display ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrsMessResultPerf ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message 4: add r2,#2 @ no perfect number odd < 10 puis 1500 cmp r2,#MAXI @ end ? blo 1b @ no -> loop   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResultPerf: .int sMessResultPerf iAdrsZoneConv: .int sZoneConv   /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Phix
Phix
with javascript_semantics constant w = 10, h = 10 sequence wall = join(repeat("+",w+1),"---")&"\n", cell = join(repeat("|",w+1)," ")&"\n", grid procedure new_grid(atom p) grid = split(join(repeat(wall,h+1),cell),'\n') -- now knock down some walls for i=1 to length(grid)-1 do integer jstart = 5-mod(i,2)*3, jlimit = length(grid[i])-3 -- (ie 2..38 on odd lines, 5..37 on even) for j=jstart to jlimit by 4 do if rnd()>p then grid[i][j..j+2] = " " end if end for end for end procedure function percolate(integer x=0, y=0) if x=0 then for j=3 to length(grid[1])-2 by 4 do if grid[1][j]=' ' and percolate(1,j) then return true end if end for elsif grid[x][y]=' ' then grid[x][y] = '*' if (x=length(grid)-1) or ( grid[x+1][y]=' ' and percolate(x+1,y)) or (y>6 and grid[x][y-2]=' ' and percolate(x,y-4)) or (y<36 and grid[x][y+2]=' ' and percolate(x,y+4)) or (x>1 and grid[x-1][y]=' ' and percolate(x-1,y)) then return true end if end if return false end function constant LIM=1000 for p=0 to 10 do integer count = 0 for t=1 to LIM do new_grid(p/10) count += percolate() end for printf(1,"p=%.1f: %5.3f\n",{p/10,count/LIM}) end for puts(1,"sample grid for p=0.6:\n") new_grid(0.6) {} = percolate() printf(1,"%s\n",{join(grid,'\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.
#Julia
Julia
using Printf, Distributions, IterTools   newv(n::Int, p::Float64) = rand(Bernoulli(p), n) runs(v::Vector{Int}) = sum((a & ~b) for (a, b) in zip(v, IterTools.chain(v[2:end], v[1])))   mrd(n::Int, p::Float64) = runs(newv(n, p)) / n   nrep = 500   for p in 0.1:0.2:1 lim = p * (1 - p)   println() for ex in 10:2:14 n = 2 ^ ex sim = mean(mrd.(n, p) for _ in 1:nrep) @printf("nrep = %3i\tp = %4.2f\tn = %5i\np · (1 - p) = %5.3f\tsim = %5.3f\tΔ = %3.1f%%\n", nrep, p, n, lim, sim, lim > 0 ? abs(sim - lim) / lim * 100 : sim * 100) end end
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.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random() const val RAND_MAX = 32767   // just generate 0s and 1s without storing them fun runTest(p: Double, len: Int, runs: Int): Double { var cnt = 0 val thresh = (p * RAND_MAX).toInt() for (r in 0 until runs) { var x = 0 var i = len while (i-- > 0) { val y = if (rand.nextInt(RAND_MAX + 1) < thresh) 1 else 0 if (x < y) cnt++ x = y } } return cnt.toDouble() / runs / len }   fun main(args: Array<String>) { println("running 1000 tests each:") println(" p\t n\tK\tp(1-p)\t diff") println("------------------------------------------------") val fmt = "%.1f\t%6d\t%.4f\t%.4f\t%+.4f (%+.2f%%)" for (ip in 1..9 step 2) { val p = ip / 10.0 val p1p = p * (1.0 - p) var n = 100 while (n <= 100_000) { val k = runTest(p, n, 1000) println(fmt.format(p, n, k, p1p, k - p1p, (k - p1p) / p1p * 100)) n *= 10 } println() } }
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Python
Python
from random import random import string from pprint import pprint as pp   M, N, t = 15, 15, 100   cell2char = ' #' + string.ascii_letters NOT_VISITED = 1 # filled cell not walked   class PercolatedException(Exception): pass   def newgrid(p): return [[int(random() < p) for m in range(M)] for n in range(N)] # cell   def pgrid(cell, percolated=None): for n in range(N): print( '%i) ' % (n % 10) + ' '.join(cell2char[cell[n][m]] for m in range(M))) if percolated: where = percolated.args[0][0] print('!) ' + ' ' * where + cell2char[cell[n][where]])   def check_from_top(cell): n, walk_index = 0, 1 try: for m in range(M): if cell[n][m] == NOT_VISITED: walk_index += 1 walk_maze(m, n, cell, walk_index) except PercolatedException as ex: return ex return None     def walk_maze(m, n, cell, indx): # fill cell cell[n][m] = indx # down if n < N - 1 and cell[n+1][m] == NOT_VISITED: walk_maze(m, n+1, cell, indx) # THE bottom elif n == N - 1: raise PercolatedException((m, indx)) # left if m and cell[n][m - 1] == NOT_VISITED: walk_maze(m-1, n, cell, indx) # right if m < M - 1 and cell[n][m + 1] == NOT_VISITED: walk_maze(m+1, n, cell, indx) # up if n and cell[n-1][m] == NOT_VISITED: walk_maze(m, n-1, cell, indx)   if __name__ == '__main__': sample_printed = False pcount = {} for p10 in range(11): p = p10 / 10.0 pcount[p] = 0 for tries in range(t): cell = newgrid(p) percolated = check_from_top(cell) if percolated: pcount[p] += 1 if not sample_printed: print('\nSample percolating %i x %i, p = %5.2f grid\n' % (M, N, p)) pgrid(cell, percolated) sample_printed = True print('\n p: Fraction of %i tries that percolate through\n' % t )   pp({p:c/float(t) for p, c in pcount.items()})
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
#AppleScript
AppleScript
----------------------- PERMUTATIONS -----------------------   -- permutations :: [a] -> [[a]] on permutations(xs) script go on |λ|(xs) script h on |λ|(x) script ts on |λ|(ys) {{x} & ys} end |λ| end script concatMap(ts, go's |λ|(|delete|(x, xs))) end |λ| end script   if {} ≠ xs then concatMap(h, xs) else {{}} end if end |λ| end script go's |λ|(xs) end permutations     --------------------------- TEST --------------------------- on run   permutations({"aardvarks", "eat", "ants"})   end run     -------------------- GENERIC FUNCTIONS ---------------------   -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) set lst to {} set lng to length of xs tell mReturn(f) repeat with i from 1 to lng set lst to (lst & |λ|(contents of item i of xs, i, xs)) end repeat end tell return lst end concatMap     -- delete :: a -> [a] -> [a] on |delete|(x, xs) if length of xs > 0 then set {h, t} to uncons(xs) if x = h then t else {h} & |delete|(x, t) end if else {} end if end |delete|     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- uncons :: [a] -> Maybe (a, [a]) on uncons(xs) if length of xs > 0 then {item 1 of xs, rest of xs} else missing value end if end uncons
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
#Dyalect
Dyalect
func shuffle(arr) { if arr.Length() % 2 != 0 { throw @InvalidValue(arr.Length()) } var half = arr.Length() / 2 var result = Array.Empty(arr.Length()) var (t, l, r) = (0, 0, half)   while l < half { result[t] = arr[l] result[t+1] = arr[r] l += 1 r += 1 t += 2 } result }   func arrayEqual(xs, ys) { if xs.Length() != ys.Length() { return false } for i in xs.Indices() { if xs[i] != ys[i] { return false } } return true }   func shuffleThrough(original) { var copy = original.Clone()   while true { copy = shuffle(copy) yield copy if arrayEqual(original, copy) { break } } }   for input in yields { 8, 24, 52, 100, 1020, 1024, 10000} { var numbers = [1..input] print("\(input) cards: \(shuffleThrough(numbers).Length())") }
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
#EchoLisp
EchoLisp
  ;; shuffler : a permutation vector which interleaves both halves of deck (define (make-shuffler n) (let ((s (make-vector n))) (for ((i (in-range 0 n 2))) (vector-set! s i (/ i 2))) (for ((i (in-range 0 n 2))) (vector-set! s (1+ i) (+ (/ n 2) (vector-ref s i)))) s))   ;; output : (n . # of shuffles needed to go back) (define (magic-shuffle n) (when (odd? n) (error "magic-shuffle:odd input" n)) (let [(deck (list->vector (iota n))) ;; (0 1 ... n-1) (dock (list->vector (iota n))) ;; keep trace or init deck (shuffler (make-shuffler n))]   (cons n (1+ (for/sum ((i Infinity)) ; (in-naturals missing in EchoLisp v2.9) (vector-permute! deck shuffler) ;; permutes in place #:break (eqv? deck dock) ;; compare to first 1)))))  
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.
#Lua
Lua
local p = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 }   -- extending for easy access for i = 1, #p do p[i+256]=p[i] end   local function fade (t) -- fade graph: https://www.desmos.com/calculator/d5cgqlrmem return t*t*t*(t*(t*6-15)+10) end   local function lerp (t, a, b) return a+t*(b-a) end   local function grad (hash, x, y, z) local h = hash%16 local cases = { x+y, -x+y, x-y, -x-y,   x+z, -x+z, x-z, -x-z,   y+z, -y+z, y-z, -y-z,   y+x, -y+z, y-x, -y-z, } return cases[h+1] end   local function noise (x,y,z) local a, b, c = math.floor(x)%256, math.floor(y)%256, math.floor(z)%256 -- values in range [0, 255] local xx, yy, zz = x%1, y%1, z%1 local u, v, w = fade (xx), fade (yy), fade (zz) local a0 = p[a+1]+b local a1, a2 = p[a0+1]+c, p[a0+2]+c local b0 = p[a+2]+b local b1, b2 = p[b0+1]+c, p[b0+2]+c local k1 = grad(p[a1+1], xx, yy, zz) local k2 = grad(p[b1+1], xx-1, yy, zz) local k3 = grad(p[a2+1], xx, yy-1, zz) local k4 = grad(p[b2+1], xx-1, yy-1, zz) local k5 = grad(p[a1+2], xx, yy, zz-1) local k6 = grad(p[b1+2], xx-1, yy, zz-1) local k7 = grad(p[a2+2], xx, yy-1, zz-1) local k8 = grad(p[b2+2], xx-1, yy-1, zz-1) return lerp(w, lerp(v, lerp(u, k1, k2), lerp(u, k3, k4)), lerp(v, lerp(u, k5, k6), lerp(u, k7, k8))) end   print (noise(3.14, 42, 7)) -- 0.136919958784 print (noise(1.4142, 1.2589, 2.718)) -- -0.17245663814988
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
#jq
jq
  # jq optimizes the recursive call of _gcd in the following: def gcd(a;b): def _gcd: if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end; [a,b] | _gcd ;   def count(s): reduce s as $x (0; .+1);   # A perfect totient number is an integer that is equal to the sum of its iterated totients. # aka Euler's phi function def totient: . as $n | count( range(0; .) | select( gcd($n; .) == 1) );   # input: the cache # output: the updated cache def cachephi($n): ($n|tostring) as $s | if (has($s)|not) then .[$s] = ($n|totient) else . end ;   # Emit the stream of perfect totients def perfect_totients: . as $n | foreach range(1; infinite) as $i ({cache: {}}; .tot = $i | .tsum = 0 | until( .tot == 1; .tot as $tot | .cache |= cachephi($tot) | .tot = .cache[$tot|tostring] | .tsum += .tot); if .tsum == $i then $i else empty end );   "The first 20 perfect totient numbers:", limit(20; perfect_totients)
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
#Julia
Julia
using Primes   eulerphi(n) = (r = one(n); for (p,k) in factor(abs(n)) r *= p^(k-1)*(p-1) end; r)   const phicache = Dict{Int, Int}()   cachedphi(n) = (if !haskey(phicache, n) phicache[n] = eulerphi(n) end; phicache[n])   function perfecttotientseries(n) perfect = Vector{Int}() i = 1 while length(perfect) < n tot = i tsum = 0 while tot != 1 tot = cachedphi(tot) tsum += tot end if tsum == i push!(perfect, i) end i += 1 end perfect end   println("The first 20 perfect totient numbers are: $(perfecttotientseries(20))") println("The first 40 perfect totient numbers are: $(perfecttotientseries(40))")  
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
#Go
Go
package cards   import ( "math/rand" )   // A Suit represents one of the four standard suites. type Suit uint8   // The four standard suites. const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 )   func (s Suit) String() string { const suites = "CDHS" // or "♣♢♡♠" return suites[s : s+1] }   // Rank is the rank or pip value of a card from Ace==1 to King==13. type Rank uint8   // The ranks from Ace to King. const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Five Rank = 5 Six Rank = 6 Seven Rank = 7 Eight Rank = 8 Nine Rank = 9 Ten Rank = 10 Jack Rank = 11 Queen Rank = 12 King Rank = 13 )   func (r Rank) String() string { const ranks = "A23456789TJQK" return ranks[r-1 : r] }   // A Card represets a specific playing card. // It's an encoded representation of Rank and Suit // with a valid range of [0,51]. type Card uint8   // NewCard returns the Card representation for the specified rank and suit. func NewCard(r Rank, s Suit) Card { return Card(13*uint8(s) + uint8(r-1)) }   // RankSuit returns the rank and suit of the card. func (c Card) RankSuit() (Rank, Suit) { return Rank(c%13 + 1), Suit(c / 13) }   // Rank returns the rank of the card. func (c Card) Rank() Rank { return Rank(c%13 + 1) }   // Suit returns the suit of the card. func (c Card) Suit() Suit { return Suit(c / 13) }   func (c Card) String() string { return c.Rank().String() + c.Suit().String() }   // A Deck represents a set of zero or more cards in a specific order. type Deck []Card   // NewDeck returns a regular 52 deck of cards in A-K order. func NewDeck() Deck { d := make(Deck, 52) for i := range d { d[i] = Card(i) } return d }   // String returns a string representation of the cards in the deck with // a newline ('\n') separating the cards into groups of thirteen. func (d Deck) String() string { s := "" for i, c := range d { switch { case i == 0: // do nothing case i%13 == 0: s += "\n" default: s += " " } s += c.String() } return s }   // Shuffle randomises the order of the cards in the deck. func (d Deck) Shuffle() { for i := range d { j := rand.Intn(i + 1) d[i], d[j] = d[j], d[i] } }   // Contains returns true if the specified card is withing the deck. func (d Deck) Contains(tc Card) bool { for _, c := range d { if c == tc { return true } } return false }   // AddDeck adds the specified deck(s) to this one at the end/bottom. func (d *Deck) AddDeck(decks ...Deck) { for _, o := range decks { *d = append(*d, o...) } }   // AddCard adds the specified card to this deck at the end/bottom. func (d *Deck) AddCard(c Card) { *d = append(*d, c) }   // Draw removes the selected number of cards from the top of the deck, // returning them as a new deck. func (d *Deck) Draw(n int) Deck { old := *d *d = old[n:] return old[:n:n] }   // DrawCard draws a single card off the top of the deck, // removing it from the deck. // It returns false if there are no cards in the deck. func (d *Deck) DrawCard() (Card, bool) { if len(*d) == 0 { return 0, false } old := *d *d = old[1:] return old[0], true }   // Deal deals out cards from the deck one at a time to multiple players. // The initial hands (decks) of each player are provided as arguments and the // modified hands are returned. The initial hands can be empty or nil. // E.g. Deal(7, nil, nil, nil) deals out seven cards to three players // each starting with no cards. // If there are insufficient cards in the deck the hands are partially dealt and // the boolean return is set to false (true otherwise). func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) { for i := 0; i < cards; i++ { for j := range hands { if len(*d) == 0 { return hands, false } hands[j] = append(hands[j], (*d)[0]) *d = (*d)[1:] } } return hands, true }
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
#FreeBASIC
FreeBASIC
' version 05-07-2018 ' compile with: fbc -s console   ' unbounded spigot ' Ctrl-c to end program or close console window   #Include "gmp.bi"   Dim As UInteger num, ndigit, fp = Not 0 Dim As mpz_ptr q,r,t,k,n,l,tmp1,tmp2 q = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(q,1) r = Allocate(Len(__Mpz_struct)) : Mpz_init(r) t = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(t,1) k = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(k,1) n = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(n,3) l = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(l,3) tmp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp1) tmp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp2)   Do mpz_mul_2exp(tmp1, q, 2) mpz_add(tmp1,tmp1,r) mpz_sub(tmp1,tmp1,t) mpz_mul(tmp2, n, t) If mpz_cmp(tmp1, tmp2) < 0 Then Print mpz_get_ui(n); : ndigit += 1 : If ndigit Mod 50 = 0 Then Print " :";ndigit If fp Then Print "."; : fp = Not fp : Print :ndigit = 0 mpz_sub(tmp1, r, tmp2) mpz_mul_ui(tmp1, tmp1, 10) mpz_mul_ui(tmp2, q, 3) mpz_add(tmp2, tmp2, r) mpz_mul_ui(tmp2, tmp2, 10) mpz_set(r, tmp1) mpz_mul_ui(tmp1, n, 10) mpz_tdiv_q(tmp2, tmp2, t) mpz_sub(n, tmp2, tmp1) mpz_mul_ui(q, q, 10) Else mpz_mul(tmp2, r, l) mpz_mul(tmp1, q, k) mpz_mul_ui(tmp1, tmp1, 7) mpz_add(tmp1, tmp1, tmp2) mpz_mul_2exp(tmp2, q, 1) mpz_add(tmp2, tmp2, r) mpz_mul(tmp2, tmp2, l) mpz_mul(t, t, l) mpz_tdiv_q(tmp1, tmp1, t) mpz_mul(q, q, k) mpz_add_ui(k, k, 1) mpz_add_ui(l, l, 2) mpz_set(n, tmp1) mpz_set(r, tmp2) End If Loop
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
#Objeck
Objeck
  class Pig { function : Main(args : String[]) ~ Nil { player_count := 2; max_score := 100; safe_score := Int->New[player_count]; player := 0; score := 0;   while(true) { safe := safe_score[player]; " Player {$player}: ({$safe}, {$score}) Rolling? (y/n) "->PrintLine(); rolling := IO.Console->ReadString(); if(safe_score[player] + score < max_score & (rolling->Equals("y") | rolling->Equals("yes"))) { rolled := ((Float->Random() * 100.0)->As(Int) % 6) + 1; " Rolled {$rolled}"->PrintLine(); if(rolled = 1) { safe := safe_score[player]; " Bust! you lose {$score} but still keep your previous {$safe}\n"->PrintLine(); score := 0; player := (player + 1) % player_count; } else { score += rolled; }; } else { safe_score[player] += score; if(safe_score[player] >= max_score) { break; }; safe := safe_score[player]; " Sticking with {$safe}\n"->PrintLine(); score := 0; player := (player + 1) % player_count; }; }; safe := safe_score[player]; "\n\nPlayer {$player} wins with a score of {$safe}"->PrintLine(); } }  
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.
#Go
Go
package main   import "fmt"   func pernicious(w uint32) bool { const ( ff = 1<<32 - 1 mask1 = ff / 3 mask3 = ff / 5 maskf = ff / 17 maskp = ff / 255 ) w -= w >> 1 & mask1 w = w&mask3 + w>>2&mask3 w = (w + w>>4) & maskf return 0xa08a28ac>>(w*maskp>>24)&1 != 0 }   func main() { for i, n := 0, uint32(1); i < 25; n++ { if pernicious(n) { fmt.Printf("%d ", n) i++ } } fmt.Println() for n := uint32(888888877); n <= 888888888; n++ { if pernicious(n) { fmt.Printf("%d ", n) } } fmt.Println() }
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#LabVIEW
LabVIEW
local( my array = array('one', 'two', 3) )   #myarray -> get(integer_random(#myarray -> size, 1))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Lasso
Lasso
local( my array = array('one', 'two', 3) )   #myarray -> get(integer_random(#myarray -> size, 1))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Liberty_BASIC
Liberty BASIC
list$ ="John Paul George Ringo Peter Paul Mary Obama Putin" wantedTerm =int( 10 *rnd( 1)) print "Selecting term "; wantedTerm; " in the list, which was "; word$( list$, wantedTerm, " ")
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
#Kotlin
Kotlin
// version 1.0.6   fun reverseEachWord(s: String) = s.split(" ").map { it.reversed() }.joinToString(" ")   fun main(args: Array<String>) { val original = "rosetta code phrase reversal" val reversed = original.reversed() println("Original string => $original") println("Reversed string => $reversed") println("Reversed words => ${reverseEachWord(original)}") println("Reversed order => ${reverseEachWord(reversed)}") }
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
#Lambdatalk
Lambdatalk
  {W.reverse word} reverses characters in a word {S.reverse words} reverses a sequence of words {S.map function words} applies a function to a sequence of words   {def S rosetta code phrase reversal} = rosetta code phrase reversal   {W.reverse {S}} -> lasrever esarhp edoc attesor {S.map W.reverse {S}} -> attesor edoc esarhp lasrever {S.reverse {S}} -> reversal phrase code rosetta  
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
#J
J
derangement=: (A.&i.~ !)~ (*/ .~: # [) i. NB. task item 1 subfactorial=: ! * +/@(_1&^ % !)@i.@>: NB. task item 3
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
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class Derangement {   public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); }   System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); }   System.out.printf ("\n!20 = %20d\n", subfact(20L)); }   static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n);   List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0;   while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j);   int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; }   j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; }   static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; }   static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); }   static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; }   static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
perms[0] = {{{}, 1}}; perms[n_] := Flatten[If[#2 == 1, Reverse, # &]@ Table[{Insert[#1, n, i], (-1)^(n + i) #2}, {i, n}] & @@@ perms[n - 1], 1];
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#Nim
Nim
# iterative Boothroyd method iterator permutations*[T](ys: openarray[T]): tuple[perm: seq[T], sign: int] = var d = 1 c = newSeq[int](ys.len) xs = newSeq[T](ys.len) sign = 1   for i, y in ys: xs[i] = y yield (xs, sign)   block outter: while true: while d > 1: dec d c[d] = 0 while c[d] >= d: inc d if d >= ys.len: break outter   let i = if (d and 1) == 1: c[d] else: 0 swap xs[i], xs[d] sign *= -1 yield (xs, sign) inc c[d]   when isMainModule: for i in permutations([0,1,2]): echo i   echo ""   for i in permutations([0,1,2,3]): echo i
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment subjects, or to a group of m {\displaystyle m} control subjects. Members of the treatment group were given the treatment, and members of the control group were given a placebo. The effect of the treatment or placebo on each volunteer was measured and reported in this table. Table of experimental results Treatment group Control group 85 68 88 41 75 10 66 49 25 16 29 65 83 32 39 92 97 28 98 Write a program that performs a permutation test to judge whether the treatment had a significantly stronger effect than the placebo. Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size n {\displaystyle n} and a control group of size m {\displaystyle m} (i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless. Note that the number of alternatives will be the binomial coefficient ( n + m n ) {\displaystyle {\tbinom {n+m}{n}}} . Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group. Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater. Note that they should sum to 100%. Extremely dissimilar values are evidence of an effect not entirely due to chance, but your program need not draw any conclusions. You may assume the experimental data are known at compile time if that's easier than loading them at run time. Test your solution on the data given above.
#Raku
Raku
sub stats ( @test, @all ) { ([+] @test / +@test) - ([+] flat @all, (@test X* -1)) / @all - @test }   my int @treated = <85 88 75 66 25 29 83 39 97>; my int @control = <68 41 10 49 16 65 32 92 28 98>; my int @all = flat @treated, @control;   my $base = stats( @treated, @all );   my atomicint @trials[3] = 0, 0, 0;   @all.combinations(+@treated).race.map: { @trials[ 1 + ( stats( $_, @all ) <=> $base ) ]⚛++ }   say 'Counts: <, =, > ', @trials; say 'Less than  : %', 100 * @trials[0] / [+] @trials; say 'Equal to  : %', 100 * @trials[1] / [+] @trials; say 'Greater than : %', 100 * @trials[2] / [+] @trials; say 'Less or Equal: %', 100 * ( [+] @trials[0,1] ) / [+] @trials;
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%
#Fortran
Fortran
program ImageDifference   use RCImageBasic use RCImageIO   implicit none   integer, parameter :: input1_u = 20, & input2_u = 21   type(rgbimage) :: lenna1, lenna2 real :: totaldiff     open(input1_u, file="Lenna100.ppm", action="read") open(input2_u, file="Lenna50.ppm", action="read") call read_ppm(input1_u, lenna1) call read_ppm(input2_u, lenna2) close(input1_u) close(input2_u)   totaldiff = sum( (abs(lenna1%red - lenna2%red) + & abs(lenna1%green - lenna2%green) + & abs(lenna1%blue - lenna2%blue)) / 255.0 )     print *, 100.0 * totaldiff / (lenna1%width * lenna1%height * 3.0)   call free_img(lenna1) call free_img(lenna2)   end program ImageDifference
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%
#Frink
Frink
  img1 = new image["file:Lenna50.jpg"] img2 = new image["file:Lenna100.jpg"]   [w1, h1] = img1.getSize[] [w2, h2] = img2.getSize[]   sum = 0 for x=0 to w1-1 for y=0 to h1-1 { [r1,g1,b1] = img1.getPixel[x,y] [r2,g2,b2] = img2.getPixel[x,y] sum = sum + abs[r1-r2] + abs[g1-g2] + abs[b1-b2] }   errors = sum / (w1 * h1 * 3) println["Error is " + (errors->"percent")]  
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Phix
Phix
with javascript_semantics constant pentominoes = split(""" ......I................................................................ ......I.....L......N.........................................Y......... .FF...I.....L.....NN....PP....TTT...........V.....W....X....YY.....ZZ.. FF....I.....L.....N.....PP.....T....U.U.....V....WW...XXX....Y.....Z... .F....I.....LL....N.....P......T....UUU...VVV...WW.....X.....Y....ZZ...""",'\n') ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- function get_shapes() sequence res = {} for offset=0 to length(pentominoes[1]) by 6 do -- -- scan left/right, and up/down, both ways, to give 8 orientations -- (computes the equivalent of those hard-coded tables in -- other examples, albeit in a slightly different order.) -- sequence shapes = {} integer letter for orientation=0 to 7 do sequence shape = {} bool found = false integer fr, fc for r=1 to 5 do for c=1 to 5 do integer rr = iff(and_bits(orientation,#01)?6-r:r), cc = iff(and_bits(orientation,#02)?6-c:c) if and_bits(orientation,#04) then {rr,cc} = {cc,rr} end if integer ch = pentominoes[rr,offset+cc] if ch!='.' then if not found then {found,fr,fc,letter} = {true,r,c,ch} else shape &= {r-fr,c-fc} end if end if end for end for if not find(shape,shapes) then shapes = append(shapes,shape) end if end for res = append(res,{letter&"",shapes}) end for return res end function constant shapes = get_shapes(), nRows = 8, nCols = 8 sequence grid = repeat(repeat(' ',nCols),nRows), placed = repeat(false,length(shapes)) procedure re_place(sequence o, integer r, c, ch=' ') grid[r][c] = ch for i=1 to length(o) by 2 do grid[r+o[i]][c+o[i+1]] = ch end for end procedure function can_place(sequence o, integer r, c, ch) for i=1 to length(o) by 2 do integer x := c + o[i+1], y := r + o[i] if x<1 or x>nCols or y<1 or y>nRows or grid[y][x]!=' ' then return false end if end for re_place(o,r,c,ch) return true end function function solve(integer pos=0, numPlaced=0) if numPlaced == length(shapes) then return true end if integer row = floor(pos/8)+1, col = mod(pos,8)+1 if grid[row][col]!=' ' then return solve(pos+1, numPlaced) end if for i=1 to length(shapes) do if not placed[i] then integer ch = shapes[i][1][1] for j=1 to length(shapes[i][2]) do sequence o = shapes[i][2][j] if can_place(o, row, col, ch) then placed[i] = true if solve(pos+1, numPlaced+1) then return true end if re_place(o, row, col) placed[i] = false end if end for end if end for return false end function function unsolveable() -- -- The only unsolvable grids seen have -- -.- or -..- or -... at edge/corner, -- - -- --- - -- or somewhere in the middle a -.- -- - -- -- Simply place all shapes at all positions/orientations, -- all the while checking for any untouchable cells. -- sequence griddled = deep_copy(grid) for r=1 to 8 do for c=1 to 8 do if grid[r][c]=' ' then for i=1 to length(shapes) do integer ch = shapes[i][1][1] for j=1 to length(shapes[i][2]) do sequence o = shapes[i][2][j] if can_place(o, r, c, ch) then grid[r][c] = ' ' griddled[r][c] = '-' for k=1 to length(o) by 2 do grid[r+o[k]][c+o[k+1]] = ' ' griddled[r+o[k]][c+o[k+1]] = '-' end for end if end for end for if griddled[r][c]!='-' then return true end if end if end for end for return false end function procedure add_four_randomly() integer count = 0 while count<4 do integer r = rand(8), c = rand(8) if grid[r][c]=' ' then grid[r][c] = '-' count += 1 end if end while end procedure procedure main() add_four_randomly() if unsolveable() then puts(1,"No solution\n") else if not solve() then ?9/0 end if end if puts(1,join(grid,"\n")&"\n") end procedure main()
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Racket
Racket
#lang racket (require srfi/14) ; character sets   ; much faster than safe fixnum functions (require racket/require ; for fancy require clause below (filtered-in (lambda (name) (regexp-replace #rx"unsafe-" name "")) racket/unsafe/ops)  ; these aren't in racket/unsafe/ops (only-in racket/fixnum for/fxvector in-fxvector fxvector-copy))   ; ...(but less safe). if in doubt use this rather than the one above ; (require racket/fixnum)   (define t (make-parameter 5))   (define (build-random-grid p M N) (define p-num (numerator p)) (define p-den (denominator p)) (for/fxvector #:length (fx* M N) ((_ (in-range (* M N)))) (if (< (random p-den) p-num) 1 0)))   (define letters (sort (char-set->list (char-set-intersection char-set:letter  ; char-set:ascii )) char<?)) (define n-letters (length letters)) (define cell->char (match-lambda (0 #\space) (1 #\.) (c (list-ref letters (modulo (- c 2) n-letters)))))   (define (draw-percol-grid M N . gs) (for ((r N)) (for ((g gs)) (define row-str (list->string (for/list ((idx (in-range (* r M) (* (+ r 1) M)))) (cell->char (fxvector-ref g idx))))) (printf "|~a| " row-str)) (newline)))   (define (count-clusters! M N g) (define (gather-cluster! k c) (when (fx= 1 (fxvector-ref g k)) (define k-r (fxquotient k M)) (define k-c (fxremainder k M)) (fxvector-set! g k c) (define-syntax-rule (gather-surrounds range? k+) (let ((idx k+)) (when (and range? (fx= 1 (fxvector-ref g idx))) (gather-cluster! idx c)))) (gather-surrounds (fx> k-r 0) (fx- k M)) (gather-surrounds (fx> k-c 0) (fx- k 1)) (gather-surrounds (fx< k-c (fx- M 1)) (fx+ k 1)) (gather-surrounds (fx< k-r (fx- N 1)) (fx+ k M))))   (define-values (rv _c) (for/fold ((rv 0) (c 2)) ((pos (in-range (fx* M N))) #:when (fx= 1 (fxvector-ref g pos))) (gather-cluster! pos c) (values (fx+ rv 1) (fx+ c 1)))) rv)   (define (display-sample-clustering p) (printf "Percolation cluster sample: p=~a~%" p) (define g (build-random-grid p 15 15)) (define g+ (fxvector-copy g)) (define g-count (count-clusters! 15 15 g+)) (draw-percol-grid 15 15 g g+) (printf "~a clusters~%" g-count))   (define (experiment p n t) (printf "Experiment: ~a ~a ~a\t" p n t) (flush-output) (define sum-Cn (for/sum ((run (in-range t))) (printf "[~a" run) (flush-output) (define g (build-random-grid p n n)) (printf "*") (flush-output) (define Cn (count-clusters! n n g)) (printf "]") (flush-output) Cn)) (printf "\tmean K(p) = ~a~%" (real->decimal-string (/ sum-Cn t (sqr n)) 6)))   (module+ main (t 10) (for ((n (in-list '(4000 1000 750 500 400 300 200 100 15)))) (experiment 1/2 n (t))) (display-sample-clustering 1/2))   (module+ test (define grd (build-random-grid 1/2 1000 1000)) (/ (for/sum ((g (in-fxvector grd)) #:when (zero? g)) 1) (fxvector-length grd)) (display-sample-clustering 1/2))
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Raku
Raku
my @perc; my $fill = 'x';   enum Direction <DeadEnd Up Right Down Left>;   my $𝘒 = perctest(15); .fmt("%-2s").say for @perc; say "𝘱 = 0.5, 𝘕 = 15, 𝘒 = $𝘒\n";   my $trials = 5; for 10, 30, 100, 300, 1000 -> $𝘕 { my $𝘒 = ( [+] perctest($𝘕) xx $trials ) / $trials; say "𝘱 = 0.5, trials = $trials, 𝘕 = $𝘕, 𝘒 = $𝘒"; }   sub infix:<deq> ( $a, $b ) { $a.defined && ($a eq $b) }   sub perctest ( $grid ) { generate $grid; my $block = 1; for ^$grid X ^$grid -> ($y, $x) { fill( [$x, $y], $block++ ) if @perc[$y; $x] eq $fill } ($block - 1) / $grid²; }   sub generate ( $grid ) { @perc = (); @perc.push: [ ( rand < .5 ?? '.' !! $fill ) xx $grid ] for ^$grid; }   sub fill ( @cur, $block ) { @perc[@cur[1]; @cur[0]] = $block; my @stack; my $current = @cur;   loop { if my $dir = direction( $current ) { @stack.push: $current; $current = move $dir, $current, $block } else { return unless @stack; $current = @stack.pop } }   sub direction( [$x, $y] ) { ( Down if @perc[$y + 1][$x] deq $fill ) || ( Left if @perc[$y][$x - 1] deq $fill ) || ( Right if @perc[$y][$x + 1] deq $fill ) || ( Up if @perc[$y - 1][$x] deq $fill ) || DeadEnd }   sub move ( $dir, @cur, $block ) { my ( $x, $y ) = @cur; given $dir { when Up { @perc[--$y; $x] = $block } when Down { @perc[++$y; $x] = $block } when Left { @perc[$y; --$x] = $block } when Right { @perc[$y; ++$x] = $block } } [$x, $y] } }  
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.
#Arturo
Arturo
divisors: $[n][ select 1..(n/2)+1 'i -> 0 = n % i ] perfect?: $[n][ n = sum divisors n ]   loop 2..1000 'i [ if perfect? i -> print i ]
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.
#AutoHotkey
AutoHotkey
Loop, 30 { If isMersennePrime(A_Index + 1) res .= "Perfect number: " perfectNum(A_Index + 1) "`n" }   MsgBox % res   perfectNum(N) { Return 2**(N - 1) * (2**N - 1) }   isMersennePrime(N) { If (isPrime(N)) && (isPrime(2**N - 1)) Return true }   isPrime(N) { Loop, % Floor(Sqrt(N)) If (A_Index > 1 && !Mod(N, A_Index)) Return false Return true }
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Python
Python
from collections import namedtuple from random import random from pprint import pprint as pp   Grid = namedtuple('Grid', 'cell, hwall, vwall')   M, N, t = 10, 10, 100   class PercolatedException(Exception): pass   HVF = [(' .', ' _'), (':', '|'), (' ', '#')] # Horiz, vert, fill chars   def newgrid(p): hwall = [[int(random() < p) for m in range(M)] for n in range(N+1)] vwall = [[(1 if m in (0, M) else int(random() < p)) for m in range(M+1)] for n in range(N)] cell = [[0 for m in range(M)] for n in range(N)] return Grid(cell, hwall, vwall)   def pgrid(grid, percolated=None): cell, hwall, vwall = grid h, v, f = HVF for n in range(N): print(' ' + ''.join(h[hwall[n][m]] for m in range(M))) print('%i) ' % (n % 10) + ''.join(v[vwall[n][m]] + f[cell[n][m] if m < M else 0] for m in range(M+1))[:-1]) n = N print(' ' + ''.join(h[hwall[n][m]] for m in range(M))) if percolated: where = percolated.args[0][0] print('!) ' + ' ' * where + ' ' + f[1])   def pour_on_top(grid): cell, hwall, vwall = grid n = 0 try: for m in range(M): if not hwall[n][m]: flood_fill(m, n, cell, hwall, vwall) except PercolatedException as ex: return ex return None     def flood_fill(m, n, cell, hwall, vwall): # fill cell cell[n][m] = 1 # bottom if n < N - 1 and not hwall[n + 1][m] and not cell[n+1][m]: flood_fill(m, n+1, cell, hwall, vwall) # THE bottom elif n == N - 1 and not hwall[n + 1][m]: raise PercolatedException((m, n+1)) # left if m and not vwall[n][m] and not cell[n][m - 1]: flood_fill(m-1, n, cell, hwall, vwall) # right if m < M - 1 and not vwall[n][m + 1] and not cell[n][m + 1]: flood_fill(m+1, n, cell, hwall, vwall) # top if n and not hwall[n][m] and not cell[n-1][m]: flood_fill(m, n-1, cell, hwall, vwall)   if __name__ == '__main__': sample_printed = False pcount = {} for p10 in range(11): p = (10 - p10) / 10.0 # count down so sample print is interesting pcount[p] = 0 for tries in range(t): grid = newgrid(p) percolated = pour_on_top(grid) if percolated: pcount[p] += 1 if not sample_printed: print('\nSample percolating %i x %i grid' % (M, N)) pgrid(grid, percolated) sample_printed = True print('\n p: Fraction of %i tries that percolate through' % t )   pp({p:c/float(t) for p, c in pcount.items()})
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
meanRunDensity[p_, len_, trials_] := Mean[Length[Cases[Split@#, {1, ___}]] & /@ Unitize[Chop[RandomReal[1, {trials, len}], 1 - p]]]/len   Column@Table[ Grid[Join[{{p, n, K, diff}}, Table[{q, n, x = meanRunDensity[q, n, 100] // N, q (1 - q) - x}, {n, {100, 1000, 10000, 100000}}], {}], Alignment -> Left], {q, {.1, .3, .5, .7, .9}}]
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.
#Nim
Nim
import random, strformat   const T = 100   var pList = [0.1, 0.3, 0.5, 0.7, 0.9] nList = [100, 1_000, 10_000, 100_000]   for p in pList:   let theory = p * (1 - p) echo &"\np: {p:.4f} theory: {theory:.4f} t: {T}" echo " n sim sim-theory"   for n in nList: var sum = 0 for _ in 1..T: var run = false for _ in 1..n: let one = rand(1.0) < p if one and not run: inc sum run = one   let k = sum / (T * n) echo &"{n:9} {k:15.4f} {k - theory:10.6f}"
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Racket
Racket
#lang racket (require racket/require (only-in racket/fixnum for*/fxvector)) (require (filtered-in (lambda (name) (regexp-replace #rx"unsafe-" name "")) racket/unsafe/ops))   (define cell-empty 0) (define cell-filled 1) (define cell-wall 2) (define cell-visited 3) (define cell-exit 4)   (define ((percol->generator p)) (if (< (random) p) cell-filled cell-empty))   (define t (make-parameter 1000))   (define ((make-percol-grid M N) p) (define p->10 (percol->generator p)) (define M+1 (fx+ 1 M)) (define M+2 (fx+ 2 M)) (for*/fxvector #:length (fx* N M+2) ((n (in-range N)) (m (in-range M+2))) (cond [(fx= 0 m) cell-wall] [(fx= m M+1) cell-wall] [else (p->10)])))   (define (cell->str c) (substring " #|+*" c (fx+ 1 c)))   (define ((draw-percol-grid M N) g) (define M+2 (fx+ M 2)) (for ((row N)) (for ((col (in-range M+2))) (define idx (fx+ (fx* M+2 row) col)) (printf "~a" (cell->str (fxvector-ref g idx)))) (newline)))   (define ((percolate-percol-grid?! M N) g) (define M+2 (fx+ M 2)) (define N-1 (fx- N 1)) (define max-idx (fx* N M+2)) (define (inner-percolate g idx) (define row (fxquotient idx M+2)) (cond ((fx< idx 0) #f) ((fx>= idx max-idx) #f) ((fx= N-1 row) (fxvector-set! g idx cell-exit) #t) ((fx= cell-filled (fxvector-ref g idx)) (fxvector-set! g idx cell-visited) (or  ; gravity first (thanks Mr Newton) (inner-percolate g (fx+ idx M+2))  ; stick-to-the-left (inner-percolate g (fx- idx 1)) (inner-percolate g (fx+ idx 1))  ; go uphill only if we have to! (inner-percolate g (fx- idx M+2)))) (else #f))) (for/first ((m (in-range 1 M+2)) #:when (inner-percolate g m)) g))   (define make-15x15-grid (make-percol-grid 15 15)) (define draw-15x15-grid (draw-percol-grid 15 15)) (define perc-15x15-grid?! (percolate-percol-grid?! 15 15))   (define (display-sample-percolation p) (printf "Percolation sample: p=~a~%" p) (for*/first ((i (in-naturals)) (g (in-value (make-15x15-grid 0.6))) #:when (perc-15x15-grid?! g)) (draw-15x15-grid g)) (newline))   (display-sample-percolation 0.4)   (for ((p (sequence-map (curry * 1/10) (in-range 0 (add1 10))))) (define n-percolated-grids (for/sum ((i (in-range (t))) #:when (perc-15x15-grid?! (make-15x15-grid p))) 1)) (define proportion-percolated (/ n-percolated-grids (t))) (printf "p=~a\t->\t~a~%" p (real->decimal-string proportion-percolated 4)))
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Raku
Raku
my $block = '▒'; my $water = '+'; my $pore = ' '; my $grid = 15; my @site;   enum Direction <DeadEnd Up Right Down Left>;   say 'Sample percolation at .6'; percolate(.6); .join.say for @site; say "\n";   my $tests = 1000; say "Doing $tests trials at each porosity:"; for .1, .2 ... 1 -> $p { printf "p = %0.1f: %0.3f\n", $p, (sum percolate($p) xx $tests) / $tests }   sub infix:<deq> ( $a, $b ) { $a.defined && ($a eq $b) }   sub percolate ( $prob = .6 ) { @site[0] = [$pore xx $grid]; @site[$grid + 1] = [$pore xx $grid];   for ^$grid X 1..$grid -> ($x, $y) { @site[$y;$x] = rand < $prob ?? $pore !! $block } @site[0;0] = $water;   my @stack; my $current = [0;0];   loop { if my $dir = direction( $current ) { @stack.push: $current; $current = move( $dir, $current ) } else { return False unless @stack; $current = @stack.pop } return True if $current[1] > $grid }   sub direction( [$x, $y] ) { (Down if @site[$y + 1][$x] deq $pore) || (Left if @site[$y][$x - 1] deq $pore) || (Right if @site[$y][$x + 1] deq $pore) || (Up if @site[$y - 1][$x] deq $pore) || DeadEnd }   sub move ( $dir, @cur ) { my ( $x, $y ) = @cur; given $dir { when Up { @site[--$y][$x] = $water } when Down { @site[++$y][$x] = $water } when Left { @site[$y][--$x] = $water } when Right { @site[$y][++$x] = $water } } [$x, $y] } }
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program permutation.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data   sMessResult: .asciz "Value  : @ \n" sMessCounter: .asciz "Permutations = @ \n" szCarriageReturn: .asciz "\n"   .align 4 TableNumber: .int 1,2,3 .equ NBELEMENTS, (. - TableNumber) / 4 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r0,iAdrTableNumber @ address number table mov r1,#NBELEMENTS @ number of élements mov r10,#0 @ counter bl heapIteratif mov r0,r10 @ display counter ldr r1,iAdrsZoneConv @ bl conversion10S @ décimal conversion ldr r0,iAdrsMessCounter ldr r1,iAdrsZoneConv @ insert conversion bl strInsertAtCharInc bl affichageMess @ display message   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrTableNumber: .int TableNumber iAdrsMessCounter: .int sMessCounter /******************************************************************/ /* permutation by heap iteratif (wikipedia) */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the eléments number */ heapIteratif: push {r3-r9,lr} @ save registers lsl r9,r1,#2 @ four bytes by count sub sp,sp,r9 mov fp,sp mov r3,#0 mov r4,#0 @ index 1: @ init area counter str r4,[fp,r3,lsl #2] add r3,r3,#1 cmp r3,r1 blt 1b   bl displayTable add r10,r10,#1 mov r3,#0 @ index 2: ldr r4,[fp,r3,lsl #2] @ load count [i] cmp r4,r3 @ compare with i bge 5f tst r3,#1 @ even ? bne 3f ldr r5,[r0] @ yes load value A[0] ldr r6,[r0,r3,lsl #2] @ and swap with value A[i] str r6,[r0] str r5,[r0,r3,lsl #2] b 4f 3: ldr r5,[r0,r4,lsl #2] @ load value A[count[i]] ldr r6,[r0,r3,lsl #2] @ and swap with value A[i] str r6,[r0,r4,lsl #2] str r5,[r0,r3,lsl #2] 4: bl displayTable add r10,r10,#1 add r4,r4,#1 @ increment count i str r4,[fp,r3,lsl #2] @ and store on stack mov r3,#0 @ raz index b 2b @ and loop 5: mov r4,#0 @ raz count [i] str r4,[fp,r3,lsl #2] add r3,r3,#1 @ increment index cmp r3,r1 @ end ? blt 2b @ no -> loop   add sp,sp,r9 @ stack alignement 100: pop {r3-r9,lr} bx lr @ return   /******************************************************************/ /* Display table elements */ /******************************************************************/ /* r0 contains the address of table */ displayTable: push {r0-r3,lr} @ save registers mov r2,r0 @ table address mov r3,#0 1: @ loop display table ldr r0,[r2,r3,lsl #2] ldr r1,iAdrsZoneConv @ bl conversion10S @ décimal conversion ldr r0,iAdrsMessResult ldr r1,iAdrsZoneConv @ insert conversion bl strInsertAtCharInc bl affichageMess @ display message add r3,#1 cmp r3,#NBELEMENTS - 1 ble 1b ldr r0,iAdrszCarriageReturn bl affichageMess mov r0,r2 100: pop {r0-r3,lr} bx lr iAdrsZoneConv: .int sZoneConv /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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
#Elixir
Elixir
defmodule Perfect do def shuffle(n) do start = Enum.to_list(1..n) m = div(n, 2) shuffle(start, magic_shuffle(start, m), m, 1) end   defp shuffle(start, start, _, step), do: step defp shuffle(start, deck, m, step) do shuffle(start, magic_shuffle(deck, m), m, step+1) end   defp magic_shuffle(deck, len) do {left, right} = Enum.split(deck, len) Enum.zip(left, right) |> Enum.map(&Tuple.to_list/1) |> List.flatten end end   Enum.each([8, 24, 52, 100, 1020, 1024, 10000], fn n -> step = Perfect.shuffle(n) IO.puts "#{n} : #{step}" end)
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
#F.23
F#
  let perfectShuffle xs = let h = (List.length xs) / 2 xs |> List.mapi (fun i x->(if i<h then i * 2 else ((i-h) * 2) + 1), x) |> List.sortBy fst |> List.map snd   let orderCount n = let xs = [1..n] let rec spin count ys = if xs=ys then count else ys |> perfectShuffle |> spin (count + 1) xs |> perfectShuffle |> spin 1   [ 8; 24; 52; 100; 1020; 1024; 10000 ] |> List.iter (fun n->n |> orderCount |> printfn "%d %d" 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.
#Nim
Nim
import math   const 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 ]   const P = static: var a: array[512, int] for i, val in Permutation: a[i] = val a[i + 256] = val a     func fade(t: float): float = t * t * t * (t * (t * 6 - 15) + 10)   func lerp(t, a, b: float): float = a + t * (b - a)   func grad(hash: int; x, y, z: float): float = ## Convert low 4 bits of hash code into 12 gradient directions. let h = hash and 15 let u = if h < 8: x else: y let v = if h < 4: y elif h == 12 or h == 14: x else: z result = (if (h and 1) == 0: u else: -u) + (if (h and 2) == 0: v else: -v)     func noise(x, y, z: float): float =   # Find unit cube that contains point. let xi = int(x) and 255 yi = int(y) and 255 zi = int(z) and 255   # Find relative x, y, z of point in cube. let x = x - floor(x) y = y - floor(y) z = z - floor(z)   # Compute fade curves for each of x, y, z. let u = fade(x) v = fade(y) w = fade(z)   # Hash coordinates of the 8 cube corners and # add blended results from 8 corners of cube. let a = P[xi] + yi aa = P[a] + zi ab = P[a + 1] + zi b = P[xi + 1] + yi ba = P[b] + zi bb = P[b + 1] + zi   result = 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))))   when isMainModule: echo 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
#Kotlin
Kotlin
// Version 1.3.21   fun totient(n: Int): Int { var tot = n var nn = n var i = 2 while (i * i <= nn) { if (nn % i == 0) { while (nn % i == 0) nn /= i tot -= tot / i } if (i == 2) i = 1 i += 2 } if (nn > 1) tot -= tot / nn return tot }   fun main() { val perfect = mutableListOf<Int>() var n = 1 while (perfect.size < 20) { var tot = n var sum = 0 while (tot != 1) { tot = totient(tot) sum += tot } if (sum == n) perfect.add(n) n += 2 } println("The first 20 perfect totient numbers are:") println(perfect) }
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
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(Y,Z) ENTRY TO GCD. A = Y B = Z LOOP WHENEVER A.E.B, FUNCTION RETURN A WHENEVER A.G.B, A = A-B WHENEVER A.L.B, B = B-A TRANSFER TO LOOP END OF FUNCTION   INTERNAL FUNCTION(C) ENTRY TO TOTENT. E = 0 THROUGH LOOP, FOR D=1, 1, D.GE.C LOOP WHENEVER GCD.(C,D).E.1, E = E+1 FUNCTION RETURN E END OF FUNCTION   INTERNAL FUNCTION(G) ENTRY TO PERFCT. H = G I = 0 LOOP H = TOTENT.(H) I = I+H WHENEVER H.G.1, TRANSFER TO LOOP FUNCTION RETURN I.E.G END OF FUNCTION   SEEN = 0 THROUGH LOOP, FOR N=3, 2, SEEN.GE.20 WHENEVER PERFCT.(N) SEEN = SEEN+1 PRINT FORMAT FMT,N END OF CONDITIONAL LOOP CONTINUE   VECTOR VALUES FMT = $I9*$ END OF PROGRAM
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
#Groovy
Groovy
import groovy.transform.TupleConstructor   enum Pip { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } enum Suit { DIAMONDS, SPADES, HEARTS, CLUBS }   @TupleConstructor class Card { final Pip pip final Suit suit   String toString() { "$pip of $suit" } }   class Deck { private LinkedList cards = []   Deck() { reset() }   void reset() { cards = [] Suit.values().each { suit -> Pip.values().each { pip -> cards << new Card(pip, suit) } } }   Card deal() { cards.poll() }   void shuffle() { Collections.shuffle cards }   String toString() { cards.isEmpty() ? "Empty Deck" : "Deck $cards" } }
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
#FunL
FunL
def compute_pi = def g( q, r, t, k, n, l ) = if 4*q + r - t < n*t n # g( 10*q, 10*(r - n*t), t, k, (10*(3*q + r))\t - 10*n, l ) else g( q*k, (2*q + r)*l, t*l, k + 1, (q*(7*k + 2) + r*l)\(t*l), l + 2 )   g( 1, 0, 1, 1, 3, 3 )   if _name_ == '-main-' print( compute_pi().head() + '.' )   if args.isEmpty() for d <- compute_pi().tail() print( d ) else for d <- compute_pi().tail().take( int(args(0)) ) print( d )   println()
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
#OCaml
OCaml
class player (name_init : string) = object val name = name_init val mutable total = 0 val mutable turn_score = 0 method get_name = name method get_score = total method end_turn = total <- total + turn_score; turn_score <- 0; method has_won = total >= 100; method rolled roll = match roll with 1 -> turn_score <- 0; |_ -> turn_score <- turn_score + roll; end;;   let print_seperator () = print_endline "#####";;   let rec one_turn p1 p2 = Printf.printf "What do you want to do %s?\n" p1#get_name; print_endline " 1)Roll the dice?"; print_endline " 2)Or end your turn?"; let choice = read_int () in if choice = 1 then begin let roll = 1 + Random.int 6 in Printf.printf "Rolled a %d\n" roll; p1#rolled roll; match roll with 1 -> print_seperator (); one_turn p2 p1 |_ -> one_turn p1 p2 end else if choice = 2 then begin p1#end_turn; match p1#has_won with false -> Printf.printf "%s's score is now %d\n" p1#get_name p1#get_score; print_seperator(); one_turn p2 p1; |true -> Printf.printf "Congratulations %s! You've won\n" p1#get_name end else begin print_endline "That's not a choice! Make a real one!"; one_turn p1 p2 end;;   Random.self_init (); let p1 = new player "Steven" and p2 = new player "John" in one_turn p1 p2;;
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.
#Groovy
Groovy
  class example{ static void main(String[] args){ def n=0; def counter=0; while(counter<25){ if(print(n)){ counter++;} n=n+1; } println(); def x=888888877; while(x<888888889){ print(x); x++;} } static def print(def a){ def primes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]; def c=Integer.toBinaryString(a); String d=c; def e=0; for(i in d){if(i=='1'){e++;}} if(e in primes){printf(a+" ");return 1;} } }  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#LiveCode
LiveCode
put "Apple,Banana,Peach,Apricot,Pear" into fruits put item (random(the number of items of fruits)) of fruits
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Logo
Logo
pick [1 2 3]
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
#Lua
Lua
-- Return a copy of table t in which each string is reversed function reverseEach (t) local rev = {} for k, v in pairs(t) do rev[k] = v:reverse() end return rev end   -- Return a reversed copy of table t function tabReverse (t) local revTab = {} for i, v in ipairs(t) do revTab[#t - i + 1] = v end return revTab end   -- Split string str into a table on space characters function wordSplit (str) local t = {} for word in str:gmatch("%S+") do table.insert(t, word) end return t end   -- Main procedure local str = "rosetta code phrase reversal" local tab = wordSplit(str) print("1. " .. str:reverse()) print("2. " .. table.concat(reverseEach(tab), " ")) print("3. " .. table.concat(tabReverse(tab), " "))
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
#jq
jq
def derangements:   # In order to reference the original array conveniently, define _derangements(ary): def _derangements(ary): # We cannot put the i-th element in the i-th place: def deranged: # state: [i, available] .[0] as $i | .[1] as $in | if $i == (ary|length) then [] else ($in[] | select (. != ary[$i])) as $j | [$j] + ([$i+1, ($in - [$j])] | deranged) end  ; [0,ary]|deranged; . as $in | _derangements($in);   def subfact: if . == 0 then 1 elif . == 1 then 0 else (.-1) * (((.-1)|subfact) + ((.-2)|subfact)) end;   # Avoid creating an array just to count the items in a stream: def count(g): reduce g as $i (0; . + 1);
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#ooRexx
ooRexx
/* REXX Compute permutations of things elements */ /* implementing Heap's algorithm nicely shown in */ /* https://en.wikipedia.org/wiki/Heap%27s_algorithm */ /* Recursive Algorithm */ Parse Arg things e.='' Select When things='?' Then Call help When things='' Then things=4 When words(things)>1 Then Do elements=things things=words(things) Do i=0 By 1 While elements<>'' Parse Var elements e.i elements End End Otherwise If datatype(things)<>'NUM' Then Call help 'bunch ('bunch') must be numeric' End n=0 Do i=0 To things-1 a.i=i End Call generate things Say time('R') 'seconds' Exit   generate: Procedure Expose a. n e. things Parse Arg k If k=1 Then Call show Else Do Call generate k-1 Do i=0 To k-2 ka=k-1 If k//2=0 Then Parse Value a.i a.ka With a.ka a.i Else Parse Value a.0 a.ka With a.ka a.0 Call generate k-1 End End Return   show: Procedure Expose a. n e. things n=n+1 ol='' Do i=0 To things-1 z=a.i If e.0<>'' Then ol=ol e.z Else ol=ol z End Say strip(ol) Return Exit   help: Parse Arg msg If msg<>'' Then Do Say 'ERROR:' msg Say '' End Say 'rexx permx -> Permutations of 1 2 3 4 ' Say 'rexx permx 2 -> Permutations of 1 2 ' Say 'rexx permx a b c d -> Permutations of a b c d in 2 positions' Exit
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.
#REXX
REXX
/*REXX program performs a permutation test on N + M subjects (volunteers): */ /* ↑ ↑ */ /* │ │ */ /* │ └─────control population. */ /* └────────treatment population. */ n= 9 /*define the number of the control pop.*/ data= 85 88 75 66 25 29 83 39 97 68 41 10 49 16 65 32 92 28 98 w= words(data); m= w - n /*w: volunteers + control population*/ L= length(w) /*L: used to align some output numbers*/ say '# of volunteers & control population: ' w say 'volunteer population given treatment: ' right(n, L) say ' control population given a placebo: ' right(m, L) say say 'treatment population efficacy % (percentages): ' subword(data, 1, n) say ' control population placebo  % (percentages): ' subword(data, n+1 ) say do v= 0 for w  ; #.v= word(data, v+1) ; end treat= 0; do i= 0 to n-1  ; treat= treat + #.i  ; end tot= 1; do j= w to m+1 by -1 ; tot= tot * j  ; end do k=w%2 to 1 by -1 ; tot= tot / k  ; end   GT= picker(n+m, n, 0) /*compute the GT value from PICKER func*/ LE= tot - GT /* " " LE " via subtraction.*/ say "<= " format(100 * LE / tot, ,3)'%' LE /*display number with 3 decimal places.*/ say " > " format(100 * GT / tot, ,3)'%' GT /* " " " " " " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ picker: procedure expose #. treat; parse arg it,rest,eff /*get the arguments.*/ if rest==0 then return eff > treat /*is REST = to zero?*/ if it>rest then q= picker(it-1, rest, eff) /*maybe recurse. */ else q= 0 itP= it - 1 /*set temporary var.*/ return picker(itP, rest - 1, eff + #.itP) + q /*recurse. */
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%
#Go
Go
package main   import ( "fmt" "image/jpeg" "os" "log" "image" )   func loadJpeg(filename string) (image.Image, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close()   img, err := jpeg.Decode(f) if err != nil { return nil, err }   return img, nil }   func diff(a, b uint32) int64 { if a > b { return int64(a - b) } return int64(b - a) }   func main() { i50, err := loadJpeg("Lenna50.jpg") if err != nil { log.Fatal(err) }   i100, err := loadJpeg("Lenna100.jpg") if err != nil { log.Fatal(err) }   if i50.ColorModel() != i100.ColorModel() { log.Fatal("different color models") }   b := i50.Bounds() if !b.Eq(i100.Bounds()) { log.Fatal("different image sizes") }   var sum int64 for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { r1, g1, b1, _ := i50.At(x, y).RGBA() r2, g2, b2, _ := i100.At(x, y).RGBA() sum += diff(r1, r2) sum += diff(g1, g2) sum += diff(b1, b2) } }   nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) fmt.Printf("Image difference: %f%%\n", float64(sum*100)/(float64(nPixels)*0xffff*3)) }
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Picat
Picat
  import sat, util. rotate(Q) = Res => % rotate right by 90 degrees NZ = len(Q[1]), NS = len(Q), Res = new_array(NZ,NS), foreach(Z in 1..NZ, S in 1..NS) Res[Z,S] = Q[S,NZ+1-Z] end.   matprint(Q) => NZ = len(Q), NS = len(Q[1]), foreach(Z in 1..NZ, S in 1..NS) printf("%d|", Q[Z,S]), if S=NS then nl end end, nl.   generate(Res) => P0 = [{{1,1,1,1}, % L {1,0,0,0}}, {{0,1,1,1}, % N {1,1,0,0}}, {{1,1,1,1}, % Y {0,1,0,0}}, {{1,1,0}, % F {0,1,1}, {0,1,0}}, {{1,1,1}, % T {0,1,0}, {0,1,0}}, {{0,0,1}, % W {0,1,1}, {1,1,0}}, {{1,1,1}, % P {1,1,0}}, {{0,0,1}, % V {0,0,1}, {1,1,1}}, {{1,0,1}, % U {1,1,1}}, {{1,0,0}, % Z {1,1,1}, {0,0,1}}, {{1,1,1,1,1}}, % I {{0,1,0}, % X {1,1,1}, {0,1,0}}], Np = len(P0), P = [], foreach(I in 1..Np) VarI = [P0[I]], foreach(_ in 1..3) VarI := [rotate(head(VarI))|VarI] end, P := [VarI|P] end, Res = P.   main => N = 8, M = new_array(N+4,N+4), foreach(R in N+1..N+4, C in 1..N) M[R,C] #= 0 end, foreach(R in 1..N, C in N+1..N+4) M[R,C] #= 0 end, generate(P),  % P[1] = X-Pentomino, then P[2] = I, P[3] = Z, and so on U, V, P, X, W, T, F, Y, N, L Np = len(P), M :: 0..Np, foreach(I in 1..Np) count(I, vars(M), 5) end, % 12 pentomino Idx = new_list(Np), % X has 1 rotation variant, I and Z each 2, the rest 4: Idx[1] #= 1, [Idx[2],Idx[3]] :: 1..2, Idx :: 1..4, DZ = new_list(Np), DZ :: 0..N-1, % translation of I.th pentomino DS = new_list(Np), DS :: 0..N-1, foreach(I in 1..Np, J in 1..4) % Constraint only if Idx[I] #= J! NZ = len(P[I,J]), NS = len(P[I,J,1]), foreach(DZI in 0..N-1, DSI in 0..N-1, Z in 1..NZ, S in 1..NS, P[I,J,Z,S]=1) (Idx[I] #= J #/\ DZ[I] #= DZI #/\ DS[I] #= DSI) #=> M[DZI+Z,DSI+S] #= I end end, solve(vars(M) ++ DZ ++ DS ++ Idx), Chr = " XIZUVPWTFYNL", foreach(Z in 1..N) foreach(S in 1..N) printf("%c|", Chr[1 + M[Z,S]]) end, nl end.  
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Racket
Racket
#lang racket   (require racket/hash)   (module+ main (Pentomino-tiling))   (define n-rows 8) (define n-cols 8) (define blank '-)   (define (build-grid) (for/fold ((grid (for*/hash ((r n-rows) (c n-cols)) (values (cons r c) #f)))) ((_ 4)) (hash-set grid (cons (random n-rows) (random n-cols)) blank)))   (define (make-shapes-map) (hash 'F (F) 'I (I) 'L (L) 'N (N) 'P (P) 'T (T) 'U (U) 'V (V) 'W (W) 'X (X) 'Y (Y) 'Z (Z)))   (define (print-grid grid) (for ((r n-rows) #:when (when (positive? r) (newline)) (c n-cols)) (write (hash-ref grid (cons r c)))) (newline))   (define (Pentomino-tiling (grid (build-grid))) (define solution (solve 0 grid (make-shapes-map))) (if solution (print-grid solution) (displayln "no solution")))   (define (solve p grid shapes (failed-shapes (hash))) (define-values (r c) (quotient/remainder p n-cols)) (cond [(not grid) #f] [(hash-empty? shapes) (and (hash-empty? failed-shapes) grid)] [(hash-ref grid (cons r c) #f) (solve (add1 p) grid shapes failed-shapes)] [else (define s (car (hash-keys shapes))) (define os (hash-ref shapes s)) (define shapes-s (hash-remove shapes s)) (define (try-place-orientation o) (and (for/and ((dy.dx o)) (let ((y (+ r (car dy.dx))) (x (+ c (cdr dy.dx)))) (and (>= x 0) (>= y 0) (< x n-cols) (< y n-rows) (not (hash-ref grid (cons y x)))))) (for/fold ((grid (hash-set grid (cons r c) s))) ((dy.dx o)) (hash-set grid (cons (+ r (car dy.dx)) (+ c (cdr dy.dx))) s)))) (or (for*/first ((o os) (solution (in-value (solve (add1 p) (try-place-orientation o) (hash-union shapes-s failed-shapes)))) #:when solution) solution) (solve p grid shapes-s (hash-set failed-shapes s os)))]))   (define (F) '(((1 . -1) (1 . 0) (1 . 1) (2 . 1)) ((0 . 1) (1 . -1) (1 . 0) (2 . 0)) ((1 . 0) (1 . 1) (1 . 2) (2 . 1)) ((1 . 0) (1 . 1) (2 . -1) (2 . 0)) ((1 . -2) (1 . -1) (1 . 0) (2 . -1)) ((0 . 1) (1 . 1) (1 . 2) (2 . 1)) ((1 . -1) (1 . 0) (1 . 1) (2 . -1)) ((1 . -1) (1 . 0) (2 . 0) (2 . 1))))   (define (I) '(((0 . 1) (0 . 2) (0 . 3) (0 . 4)) ((1 . 0) (2 . 0) (3 . 0) (4 . 0))))   (define (L) '(((1 . 0) (1 . 1) (1 . 2) (1 . 3)) ((1 . 0) (2 . 0) (3 . -1) (3 . 0)) ((0 . 1) (0 . 2) (0 . 3) (1 . 3)) ((0 . 1) (1 . 0) (2 . 0) (3 . 0)) ((0 . 1) (1 . 1) (2 . 1) (3 . 1)) ((0 . 1) (0 . 2) (0 . 3) (1 . 0)) ((1 . 0) (2 . 0) (3 . 0) (3 . 1)) ((1 . -3) (1 . -2) (1 . -1) (1 . 0))))   (define (N) '(((0 . 1) (1 . -2) (1 . -1) (1 . 0)) ((1 . 0) (1 . 1) (2 . 1) (3 . 1)) ((0 . 1) (0 . 2) (1 . -1) (1 . 0)) ((1 . 0) (2 . 0) (2 . 1) (3 . 1)) ((0 . 1) (1 . 1) (1 . 2) (1 . 3)) ((1 . 0) (2 . -1) (2 . 0) (3 . -1)) ((0 . 1) (0 . 2) (1 . 2) (1 . 3)) ((1 . -1) (1 . 0) (2 . -1) (3 . -1))))   (define (P) '(((0 . 1) (1 . 0) (1 . 1) (2 . 1)) ((0 . 1) (0 . 2) (1 . 0) (1 . 1)) ((1 . 0) (1 . 1) (2 . 0) (2 . 1)) ((0 . 1) (1 . -1) (1 . 0) (1 . 1)) ((0 . 1) (1 . 0) (1 . 1) (1 . 2)) ((1 . -1) (1 . 0) (2 . -1) (2 . 0)) ((0 . 1) (0 . 2) (1 . 1) (1 . 2)) ((0 . 1) (1 . 0) (1 . 1) (2 . 0))))   (define (T) '(((0 . 1) (0 . 2) (1 . 1) (2 . 1)) ((1 . -2) (1 . -1) (1 . 0) (2 . 0)) ((1 . 0) (2 . -1) (2 . 0) (2 . 1)) ((1 . 0) (1 . 1) (1 . 2) (2 . 0))))   (define (U) '(((0 . 1) (0 . 2) (1 . 0) (1 . 2)) ((0 . 1) (1 . 1) (2 . 0) (2 . 1)) ((0 . 2) (1 . 0) (1 . 1) (1 . 2)) ((0 . 1) (1 . 0) (2 . 0) (2 . 1))))   (define (V) '(((1 . 0) (2 . 0) (2 . 1) (2 . 2)) ((0 . 1) (0 . 2) (1 . 0) (2 . 0)) ((1 . 0) (2 . -2) (2 . -1) (2 . 0)) ((0 . 1) (0 . 2) (1 . 2) (2 . 2))))   (define (W) '(((1 . 0) (1 . 1) (2 . 1) (2 . 2)) ((1 . -1) (1 . 0) (2 . -2) (2 . -1)) ((0 . 1) (1 . 1) (1 . 2) (2 . 2)) ((0 . 1) (1 . -1) (1 . 0) (2 . -1))))   (define (X) '(((1 . -1) (1 . 0) (1 . 1) (2 . 0))))   (define (Y) '(((1 . -2) (1 . -1) (1 . 0) (1 . 1)) ((1 . -1) (1 . 0) (2 . 0) (3 . 0)) ((0 . 1) (0 . 2) (0 . 3) (1 . 1)) ((1 . 0) (2 . 0) (2 . 1) (3 . 0)) ((0 . 1) (0 . 2) (0 . 3) (1 . 2)) ((1 . 0) (1 . 1) (2 . 0) (3 . 0)) ((1 . -1) (1 . 0) (1 . 1) (1 . 2)) ((1 . 0) (2 . -1) (2 . 0) (3 . 0))))   (define (Z) '(((0 . 1) (1 . 0) (2 . -1) (2 . 0)) ((1 . 0) (1 . 1) (1 . 2) (2 . 2)) ((0 . 1) (1 . 1) (2 . 1) (2 . 2)) ((1 . -2) (1 . -1) (1 . 0) (2 . -2))))  
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\displaystyle c} be a 2D boolean square matrix of n × n {\displaystyle n\times n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} , (and of 0 is therefore 1 − p {\displaystyle 1-p} ). We define a cluster of 1's as being a group of 1's connected vertically or horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either 0 {\displaystyle 0} or by the limits of the matrix. Let the number of such clusters in such a randomly constructed matrix be C n {\displaystyle C_{n}} . Percolation theory states that K ( p ) {\displaystyle K(p)} (the mean cluster density) will satisfy K ( p ) = C n / n 2 {\displaystyle K(p)=C_{n}/n^{2}} as n {\displaystyle n} tends to infinity. For p = 0.5 {\displaystyle p=0.5} , K ( p ) {\displaystyle K(p)} is found numerically to approximate 0.065770 {\displaystyle 0.065770} ... Task Show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} for p = 0.5 {\displaystyle p=0.5} and for values of n {\displaystyle n} up to at least 1000 {\displaystyle 1000} . Any calculation of C n {\displaystyle C_{n}} for finite n {\displaystyle n} is subject to randomness, so an approximation should be computed as the average of t {\displaystyle t} runs, where t {\displaystyle t} ≥ 5 {\displaystyle 5} . For extra credit, graphically show clusters in a 15 × 15 {\displaystyle 15\times 15} , p = 0.5 {\displaystyle p=0.5} grid. Show your output here. See also s-Cluster on Wolfram mathworld.
#Tcl
Tcl
package require Tcl 8.6   proc determineClusters {w h p} { # Construct the grid set grid [lrepeat $h [lrepeat $w 0]] for {set i 0} {$i < $h} {incr i} { for {set j 0} {$j < $w} {incr j} { lset grid $i $j [expr {rand() < $p ? -1 : 0}] } } # Find (and count) the clusters set cl 0 for {set i 0} {$i < $h} {incr i} { for {set j 0} {$j < $w} {incr j} { if {[lindex $grid $i $j] == -1} { incr cl for {set q [list $i $j];set k 0} {$k<[llength $q]} {incr k} { set y [lindex $q $k] set x [lindex $q [incr k]] if {[lindex $grid $y $x] != -1} continue lset grid $y $x $cl foreach dx {1 0 -1 0} dy {0 1 0 -1} { set nx [expr {$x+$dx}] set ny [expr {$y+$dy}] if { $nx >= 0 && $ny >= 0 && $nx < $w && $ny < $h && [lindex $grid $ny $nx] == -1 } then { lappend q $ny $nx } } } } } } return [list $cl $grid] }   # Print a sample 15x15 grid lassign [determineClusters 15 15 0.5] n g puts "15x15 grid, p=0.5, with $n clusters" puts "+[string repeat - 15]+" foreach r $g {puts |[join [lmap x $r {format %c [expr {$x==0?32:64+$x}]}] ""]|} puts "+[string repeat - 15]+"   # Determine the densities as the grid size increases puts "p=0.5, iter=5" foreach n {5 30 180 1080 6480} { set tot 0 for {set i 0} {$i < 5} {incr i} { lassign [determineClusters $n $n 0.5] nC incr tot $nC } puts "n=$n, K(p)=[expr {$tot/5.0/$n**2}]" }
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.
#AWK
AWK
$ awk 'func perf(n){s=0;for(i=1;i<n;i++)if(n%i==0)s+=i;return(s==n)} BEGIN{for(i=1;i<10000;i++)if(perf(i))print i}' 6 28 496 8128
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Racket
Racket
#lang racket   (define has-left-wall? (lambda (x) (bitwise-bit-set? x 0))) (define has-right-wall? (lambda (x) (bitwise-bit-set? x 1))) (define has-top-wall? (lambda (x) (bitwise-bit-set? x 2))) (define has-bottom-wall? (lambda (x) (bitwise-bit-set? x 3))) (define has-fluid? (lambda (x) (bitwise-bit-set? x 4)))   (define (walls->cell l? r? t? b?) (+ (if l? 1 0) (if r? 2 0) (if t? 4 0) (if b? 8 0)))   (define (bonded-percol-grid M N p) (define rv (make-vector (* M N))) (for* ((idx (in-range (* M N)))) (define left-wall? (or (zero? (modulo idx M)) (has-right-wall? (vector-ref rv (sub1 idx))))) (define right-wall? (or (= (modulo idx M) (sub1 M)) (< (random) p))) (define top-wall? (if (< idx M) (< (random) p) (has-bottom-wall? (vector-ref rv (- idx M))))) (define bottom-wall? (< (random) p)) (define cell-value (walls->cell left-wall? right-wall? top-wall? bottom-wall?)) (vector-set! rv idx cell-value)) rv)   (define (display-percol-grid M . vs) (define N (/ (vector-length (car vs)) M)) (define-syntax-rule (tab-eol m) (when (= m (sub1 M)) (printf "\t"))) (for ((n N)) (for* ((v vs) (m M)) (when (zero? m) (printf "+")) (printf (match (vector-ref v (+ (* n M) m)) ((? has-top-wall?) "-+") ((? has-fluid?) "#+") (else ".+"))) (tab-eol m)) (newline) (for* ((v vs) (m M)) (when (zero? m) (printf "|")) (printf (match (vector-ref v (+ (* n M) m)) ((and (? has-fluid?) (? has-right-wall?)) "#|") ((? has-right-wall?) ".|") ((? has-fluid?) "##") (else ".."))) (tab-eol m)) (newline)) (for* ((v vs) (m M)) (when (zero? m) (printf "+")) (printf (match (vector-ref v (+ (* (sub1 M) M) m)) ((? has-bottom-wall?) "-+") ((? has-fluid?) "#+") (else ".+"))) (tab-eol m)) (newline))   (define (find-bonded-grid-t/b-path M v) (define N (/ (vector-length v) M))   (define (flood-cell idx) (cond [(= (quotient idx M) N) #t] ; wootiments! [(has-fluid? (vector-ref v idx)) #f] ; been here [else (define cell (vector-ref v idx)) (vector-set! v idx (bitwise-ior cell 16)) (or (and (not (has-bottom-wall? cell)) (flood-cell (+ idx M))) (and (not (has-left-wall? cell)) (flood-cell (- idx 1))) (and (not (has-right-wall? cell)) (flood-cell (+ idx 1))) (and (not (has-top-wall? cell)) (>= idx M) ; not top row (flood-cell (- idx M))))]))   (for/first ((m (in-range M)) #:unless (has-top-wall? (vector-ref v m)) #:when (flood-cell m)) #t))   (define t (make-parameter 1000)) (define (experiment p) (/ (for*/sum ((sample (in-range (t))) (v (in-value (bonded-percol-grid 10 10 p))) #:when (find-bonded-grid-t/b-path 10 v)) 1) (t)))   (define (main) (for ((tenths (in-range 0 (add1 10)))) (define p (/ tenths 10)) (define e (experiment p)) (printf "proportion of grids that percolate p=~a : ~a (~a)~%" p e (real->decimal-string e 5))))   (module+ test (define (make/display/flood/display-bonded-grid M N p attempts (atmpt 1)) (define v (bonded-percol-grid M N p)) (define v+ (vector-copy v)) (cond [(or (find-bonded-grid-t/b-path M v+) (= attempts 0)) (define v* (vector-copy v+)) (define (flood-bonded-grid) (when (find-bonded-grid-t/b-path M v*) (flood-bonded-grid))) (flood-bonded-grid) (display-percol-grid M v v+ v*) (printf "After ~a attempt(s)~%~%" atmpt)] [else (make/display/flood/display-bonded-grid M N p (sub1 attempts) (add1 atmpt))]))   (make/display/flood/display-bonded-grid 10 10 0 20) (make/display/flood/display-bonded-grid 10 10 .25 20) (make/display/flood/display-bonded-grid 10 10 .50 20) (make/display/flood/display-bonded-grid 10 10 .75 20000))
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} , assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Each c e l l [ m , n ] {\displaystyle \mathrm {cell} [m,n]} is bounded by (horizontal) walls h w a l l [ m , n ] {\displaystyle \mathrm {hwall} [m,n]} and h w a l l [ m + 1 , n ] {\displaystyle \mathrm {hwall} [m+1,n]} ; (vertical) walls v w a l l [ m , n ] {\displaystyle \mathrm {vwall} [m,n]} and v w a l l [ m , n + 1 ] {\displaystyle \mathrm {vwall} [m,n+1]} Assume that the probability of any wall being present is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} Except for the outer horizontal walls at m = 0 {\displaystyle m=0} and m = M {\displaystyle m=M} which are always present. The task Simulate pouring a fluid onto the top surface ( n = 0 {\displaystyle n=0} ) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. The fluid does not move beyond the horizontal constraints of the grid. The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t = 100 {\displaystyle t=100} . Use an M = 10 , N = 10 {\displaystyle M=10,N=10} grid of cells for all cases. Optionally depict fluid successfully percolating through a grid graphically. Show all output on this page.
#Raku
Raku
my @bond; my $grid = 10; my $geom = $grid - 1; my $water = '▒';   enum Direction <DeadEnd Up Right Down Left>;   say 'Sample percolation at .6'; percolate .6; .join.say for @bond; say "\n";   my $tests = 100; say "Doing $tests trials at each porosity:"; for .1, .2 ... 1 -> $p { printf "p = %0.1f: %0.2f\n", $p, (sum percolate($p) xx $tests) / $tests }   sub percolate ( $prob ) { generate $prob; my @stack; my $current = [1;0]; $current.&fill;   loop { if my $dir = direction( $current ) { @stack.push: $current; $current = move $dir, $current } else { return False unless @stack; $current = @stack.pop } return True if $current[1] == +@bond - 1 }   sub direction( [$x, $y] ) { ( Down if @bond[$y + 1][$x].contains: ' ' ) || ( Left if @bond[$y][$x - 1].contains: ' ' ) || ( Right if @bond[$y][$x + 1].contains: ' ' ) || ( Up if @bond[$y - 1][$x].defined && @bond[$y - 1][$x].contains: ' ' ) || DeadEnd }   sub move ( $dir, @cur ) { my ( $x, $y ) = @cur; given $dir { when Up { [$x,--$y].&fill xx 2 } when Down { [$x,++$y].&fill xx 2 } when Left { [--$x,$y].&fill xx 2 } when Right { [++$x,$y].&fill xx 2 } } [$x, $y] }   sub fill ( [$x, $y] ) { @bond[$y;$x].=subst(' ', $water, :g) } }   sub generate ( $prob = .5 ) { @bond = (); my $sp = ' '; append @bond, [flat '│', ($sp, ' ') xx $geom, $sp, '│'], [flat '├', (h(), '┬') xx $geom, h(), '┤']; append @bond, [flat '│', ($sp, v()) xx $geom, $sp, '│'], [flat '├', (h(), '┼') xx $geom, h(), '┤'] for ^$geom; append @bond, [flat '│', ($sp, v()) xx $geom, $sp, '│'], [flat '├', (h(), '┴') xx $geom, h(), '┤'], [flat '│', ($sp, ' ') xx $geom, $sp, '│'];   sub h () { rand < $prob ?? $sp !! '───' } sub v () { rand < $prob ?? ' ' !! '│' } }
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.
#Pascal
Pascal
  {$MODE objFPC}//for using result,parameter runs becomes for variable.. uses sysutils;//Format const MaxN = 100*1000;   function run_test(p:double;len,runs: NativeInt):double; var x, y, i,cnt : NativeInt; Begin result := 1/ (runs * len); cnt := 0; for runs := runs-1 downto 0 do Begin x := 0; y := 0; for i := len-1 downto 0 do begin x := y; y := Ord(Random() < p); cnt := cnt+ord(x < y); end; end; result := result *cnt; end;   //main var p, p1p, K : double; ip, n : nativeInt; Begin randomize; writeln( 'running 1000 tests each:'#13#10, ' p n K p(1-p) diff'#13#10, '-----------------------------------------------'); ip:= 1; while ip < 10 do Begin p := ip / 10; p1p := p * (1 - p); n := 100; While n <= MaxN do Begin K := run_test(p, n, 1000); writeln(Format('%4.1f %6d  %6.4f  %6.4f %7.4f (%5.2f %%)', [p, n, K, p1p, K - p1p, (K - p1p) / p1p * 100])); n := n*10; end; writeln; ip := ip+2; end; end.
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N {\displaystyle M\times N} rectangular array of cells numbered c e l l [ 0.. M − 1 , 0.. N − 1 ] {\displaystyle \mathrm {cell} [0..M-1,0..N-1]} assume M {\displaystyle M} is horizontal and N {\displaystyle N} is downwards. Assume that the probability of any cell being filled is a constant p {\displaystyle p} where 0.0 ≤ p ≤ 1.0 {\displaystyle 0.0\leq p\leq 1.0} The task Simulate creating the array of cells with probability p {\displaystyle p} and then testing if there is a route through adjacent filled cells from any on row 0 {\displaystyle 0} to any on row N {\displaystyle N} , i.e. testing for site percolation. Given p {\displaystyle p} repeat the percolation t {\displaystyle t} times to estimate the proportion of times that the fluid can percolate to the bottom for any given p {\displaystyle p} . Show how the probability of percolating through the random grid changes with p {\displaystyle p} going from 0.0 {\displaystyle 0.0} to 1.0 {\displaystyle 1.0} in 0.1 {\displaystyle 0.1} increments and with the number of repetitions to estimate the fraction at any given p {\displaystyle p} as t >= 100 {\displaystyle t>=100} . Use an M = 15 , N = 15 {\displaystyle M=15,N=15} grid of cells for all cases. Optionally depict a percolation through a cell grid graphically. Show all output on this page.
#Sidef
Sidef
class Percolate {   has block = '▒' has water = '+' has pore = ' ' has grid = 15 has site = []   enum <DeadEnd, Up, Right, Down, Left>   method direction(x, y) { ((site[y + 1][x] == pore) && Down ) || ((site[y][x - 1] == pore) && Left ) || ((site[y][x + 1] == pore) && Right) || ((site[y - 1][x] == pore) && Up ) || DeadEnd }   method move(dir, x, y) { given (dir) { when (Up) { site[--y][x] = water } when (Down) { site[++y][x] = water } when (Left) { site[y][--x] = water } when (Right) { site[y][++x] = water } } return (x, y) }   method percolate (prob = 0.6) { site[0] = grid.of(pore) site[grid + 1] = grid.of(pore)   for x = ^grid, y = 1..grid { site[y][x] = (1.rand < prob ? pore : block) }   site[0][0] = water   var stack = [] var (x, y) = (0, 0)   loop { if (var dir = self.direction(x, y)) { stack << [x, y] (x,y) = self.move(dir, x, y) } else { stack || return 0 (x,y) = stack.pop... } return 1 if (y > grid) } } }   var obj = Percolate() say 'Sample percolation at 0.6' obj.percolate(0.6) obj.site.each { .join.say } say ''   var tests = 100 say "Doing #{tests} trials at each porosity:" for p in (0.1..1 `by` 0.1) { printf("p = %0.1f: %0.3f\n", p, tests.of { obj.percolate(p) }.sum / tests) }
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
#Arturo
Arturo
print permutate [1 2 3]
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
#Factor
Factor
USING: arrays formatting kernel math prettyprint sequences sequences.merged ; IN: rosetta-code.perfect-shuffle   CONSTANT: test-cases { 8 24 52 100 1020 1024 10000 }   : shuffle ( seq -- seq' ) halves 2merge ;   : shuffle-count ( n -- m ) <iota> >array 0 swap dup [ 2dup = ] [ shuffle [ 1 + ] 2dip ] do until 2drop ;   "Deck size" "Number of shuffles required" "%-11s %-11s\n" printf test-cases [ dup shuffle-count "%-11d %-11d\n" printf ] each
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
#Fortran
Fortran
MODULE PERFECT_SHUFFLE IMPLICIT NONE   CONTAINS   ! Shuffle the deck/array of integers FUNCTION SHUFFLE(NUM_ARR) INTEGER, DIMENSION(:), INTENT(IN) :: NUM_ARR INTEGER, DIMENSION(SIZE(NUM_ARR)) :: SHUFFLE INTEGER :: I, IDX   IF (MOD(SIZE(NUM_ARR), 2) .NE. 0) THEN WRITE(*,*) "ERROR: SIZE OF DECK MUST BE EVEN NUMBER" CALL EXIT(1) END IF   IDX = 1   DO I=1, SIZE(NUM_ARR)/2 SHUFFLE(IDX) = NUM_ARR(I) SHUFFLE(IDX+1) = NUM_ARR(SIZE(NUM_ARR)/2+I) IDX = IDX + 2 END DO   END FUNCTION SHUFFLE   ! Compare two arrays element by element FUNCTION COMPARE_ARRAYS(ARRAY_1, ARRAY_2) INTEGER, DIMENSION(:) :: ARRAY_1, ARRAY_2 LOGICAL :: COMPARE_ARRAYS INTEGER :: I   DO I=1,SIZE(ARRAY_1) IF (ARRAY_1(I) .NE. ARRAY_2(I)) THEN COMPARE_ARRAYS = .FALSE. RETURN END IF END DO   COMPARE_ARRAYS = .TRUE. END FUNCTION COMPARE_ARRAYS   ! Generate a deck/array of consecutive integers FUNCTION GEN_DECK(DECK_SIZE) INTEGER, INTENT(IN) :: DECK_SIZE INTEGER, DIMENSION(DECK_SIZE) :: GEN_DECK INTEGER :: I   GEN_DECK = (/(I, I=1,DECK_SIZE)/) END FUNCTION GEN_DECK END MODULE PERFECT_SHUFFLE   ! Program to demonstrate the perfect shuffle algorithm ! for various deck sizes PROGRAM DEMO_PERFECT_SHUFFLE USE PERFECT_SHUFFLE IMPLICIT NONE   INTEGER, PARAMETER, DIMENSION(7) :: DECK_SIZES = (/8, 24, 52, 100, 1020, 1024, 10000/) INTEGER, DIMENSION(:), ALLOCATABLE :: DECK, SHUFFLED INTEGER :: I, COUNTER   WRITE(*,'(A, A, A)') "input (deck size)", " | ", "output (number of shuffles required)" WRITE(*,*) REPEAT("-", 55)   DO I=1, SIZE(DECK_SIZES) IF (I .GT. 1) THEN DEALLOCATE(DECK) DEALLOCATE(SHUFFLED) END IF ALLOCATE(DECK(DECK_SIZES(I))) ALLOCATE(SHUFFLED(DECK_SIZES(I))) DECK = GEN_DECK(DECK_SIZES(I)) SHUFFLED = SHUFFLE(DECK) COUNTER = 1 DO WHILE (.NOT. COMPARE_ARRAYS(DECK, SHUFFLED)) SHUFFLED = SHUFFLE(SHUFFLED) COUNTER = COUNTER + 1 END DO   WRITE(*,'(I17, A, I35)') DECK_SIZES(I), " | ", COUNTER END DO END PROGRAM DEMO_PERFECT_SHUFFLE
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.
#OCaml
OCaml
let 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]   let lerp (t, a, b) = a +. t *. (b -. a)   let fade t = (t *. t *. t) *. (t *. (t *. 6. -. 15.) +. 10.)   let grad (hash, x, y, z) = let h = hash land 15 in let u = if (h < 8) then x else y in let v = if (h < 4) then y else (if (h = 12 || h = 14) then x else z) in (if (h land 1 = 0) then u else (0. -. u)) +. (if (h land 2 = 0) then v else (0. -. v))   let perlin_init p = List.rev (List.fold_left (fun i x -> x :: i) (List.rev p) p);;   let perlin_noise p x y z = let x1 = (int_of_float x) land 255 and y1 = (int_of_float y) land 255 and z1 = (int_of_float z) land 255 and xi = x -. (float (int_of_float x)) and yi = y -. (float (int_of_float y)) and zi = z -. (float (int_of_float z)) in let u = fade xi and v = fade yi and w = fade zi and a = (List.nth p x1) + y1 in let aa = (List.nth p a) + z1 and ab = (List.nth p (a + 1)) + z1 and b = (List.nth p (x1 + 1)) + y1 in let ba = (List.nth p b) + z1 and bb = (List.nth p (b + 1)) + z1 in lerp(w, lerp(v, lerp(u, (grad ((List.nth p aa), xi, yi, zi)), (grad ((List.nth p ba), xi -. 1., yi , zi))), lerp(u, (grad ((List.nth p ab), xi , yi -. 1., zi)), (grad ((List.nth p bb), xi -. 1., yi -. 1., zi)))), lerp(v, lerp(u, (grad ((List.nth p (aa + 1)), xi, yi, zi -. 1.)), (grad ((List.nth p (ba + 1)), xi -. 1., yi , zi -. 1.))), lerp(u, (grad ((List.nth p (ab + 1)), xi , yi -. 1., zi -. 1.)), (grad ((List.nth p (bb + 1)), xi -. 1., yi -. 1., zi -. 1.)))))   ;;   let p = perlin_init permutation in print_string ((Printf.sprintf "%0.17f" (perlin_noise p 3.14 42.0 7.0)) ^ "\n")
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
#Maple
Maple
iterated_totient := proc(n::posint, total) if NumberTheory:-Totient(n) = 1 then return total + 1; else return iterated_totient(NumberTheory:-Totient(n), total + NumberTheory:-Totient(n)); end if; end proc:   isPerfect := n -> evalb(iterated_totient(n, 0) = n):   count := 0: num_list := []: for i while count < 20 do if isPerfectTotient(i) then num_list := [op(num_list), i]; count := count + 1; end if; end do; num_list;
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[PerfectTotientNumberQ] PerfectTotientNumberQ[n_Integer] := Total[Rest[Most[FixedPointList[EulerPhi, n]]]] == n res = {}; i = 0; While[Length[res] < 20, i++; If[PerfectTotientNumberQ[i], AppendTo[res, i]] ] res
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
#Modula-2
Modula-2
MODULE PerfectTotient; FROM InOut IMPORT WriteCard, WriteLn;   CONST Amount = 20; VAR n, seen: CARDINAL;   PROCEDURE GCD(a, b: CARDINAL): CARDINAL; VAR c: CARDINAL; BEGIN WHILE b # 0 DO c := a MOD b; a := b; b := c; END; RETURN a; END GCD;   PROCEDURE Totient(n: CARDINAL): CARDINAL; VAR i, tot: CARDINAL; BEGIN tot := 0; FOR i := 1 TO n/2 DO IF GCD(n,i) = 1 THEN tot := tot + 1; END; END; RETURN tot; END Totient;   PROCEDURE Perfect(n: CARDINAL): BOOLEAN; VAR sum, x: CARDINAL; BEGIN sum := 0; x := n; REPEAT x := Totient(x); sum := sum + x; UNTIL x = 1; RETURN sum = n; END Perfect;   BEGIN seen := 0; n := 3; WHILE seen < Amount DO IF Perfect(n) THEN WriteCard(n,5); seen := seen + 1; IF seen MOD 14 = 0 THEN WriteLn(); END; END; n := n + 2; END; WriteLn(); END PerfectTotient.
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
#Haskell
Haskell
import System.Random   data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Ord, Enum, Bounded, Eq, Show)   data Suit = Diamonds | Spades | Hearts | Clubs deriving (Ord, Enum, Bounded, Eq, Show)   type Card = (Pip, Suit)   fullRange :: (Bounded a, Enum a) => [a] fullRange = [minBound..maxBound]   fullDeck :: [Card] fullDeck = [(pip, suit) | pip <- fullRange, suit <- fullRange]   insertAt :: Int -> a -> [a] -> [a] insertAt 0 x ys = x:ys insertAt n _ [] = error "insertAt: list too short" insertAt n x (y:ys) = y : insertAt (n-1) x ys   shuffle :: RandomGen g => g -> [a] -> [a] shuffle g xs = shuffle' g xs 0 [] where shuffle' g [] _ ys = ys shuffle' g (x:xs) n ys = shuffle' g' xs (n+1) (insertAt k x ys) where (k,g') = randomR (0,n) g
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
#FutureBasic
FutureBasic
  include "ConsoleWindow"   dim as long kf, ks xref mf(_maxLong - 1) as long xref ms(_maxLong - 1) as long dim as long cnt, n, temp, nd dim as long col, col1 dim as long lloc, stor(50)   end globals   local mode local fn FmtStr( nn as long, s as Str255 ) as Str255 dim l as long dim as Str255 f l = s[0] select case case ( nn => l ) f = string$( nn-l, 32 ) + s case ( -nn > l) f = s + string$( -nn-l, 32 ) case else f = s end select end fn = f     local mode local fn FmtInt( nn as long, s as Str255 ) as Str255 if ( left$( s, 1 ) = " " ) then s = mid$( s, 2 ) end fn = fn FmtStr( nn, s )     local fn yprint( m as long ) if ( cnt < n ) col++ if ( col == 11 ) col = 1 col1++ long if ( col1 == 6 ) col1 = 0 print print fn FmtInt( 4, str$( m mod 10) ); else print fn FmtInt( 3, str$ (m mod 10) ); end if else print mid$( str$( m ), 2 ) ; end if cnt++ end if end fn     local fn xprint( m as long) dim as long ii, wk, wk1   if ( m < 8 ) ii = 1 while ( ii <= lloc ) fn yprint( stor(ii) ) ii++ wend lloc = 0 else if ( m > 9 ) wk = m / 10 m = m mod 10 wk1 = lloc while ( wk1 >= 1 ) wk += stor(wk1) stor(wk1) = wk mod 10 wk = wk/10 wk1-- wend end if end if lloc++ stor(lloc) = m end fn     local mode local fn shift( l1 as ^long, l2 as ^long, lp as long, lmod as long ) dim as long k   if ( l2.nil& > 0 ) k = ( l2.nil& ) / lmod else k = -( -l2.nil& / lmod ) - 1 end if l2.nil& = l2.nil& - k*lmod l1.nil& = l1.nil& + k*lp end fn     local fn Main( nDig as long ) dim as long i   n = nDig stor(0) = 0   mf = fn malloc( ( n + 10 ) * sizeof(long) ) if ( 0 == mf ) then stop "Out of memory"   ms = fn malloc( ( n + 10 ) * sizeof(long) ) if ( 0 == ms ) then stop "Out of memory"   print : print "Approximation of π to"; n; " digits"   cnt = 0 kf = 25 ks = 57121 mf(1) = 1   i = 2 while ( i <= n ) mf(i) = -16 mf(i + 1) = 16 i += 2 wend   i = 1 while ( i <= n ) ms(i) = -4 ms(i + 1) = 4 i += 2 wend   print : print " 3.";   while ( cnt < n ) i = 0 i++ while ( i <= n - cnt ) mf(i) = mf(i) * 10 ms(i) = ms(i) * 10 i++ wend   i = ( n - cnt + 1 ) i-- while ( i >= 2 ) temp = 2 * i - 1 fn shift( @mf(i - 1), @mf(i), temp - 2, temp * kf ) fn shift( @ms(i - 1), @ms(i), temp - 2, temp * ks ) i-- wend   nd = 0   fn shift( @nd, @mf(1), 1, 5 ) fn shift( @nd, @ms(1), 1, 239 ) fn xprint( nd )   wend   print : print "Done" fn free( ms ) fn free( mf ) end fn     dim as unsigned long ticks ticks = fn TickCount() // Here we specify the number of decimal places fn Main( 4000 ) ticks = fn TickCount() - ticks print "Elapsed time:" str$( ticks ) " ticks  
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
#Pascal
Pascal
program Pig;   const WinningScore = 100;   type DieRoll = 1..6; Score = integer; Player = record Name: string; Points: score; Victory: Boolean end;   { Assume a 2-player game. } var Player1, Player2: Player;   function RollTheDie: DieRoll; { Return a random number 1 thru 6. } begin RollTheDie := random(6) + 1 end;   procedure TakeTurn (var P: Player); { Play a round of Pig. } var Answer: char; Roll: DieRoll; NewPoints: Score; KeepPlaying: Boolean; begin NewPoints := 0; writeln ; writeln('It''s your turn, ', P.Name, '!'); writeln('So far, you have ', P.Points, ' points in all.'); writeln ; { Keep playing until the user rolls a 1 or chooses not to roll. } write('Do you want to roll the die (y/n)? '); readln(Answer); KeepPlaying := upcase(Answer) = 'Y'; while KeepPlaying do begin Roll := RollTheDie; if Roll = 1 then begin NewPoints := 0; KeepPlaying := false; writeln('Oh no! You rolled a 1! No new points after all.') end else begin NewPoints := NewPoints + Roll; write('You rolled a ', Roll:1, '. '); writeln('That makes ', NewPoints, ' new points so far.'); writeln ; write('Roll again (y/n)? '); readln(Answer); KeepPlaying := upcase(Answer) = 'Y' end end; { Update the player's score and check for a winner. } writeln ; if NewPoints = 0 then writeln(P.Name, ' still has ', P.Points, ' points.') else begin P.Points := P.Points + NewPoints; writeln(P.Name, ' now has ', P.Points, ' points total.'); P.Victory := P.Points >= WinningScore end end;   procedure Congratulate(Winner: Player); begin writeln ; write('Congratulations, ', Winner.Name, '! '); writeln('You won with ', Winner.Points, ' points.'); writeln end;   begin { Greet the players and initialize their data. } writeln('Let''s play Pig!');   writeln ; write('Player 1, what is your name? '); readln(Player1.Name); Player1.Points := 0; Player1.Victory := false;   writeln ; write('Player 2, what is your name? '); readln(Player2.Name); Player2.Points := 0; Player2.Victory := false;   { Take turns until there is a winner. } randomize; repeat TakeTurn(Player1); if not Player1.Victory then TakeTurn(Player2) until Player1.Victory or Player2.Victory;   { Announce the winner. } if Player1.Victory then Congratulate(Player1) else Congratulate(Player2) end.
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.
#Haskell
Haskell
module Pernicious where   isPernicious :: Integer -> Bool isPernicious num = isPrime $ toInteger $ length $ filter ( == 1 ) $ toBinary num   isPrime :: Integer -> Bool isPrime number = divisors number == [1, number] where divisors :: Integer -> [Integer] divisors number = [ m | m <- [1 .. number] , number `mod` m == 0 ]   toBinary :: Integer -> [Integer] toBinary num = reverse $ map ( `mod` 2 ) ( takeWhile ( /= 0 ) $ iterate ( `div` 2 ) num )   solution1 = take 25 $ filter isPernicious [1 ..] solution2 = filter isPernicious [888888877 .. 888888888]
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Lua
Lua
math.randomseed(os.time()) local a = {1,2,3} print(a[math.random(1,#a)])
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Maple
Maple
a := [bear, giraffe, dog, rabbit, koala, lion, fox, deer, pony]: randomNum := rand(1 ..numelems(a)): a[randomNum()];
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
#Maple
Maple
#reverse the string str := "rosetta code phrase reversal": print(StringTools:-Reverse(str)): #reverse each word lst := convert(StringTools:-Split(str, " "), Array): for i to numelems(lst) do lst[i] := StringTools:-Reverse(lst[i]): end do: print(StringTools:-Join(convert(lst,list)," ")): #reverse word order print(StringTools:-Join(ListTools:-Reverse(StringTools:-Split(str," ")), " ")):
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
phrase = "Rosetta Code Phrase Reversal";   reverseWords[phrase_String] := StringJoin @@ Riffle[Reverse@StringSplit@phrase, " "]   reverseLetters[phrase_String] :=   StringJoin @@ Riffle[Map[StringJoin @@ Reverse[Characters@#] &, StringSplit@phrase], " "]   {phrase, reverseWords@phrase, reverseLetters@phrase, reverseWords@reverseLetters@phrase} // TableForm
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
#Julia
Julia
using Printf, Combinatorics   derangements(n::Int) = (perm for perm in permutations(1:n) if all(indx != p for (indx, p) in enumerate(perm)))   function subfact(n::Integer)::Integer if n in (0, 2) return 1 elseif n == 1 return 0 elseif 1 ≤ n ≤ 18 return round(Int, factorial(n) / e) elseif n > 0 return (n - 1) * ( subfact(n - 1) + subfact(n - 2) ) else error() end end   println("Derangements of [1, 2, 3, 4]") for perm in derangements(4) println(perm) end   @printf("\n%5s%13s%13s\n", "n", "derangements", "!n") for n in 1:10 ders = derangements(n) subf = subfact(n) @printf("%5i%13i%13i\n", n, length(collect(ders)), subf) end   println("\n!20 = ", subfact(20))
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#Perl
Perl
  #!perl use strict; use warnings;   # This code uses "Even's Speedup," as described on # the Wikipedia page about the Steinhaus–Johnson– # Trotter algorithm.   # Any resemblance between this code and the Python # code elsewhere on the page is purely a coincidence, # caused by them both implementing the same algorithm.   # The code was written to be read relatively easily # while demonstrating some common perl idioms.   sub perms(&@) { my $callback = shift; my @perm = map [$_, -1], @_; $perm[0][1] = 0;   my $sign = 1; while( ) { $callback->($sign, map $_->[0], @perm); $sign *= -1;   my ($chosen, $index) = (-1, -1); for my $i ( 0 .. $#perm ) { ($chosen, $index) = ($perm[$i][0], $i) if $perm[$i][1] and $perm[$i][0] > $chosen; } return if $index == -1;   my $direction = $perm[$index][1]; my $next = $index + $direction;   @perm[ $index, $next ] = @perm[ $next, $index ];   if( $next <= 0 or $next >= $#perm ) { $perm[$next][1] = 0; } elsif( $perm[$next + $direction][0] > $chosen ) { $perm[$next][1] = 0; }   for my $i ( 0 .. $next - 1 ) { $perm[$i][1] = +1 if $perm[$i][0] > $chosen; } for my $i ( $next + 1 .. $#perm ) { $perm[$i][1] = -1 if $perm[$i][0] > $chosen; } } }   my $n = shift(@ARGV) || 4;   perms { my ($sign, @perm) = @_; print "[", join(", ", @perm), "]"; print $sign < 0 ? " => -1\n" : " => +1\n"; } 1 .. $n;  
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.
#Ruby
Ruby
def statistic(ab, a) sumab, suma = ab.inject(:+).to_f, a.inject(:+).to_f suma / a.size - (sumab - suma) / (ab.size - a.size) end   def permutationTest(a, b) ab = a + b tobs = statistic(ab, a) under = count = 0 ab.combination(a.size) do |perm| under += 1 if statistic(ab, perm) <= tobs count += 1 end under * 100.0 / count end   treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] under = permutationTest(treatmentGroup, controlGroup) puts "under=%.2f%%, over=%.2f%%" % [under, 100 - under]
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#Haskell
Haskell
import Bitmap import Bitmap.Netpbm import Bitmap.RGB   import Control.Monad import Control.Monad.ST import System.Environment (getArgs)   main = do [path1, path2] <- getArgs image1 <- readNetpbm path1 image2 <- readNetpbm path2 diff <- stToIO $ imageDiff image1 image2 putStrLn $ "Difference: " ++ show (100 * diff) ++ "%"   imageDiff :: Image s RGB -> Image s RGB -> ST s Double imageDiff image1 image2 = do i1 <- getPixels image1 i2 <- getPixels image2 unless (length i1 == length i2) $ fail "imageDiff: Images are of different sizes" return $ toEnum (sum $ zipWith minus i1 i2) / toEnum (3 * 255 * length i1) where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) = abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. Task Create an 8 by 8 tiling and print the result. Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U Related tasks Free polyominoes enumeration
#Python
Python
from itertools import product   minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),))   tiles = [] for row in minos: tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift)     def img(seq): b = [[-1]*10 for _ in range(10)]   for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i   vert = ([' |'[row[i] != row[i+1]] for i in range(9)] for row in b) hori = ([' _'[b[i+1][j] != b[i][j]] for j in range(1, 10)] for i in range(9))   return '\n'.join([''.join(a + b for a, b in zip(v, h)) for v, h in zip(vert, hori)])     def tile(board, i, seq=tuple()): if not i: yield img(seq) else: for c in [c for c in tiles[i - 1] if not board & c]: yield from tile(board|c, i - 1, (c,) + seq)   for i in tile(0, len(tiles)): print(i)