task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Perfect_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
#C
C
#include<stdlib.h> #include<stdio.h>   long totient(long n){ long tot = n,i;   for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; }   if(i==2) i=1; }   if(n>1) tot-=tot/n;   return tot; }   long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;   for(m=1;count<n;m++){ tot = m; sum = 0; while(tot != 1){ tot = totient(tot); sum += tot; } if(sum == m) ptList[count++] = m; }   return ptList; }   long main(long argC, char* argV[]) { long *ptList,i,n;   if(argC!=2) printf("Usage : %s <number of perfect Totient numbers required>",argV[0]); else{ n = atoi(argV[1]);   ptList = perfectTotients(n);   printf("The first %d perfect Totient numbers are : \n[",n);   for(i=0;i<n;i++) printf(" %d,",ptList[i]); printf("\b]"); }   return 0; }  
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
#E
E
defmodule Card do defstruct pip: nil, suit: nil end   defmodule Playing_cards do @pips ~w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]a @suits ~w[Clubs Hearts Spades Diamonds]a @pip_value Enum.with_index(@pips) @suit_value Enum.with_index(@suits)   def deal( n_cards, deck ), do: Enum.split( deck, n_cards )   def deal( n_hands, n_cards, deck ) do Enum.reduce(1..n_hands, {[], deck}, fn _,{acc,d} -> {hand, new_d} = deal(n_cards, d) {[hand | acc], new_d} end) end   def deck, do: (for x <- @suits, y <- @pips, do: %Card{suit: x, pip: y})   def print( cards ), do: IO.puts (for x <- cards, do: "\t#{inspect x}")   def shuffle( deck ), do: Enum.shuffle( deck )   def sort_pips( cards ), do: Enum.sort_by( cards, &@pip_value[&1.pip] )   def sort_suits( cards ), do: Enum.sort_by( cards, &(@suit_value[&1.suit]) )   def task do shuffled = shuffle( deck ) {hand, new_deck} = deal( 3, shuffled ) {hands, _deck} = deal( 2, 3, new_deck ) IO.write "Hand:" print( hand ) IO.puts "Hands:" for x <- hands, do: print(x) end end   Playing_cards.task
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
#D
D
import std.stdio, std.conv, std.string;   struct PiDigits { immutable uint nDigits;   int opApply(int delegate(ref string /*chunk of pi digit*/) dg){ // Maximum width for correct output, for type ulong. enum size_t width = 9;   enum ulong scale = 10UL ^^ width; enum ulong initDigit = 2UL * 10UL ^^ (width - 1); enum string formatString = "%0" ~ text(width) ~ "d";   immutable size_t len = 10 * nDigits / 3; auto arr = new ulong[len]; arr[] = initDigit; ulong carry;   foreach (i; 0 .. nDigits / width) { ulong sum; foreach_reverse (j; 0 .. len) { auto quo = sum * (j + 1) + scale * arr[j]; arr[j] = quo % (j*2 + 1); sum = quo / (j*2 + 1); } auto yield = format(formatString, carry + sum/scale); if (dg(yield)) break; carry = sum % scale; } return 0; } }   void main() { foreach (d; PiDigits(100)) writeln(d); }
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | | | |1 H He | | | |2 Li Be B C N O F Ne | | | |3 Na Mg Al Si P S Cl Ar | | | |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr | | | |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe | | | |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn | | | |7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og | |__________________________________________________________________________| | | | | |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu | | | |9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr | |__________________________________________________________________________| Example test cases;   1 -> 1 1   2 -> 1 18   29 -> 4 11   42 -> 5 6   57 -> 8 4   58 -> 8 5   72 -> 6 4   89 -> 9 4 Details; The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3. You may take a look at the atomic number repartitions here. The atomic number is at least 1, at most 118. See also   the periodic table   This task was an idea from CompSciFact   The periodic table in ascii that was used as template
#Python
Python
  def perta(atomic) -> (int, int):   NOBLES = 2, 10, 18, 36, 54, 86, 118 INTERTWINED = 0, 0, 0, 0, 0, 57, 89 INTERTWINING_SIZE = 14 LINE_WIDTH = 18   prev_noble = 0 for row, noble in enumerate(NOBLES): if atomic <= noble: # we are at the good row. We now need to determine the column nb_elem = noble - prev_noble # number of elements on that row rank = atomic - prev_noble # rank of the input element among elements if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE: # lantanides or actinides row += 2 col = rank + 1 else: # not a lantanide nor actinide # handle empty spaces between 1-2, 4-5 and 12-13. nb_empty = LINE_WIDTH - nb_elem # spaces count as columns inside_left_element_rank = 2 if noble > 2 else 1 col = rank + (nb_empty if rank > inside_left_element_rank else 0) break prev_noble = noble return row+1, col       # small test suite   TESTS = { 1: (1, 1), 2: (1, 18), 29: (4,11), 42: (5, 6), 58: (8, 5), 59: (8, 6), 57: (8, 4), 71: (8, 18), 72: (6, 4), 89: (9, 4), 90: (9, 5), 103: (9, 18), }   for input, out in TESTS.items(): found = perta(input) print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))    
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
#Julia
Julia
  type PigPlayer name::String score::Int strat::Function end   function PigPlayer(a::String) PigPlayer(a, 0, pig_manual) end   function scoreboard(pps::Array{PigPlayer,1}) join(map(x->@sprintf("%s has %d", x.name, x.score), pps), " | ") end   function pig_manual(pps::Array{PigPlayer,1}, pdex::Integer, pot::Integer) pname = pps[pdex].name print(pname, " there is ", @sprintf("%3d", pot), " in the pot. ") print("<ret> to continue rolling? ") return chomp(readline()) == "" end   function pig_round(pps::Array{PigPlayer,1}, pdex::Integer) pot = 0 rcnt = 0 while pps[pdex].strat(pps, pdex, pot) rcnt += 1 roll = rand(1:6) if roll == 1 return (0, rcnt, false) else pot += roll end end return (pot, rcnt, true) end   function pig_game(pps::Array{PigPlayer,1}, winscore::Integer=100) pnum = length(pps) pdex = pnum println("Playing a game of Pig the Dice.") while(pps[pdex].score < winscore) pdex = rem1(pdex+1, pnum) println(scoreboard(pps)) println(pps[pdex].name, " is now playing.") (pot, rcnt, ispotwon) = pig_round(pps, pdex) print(pps[pdex].name, " played ", rcnt, " rolls ") if ispotwon println("and scored ", pot, " points.") pps[pdex].score += pot else println("and butsted.") end end println(pps[pdex].name, " won, scoring ", pps[pdex].score, " points.") end   pig_game([PigPlayer("Alice"), PigPlayer("Bob")])  
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.
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make -- Test of is_pernicious_number. local test: LINKED_LIST [INTEGER] i: INTEGER do create test.make from i := 1 until test.count = 25 loop if is_pernicious_number (i) then test.extend (i) end i := i + 1 end across test as t loop io.put_string (t.item.out + " ") end io.new_line across 888888877 |..| 888888888 as c loop if is_pernicious_number (c.item) then io.put_string (c.item.out + " ") end end end   is_pernicious_number (n: INTEGER): BOOLEAN -- Is 'n' a pernicious_number? require positiv_input: n > 0 do Result := is_prime (count_population (n)) end   feature{NONE}   count_population (n: INTEGER): INTEGER -- Population count of 'n'. require positiv_input: n > 0 local j: INTEGER math: DOUBLE_MATH do create math j := math.log_2 (n).ceiling + 1 across 0 |..| j as c loop if n.bit_test (c.item) then Result := Result + 1 end end end   is_prime (n: INTEGER): BOOLEAN --Is 'n' a prime number? require positiv_input: n > 0 local i: INTEGER max: REAL_64 math: DOUBLE_MATH do create math if n = 2 then Result := True elseif n <= 1 or n \\ 2 = 0 then Result := False else Result := True max := math.sqrt (n) from i := 3 until i > max loop if n \\ i = 0 then Result := False end i := i + 2 end end end   end  
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
Permutations/Rank of a permutation
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers 0.. ( n − 1 ) {\displaystyle 0..(n-1)} . For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank: PERMUTATION RANK (0, 1, 2, 3) -> 0 (0, 1, 3, 2) -> 1 (0, 2, 1, 3) -> 2 (0, 2, 3, 1) -> 3 (0, 3, 1, 2) -> 4 (0, 3, 2, 1) -> 5 (1, 0, 2, 3) -> 6 (1, 0, 3, 2) -> 7 (1, 2, 0, 3) -> 8 (1, 2, 3, 0) -> 9 (1, 3, 0, 2) -> 10 (1, 3, 2, 0) -> 11 (2, 0, 1, 3) -> 12 (2, 0, 3, 1) -> 13 (2, 1, 0, 3) -> 14 (2, 1, 3, 0) -> 15 (2, 3, 0, 1) -> 16 (2, 3, 1, 0) -> 17 (3, 0, 1, 2) -> 18 (3, 0, 2, 1) -> 19 (3, 1, 0, 2) -> 20 (3, 1, 2, 0) -> 21 (3, 2, 0, 1) -> 22 (3, 2, 1, 0) -> 23 Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above). One use of such algorithms could be in generating a small, random, sample of permutations of n {\displaystyle n} items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n {\displaystyle n} items is given by n ! {\displaystyle n!} which grows large very quickly: A 32 bit integer can only hold 12 ! {\displaystyle 12!} , a 64 bit integer only 20 ! {\displaystyle 20!} . It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them. A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items. Task Create a function to generate a permutation from a rank. Create the inverse function that given the permutation generates its rank. Show that for n = 3 {\displaystyle n=3} the two functions are indeed inverses of each other. Compute and show here 4 random, individual, samples of permutations of 12 objects. Stretch goal State how reasonable it would be to use your program to address the limits of the Stack Overflow question. References Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here). Ranks on the DevData site. Another answer on Stack Overflow to a different question that explains its algorithm in detail. Related tasks Factorial_base_numbers_indexing_permutations_of_a_collection
#Tcl
Tcl
# A functional swap routine proc swap {v idx1 idx2} { lset v $idx2 [lindex $v $idx1][lset v $idx1 [lindex $v $idx2];subst ""] }   # Fill the integer array <vec> with the permutation at rank <rank> proc computePermutation {vecName rank} { upvar 1 $vecName vec if {![info exist vec] || ![llength $vec]} return set N [llength $vec] for {set n 0} {$n < $N} {incr n} {lset vec $n $n} for {set n $N} {$n>=1} {incr n -1} { set r [expr {$rank % $n}] set rank [expr {$rank / $n}] set vec [swap $vec $r [expr {$n-1}]] } }   # Return the rank of the current permutation. proc computeRank {vec} { if {![llength $vec]} return set inv [lrepeat [llength $vec] 0] set i -1 foreach v $vec {lset inv $v [incr i]} # First argument is lambda term set mrRank1 {{f n vec inv} { if {$n < 2} {return 0} set s [lindex $vec [set n1 [expr {$n - 1}]]] set vec [swap $vec $n1 [lindex $inv $n1]] set inv [swap $inv $s $n1] return [expr {$s + $n * [apply $f $f $n1 $vec $inv]}] }} return [apply $mrRank1 $mrRank1 [llength $vec] $vec $inv] }
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
#Python
Python
import random   # Copied from https://rosettacode.org/wiki/Miller-Rabin_primality_test#Python def is_Prime(n): """ Miller-Rabin primality test.   A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. """ if n!=int(n): return False n=int(n) #Miller-Rabin test for prime if n==0 or n==1 or n==4 or n==6 or n==8 or n==9: return False   if n==2 or n==3 or n==5 or n==7: return True s = 0 d = n-1 while d%2==0: d>>=1 s+=1 assert(2**s * d == n-1)   def trial_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True   for i in range(8):#number of trials a = random.randrange(2, n) if trial_composite(a): return False   return True   def pierpont(ulim, vlim, first): p = 0 p2 = 1 p3 = 1 pp = [] for v in xrange(vlim): for u in xrange(ulim): p = p2 * p3 if first: p = p + 1 else: p = p - 1 if is_Prime(p): pp.append(p) p2 = p2 * 2 p3 = p3 * 3 p2 = 1 pp.sort() return pp   def main(): print "First 50 Pierpont primes of the first kind:" pp = pierpont(120, 80, True) for i in xrange(50): print "%8d " % pp[i], if (i - 9) % 10 == 0: print print "First 50 Pierpont primes of the second kind:" pp2 = pierpont(120, 80, False) for i in xrange(50): print "%8d " % pp2[i], if (i - 9) % 10 == 0: print print "250th Pierpont prime of the first kind:", pp[249] print "250th Pierpont prime of the second kind:", pp2[249]   main()
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Gambas
Gambas
Public Sub Main() Dim sList As String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]   Print sList[Rand(0, 11)]   End
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#GAP
GAP
a := [2, 9, 4, 7, 5, 3]; Random(a);
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#VBScript
VBScript
Function IsPrime(n) If n = 2 Then IsPrime = True ElseIf n <= 1 Or n Mod 2 = 0 Then IsPrime = False Else IsPrime = True For i = 3 To Int(Sqr(n)) Step 2 If n Mod i = 0 Then IsPrime = False Exit For End If Next End If End Function   For n = 1 To 50 If IsPrime(n) Then WScript.StdOut.Write n & " " End If Next
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
#Go
Go
package main   import ( "fmt" "strings" )   const phrase = "rosetta code phrase reversal"   func revStr(s string) string { rs := make([]rune, len(s)) i := len(s) for _, r := range s { i-- rs[i] = r } return string(rs[i:]) }   func main() { fmt.Println("Reversed: ", revStr(phrase))   ws := strings.Fields(phrase) for i, w := range ws { ws[i] = revStr(w) } fmt.Println("Words reversed: ", strings.Join(ws, " "))   ws = strings.Fields(phrase) last := len(ws) - 1 for i, w := range ws[:len(ws)/2] { ws[i], ws[last-i] = ws[last-i], w } fmt.Println("Word order reversed:", strings.Join(ws, " ")) }
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
#Elixir
Elixir
defmodule Permutation do def derangements(n) do list = Enum.to_list(1..n) Enum.filter(permutation(list), fn perm -> Enum.zip(list, perm) |> Enum.all?(fn {a,b} -> a != b end) end) end   def subfact(0), do: 1 def subfact(1), do: 0 def subfact(n), do: (n-1) * (subfact(n-1) + subfact(n-2))   def permutation([]), do: [[]] def permutation(list) do for x <- list, y <- permutation(list -- [x]), do: [x|y] end end   IO.puts "derangements for n = 4" Enum.each(Permutation.derangements(4), &IO.inspect &1)   IO.puts "\nNumber of derangements" IO.puts " n derange subfact" Enum.each(0..9, fn n ->  :io.format "~2w :~9w,~9w~n", [n, length(Permutation.derangements(n)), Permutation.subfact(n)] end) Enum.each(10..20, fn n ->  :io.format "~2w :~19w~n", [n, Permutation.subfact(n)] end)
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
#Forth
Forth
S" fsl-util.fs" REQUIRED S" fsl/dynmem.seq" REQUIRED   cell darray p{   : sgn DUP 0 > IF DROP 1 ELSE 0 < IF -1 ELSE 0 THEN THEN ; : arr-swap {: addr1 addr2 | tmp -- :} addr1 @ TO tmp addr2 @ addr1 ! tmp addr2 ! ; : perms {: n xt | my-i k s -- :} & p{ n 1+ }malloc malloc-fail? ABORT" perms :: out of memory" 0 p{ 0 } ! n 1+ 1 DO I NEGATE p{ I } ! LOOP 1 TO s BEGIN 1 n 1+ DO p{ I } @ ABS -1 +LOOP n 1+ s xt EXECUTE 0 TO k n 1+ 2 DO p{ I } @ 0 < ( flag ) p{ I } @ ABS p{ I 1- } @ ABS > ( flag flag ) p{ I } @ ABS p{ k } @ ABS > ( flag flag flag ) AND AND IF I TO k THEN LOOP n 1 DO p{ I } @ 0 > ( flag ) p{ I } @ ABS p{ I 1+ } @ ABS > ( flag flag ) p{ I } @ ABS p{ k } @ ABS > ( flag flag flag ) AND AND IF I TO k THEN LOOP k IF n 1+ 1 DO p{ I } @ ABS p{ k } @ ABS > IF p{ I } @ NEGATE p{ I } ! THEN LOOP p{ k } @ sgn k + TO my-i p{ k } p{ my-i } arr-swap s NEGATE TO s THEN k 0 = UNTIL ; : .perm ( p0 p1 p2 ... pn n s ) >R ." Perm: [ " 1 DO . SPACE LOOP R> ." ] Sign: " . CR ;   3 ' .perm perms CR 4 ' .perm perms
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
#FreeBASIC
FreeBASIC
' version 31-03-2017 ' compile with: fbc -s console   Sub perms(n As ULong)   Dim As Long p(n), i, k, s = 1   For i = 1 To n p(i) = -i Next   Do Print "Perm: [ "; For i = 1 To n Print Abs(p(i)); " "; Next Print "] Sign: "; s   k = 0 For i = 2 To n If p(i) < 0 Then If Abs(p(i)) > Abs(p(i -1)) Then If Abs(p(i)) > Abs(p(k)) Then k = i End If End If Next   For i = 1 To n -1 If p(i) > 0 Then If Abs(p(i)) > Abs(p(i +1)) Then If Abs(p(i)) > Abs(p(k)) Then k = i End If End If Next   If k Then For i = 1 To n If Abs(p(i)) > Abs(p(k)) Then p(i) = -p(i) Next i = k + Sgn(p(k)) Swap p(k), p(i) s = -s End If   Loop Until k = 0   End Sub   ' ------=< MAIN >=------   perms(3) print perms(4)   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End  
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.
#J
J
require'stats' trmt=: 0.85 0.88 0.75 0.66 0.25 0.29 0.83 0.39 0.97 ctrl=: 0.68 0.41 0.1 0.49 0.16 0.65 0.32 0.92 0.28 0.98 difm=: -&mean result=: trmt difm ctrl all=: trmt(#@[ ({. difm }.) |:@([ (comb ~.@,"1 i.@])&# ,) { ,) ctrl smoutput 'under: ','%',~":100*mean all <: result smoutput 'over: ','%',~":100*mean all > result
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.
#Java
Java
public class PermutationTest { private static final int[] data = new int[]{ 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };   private static int pick(int at, int remain, int accu, int treat) { if (remain == 0) return (accu > treat) ? 1 : 0; return pick(at - 1, remain - 1, accu + data[at - 1], treat) + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0); }   public static void main(String[] args) { int treat = 0; double total = 1.0; for (int i = 0; i <= 8; ++i) { treat += data[i]; } for (int i = 19; i >= 11; --i) { total *= i; } for (int i = 9; i >= 1; --i) { total /= i; } int gt = pick(19, 9, 0, treat); int le = (int) (total - gt); System.out.printf("<= : %f%%  %d\n", 100.0 * le / total, le); System.out.printf(" > : %f%%  %d\n", 100.0 * gt / total, gt); } }
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#Ada
Ada
type Count is mod 2**64;
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.
#D
D
import std.stdio, std.algorithm, std.random, std.math, std.array, std.range, std.ascii;   alias Cell = ubyte; alias Grid = Cell[][]; enum Cell notClustered = 1; // Filled cell, but not in a cluster.   Grid initialize(Grid grid, in double prob, ref Xorshift rng) nothrow { foreach (row; grid) foreach (ref cell; row) cell = Cell(rng.uniform01 < prob); return grid; }   void show(in Grid grid) { immutable static cell2char = " #" ~ letters; writeln('+', "-".replicate(grid.length), '+'); foreach (row; grid) { write('|'); row.map!(c => c < cell2char.length ? cell2char[c] : '@').write; writeln('|'); } writeln('+', "-".replicate(grid.length), '+'); }   size_t countClusters(bool justCount=false)(Grid grid) pure nothrow @safe @nogc { immutable side = grid.length; static if (justCount) enum Cell clusterID = 2; else Cell clusterID = 1;   void walk(in size_t r, in size_t c) nothrow @safe @nogc { grid[r][c] = clusterID; // Fill grid.   if (r < side - 1 && grid[r + 1][c] == notClustered) // Down. walk(r + 1, c); if (c < side - 1 && grid[r][c + 1] == notClustered) // Right. walk(r, c + 1); if (c > 0 && grid[r][c - 1] == notClustered) // Left. walk(r, c - 1); if (r > 0 && grid[r - 1][c] == notClustered) // Up. walk(r - 1, c); }   size_t nClusters = 0;   foreach (immutable r; 0 .. side) foreach (immutable c; 0 .. side) if (grid[r][c] == notClustered) { static if (!justCount) clusterID++; nClusters++; walk(r, c); } return nClusters; }   double clusterDensity(Grid grid, in double prob, ref Xorshift rng) { return grid.initialize(prob, rng).countClusters!true / double(grid.length ^^ 2); }   void showDemo(in size_t side, in double prob, ref Xorshift rng) { auto grid = new Grid(side, side); grid.initialize(prob, rng); writefln("Found %d clusters in this %d by %d grid:\n", grid.countClusters, side, side); grid.show; }   void main() { immutable prob = 0.5; immutable nIters = 5; auto rng = Xorshift(unpredictableSeed);   showDemo(15, prob, rng); writeln; foreach (immutable i; iota(4, 14, 2)) { immutable side = 2 ^^ i; auto grid = new Grid(side, side); immutable density = nIters .iota .map!(_ => grid.clusterDensity(prob, rng)) .sum / nIters; writefln("n_iters=%3d, p=%4.2f, n=%5d, sim=%7.8f", nIters, prob, side, density); } }
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.
#360_Assembly
360 Assembly
* Perfect numbers 15/05/2016 PERFECTN CSECT USING PERFECTN,R13 prolog SAVEAREA B STM-SAVEAREA(R15) " DC 17F'0' " STM STM R14,R12,12(R13) " ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 " LA R6,2 i=2 LOOPI C R6,NN do i=2 to nn BH ELOOPI LR R1,R6 i BAL R14,PERFECT LTR R0,R0 if perfect(i) BZ NOTPERF XDECO R6,PG edit i XPRNT PG,L'PG print i NOTPERF LA R6,1(R6) i=i+1 B LOOPI ELOOPI L R13,4(0,R13) epilog LM R14,R12,12(R13) " XR R15,R15 " BR R14 exit PERFECT SR R9,R9 function perfect(n); sum=0 LA R7,1 j LR R8,R1 n SRA R8,1 n/2 LOOPJ CR R7,R8 do j=1 to n/2 BH ELOOPJ LR R4,R1 n SRDA R4,32 DR R4,R7 n/j LTR R4,R4 if mod(n,j)=0 BNZ NOTMOD AR R9,R7 sum=sum+j NOTMOD LA R7,1(R7) j=j+1 B LOOPJ ELOOPJ SR R0,R0 r0=false CR R9,R1 if sum=n BNE NOTEQ BCTR R0,0 r0=true NOTEQ BR R14 return(r0); end perfect NN DC F'10000' PG DC CL12' ' buffer YREGS END PERFECTN
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   // cell states #define FILL 1 #define RWALL 2 // right wall #define BWALL 4 // bottom wall   typedef unsigned int c_t;   c_t *cells, *start, *end; int m, n;   void make_grid(double p, int x, int y) { int i, j, thresh = RAND_MAX * p; m = x, n = y;   // Allocate two addition rows to avoid checking bounds. // Bottom row is also required by drippage start = realloc(start, m * (n + 2) * sizeof(c_t)); cells = start + m;   for (i = 0; i < m; i++) start[i] = BWALL | RWALL;   for (i = 0, end = cells; i < y; i++) { for (j = x; --j; ) *end++ = (rand() < thresh ? BWALL : 0) |(rand() < thresh ? RWALL : 0); *end++ = RWALL | (rand() < thresh ? BWALL: 0); } memset(end, 0, sizeof(c_t) * m); }   void show_grid(void) { int i, j;   for (j = 0; j < m; j++) printf("+--"); puts("+");   for (i = 0; i <= n; i++) { putchar(i == n ? ' ' : '|'); for (j = 0; j < m; j++) { printf((cells[i*m + j] & FILL) ? "[]" : " "); putchar((cells[i*m + j] & RWALL) ? '|' : ' '); } putchar('\n');   if (i == n) return;   for (j = 0; j < m; j++) printf((cells[i*m + j] & BWALL) ? "+--" : "+ "); puts("+"); } }   int fill(c_t *p) { if ((*p & FILL)) return 0; *p |= FILL; if (p >= end) return 1; // success: reached bottom row   return ( !(p[ 0] & BWALL) && fill(p + m) ) || ( !(p[ 0] & RWALL) && fill(p + 1) ) || ( !(p[-1] & RWALL) && fill(p - 1) ) || ( !(p[-m] & BWALL) && fill(p - m) ); }   int percolate(void) { int i; for (i = 0; i < m && !fill(cells + i); i++);   return i < m; }   int main(void) { make_grid(.5, 10, 10); percolate(); show_grid();   int cnt, i, p;   puts("\nrunning 10x10 grids 10000 times for each p:"); for (p = 1; p < 10; p++) { for (cnt = i = 0; i < 10000; i++) { make_grid(p / 10., 10, 10); cnt += percolate(); //show_grid(); // don't } printf("p = %3g: %.4f\n", p / 10., (double)cnt / i); }   free(start); return 0; }
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\displaystyle v} be a vector of n {\displaystyle n} values of either 1 or 0 where the probability of any value being 1 is p {\displaystyle p} ; the probability of a value being 0 is therefore 1 − p {\displaystyle 1-p} . Define a run of 1s as being a group of consecutive 1s in the vector bounded either by the limits of the vector or by a 0. Let the number of such runs in a given vector of length n {\displaystyle n} be R n {\displaystyle R_{n}} . For example, the following vector has R 10 = 3 {\displaystyle R_{10}=3} [1 1 0 0 0 1 0 1 1 1] ^^^ ^ ^^^^^ Percolation theory states that K ( p ) = lim n → ∞ R n / n = p ( 1 − p ) {\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)} Task Any calculation of R n / n {\displaystyle R_{n}/n} for finite n {\displaystyle n} is subject to randomness so should be computed as the average of t {\displaystyle t} runs, where t ≥ 100 {\displaystyle t\geq 100} . For values of p {\displaystyle p} of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying n {\displaystyle n} on the accuracy of simulated K ( p ) {\displaystyle K(p)} . Show your output here. See also s-Run on Wolfram mathworld.
#EchoLisp
EchoLisp
  ;; count 1-runs - The vector is not stored (define (runs p n) (define ct 0) (define run-1 #t) (for ([i n]) (if (< (random) p) (set! run-1 #t) ;; 0 case (begin ;; 1 case (when run-1 (set! ct (1+ ct))) (set! run-1 #f)))) (// ct n))   ;; mean of t counts (define (truns p (n 1000 ) (t 1000)) (// (for/sum ([i t]) (runs p n)) t))   (define (task) (for ([p (in-range 0.1 1.0 0.2)]) (writeln) (writeln '🔸 'p p 'Kp (* p (- 1 p))) (for ([n '(10 100 1000)]) (printf "\t-- n %5d →  %d" n (truns p n)))))  
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.
#FreeBASIC
FreeBASIC
#define SOLID "#" #define EMPTY " " #define WET "v"   Dim Shared As String grid() Dim Shared As Integer last, lastrow, m, n   Sub make_grid(x As Integer, y As Integer, p As Double) m = x n = y Redim Preserve grid(x*(y+1)+1) last = Len(grid) Dim As Integer lastrow = last-n Dim As Integer i, j   For i = 0 To x-1 For j = 1 To y grid(1+i*(y+1)+j) = Iif(Rnd < p, EMPTY, SOLID) Next j Next i End Sub   Function ff(i As Integer) As Boolean If i <= 0 Or i >= last Or grid(i) <> EMPTY Then Return 0 grid(i) = WET Return i >= lastrow Or (ff(i+m+1) Or ff(i+1) Or ff(i-1) Or ff(i-m-1)) End Function   Function percolate() As Integer For i As Integer = 2 To m+1 If ff(i) Then Return 1 Next i Return 0 End Function   Dim As Double p Dim As Integer ip, i, cont   make_grid(15, 15, 0.55) Print "15x15 grid:" For i = 1 To Ubound(grid) Print grid(i); If i Mod 15 = 0 Then Print Next i   Print !"\nrunning 10,000 tests for each case:" For ip As Ubyte = 0 To 10 p = ip / 10 cont = 0 For i = 1 To 10000 make_grid(15, 15, p) cont += percolate() Next i Print Using "p=#.#: #.####"; p; cont/10000 Next ip Sleep
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
#ABAP
ABAP
data: lv_flag type c, lv_number type i, lt_numbers type table of i.   append 1 to lt_numbers. append 2 to lt_numbers. append 3 to lt_numbers.   do. perform permute using lt_numbers changing lv_flag. if lv_flag = 'X'. exit. endif. loop at lt_numbers into lv_number. write (1) lv_number no-gap left-justified. if sy-tabix <> '3'. write ', '. endif. endloop. skip. enddo.   " Permutation function - this is used to permute: " Can be used for an unbounded size set. form permute using iv_set like lt_numbers changing ev_last type c. data: lv_len type i, lv_first type i, lv_third type i, lv_count type i, lv_temp type i, lv_temp_2 type i, lv_second type i, lv_changed type c, lv_perm type i. describe table iv_set lines lv_len.   lv_perm = lv_len - 1. lv_changed = ' '. " Loop backwards through the table, attempting to find elements which " can be permuted. If we find one, break out of the table and set the " flag indicating a switch. do. if lv_perm <= 0. exit. endif. " Read the elements. read table iv_set index lv_perm into lv_first. add 1 to lv_perm. read table iv_set index lv_perm into lv_second. subtract 1 from lv_perm. if lv_first < lv_second. lv_changed = 'X'. exit. endif. subtract 1 from lv_perm. enddo.   " Last permutation. if lv_changed <> 'X'. ev_last = 'X'. exit. endif.   " Swap tail decresing to get a tail increasing. lv_count = lv_perm + 1. do. lv_first = lv_len + lv_perm - lv_count + 1. if lv_count >= lv_first. exit. endif.   read table iv_set index lv_count into lv_temp. read table iv_set index lv_first into lv_temp_2. modify iv_set index lv_count from lv_temp_2. modify iv_set index lv_first from lv_temp. add 1 to lv_count. enddo.   lv_count = lv_len - 1. do. if lv_count <= lv_perm. exit. endif.   read table iv_set index lv_count into lv_first. read table iv_set index lv_perm into lv_second. read table iv_set index lv_len into lv_third. if ( lv_first < lv_third ) and ( lv_first > lv_second ). lv_len = lv_count. endif.   subtract 1 from lv_count. enddo.   read table iv_set index lv_perm into lv_temp. read table iv_set index lv_len into lv_temp_2. modify iv_set index lv_perm from lv_temp_2. modify iv_set index lv_len from lv_temp. endform.
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
#APL
APL
faro ← ∊∘⍉(2,2÷⍨≢)⍴⊢ count ← {⍺←⍵ ⋄ ⍺≡r←⍺⍺ ⍵:1 ⋄ 1+⍺∇r} (⊢,[1.5] (faro count ⍳)¨) 8 24 52 100 1020 1024 10000
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#Arturo
Arturo
perfectShuffle: function [deckSize][ deck: 1..deckSize original: new deck halfDeck: deckSize/2   i: 1 while [true][ deck: flatten couple first.n: halfDeck deck last.n: halfDeck deck if deck = original -> return i i: i+1 ] ]   loop [8 24 52 100 1020 1024 10000] 's -> print [ pad.right join @["Perfect shuffles required for deck size " to :string s ":"] 48 perfectShuffle s ]
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.
#Fortran
Fortran
  PROGRAM PERLIN IMPLICIT NONE INTEGER :: i INTEGER, DIMENSION(0:511) :: p INTEGER, DIMENSION(0:255), PARAMETER :: 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/)   DO i=0, 255 p(i) = permutation(i) p(256+i) = permutation(i) END DO   WRITE(*,"(F19.17)") NOISE(3.14d0, 42d0, 7d0)   CONTAINS   DOUBLE PRECISION FUNCTION NOISE(x_in, y_in, z_in) DOUBLE PRECISION, INTENT(IN) :: x_in, y_in, z_in DOUBLE PRECISION :: x, y, z INTEGER :: xx, yy, zz, a, aa, ab, b, ba, bb DOUBLE PRECISION :: u, v, w   x = x_in y = y_in z = z_in   xx = IAND(FLOOR(x), 255) yy = IAND(FLOOR(y), 255) zz = IAND(FLOOR(z), 255)   x = x - FLOOR(x) y = y - FLOOR(y) z = z - FLOOR(z)   u = FADE(x) v = FADE(y) w = FADE(z)   a = p(xx) + yy aa = p(a) + zz ab = p(a+1) + zz b = p(xx+1) + yy ba = p(b) + zz bb = p(b+1) + zz   NOISE = 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)))) END FUNCTION     DOUBLE PRECISION FUNCTION FADE(t) DOUBLE PRECISION, INTENT(IN) :: t   FADE = t ** 3 * (t * ( t * 6 - 15) + 10) END FUNCTION     DOUBLE PRECISION FUNCTION LERP(t, a, b) DOUBLE PRECISION, INTENT(IN) :: t, a, b   LERP = a + t * (b - a) END FUNCTION     DOUBLE PRECISION FUNCTION GRAD(hash, x, y, z) INTEGER, INTENT(IN) :: hash DOUBLE PRECISION, INTENT(IN) :: x, y, z INTEGER :: h DOUBLE PRECISION :: u, v   h = IAND(hash, 15)   u = MERGE(x, y, h < 8)   v = MERGE(y, MERGE(x, z, h == 12 .OR. h == 14), h < 4)   GRAD = MERGE(u, -u, IAND(h, 1) == 0) + MERGE(v, -v, IAND(h, 2) == 0) END FUNCTION     END PROGRAM  
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
#C.2B.2B
C++
#include <cassert> #include <iostream> #include <vector>   class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; };   bool perfect_totient_number(const totient_calculator& tc, int n) { int sum = 0; for (int m = n; m > 1; ) { int t = tc.totient(m); sum += t; m = t; } return sum == n; }   int main() { totient_calculator tc(10000); int count = 0, n = 1; std::cout << "First 20 perfect totient numbers:\n"; for (; count < 20; ++n) { if (perfect_totient_number(tc, n)) { if (count > 0) std::cout << ' '; ++count; std::cout << n; } } std::cout << '\n'; return 0; }
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
#Elixir
Elixir
defmodule Card do defstruct pip: nil, suit: nil end   defmodule Playing_cards do @pips ~w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]a @suits ~w[Clubs Hearts Spades Diamonds]a @pip_value Enum.with_index(@pips) @suit_value Enum.with_index(@suits)   def deal( n_cards, deck ), do: Enum.split( deck, n_cards )   def deal( n_hands, n_cards, deck ) do Enum.reduce(1..n_hands, {[], deck}, fn _,{acc,d} -> {hand, new_d} = deal(n_cards, d) {[hand | acc], new_d} end) end   def deck, do: (for x <- @suits, y <- @pips, do: %Card{suit: x, pip: y})   def print( cards ), do: IO.puts (for x <- cards, do: "\t#{inspect x}")   def shuffle( deck ), do: Enum.shuffle( deck )   def sort_pips( cards ), do: Enum.sort_by( cards, &@pip_value[&1.pip] )   def sort_suits( cards ), do: Enum.sort_by( cards, &(@suit_value[&1.suit]) )   def task do shuffled = shuffle( deck ) {hand, new_deck} = deal( 3, shuffled ) {hands, _deck} = deal( 2, 3, new_deck ) IO.write "Hand:" print( hand ) IO.puts "Hands:" for x <- hands, do: print(x) end end   Playing_cards.task
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
#Delphi
Delphi
  unit Pi_BBC_Main;   interface   uses Classes, Controls, Forms, Dialogs, StdCtrls;   type TForm1 = class(TForm) btnRunSpigotAlgo: TButton; memScreen: TMemo; procedure btnRunSpigotAlgoClick(Sender: TObject); procedure FormCreate(Sender: TObject); private fScreenWidth : integer; fLineBuffer : string; procedure ClearText(); procedure AddText( const s : string); procedure FlushText(); end;   var Form1: TForm1;   implementation   {$R *.dfm}   uses SysUtils;   // Button clicked to run algorithm procedure TForm1.btnRunSpigotAlgoClick(Sender: TObject); var // BBC Basic variables. Delphi longint is 32 bits. B : array of longint; A, C, D, E, I, L, M, P : longint; // Added for Delphi version temp : string; h, j, t : integer; begin fScreenWidth := 80; ClearText(); M := 5368709; // floor( (2^31 - 1)/400 )   // DIM B%(M%) in BBC Basic declares an array [0..M%], i.e. M% + 1 elements SetLength( B, M + 1); for I := 0 to M do B[I] := 20; E := 0; L := 2;   // FOR C% = M% TO 14 STEP -7 // In Delphi (or at least Delphi 7) the step size in a for loop has to be 1. // So the BBC Basic FOR loop has been replaced by a repeat loop. C := M; repeat D := 0; A := C*2 - 1; for P := C downto 1 do begin D := D*P + B[P]*$64; // hex notation copied from BBC version B[P] := D mod A; D := D div A; dec( A, 2); end;   // The BBC CASE statement here amounts to a series of if ... else if (D = 99) then begin E := E*100 + D; inc( L, 2); end else if (C = M) then begin AddText( SysUtils.Format( '%2.1f', [1.0*(D div 100) / 10.0] )); E := D mod 100; end else begin // PRINT RIGHT$(STRING$(L%,"0") + STR$(E% + D% DIV 100),L%); // This can't be done so concisely in Delphi 7 SetLength( temp, L); for j := 1 to L do temp[j] := '0'; temp := temp + SysUtils.IntToStr( E + D div 100); t := Length( temp); AddText( Copy( temp, t - L + 1, L)); E := D mod 100; L := 2; end; dec( C, 7); until (C < 14); FlushText();   // Delphi addition: Write screen output to a file for checking h := SysUtils.FileCreate( 'C:\Delphi\PiDigits.txt'); // h = file handle for j := 0 to memScreen.Lines.Count - 1 do SysUtils.FileWrite( h, memScreen.Lines[j][1], Length( memScreen.Lines[j])); SysUtils.FileClose( h); end;   {=========================== Auxiliary routines ===========================}   // Form created procedure TForm1.FormCreate(Sender: TObject); begin fScreenWidth := 80; // in case not set by the algotithm ClearText(); end;   // This Delphi version builds each screen line in a buffer and puts // the line into the TMemo when the buffer is full. // This is faster than writing to the TMemo a few characters at a time, // but note that the buffer must be flushed at the end of the program. procedure TForm1.ClearText(); begin memScreen.Lines.Clear(); fLineBuffer := ''; end;   procedure TForm1.AddText( const s : string); var nrChars, nrLeft : integer; begin nrChars := Length( s); nrLeft := fScreenWidth - Length( fLineBuffer); // nr chars left in line if (nrChars <= nrLeft) then fLineBuffer := fLineBuffer + s else begin fLineBuffer := fLineBuffer + Copy( s, 1, nrLeft); memScreen.Lines.Add( fLineBuffer); fLineBuffer := Copy( s, nrLeft + 1, nrChars - nrLeft); end; end;   procedure TForm1.FlushText(); begin if (Length(fLineBuffer) > 0) then begin memScreen.Lines.Add( fLineBuffer); fLineBuffer := ''; end; end;   end.  
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | | | |1 H He | | | |2 Li Be B C N O F Ne | | | |3 Na Mg Al Si P S Cl Ar | | | |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr | | | |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe | | | |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn | | | |7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og | |__________________________________________________________________________| | | | | |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu | | | |9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr | |__________________________________________________________________________| Example test cases;   1 -> 1 1   2 -> 1 18   29 -> 4 11   42 -> 5 6   57 -> 8 4   58 -> 8 5   72 -> 6 4   89 -> 9 4 Details; The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3. You may take a look at the atomic number repartitions here. The atomic number is at least 1, at most 118. See also   the periodic table   This task was an idea from CompSciFact   The periodic table in ascii that was used as template
#Raku
Raku
my $b = 18; my @offset = 16, 10, 10, (2×$b)+1, (-2×$b)-15, (2×$b)+1, (-2×$b)-15; my @span = flat ^8 Zxx <1 3 8 44 15 17 15 15>;   for <1 2 29 42 57 58 72 89 90 103> -> $n { printf "%3d: %2d, %2d\n", $n, map {$_+1}, ($n-1 + [+] @offset.head(@span[$n-1])).polymod($b).reverse; }
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | | | |1 H He | | | |2 Li Be B C N O F Ne | | | |3 Na Mg Al Si P S Cl Ar | | | |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr | | | |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe | | | |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn | | | |7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og | |__________________________________________________________________________| | | | | |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu | | | |9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr | |__________________________________________________________________________| Example test cases;   1 -> 1 1   2 -> 1 18   29 -> 4 11   42 -> 5 6   57 -> 8 4   58 -> 8 5   72 -> 6 4   89 -> 9 4 Details; The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3. You may take a look at the atomic number repartitions here. The atomic number is at least 1, at most 118. See also   the periodic table   This task was an idea from CompSciFact   The periodic table in ascii that was used as template
#Wren
Wren
import "./fmt" for Fmt   var limits = [3..10, 11..18, 19..36, 37..54, 55..86, 87..118]   var periodicTable = Fn.new { |n| if (n < 1 || n > 118) Fiber.abort("Atomic number is out of range.") if (n == 1) return [1, 1] if (n == 2) return [1, 18] if (n >= 57 && n <= 71) return [8, n - 53] if (n >= 89 && n <= 103) return [9, n - 85] var row var start var end for (i in 0...limits.count) { var limit = limits[i] if (n >= limit.from && n <= limit.to) { row = i + 2 start = limit.from end = limit.to break } } if (n < start + 2 || row == 4 || row == 5) return [row, n - start + 1] return [row, n - end + 18] }   for (n in [1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113]) { var rc = periodicTable.call(n) Fmt.print("Atomic number $3d -> $d, $-2d", n, rc[0], rc[1]) }
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
#Kotlin
Kotlin
// version 1.1.2   fun main(Args: Array<String>) { print("Player 1 - Enter your name : ") val name1 = readLine()!!.trim().let { if (it == "") "PLAYER 1" else it.toUpperCase() } print("Player 2 - Enter your name : ") val name2 = readLine()!!.trim().let { if (it == "") "PLAYER 2" else it.toUpperCase() } val names = listOf(name1, name2) val r = java.util.Random() val totals = intArrayOf(0, 0) var player = 0 while (true) { println("\n${names[player]}") println(" Your total score is currently ${totals[player]}") var score = 0 while (true) { print(" Roll or Hold r/h : ") val rh = readLine()!![0].toLowerCase() if (rh == 'h') { totals[player] += score println(" Your total score is now ${totals[player]}") if (totals[player] >= 100) { println(" So, ${names[player]}, YOU'VE WON!") return } player = if (player == 0) 1 else 0 break } if (rh != 'r') { println(" Must be 'r'or 'h', try again") continue } val dice = 1 + r.nextInt(6) println(" You have thrown a $dice") if (dice == 1) { println(" Sorry, your score for this round is now 0") println(" Your total score remains at ${totals[player]}") player = if (player == 0) 1 else 0 break } score += dice println(" Your score for the round is now $score") } } }
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.
#Elixir
Elixir
  defmodule SieveofEratosthenes do def init(lim) do find_primes(2,lim,(2..lim)) end   def find_primes(count,lim,nums) when (count * count) > lim do nums end   def find_primes(count,lim,nums) when (count * count) <= lim do e = Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count)) find_primes(count+1,lim,e) end end   defmodule PerniciousNumbers do def take(n) do primes = SieveofEratosthenes.init(100) Stream.iterate(1,&(&1+1)) |> Stream.filter(&(pernicious?(&1,primes))) |> Enum.take(n) |> IO.inspect end   def between(a..b) do primes = SieveofEratosthenes.init(100) a..b |> Stream.filter(&(pernicious?(&1,primes))) |> Enum.to_list |> IO.inspect end   def ones(num) do num |> Integer.to_string(2) |> String.codepoints |> Enum.count(fn n -> n == "1" end) end   def pernicious?(n,primes), do: Enum.member?(primes,ones(n)) end  
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
Permutations/Rank of a permutation
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers 0.. ( n − 1 ) {\displaystyle 0..(n-1)} . For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank: PERMUTATION RANK (0, 1, 2, 3) -> 0 (0, 1, 3, 2) -> 1 (0, 2, 1, 3) -> 2 (0, 2, 3, 1) -> 3 (0, 3, 1, 2) -> 4 (0, 3, 2, 1) -> 5 (1, 0, 2, 3) -> 6 (1, 0, 3, 2) -> 7 (1, 2, 0, 3) -> 8 (1, 2, 3, 0) -> 9 (1, 3, 0, 2) -> 10 (1, 3, 2, 0) -> 11 (2, 0, 1, 3) -> 12 (2, 0, 3, 1) -> 13 (2, 1, 0, 3) -> 14 (2, 1, 3, 0) -> 15 (2, 3, 0, 1) -> 16 (2, 3, 1, 0) -> 17 (3, 0, 1, 2) -> 18 (3, 0, 2, 1) -> 19 (3, 1, 0, 2) -> 20 (3, 1, 2, 0) -> 21 (3, 2, 0, 1) -> 22 (3, 2, 1, 0) -> 23 Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above). One use of such algorithms could be in generating a small, random, sample of permutations of n {\displaystyle n} items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n {\displaystyle n} items is given by n ! {\displaystyle n!} which grows large very quickly: A 32 bit integer can only hold 12 ! {\displaystyle 12!} , a 64 bit integer only 20 ! {\displaystyle 20!} . It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them. A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items. Task Create a function to generate a permutation from a rank. Create the inverse function that given the permutation generates its rank. Show that for n = 3 {\displaystyle n=3} the two functions are indeed inverses of each other. Compute and show here 4 random, individual, samples of permutations of 12 objects. Stretch goal State how reasonable it would be to use your program to address the limits of the Stack Overflow question. References Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here). Ranks on the DevData site. Another answer on Stack Overflow to a different question that explains its algorithm in detail. Related tasks Factorial_base_numbers_indexing_permutations_of_a_collection
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var swap = Fn.new { |a, i, j| var t = a[i] a[i] = a[j] a[j] = t }   var mrUnrank1 // recursive mrUnrank1 = Fn.new { |rank, n, vec| if (n < 1) return var q = (rank/n).floor var r = rank % n swap.call(vec, r, n - 1) mrUnrank1.call(q, n - 1, vec) }   var mrRank1 // recursive mrRank1 = Fn.new { |n, vec, inv| if (n < 2) return 0 var s = vec[n-1] swap.call(vec, n - 1, inv[n-1]) swap.call(inv, s, n - 1) return s + n * mrRank1.call(n - 1, vec, inv) }   var getPermutation = Fn.new { |rank, n, vec| for (i in 0...n) vec[i] = i mrUnrank1.call(rank, n, vec) }   var getRank = Fn.new { |n, vec| var v = List.filled(n, 0) var inv = List.filled(n, 0) for (i in 0...n) { v[i] = vec[i] inv[vec[i]] = i } return mrRank1.call(n, v, inv) }   var tv = List.filled(3, 0) for (r in 0..5) { getPermutation.call(r, 3, tv) Fmt.print("$2d -> $n -> $d", r, tv, getRank.call(3, tv)) } System.print() tv = List.filled(4, 0) for (r in 0..23) { getPermutation.call(r, 4, tv) Fmt.print("$2d -> $n -> $d", r, tv, getRank.call(4, tv)) } System.print() tv = List.filled(12, 0) var a = List.filled(4, 0) var rand = Random.new() var fact12 = (2..12).reduce(1) { |acc, i| acc * i } for (i in 0..3) a[i] = rand.int(fact12) for (r in a) { getPermutation.call(r, 12, tv) Fmt.print("$9d -> $n -> $d", r, tv, getRank.call(12, tv)) }
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
#Quackery
Quackery
[ stack ] is pierponts [ stack ] is kind [ stack ] is quantity   [ 1 - -2 * 1+ kind put 1+ quantity put ' [ -1 ] pierponts put ' [ 2 3 ] smoothwith [ -1 peek kind share + dup isprime not iff [ drop false ] done pierponts share -1 peek over = iff [ drop false ] done pierponts take swap join dup size swap pierponts put quantity share = ] drop quantity release kind release pierponts take behead drop ] is pierpontprimes   say "Pierpont primes of the first kind." cr 50 1 pierpontprimes echo cr cr say "Pierpont primes of the second kind." cr 50 2 pierpontprimes echo
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}   func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(list[rand.Intn(len(list))]) }
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Groovy
Groovy
def list = [25, 30, 1, 450, 3, 78] def random = new Random();   (0..3).each { def i = random.nextInt(list.size()) println "list[${i}] == ${list[i]}" }
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Wren
Wren
import "/fmt" for Fmt   var isPrime = Fn.new { |n| if (n < 2) return false if (n%2 == 0) return n == 2 var p = 3 while (p * p <= n) { if (n%p == 0) return false p = p + 2 } return true }   var tests = [2, 5, 12, 19, 57, 61, 97] System.print("Are the following prime?") for (test in tests) { System.print("%(Fmt.d(2, test)) -> %(isPrime.call(test) ? "yes" : "no")") }
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
#Groovy
Groovy
def phaseReverse = { text, closure -> closure(text.split(/ /)).join(' ')}   def text = 'rosetta code phrase reversal' println "Original: $text" println "Reversed: ${phaseReverse(text) { it.reverse().collect { it.reverse() } } }" println "Reversed Words: ${phaseReverse(text) { it.collect { it.reverse() } } }" println "Reversed Order: ${phaseReverse(text) { it.reverse() } }"
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
#F.23
F#
  // Generate derangements. Nigel Galloway: July 9th., 2019 let derange n= let fG n i g=let e=Array.copy n in e.[i]<-n.[g]; e.[g]<-n.[i]; e let rec derange n g α=seq{ match (α>0,n&&&(1<<<α)=0) with (true,true)->for i in [0..α-1] do if n&&&(1<<<i)=0 then let g=(fG g α i) in yield! derange (n+(1<<<i)) g (α-1); yield! derange n g (α-1) |(true,false)->yield! derange n g (α-1) |(false,false)->yield g |_->()} derange 0 [|1..n|] (n-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
#Go
Go
package permute   // Iter takes a slice p and returns an iterator function. The iterator // permutes p in place and returns the sign. After all permutations have // been generated, the iterator returns 0 and p is left in its initial order. func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } }   // Recursive function used by perm, returns a chain of closures that // implement a loopless recursive SJT. func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } default: p0 := pf(n - 1) i := n var d int return func(p []int) int { switch { case sign == 0: case i == n: i-- sign = p0(p[:i]) d = -1 case i == 0: i++ sign *= p0(p[1:]) d = 1 if sign == 0 { p[0], p[1] = p[1], p[0] } default: p[i], p[i-1] = p[i-1], p[i] sign = -sign i += d } return sign } } }
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.
#jq
jq
# combination(r) generates a stream of combinations of r items from the input array. def combination(r): if r > length or r < 0 then empty elif r == length then . else ( [.[0]] + (.[1:]|combination(r-1))), ( .[1:]|combination(r)) end;  
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.
#Julia
Julia
using Combinatorics   meandiff(a::Vector{T}, b::Vector{T}) where T <: Real = mean(a) - mean(b)   function bifurcate(a::AbstractVector, sel::Vector{T}) where T <: Integer x = a[sel] asel = trues(length(a)) asel[sel] = false y = a[asel] return x, y end   function permutation_test(treated::Vector{T}, control::Vector{T}) where T <: Real effect0 = meandiff(treated, control) pool = vcat(treated, control) tlen = length(treated) plen = length(pool) better = worse = 0 for subset in combinations(1:plen, tlen) t, c = bifurcate(pool, subset) if effect0 < meandiff(t, c) better += 1 else worse += 1 end end return better, worse end
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.
#Kotlin
Kotlin
// version 1.1.2   val data = intArrayOf( 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 )   fun pick(at: Int, remain: Int, accu: Int, treat: Int): Int { if (remain == 0) return if (accu > treat) 1 else 0 return pick(at - 1, remain - 1, accu + data[at - 1], treat) + if (at > remain) pick(at - 1, remain, accu, treat) else 0 }   fun main(args: Array<String>) { var treat = 0 var total = 1.0 for (i in 0..8) treat += data[i] for (i in 19 downTo 11) total *= i for (i in 9 downTo 1) total /= i val gt = pick(19, 9, 0, treat) val le = (total - gt).toInt() System.out.printf("<= : %f%%  %d\n", 100.0 * le / total, le) System.out.printf(" > : %f%%  %d\n", 100.0 * gt / total, gt) }
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#AutoHotkey
AutoHotkey
startup() dibSection := getPixels("lenna100.jpg") dibSection2 := getPixels("lenna50.jpg") ; ("File-Lenna100.jpg") pixels := dibSection.pBits pixels2 := dibSection2.pBits z := 0 loop % dibSection.width * dibSection.height * 4 { x := numget(pixels - 1, A_Index, "uchar") y := numget(pixels2 - 1, A_Index, "uchar") z += abs(y - x) } msgbox % z / (dibSection.width * dibSection.height * 3 * 255 / 100 ) ; 1.626 return   CreateDIBSection2(hDC, nW, nH, bpp = 32, ByRef pBits = "") { dib := object() NumPut(VarSetCapacity(bi, 40, 0), bi) NumPut(nW, bi, 4) NumPut(nH, bi, 8) NumPut(bpp, NumPut(1, bi, 12, "UShort"), 0, "Ushort") NumPut(0, bi,16) hbm := DllCall("gdi32\CreateDIBSection", "Uint", hDC, "Uint", &bi, "Uint", 0, "UintP", pBits, "Uint", 0, "Uint", 0)   dib.hbm := hbm dib.pBits := pBits dib.width := nW dib.height := nH dib.bpp := bpp dib.header := header Return dib }       startup() { global disposables disposables := object() disposables.pBitmaps := object() disposables.hBitmaps := object()   If !(disposables.pToken := Gdip_Startup()) { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp } OnExit, gdipExit }     gdipExit: loop % disposables.hBitmaps._maxindex() DllCall("DeleteObject", "Uint", disposables.hBitmaps[A_Index]) Gdip_Shutdown(disposables.pToken) ExitApp   getPixels(imageFile) { global disposables ; hBitmap will be disposed later pBitmapFile1 := Gdip_CreateBitmapFromFile(imageFile) hbmi := Gdip_CreateHBITMAPFromBitmap(pBitmapFile1) width := Gdip_GetImageWidth(pBitmapFile1) height := Gdip_GetImageHeight(pBitmapFile1)   mDCo := DllCall("CreateCompatibleDC", "Uint", 0) mDCi := DllCall("CreateCompatibleDC", "Uint", 0) dibSection := CreateDIBSection2(mDCo, width, height) hBMo := dibSection.hbm   oBM := DllCall("SelectObject", "Uint", mDCo, "Uint", hBMo) iBM := DllCall("SelectObject", "Uint", mDCi, "Uint", hbmi)   DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020)   DllCall("SelectObject", "Uint", mDCo, "Uint", oBM) DllCall("DeleteDC", "Uint", 0, "Uint", mDCi) DllCall("DeleteDC", "Uint", 0, "Uint", mDCo) Gdip_DisposeImage(pBitmapFile1) DllCall("DeleteObject", "Uint", hBMi) disposables.hBitmaps._insert(hBMo) return dibSection } #Include Gdip.ahk ; Thanks to tic (Tariq Porter) for his GDI+ Library  
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.
#EchoLisp
EchoLisp
  (define-constant BLACK (rgb 0 0 0.6)) (define-constant WHITE -1) ;; sets pixels to clusterize to WHITE ;; returns bit-map vector (define (init-C n p ) (plot-size n n) (define C (pixels->int32-vector )) ;; get canvas bit-map (pixels-map (lambda (x y) (if (< (random) p) WHITE BLACK )) C) C )   ;; random color for new cluster (define (new-color) (hsv->rgb (random) 0.9 0.9))   ;; make-region predicate (define (in-cluster C x y) (= (pixel-ref C x y) WHITE))   ;; paint all adjacents to (x0,y0) with new color (define (make-cluster C x0 y0) (pixel-set! C x0 y0 (new-color)) (make-region in-cluster C x0 y0))   ;; task (define (make-clusters (n 400) (p 0.5)) (define Cn 0) (define C null) (for ((t 5)) ;; 5 iterations (plot-clear) (set! C (init-C n p)) (for* ((x0 n) (y0 n)) #:when (= (pixel-ref C x0 y0) WHITE) (set! Cn (1+ Cn)) (make-cluster C x0 y0)))   (writeln 'n n 'Cn Cn 'density (// Cn (* n n) 5) ) (vector->pixels C)) ;; to screen  
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program perfectNumber64.s */ /* use Euclide Formula : if M=(2puis p)-1 is prime M * (M+1)/2 is perfect see Wikipedia */ /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstantesARM64.inc"   .equ MAXI, 63   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Perfect  : @ \n" szMessOverflow: .asciz "Overflow in function isPrime.\n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program mov x4,2 // start 2 mov x3,1 // counter 2 power 1: // begin loop lsl x4,x4,1 // 2 power sub x0,x4,1 // - 1 bl isPrime // is prime ? cbz x0,2f // no sub x0,x4,1 // yes mul x1,x0,x4 // multiply m by m-1 lsr x0,x1,1 // divide by 2 bl displayPerfect // and display 2: add x3,x3,1 // next power of 2 cmp x3,MAXI blt 1b   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult   /******************************************************************/ /* Display perfect number */ /******************************************************************/ /* x0 contains the number */ displayPerfect: stp x1,lr,[sp,-16]! // save registers ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess // display message 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrsZoneConv: .quad sZoneConv   /***************************************************/ /* is a number prime ? */ /***************************************************/ /* x0 contains the number */ /* x0 return 1 if prime else 0 */ //2147483647 OK //4294967297 NOK //131071 OK //1000003 OK //10001363 OK isPrime: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres mov x2,x0 sub x1,x0,#1 cmp x2,0 beq 99f // return zero cmp x2,2 // for 1 and 2 return 1 ble 2f mov x0,#2 bl moduloPuR64 bcs 100f // error overflow cmp x0,#1 bne 99f // no prime cmp x2,3 beq 2f mov x0,#3 bl moduloPuR64 blt 100f // error overflow cmp x0,#1 bne 99f   cmp x2,5 beq 2f mov x0,#5 bl moduloPuR64 bcs 100f // error overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,7 beq 2f mov x0,#7 bl moduloPuR64 bcs 100f // error overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,11 beq 2f mov x0,#11 bl moduloPuR64 bcs 100f // error overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,13 beq 2f mov x0,#13 bl moduloPuR64 bcs 100f // error overflow cmp x0,#1 bne 99f // Pas premier 2: cmn x0,0 // carry à zero no error mov x0,1 // prime b 100f 99: cmn x0,0 // carry à zero no error mov x0,#0 // prime 100: ldp x2,x3,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret     /**************************************************************/ /********************************************************/ /* Compute modulo de b power e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /********************************************************/ /* x0 number */ /* x1 exposant */ /* x2 modulo */ moduloPuR64: stp x1,lr,[sp,-16]! // save registres stp x3,x4,[sp,-16]! // save registres stp x5,x6,[sp,-16]! // save registres stp x7,x8,[sp,-16]! // save registres stp x9,x10,[sp,-16]! // save registres cbz x0,100f cbz x1,100f mov x8,x0 mov x7,x1 mov x6,1 // result udiv x4,x8,x2 msub x9,x4,x2,x8 // remainder 1: tst x7,1 // if bit = 1 beq 2f mul x4,x9,x6 umulh x5,x9,x6 mov x6,x4 mov x0,x6 mov x1,x5 bl divisionReg128U // division 128 bits cbnz x1,99f // overflow mov x6,x3 // remainder 2: mul x8,x9,x9 umulh x5,x9,x9 mov x0,x8 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x9,x3 lsr x7,x7,1 cbnz x7,1b mov x0,x6 // result cmn x0,0 // carry à zero no error b 100f 99: ldr x0,qAdrszMessOverflow bl affichageMess // display error message cmp x0,0 // carry set error mov x0,-1 // code erreur   100: ldp x9,x10,[sp],16 // restaur des 2 registres ldp x7,x8,[sp],16 // restaur des 2 registres ldp x5,x6,[sp],16 // restaur des 2 registres ldp x3,x4,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessOverflow: .quad szMessOverflow /***************************************************/ /* division d un nombre de 128 bits par un nombre de 64 bits */ /***************************************************/ /* x0 contient partie basse dividende */ /* x1 contient partie haute dividente */ /* x2 contient le diviseur */ /* x0 retourne partie basse quotient */ /* x1 retourne partie haute quotient */ /* x3 retourne le reste */ divisionReg128U: stp x6,lr,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres mov x5,#0 // raz du reste R mov x3,#128 // compteur de boucle mov x4,#0 // dernier bit 1: lsl x5,x5,#1 // on decale le reste de 1 tst x1,1<<63 // test du bit le plus à gauche lsl x1,x1,#1 // on decale la partie haute du quotient de 1 beq 2f orr x5,x5,#1 // et on le pousse dans le reste R 2: tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 3f orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute 3: orr x0,x0,x4 // position du dernier bit du quotient mov x4,#0 // raz du bit cmp x5,x2 blt 4f sub x5,x5,x2 // on enleve le diviseur du reste mov x4,#1 // dernier bit à 1 4: // et boucle subs x3,x3,#1 bgt 1b lsl x1,x1,#1 // on decale le quotient de 1 tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 5f orr x1,x1,#1 5: orr x0,x0,x4 // position du dernier bit du quotient mov x3,x5 100: ldp x4,x5,[sp],16 // restaur des 2 registres ldp x6,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.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.
#C.2B.2B
C++
#include <cstdlib> #include <cstring> #include <iostream> #include <string>   using namespace std;   class Grid { public: Grid(const double p, const int x, const int y) : m(x), n(y) { const int thresh = static_cast<int>(RAND_MAX * p);   // Allocate two addition rows to avoid checking bounds. // Bottom row is also required by drippage start = new cell[m * (n + 2)]; cells = start + m; for (auto i = 0; i < m; i++) start[i] = RBWALL; end = cells; for (auto i = 0; i < y; i++) { for (auto j = x; --j;) *end++ = (rand() < thresh ? BWALL : 0) | (rand() < thresh ? RWALL : 0); *end++ = RWALL | (rand() < thresh ? BWALL : 0); } memset(end, 0u, sizeof(cell) * m); }   ~Grid() { delete[] start; cells = 0; start = 0; end = 0; }   int percolate() const { auto i = 0; for (; i < m && !fill(cells + i); i++); return i < m; }   void show() const { for (auto j = 0; j < m; j++) cout << ("+-"); cout << '+' << endl;   for (auto i = 0; i <= n; i++) { cout << (i == n ? ' ' : '|'); for (auto j = 0; j < m; j++) { cout << ((cells[i * m + j] & FILL) ? "#" : " "); cout << ((cells[i * m + j] & RWALL) ? '|' : ' '); } cout << endl;   if (i == n) return;   for (auto j = 0; j < m; j++) cout << ((cells[i * m + j] & BWALL) ? "+-" : "+ "); cout << '+' << endl; } }   private: enum cell_state { FILL = 1 << 0, RWALL = 1 << 1, // right wall BWALL = 1 << 2, // bottom wall RBWALL = RWALL | BWALL // right/bottom wall };   typedef unsigned int cell;   bool fill(cell* p) const { if ((*p & FILL)) return false; *p |= FILL; if (p >= end) return true; // success: reached bottom row   return (!(p[0] & BWALL) && fill(p + m)) || (!(p[0] & RWALL) && fill(p + 1)) ||(!(p[-1] & RWALL) && fill(p - 1)) || (!(p[-m] & BWALL) && fill(p - m)); }   cell* cells; cell* start; cell* end; const int m; const int n; };   int main() { const auto M = 10, N = 10; const Grid grid(.5, M, N); grid.percolate(); grid.show();   const auto C = 10000; cout << endl << "running " << M << "x" << N << " grids " << C << " times for each p:" << endl; for (auto p = 1; p < M; p++) { auto cnt = 0, i = 0; for (; i < C; i++) cnt += Grid(p / static_cast<double>(M), M, N).percolate(); cout << "p = " << p / static_cast<double>(M) << ": " << static_cast<double>(cnt) / i << endl; }   return EXIT_SUCCESS; }
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.
#Factor
Factor
USING: formatting fry io kernel math math.ranges math.statistics random sequences ; IN: rosetta-code.mean-run-density   : rising? ( ? ? -- ? ) [ f = ] [ t = ] bi* and ;   : count-run ( n ? ? -- m ? ) 2dup rising? [ [ 1 + ] 2dip ] when nip ;   : runs ( n p -- n ) [ 0 f ] 2dip '[ random-unit _ < count-run ] times drop ;   : rn ( n p -- x ) over [ runs ] dip /f ;   : sim ( n p -- avg ) [ 1000 ] 2dip [ rn ] 2curry replicate mean ;   : theory ( p -- x ) 1 over - * ;   : result ( n p -- ) [ swap ] [ sim ] [ nip theory ] 2tri 2dup - abs "%.1f  %-5d  %.4f  %.4f  %.4f\n" printf ;   : test ( p -- ) { 100 1,000 10,000 } [ swap result ] with each nl ;   : header ( -- ) "1000 tests each:\np n K p(1-p) diff" print ;   : main ( -- ) header .1 .9 .2 <range> [ test ] each ;   MAIN: main
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.
#Fortran
Fortran
  ! loosely translated from python. We do not need to generate and store the entire vector at once. ! compilation: gfortran -Wall -std=f2008 -o thisfile thisfile.f08   program percolation_mean_run_density implicit none integer :: i, p10, n2, n, t real :: p, limit, sim, delta data n,p,t/100,0.5,500/ write(6,'(a3,a5,4a7)')'t','p','n','p(1-p)','sim','delta%' do p10=1,10,2 p = p10/10.0 limit = p*(1-p) write(6,'()') do n2=10,15,2 n = 2**n2 sim = 0 do i=1,t sim = sim + mean_run_density(n,p) end do sim = sim/t if (limit /= 0) then delta = abs(sim-limit)/limit else delta = sim end if delta = delta * 100 write(6,'(i3,f5.2,i7,2f7.3,f5.1)')t,p,n,limit,sim,delta end do end do   contains   integer function runs(n, p) integer, intent(in) :: n real, intent(in) :: p real :: harvest logical :: q integer :: count, i count = 0 q = .false. do i=1,n call random_number(harvest) if (harvest < p) then q = .true. else if (q) count = count+1 q = .false. end if end do runs = count end function runs   real function mean_run_density(n, p) integer, intent(in) :: n real, intent(in) :: p mean_run_density = real(runs(n,p))/real(n) end function mean_run_density   end program percolation_mean_run_density  
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.
#Go
Go
package main   import ( "bytes" "fmt" "math/rand" "time" )   func main() { const ( m, n = 15, 15 t = 1e4 minp, maxp, Δp = 0, 1, 0.1 )   rand.Seed(2) // Fixed seed for repeatable example grid g := NewGrid(.5, m, n) g.Percolate() fmt.Println(g)   rand.Seed(time.Now().UnixNano()) // could pick a better seed for p := float64(minp); p < maxp; p += Δp { count := 0 for i := 0; i < t; i++ { g := NewGrid(p, m, n) if g.Percolate() { count++ } } fmt.Printf("p=%.2f, %.4f\n", p, float64(count)/t) } }   const ( full = '.' used = '#' empty = ' ' )   type grid struct { cell [][]byte // row first, i.e. [y][x] }   func NewGrid(p float64, xsize, ysize int) *grid { g := &grid{cell: make([][]byte, ysize)} for y := range g.cell { g.cell[y] = make([]byte, xsize) for x := range g.cell[y] { if rand.Float64() < p { g.cell[y][x] = full } else { g.cell[y][x] = empty } } } return g }   func (g *grid) String() string { var buf bytes.Buffer // Don't really need to call Grow but it helps avoid multiple // reallocations if the size is large. buf.Grow((len(g.cell) + 2) * (len(g.cell[0]) + 3))   buf.WriteByte('+') for _ = range g.cell[0] { buf.WriteByte('-') } buf.WriteString("+\n")   for y := range g.cell { buf.WriteByte('|') buf.Write(g.cell[y]) buf.WriteString("|\n") }   buf.WriteByte('+') ly := len(g.cell) - 1 for x := range g.cell[ly] { if g.cell[ly][x] == used { buf.WriteByte(used) } else { buf.WriteByte('-') } } buf.WriteByte('+') return buf.String() }   func (g *grid) Percolate() bool { for x := range g.cell[0] { if g.use(x, 0) { return true } } return false }   func (g *grid) use(x, y int) bool { if y < 0 || x < 0 || x >= len(g.cell[0]) || g.cell[y][x] != full { return false // Off the edges, empty, or used } g.cell[y][x] = used if y+1 == len(g.cell) { return true // We're on the bottom }   // Try down, right, left, up in that order. return g.use(x, y+1) || g.use(x+1, y) || g.use(x-1, y) || g.use(x, y-1) }
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Action.21
Action!
PROC PrintArray(BYTE ARRAY a BYTE len) BYTE i   FOR i=0 TO len-1 DO PrintB(a(i)) OD Print(" ") RETURN   BYTE FUNC NextPermutation(BYTE ARRAY a BYTE len) BYTE i,j,k,tmp   i=len-1 WHILE i>0 AND a(i-1)>a(i) DO i==-1 OD   j=i k=len-1 WHILE j<k DO tmp=a(j) a(j)=a(k) a(k)=tmp j==+1 k==-1 OD   IF i=0 THEN RETURN (0) FI   j=i WHILE a(j)<a(i-1) DO j==+1 OD tmp=a(i-1) a(i-1)=a(j) a(j)=tmp RETURN (1)   PROC Main() DEFINE len="5" BYTE ARRAY a(len) BYTE RMARGIN=$53,oldRMARGIN BYTE i   oldRMARGIN=RMARGIN RMARGIN=37 ;change right margin on the screen   FOR i=0 TO len-1 DO a(i)=i OD   DO PrintArray(a,len) UNTIL NextPermutation(a,len)=0 OD   RMARGIN=oldRMARGIN ;restore right margin on the screen RETURN
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#AutoHotkey
AutoHotkey
Shuffle(cards){ n := cards.MaxIndex()/2, res := [] loop % n res.push(cards[A_Index]), res.push(cards[round(A_Index + n)]) return res }
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#C
C
/* ===> INCLUDES <============================================================*/ #include <stdlib.h> #include <stdio.h> #include <string.h>   /* ===> CONSTANTS <===========================================================*/ #define N_DECKS 7 const int kDecks[N_DECKS] = { 8, 24, 52, 100, 1020, 1024, 10000 };   /* ===> FUNCTION PROTOTYPES <=================================================*/ int CreateDeck( int **deck, int nCards ); void InitDeck( int *deck, int nCards ); int DuplicateDeck( int **dest, const int *orig, int nCards ); int InitedDeck( int *deck, int nCards ); int ShuffleDeck( int *deck, int nCards ); void FreeDeck( int **deck );   /* ===> FUNCTION DEFINITIONS <================================================*/   int main() { int i, nCards, nShuffles; int *deck = NULL;   for( i=0; i<N_DECKS; ++i ) { nCards = kDecks[i];   if( !CreateDeck(&deck,nCards) ) { fprintf( stderr, "Error: malloc() failed!\n" ); return 1; }   InitDeck( deck, nCards ); nShuffles = 0;   do { ShuffleDeck( deck, nCards ); ++nShuffles; } while( !InitedDeck(deck,nCards) );   printf( "Cards count: %d, shuffles required: %d.\n", nCards, nShuffles );   FreeDeck( &deck ); }   return 0; }   int CreateDeck( int **deck, int nCards ) { int *tmp = NULL;   if( deck != NULL ) tmp = malloc( nCards*sizeof(*tmp) );   return tmp!=NULL ? (*deck=tmp)!=NULL : 0; /* (?success) (:failure) */ }   void InitDeck( int *deck, int nCards ) { if( deck != NULL ) { int i;   for( i=0; i<nCards; ++i ) deck[i] = i; } }   int DuplicateDeck( int **dest, const int *orig, int nCards ) { if( orig != NULL && CreateDeck(dest,nCards) ) { memcpy( *dest, orig, nCards*sizeof(*orig) ); return 1; /* success */ } else { return 0; /* failure */ } }   int InitedDeck( int *deck, int nCards ) { int i;   for( i=0; i<nCards; ++i ) if( deck[i] != i ) return 0; /* not inited */   return 1; /* inited */ }   int ShuffleDeck( int *deck, int nCards ) { int *copy = NULL;   if( DuplicateDeck(&copy,deck,nCards) ) { int i, j;   for( i=j=0; i<nCards/2; ++i, j+=2 ) { deck[j] = copy[i]; deck[j+1] = copy[i+nCards/2]; }   FreeDeck( &copy ); return 1; /* success */ } else { return 0; /* failure */ } }   void FreeDeck( int **deck ) { if( *deck != NULL ) { free( *deck ); *deck = NULL; } }  
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.
#FreeBASIC
FreeBASIC
  #define floor(x) ((x*2.0-0.5) Shr 1) Dim Shared As Byte p(256) => { _ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, _ 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, _ 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, _ 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, _ 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, _ 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, _ 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, _ 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, _ 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, _ 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, _ 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, _ 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, _ 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, _ 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, _ 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, _ 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}   Function fade(t As Double) As Double Return t * t * t * (t * (t * 6 - 15) + 10) End Function   Function lerp(t As Double, a As Double, b As Double) As Double Return a + t * (b - a) End Function   Function grad(hash As Integer, x As Double, y As Double, z As Double) As Double Select Case (hash And 15) Case 0  : Return x+y Case 1  : Return y-x Case 2  : Return x-y Case 3  : Return -x-y Case 4  : Return x+z Case 5  : Return z-x Case 6  : Return x-z Case 7  : Return -x-y ' maybe -x-z? Case 8  : Return y+z Case 9  : Return z-y Case 10 : Return y-z Case 11 : Return -y-z Case 12 : Return x+y Case 13 : Return z-y Case 14 : Return y-x Case 15 : Return -y-z End Select End Function   Function noise(x As Double, y As Double, z As Double) As Double Dim As Integer a = Int(x) And 255, b = Int(y) And 255, c = Int(z) And 255 x -= floor(x) : y -= floor(y) : z -= floor(z) Dim As Double u = fade(x), v = fade(y), w = fade(z) Dim As Integer A0 = p(a)+b, A1 = p(A0)+c, A2 = p(A0+1)+c Dim As Integer B0 = p(a+1)+b, B1 = p(B0)+c, B2 = p(B0+1)+c   Return lerp(w, lerp(v, lerp(u, grad(p(A1), x, y, z), _ grad(p(B1), x-1, y, z)), _ lerp(u, grad(p(A2), x, y-1, z), _ grad(p(B2), x-1, y-1, z))), _ lerp(v, lerp(u, grad(p(A1+1), x, y, z-1), _ grad(p(B1+1), x-1, y, z-1)), _ lerp(u, grad(p(A2+1), x, y-1, z-1), _ grad(p(B2+1), x-1, y-1, z-1)))) End Function   Print Using "El Ruido Perlin para (3.14, 42, 7) es #.################"; noise(3.14, 42, 7) Sleep  
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
#CLU
CLU
gcd = proc (a, b: int) returns (int) while b ~= 0 do a, b := b, a//b end return(a) end gcd   totient = proc (n: int) returns (int) tot: int := 0 for i: int in int$from_to(1,n-1) do if gcd(n,i)=1 then tot := tot + 1 end end return(tot) end totient   perfect = proc (n: int) returns (bool) sum: int := 0 x: int := n while true do x := totient(x) sum := sum + x if x=1 then break end end return(sum = n) end perfect   start_up = proc () po: stream := stream$primary_output() seen: int := 0 n: int := 3 while seen < 20 do if perfect(n) then stream$puts(po, int$unparse(n) || " ") seen := seen + 1 end n := n + 2 end end start_up
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
#Cowgol
Cowgol
include "cowgol.coh";   sub gcd(a: uint16, b: uint16): (r: uint16) is while b != 0 loop r := a; a := b; b := r % b; end loop; r := a; end sub;   sub totient(n: uint16): (tot: uint16) is var i: uint16 := 1; tot := 0; while i < n loop if gcd(n,i) == 1 then tot := tot + 1; end if; i := i + 1; end loop; end sub;   sub totientSum(n: uint16): (sum: uint16) is var x := n; sum := 0; while x > 1 loop x := totient(x); sum := sum + x; end loop; end sub;   var seen: uint8 := 0; var n: uint16 := 3; while seen < 20 loop if totientSum(n) == n then print_i16(n); print_char(' '); seen := seen + 1; end if; n := n + 2; end loop; print_nl();
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
#Delphi
Delphi
  program Perfect_totient_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function totient(n: Integer): Integer; begin var tot := n; var i := 2; while i * i <= n do begin if (n mod i) = 0 then begin while (n mod i) = 0 do n := n div i; dec(tot, tot div i); end; if i = 2 then i := 1; inc(i, 2); end; if n > 1 then dec(tot, tot div n); Result := tot; end;   begin var perfect: TArray<Integer>; var n := 1; while length(perfect) < 20 do begin var tot := n; var sum := 0; while tot <> 1 do begin tot := totient(tot); inc(sum, tot); end; if sum = n then begin SetLength(perfect, Length(perfect) + 1); perfect[High(perfect)] := n; end; inc(n, 2); end; writeln('The first 20 perfect totient numbers are:'); write('['); for var e in perfect do write(e, ' '); writeln(']'); readln; end.
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
#Erlang
Erlang
  -module( playing_cards ).   -export( [deal/2, deal/3, deck/0, print/1, shuffle/1, sort_pips/1, sort_suites/1, task/0] ).   -record( card, {pip, suite} ).   -spec( deal( N_cards::integer(), Deck::[#card{}]) -> {Hand::[#card{}], Deck::[#card{}]} ). deal( N_cards, Deck ) -> lists:split( N_cards, Deck ). -spec( deal( N_hands::integer(), N_cards::integer(), Deck::[#card{}]) -> {List_of_hands::[[#card{}]], Deck::[#card{}]} ). deal( N_hands, N_cards, Deck ) -> lists:foldl( fun deal_hands/2, {lists:duplicate(N_hands, []), Deck}, lists:seq(1, N_cards * N_hands) ).   deck() -> [#card{suite=X, pip=Y} || X <- suites(), Y <- pips()].   print( Cards ) -> [io:fwrite( " ~p", [X]) || X <- Cards], io:nl().   shuffle( Deck ) -> knuth_shuffle:list( Deck ).   sort_pips( Cards ) -> lists:keysort( #card.pip, Cards ).   sort_suites( Cards ) -> lists:keysort( #card.suite, Cards ).   task() -> Deck = deck(), Shuffled = shuffle( Deck ), {Hand, New_deck} = deal( 3, Shuffled ), {Hands, _Deck} = deal( 2, 3, New_deck ), io:fwrite( "Hand:" ), print( Hand ), io:fwrite( "Hands:~n" ), [print(X) || X <- Hands].       deal_hands( _N, {[Hand | T], [Card | Deck]} ) -> {T ++ [[Card | Hand]], Deck}.   pips() -> ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"].   suites() -> ["Clubs", "Hearts", "Spades", "Diamonds"].  
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
#EDSAC_order_code
EDSAC order code
  [EDSAC program, Initial Orders 2. Calculates digits of pi by spigot algorithm. Easily edited to calculate digits of e (see "if pi" and "if e" in comments). Based on http://pi314.net/eng/goutte.php See also https://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml   Uses 17-bit values throughout. Array index and counters are stored in the address field, i.e. with the least significant bit in bit 1. For integer arithmetic, the least significant bit is bit 0.   Variables don't need to be initialized at load time, so they overwrite locations 6..12 of initial orders to save space.] [6] P F [index into remainder array] [7] P F [carry in the spigot algorithm] [8] P F [negative count of digits] [9] P F [pending digit, always < 9] [10] P F [negative count of pending 9's] [11] P F [9 or 0 in top 5 bits, for printing] [12] P F [negative count of characters in current line]   [Array corresponding to Remainder row on http://pi314.net/eng/goutte.php] T 53 K [refer to array via B parameter] P 13 F [start array immediately after variables]   [Subroutine for short (17-bit) integer division. Input: dividend at 4F, divisor at 5F. Output: remainder at 4F, quotient at 5F. Working locations 0F, 1F. 37 locations.] T 987 K GKA3FT34@A5FUFT35@A4FRDS35@G13@T1FA35@LDE4@T1FT5FA4FS35@G22@ T4FA5FA36@T5FT1FAFS35@E34@T1FA35@RDT35@A5FLDT5FE15@EFPFPD   T 845 K G K [Constants] [Enter the editable numbers as addresses, e.g. P 100 F for 100. Reducing the maximum array index will make the program take less time. A maximum index of 831 (i.e. using all available memory) will give 252 correct digits of pi, or 2070 correct digits of e.] [0] P 831 F [maximum array index <-- EDIT HERE, don't exceed 831] [1] P 252 F [number of digits <-- EDIT HERE] [2] P 72 F [digits per line <-- EDIT HERE] [3] P D [short-value 1] [4] P 5 F [short-value 10] [5] J F [10*(2^12)] [6] X F [add to T order to make V order] [7] M F [used to convert T order to A order] [8] # F [figures shift (for printer)] [9] @ F [carriage return] [10] & F [line feed]   [Main routine. Enter with acc = 0.] [11] O 8 @ [set printer to figures; also used to print '9'] S 2 @ [load negative characters per line] T 12 F [initialize character count] S 1 @ [load negated number of digits] T 8 F [initialize digit count] T 10 F [clear negative count of 9's] S 2 F [load -2 (any value < -1 would do)] T 9 F [initialize digit buffer] [Start algorithm: fill the remainder array with 2's (or 1's for e) The code is a bit neater if we work backwards.] A @ [maximum index] [20] A 81 @ [make T order for array entry] T 23 @ [plant in code] [if pi] A 2 F [acc := 2] [if e] [A 3 @] [acc := 1] [23] T F [store in array entry] A 23 @ [dec address in array] S 2 F S 81 @ [finished array?] E 20 @ [loop back if not   Outer loop. Here for next digit.] [28] T F [clear acc] [Multiply remainder array by 10. NB To preserve integer scaling, we need product times 2^16.] H 5 @ [mult reg := 10*(2^12)] A @ [acc := maximum index] [31] A 81 @ [make T order for array entry] U 37 @ [plant in code] A 6 @ [convert to V order, same address] T 35 @ [plant in code] [35] V F [acc := array entry * 10*(2^12)] L 4 F [shift to complete mult by 10*(2^16)] [37] T F [store result in array] A 37 @ [load T order] S 2 F [dec address] S 81 @ [test for done] E 31 @ [loop back if not] T F [clear acc] T 7 F [clear carry] A @ [acc := maximum index] T 6 F [initialize array index] [Inner loop to get next digit. Work backwards through remainder array.] [46] T F [clear acc] A 6 F [load index] A 81 @ [make T order for array entry] U 61 @ [plant in code] A 7 @ [convert to A order] T 52 @ [plant in code] [52] A F [load array element] A 7 F [add carry from last time round loop] T 4 F [sum to 4F for division routine] A 6 F [acc := index as address = 2*(index as integer)] [if pi] A 3 @ [plus 1] [if e] [R D] [shift right, address --> integer] T 5 F [to 5F for division routine (for e, 5F = index/2)] [58] A 58 @ [call routine to divide 4F by 5F] G 987 F A 4 F [load remainder] [61] T F [update element of remainder array] [if pi: 4 orders] H 5 F [mult reg := quotient] V 6 F [multiply by index NB need to shift 15 left to preserve integer scaling] L F [shift 13 left] L 1 F [shift 2 more left (for e, just use quotient) [if e: 1 order, plus 3 no-ops to keep addresses the same] [A 5 F] [load quotient] [XF XF XF] T 7 F [update carry for next time round loop] A 6 F [load index] S 2 F [decrement] U 6 F [store back] [We want to terminate after doing index = 1] S 2 F [dec again] E 46 @ [jump back if index >= 1] [Treatment of index = 0 is different] T F [clear acc] A B [load rem{0)] A 7 F [add carry] T 4 F [sum to 4F for division routine] A 4 @ [load 10] T 5 F [to 5F for division routine] [78] A 78 @ [call division routine] G 987 F A 4 F [load remainder] [81] T B [store in rem{0}; also used to manufacture orders] [82] A 82 @ [call subroutine to deal with quotient (clears acc)] G 93 @ A 8 F [load negative digit count] A 2 F [increment] U 8 F [store back] G 28 @ [if not yet 0, loop for next digit] [Fake a zero digit to flush the last genuine digit(s)] T 5 F [store fake digit 0 in 5F] [89] A 89 @ [call subroutine to deal with digit] G 93 @ O 8 @ [set figures: dummy character to flush print buffer] Z F [stop]   [Subroutine to handle buffering and printing of digits. Here with quotient from spigot algorithm still in 5F. The quotient at 5F is usually the new decimal digit. But the quotient can be 10, in which case we must treat it as 0 and ripple a carry through the previously-computed digits. Hence the need for buffering.] [93] A 3 F [make and plant return link] T 130 @ A 5 F [load quotient] S 4 @ [subtract 10] E 105 @ [jump if quotient >= 10] A 3 @ [add 1] G 109 @ [jump if quotient < 9] [Here if quotient = 9. Update count of 9's, don't do anything with the buffer.] T F [clear acc] A 10 F [load negative count of 9's] S 2 F [subtract 1] T 10 F [update count] E 130 @ [exit with acc = 0] [Here if quotient >= 10. Take digit = quotient - 10, and ripple a carry through the buffered digits.] [105] T 5 F [store (quotient - 10) formed above] T 11 F [store 0 to print '0' not '9'] A 3 @ [add 1 to buffered digit] E 112 @ [join common code] [Here if quotient < 9. Flush the stored digits.] [109] T F [clear acc] A 11 @ [load any O order (code for O is 9)] T 11 F [store to print '9'] [112] A 9 F [load buffered digit, plus 1 if quotient >= 10] G 118 @ [skip printing if buffer is empty] L 1024 F [shift digits to top 5 bits] T 1 F [store in 1F for printing] [116] A 116 @ [call print routine] G 131 @ [118] T F [clear acc] A 5 F [load quotient (possibly modified as above)] T 9 F [store in buffer] [121] A 10 F [load negative count of 9's] E 130 @ [if none, exit with acc = 0] A 2 F [inc count] T 10 F A 11 F [load 9 (or 0 if there's a carry)] T 1 F [to 1F for printing] [127] A 127 @ [call print routine (clears acc)] G 131 @ E 121 @ [jump back (always)] [130] E F [return to caller]   [Subroutine to print character at 1F. Also prints CR LF if necessary.] [131] A 3 F [make and plant link for return] T 141 @ A 12 F [load negative character count] G 138 @ [jump if not end of line] S 2 @ [reset character count] O 9 @ [print CR LF] O 10 @ [138] O 1 F [print character] A 2 F [add 1] T 12 F [141] E F E 11 Z [define entry point] P F [acc = 0 on entry]  
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | | | |1 H He | | | |2 Li Be B C N O F Ne | | | |3 Na Mg Al Si P S Cl Ar | | | |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr | | | |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe | | | |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn | | | |7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og | |__________________________________________________________________________| | | | | |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu | | | |9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr | |__________________________________________________________________________| Example test cases;   1 -> 1 1   2 -> 1 18   29 -> 4 11   42 -> 5 6   57 -> 8 4   58 -> 8 5   72 -> 6 4   89 -> 9 4 Details; The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3. You may take a look at the atomic number repartitions here. The atomic number is at least 1, at most 118. See also   the periodic table   This task was an idea from CompSciFact   The periodic table in ascii that was used as template
#XPL0
XPL0
proc ShowPosn(N); \Show row and column for element int N, M, A, B, I, R, C; [A:= [ 1, 2, 5, 13, 57, 72, 89, 104]; \magic numbers B:= [-1, 15, 25, 35, 72, 21, 58, 7]; I:= 7; while A(I) > N do I:= I-1; M:= N + B(I); R:= M/18 +1; C:= rem(0) +1; IntOut(0, N); Text(0, " -> "); IntOut(0, R); Text(0, ", "); IntOut(0, C); CrLf(0); ];   int Element, I; [Element:= [1, 2, 29, 42, 57, 58, 72, 89, 90, 103]; for I:= 0 to 10-1 do ShowPosn(Element(I)); ]
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
#Lua
Lua
local numPlayers = 2 local maxScore = 100 local scores = { } for i = 1, numPlayers do scores[i] = 0 -- total safe score for each player end math.randomseed(os.time()) print("Enter a letter: [h]old or [r]oll?") local points = 0 -- points accumulated in current turn local p = 1 -- start with first player while true do io.write("\nPlayer "..p..", your score is ".. scores[p]..", with ".. points.." temporary points. ") local reply = string.sub(string.lower(io.read("*line")), 1, 1) if reply == 'r' then local roll = math.random(6) io.write("You rolled a " .. roll) if roll == 1 then print(". Too bad. :(") p = (p % numPlayers) + 1 points = 0 else points = points + roll end elseif reply == 'h' then scores[p] = scores[p] + points if scores[p] >= maxScore then print("Player "..p..", you win with a score of "..scores[p]) break end print("Player "..p..", your new score is " .. scores[p]) p = (p % numPlayers) + 1 points = 0 end 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.
#F.23
F#
open System   //Taken from https://gist.github.com/rmunn/bc49d32a586cdfa5bcab1c3e7b45d7ac let bitcount (n : int) = let count2 = n - ((n >>> 1) &&& 0x55555555) let count4 = (count2 &&& 0x33333333) + ((count2 >>> 2) &&& 0x33333333) let count8 = (count4 + (count4 >>> 4)) &&& 0x0f0f0f0f (count8 * 0x01010101) >>> 24   //Modified from other examples to actually state the 1 is not prime let isPrime n = if n < 2 then false else let sqrtn n = int <| sqrt (float n) seq { 2 .. sqrtn n } |> Seq.exists(fun i -> n % i = 0) |> not   [<EntryPoint>] let main _ = [1 .. 100] |> Seq.filter (bitcount >> isPrime) |> Seq.take 25 |> Seq.toList |> printfn "%A" [888888877 .. 888888888] |> Seq.filter (bitcount >> isPrime) |> Seq.toList |> printfn "%A" 0 // return an integer exit code
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
Permutations/Rank of a permutation
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers 0.. ( n − 1 ) {\displaystyle 0..(n-1)} . For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank: PERMUTATION RANK (0, 1, 2, 3) -> 0 (0, 1, 3, 2) -> 1 (0, 2, 1, 3) -> 2 (0, 2, 3, 1) -> 3 (0, 3, 1, 2) -> 4 (0, 3, 2, 1) -> 5 (1, 0, 2, 3) -> 6 (1, 0, 3, 2) -> 7 (1, 2, 0, 3) -> 8 (1, 2, 3, 0) -> 9 (1, 3, 0, 2) -> 10 (1, 3, 2, 0) -> 11 (2, 0, 1, 3) -> 12 (2, 0, 3, 1) -> 13 (2, 1, 0, 3) -> 14 (2, 1, 3, 0) -> 15 (2, 3, 0, 1) -> 16 (2, 3, 1, 0) -> 17 (3, 0, 1, 2) -> 18 (3, 0, 2, 1) -> 19 (3, 1, 0, 2) -> 20 (3, 1, 2, 0) -> 21 (3, 2, 0, 1) -> 22 (3, 2, 1, 0) -> 23 Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above). One use of such algorithms could be in generating a small, random, sample of permutations of n {\displaystyle n} items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n {\displaystyle n} items is given by n ! {\displaystyle n!} which grows large very quickly: A 32 bit integer can only hold 12 ! {\displaystyle 12!} , a 64 bit integer only 20 ! {\displaystyle 20!} . It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them. A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items. Task Create a function to generate a permutation from a rank. Create the inverse function that given the permutation generates its rank. Show that for n = 3 {\displaystyle n=3} the two functions are indeed inverses of each other. Compute and show here 4 random, individual, samples of permutations of 12 objects. Stretch goal State how reasonable it would be to use your program to address the limits of the Stack Overflow question. References Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here). Ranks on the DevData site. Another answer on Stack Overflow to a different question that explains its algorithm in detail. Related tasks Factorial_base_numbers_indexing_permutations_of_a_collection
#zkl
zkl
fcn computePermutation(items,rank){ // in place permutation of items foreach n in ([items.len()..1,-1]){ r:=rank%n; rank/=n; items.swap(r,n-1); } items }
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
#Raku
Raku
use ntheory:from<Perl5> <is_prime>;   sub pierpont ($kind is copy = 1) { fail "Unknown type: $kind. Must be one of 1 (default) or 2" if $kind !== 1|2; $kind = -1 if $kind == 2; my $po3 = 3; my $add-one = 3; my @iterators = [1,2,4,8 … *].iterator, [3,9,27 … *].iterator; my @head = @iterators».pull-one;   gather { loop { my $key = @head.pairs.min( *.value ).key; my $min = @head[$key]; @head[$key] = @iterators[$key].pull-one;   take $min + $kind if "{$min + $kind}".&is_prime;   if $min >= $add-one { @iterators.push: ([|((2,4,8).map: * * $po3) … *]).iterator; $add-one = @head[+@iterators - 1] = @iterators[+@iterators - 1].pull-one; $po3 *= 3; } } } }   say "First 50 Pierpont primes of the first kind:\n" ~ pierpont[^50].rotor(10)».fmt('%8d').join: "\n";   say "\nFirst 50 Pierpont primes of the second kind:\n" ~ pierpont(2)[^50].rotor(10)».fmt('%8d').join: "\n";   say "\n250th Pierpont prime of the first kind: " ~ pierpont[249];   say "\n250th Pierpont prime of the second kind: " ~ pierpont(2)[249];
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#GW-BASIC
GW-BASIC
10 RANDOMIZE TIMER  : REM set random number seed to something arbitrary 20 DIM ARR(10)  : REM initialise array 30 FOR I = 1 TO 10 40 ARR(I) = I*I  : REM squares of the integers is OK as a demo 50 NEXT I 60 C = 1 + INT(RND*10)  : REM get a random index from 1 to 10 inclusive 70 PRINT ARR(C)
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#XPL0
XPL0
func Prime(N); \Return 'true' if N is a prime number int N; int I; [if N <= 1 then return false; for I:= 2 to sqrt(N) do if rem(N/I) = 0 then return false; return true; ];   int Num; repeat Num:= IntIn(0); Text(0, if Prime(Num) then "is " else "not "); Text(0, "prime^M^J"); until Num = 0
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Haskell
Haskell
reverseString, reverseEachWord, reverseWordOrder :: String -> String reverseString = reverse   reverseEachWord = wordLevel (fmap reverse)   reverseWordOrder = wordLevel reverse   wordLevel :: ([String] -> [String]) -> String -> String wordLevel f = unwords . f . words   main :: IO () main = (putStrLn . unlines) $ [reverseString, reverseEachWord, reverseWordOrder] <*> ["rosetta code phrase reversal"]
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n. Task Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer). Generate and show all the derangements of 4 integers using the above routine. Create a function that calculates the subfactorial of n, !n. Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive. Optional stretch goal   Calculate    !20 Related tasks   Anagrams/Deranged anagrams   Best shuffle   Left_factorials Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Factor
Factor
USING: combinators formatting io kernel math math.combinatorics prettyprint sequences ; IN: rosetta-code.derangements   : !n ( n -- m ) { { 0 [ 1 ] } { 1 [ 0 ] } [ [ 1 - !n ] [ 2 - !n + ] [ 1 - * ] tri ] } case ;   : derangements ( n -- seq ) <iota> dup [ [ = ] 2map [ f = ] all? ] with filter-permutations ;   "4 derangements" print 4 derangements . nl "n count calc\n= ====== ======" print 10 <iota> [ dup [ derangements length ] [ !n ] bi "%d%8d%8d\n" printf ] each nl "!20 = " write 20 !n .
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#Haskell
Haskell
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [-1, 1]) . foldr aux [[]] where aux x items = do (f, item) <- zip (repeat id) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x : l) : ((y :) <$> insertEv x ys)   main :: IO () main = do putStrLn "3 items:" mapM_ print $ sPermutations [1 .. 3] putStrLn "\n4 items:" mapM_ print $ sPermutations [1 .. 4]
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment subjects, or to a group of m {\displaystyle m} control subjects. Members of the treatment group were given the treatment, and members of the control group were given a placebo. The effect of the treatment or placebo on each volunteer was measured and reported in this table. Table of experimental results Treatment group Control group 85 68 88 41 75 10 66 49 25 16 29 65 83 32 39 92 97 28 98 Write a program that performs a permutation test to judge whether the treatment had a significantly stronger effect than the placebo. Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size n {\displaystyle n} and a control group of size m {\displaystyle m} (i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless. Note that the number of alternatives will be the binomial coefficient ( n + m n ) {\displaystyle {\tbinom {n+m}{n}}} . Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group. Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater. Note that they should sum to 100%. Extremely dissimilar values are evidence of an effect not entirely due to chance, but your program need not draw any conclusions. You may assume the experimental data are known at compile time if that's easier than loading them at run time. Test your solution on the data given above.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Global data(), treat=0 data()=(85, 88, 75, 66, 25, 29, 83, 39, 97,68, 41, 10, 49, 16, 65, 32, 92, 28, 98) Function pick(at, remain, accu) { If remain Else =If(accu>treat->1,0):Exit =pick(at-1,remain-1,accu+data(at-1))+If(at>remain->pick(at-1, remain, accu),0) } total=1 For i=0 to 8 {treat+=data(i)} For i=19 to 11 {total*=i} For i=9 to 1 {total/=i} gt=pick(19,9,0) le=total-gt Print Format$("<= : {0:1}% {1}", 100*le/total, le) Print Format$(" > : {0:1}% {1}", 100*gt/total, gt) } Checkit  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
"<=: " <> ToString[#1] <> " " <> ToString[100. #1/#2] <> "%\n >: " <> ToString[#2 - #1] <> " " <> ToString[100. (1 - #1/#2)] <> "%" &[ Count[Total /@ Subsets[Join[#1, #2], {Length@#1}], n_ /; n <= Total@#1], Binomial[Length@#1 + Length@#2, Length@#1]] &[{85, 88, 75, 66, 25, 29, 83, 39, 97}, {68, 41, 10, 49, 16, 65, 32, 92, 28, 98}]
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%
#BBC_BASIC
BBC BASIC
hbm1% = FNloadimage("C:lenna50.jpg") hbm2% = FNloadimage("C:lenna100.jpg")   SYS "CreateCompatibleDC", @memhdc% TO hdc1% SYS "CreateCompatibleDC", @memhdc% TO hdc2%   SYS "SelectObject", hdc1%, hbm1% SYS "SelectObject", hdc2%, hbm2%   diff% = 0 FOR y% = 0 TO 511 FOR x% = 0 TO 511 SYS "GetPixel", hdc1%, x%, y% TO rgb1% SYS "GetPixel", hdc2%, x%, y% TO rgb2% diff% += ABS((rgb1% AND &FF) - (rgb2% AND &FF)) diff% += ABS((rgb1% >> 8 AND &FF) - (rgb2% >> 8 AND &FF)) diff% += ABS((rgb1% >> 16) - (rgb2% >> 16)) NEXT NEXT y% PRINT "Image difference = "; 100 * diff% / 512^2 / 3 / 255 " %"   SYS "DeleteDC", hdc1% SYS "DeleteDC", hdc2% SYS "DeleteObject", hbm1% SYS "DeleteObject", hbm2% END   DEF FNloadimage(file$) LOCAL iid{}, hbm%, pic%, ole%, olpp%, text% DIM iid{a%,b%,c%,d%}, text% LOCAL 513   iid.a% = &7BF80980 : REM. 128-bit iid iid.b% = &101ABF32 iid.c% = &AA00BB8B iid.d% = &AB0C3000   SYS "MultiByteToWideChar", 0, 0, file$, -1, text%, 256   SYS "LoadLibrary", "OLEAUT32.DLL" TO ole% SYS "GetProcAddress", ole%, "OleLoadPicturePath" TO olpp% IF olpp%=0 THEN = 0   SYS olpp%, text%, 0, 0, 0, iid{}, ^pic% : REM. OleLoadPicturePath IF pic%=0 THEN = 0   SYS !(!pic%+12), pic%, ^hbm% : REM. IPicture::get_Handle SYS "FreeLibrary", ole% = hbm%
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> /* #include "imglib.h" */   #define RED_C 0 #define GREEN_C 1 #define BLUE_C 2 #define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])   int main(int argc, char **argv) { image im1, im2; double totalDiff = 0.0; unsigned int x, y;   if ( argc < 3 ) { fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]); exit(1); } im1 = read_image(argv[1]); if ( im1 == NULL ) exit(1); im2 = read_image(argv[2]); if ( im2 == NULL ) { free_img(im1); exit(1); } if ( (im1->width != im2->width) || (im1->height != im2->height) ) { fprintf(stderr, "width/height of the images must match!\n"); } else { /* BODY: the "real" part! */ for(x=0; x < im1->width; x++) { for(y=0; y < im1->width; y++) { totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0; totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0; totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0; } } printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) ); /* BODY ends */ } free_img(im1); free_img(im2); }
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.
#Factor
Factor
USING: combinators formatting generalizations kernel math math.matrices random sequences ; IN: rosetta-code.mean-cluster-density   CONSTANT: p 0.5 CONSTANT: iterations 5   : rand-bit-matrix ( n probability -- matrix ) dupd [ random-unit > 1 0 ? ] curry make-matrix ;   : flood-fill ( x y matrix -- ) 3dup ?nth ?nth 1 = [ [ [ -1 ] 3dip nth set-nth ] [ { [ [ 1 + ] 2dip ] [ [ 1 - ] 2dip ] [ [ 1 + ] dip ] [ [ 1 - ] dip ] } [ flood-fill ] map-compose 3cleave ] 3bi ] [ 3drop ] if ;   : count-clusters ( matrix -- Cn ) 0 swap dup dim matrix-coordinates flip concat [ first2 rot 3dup ?nth ?nth 1 = [ flood-fill 1 + ] [ 3drop ] if ] with each ;   : mean-cluster-density ( matrix -- mcd ) [ count-clusters ] [ dim first sq / ] bi ;   : simulate ( n -- avg-mcd ) iterations swap [ p rand-bit-matrix mean-cluster-density ] curry replicate sum iterations / ;   : main ( -- ) { 4 64 256 1024 4096 } [ [ iterations p ] dip dup simulate "iterations = %d p = %.1f n = %4d sim = %.5f\n" printf ] each ;   MAIN: 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.
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   var ( n_range = []int{4, 64, 256, 1024, 4096} M = 15 N = 15 )   const ( p = .5 t = 5 NOT_CLUSTERED = 1 cell2char = " #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" )   func newgrid(n int, p float64) [][]int { g := make([][]int, n) for y := range g { gy := make([]int, n) for x := range gy { if rand.Float64() < p { gy[x] = 1 } } g[y] = gy } return g }   func pgrid(cell [][]int) { for n := 0; n < N; n++ { fmt.Print(n%10, ") ") for m := 0; m < M; m++ { fmt.Printf(" %c", cell2char[cell[n][m]]) } fmt.Println() } }   func cluster_density(n int, p float64) float64 { cc := clustercount(newgrid(n, p)) return float64(cc) / float64(n) / float64(n) }   func clustercount(cell [][]int) int { walk_index := 1 for n := 0; n < N; n++ { for m := 0; m < M; m++ { if cell[n][m] == NOT_CLUSTERED { walk_index++ walk_maze(m, n, cell, walk_index) } } } return walk_index - 1 }   func walk_maze(m, n int, cell [][]int, indx int) { cell[n][m] = indx if n < N-1 && cell[n+1][m] == NOT_CLUSTERED { walk_maze(m, n+1, cell, indx) } if m < M-1 && cell[n][m+1] == NOT_CLUSTERED { walk_maze(m+1, n, cell, indx) } if m > 0 && cell[n][m-1] == NOT_CLUSTERED { walk_maze(m-1, n, cell, indx) } if n > 0 && cell[n-1][m] == NOT_CLUSTERED { walk_maze(m, n-1, cell, indx) } }   func main() { rand.Seed(time.Now().Unix()) cell := newgrid(N, .5) fmt.Printf("Found %d clusters in this %d by %d grid\n\n", clustercount(cell), N, N) pgrid(cell) fmt.Println()   for _, n := range n_range { M = n N = n sum := 0. for i := 0; i < t; i++ { sum += cluster_density(n, p) } sim := sum / float64(t) fmt.Printf("t=%3d p=%4.2f n=%5d sim=%7.5f\n", 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.
#Action.21
Action!
PROC Main() DEFINE MAXNUM="10000" CARD ARRAY pds(MAXNUM+1) CARD i,j   FOR i=2 TO MAXNUM DO pds(i)=1 OD FOR i=2 TO MAXNUM DO FOR j=i+i TO MAXNUM STEP i DO pds(j)==+i OD OD   FOR i=2 TO MAXNUM DO IF pds(i)=i THEN PrintCE(i) FI OD RETURN
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.
#D
D
import std.stdio, std.random, std.array, std.range, std.algorithm;   struct Grid { // Not enforced by runtime and type system: // a Cell must contain only the flags bits. alias Cell = uint;   enum : Cell { // Cell states (bit flags). empty = 0, filled = 1, rightWall = 2, bottomWall = 4 }   const size_t nc, nr; Cell[] cells;   this(in size_t nRows, in size_t nCols) pure nothrow { nr = nRows; nc = nCols;   // Allocate two addition rows to avoid checking bounds. // Bottom row is also required by drippage. cells = new Cell[nc * (nr + 2)]; }   void initialize(in double prob, ref Xorshift rng) { cells[0 .. nc] = bottomWall | rightWall; // First row.   uint pos = nc; foreach (immutable r; 1 .. nr + 1) { foreach (immutable c; 1 .. nc) cells[pos++] = (uniform01 < prob ?bottomWall : empty) | (uniform01 < prob ? rightWall : empty); cells[pos++] = rightWall | (uniform01 < prob ? bottomWall : empty); }   cells[$ - nc .. $] = empty; // Last row. }   bool percolate() pure nothrow @nogc { bool fill(in size_t i) pure nothrow @nogc { if (cells[i] & filled) return false;   cells[i] |= filled;   if (i >= cells.length - nc) return true; // Success: reached bottom row.   return (!(cells[i] & bottomWall) && fill(i + nc)) || (!(cells[i] & rightWall) && fill(i + 1)) || (!(cells[i - 1] & rightWall) && fill(i - 1)) || (!(cells[i - nc] & bottomWall) && fill(i - nc)); }   return iota(nc, nc + nc).any!fill; }   void show() const { writeln("+-".replicate(nc), '+');   foreach (immutable r; 1 .. nr + 2) { write(r == nr + 1 ? ' ' : '|'); foreach (immutable c; 0 .. nc) { immutable cell = cells[r * nc + c]; write((cell & filled) ? (r <= nr ? '#' : 'X') : ' '); write((cell & rightWall) ? '|' : ' '); } writeln;   if (r == nr + 1) return;   foreach (immutable c; 0 .. nc) write((cells[r * nc + c] & bottomWall) ? "+-" : "+ "); '+'.writeln; } } }   void main() { enum uint nr = 10, nc = 10; // N. rows and columns of the grid. enum uint nTries = 10_000; // N. simulations for each probability. enum uint nStepsProb = 10; // N. steps of probability.   auto rng = Xorshift(2); auto g = Grid(nr, nc); g.initialize(0.5, rng); g.percolate; g.show;   writefln("\nRunning %dx%d grids %d times for each p:", nr, nc, nTries); foreach (immutable p; 0 .. nStepsProb) { immutable probability = p / double(nStepsProb); uint nPercolated = 0; foreach (immutable i; 0 .. nTries) { g.initialize(probability, rng); nPercolated += g.percolate; } writefln("p = %0.2f: %.4f", probability, nPercolated / double(nTries)); } }
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.
#FreeBASIC
FreeBASIC
Function run_test(p As Double, longitud As Integer, runs As Integer) As Double Dim As Integer r, l, cont = 0 Dim As Integer v, pv   For r = 1 To runs pv = 0 For l = 1 To longitud v = Rnd < p cont += Iif(pv < v, 1, 0) pv = v Next l Next r Return (cont/runs/longitud) End Function   Print "Running 1000 tests each:" Print " p n K p(1-p) delta" Print String(46,"-")   Dim As Double K, p, p1p Dim As Integer n, ip   For ip = 1 To 10 Step 2 p = ip / 10 p1p = p * (1-p) n = 100 While n <= 100000 K = run_test(p, n, 1000) Print Using !"#.# ###### #.#### #.#### +##.#### (##.## \b%)"; _ p; n; K; p1p; K-p1p; (K-p1p)/p1p*100 n *= 10 Wend Print Next ip Sleep
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.
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Monad.Random import Data.Array.Unboxed import Data.List import Formatting   type Field = UArray (Int, Int) Char   -- Start percolating some seepage through a field. -- Recurse to continue percolation with new seepage. percolateR :: [(Int, Int)] -> Field -> (Field, [(Int,Int)]) percolateR [] f = (f, []) percolateR seep f = let ((xLo,yLo),(xHi,yHi)) = bounds f validSeep = filter (\p@(x,y) -> x >= xLo && x <= xHi && y >= yLo && y <= yHi && f!p == ' ') $ nub $ sort seep   neighbors (x,y) = [(x,y-1), (x,y+1), (x-1,y), (x+1,y)]   in percolateR (concatMap neighbors validSeep) (f // map (\p -> (p,'.')) validSeep)   -- Percolate a field. Return the percolated field. percolate :: Field -> Field percolate start = let ((_,_),(xHi,_)) = bounds start (final, _) = percolateR [(x,0) | x <- [0..xHi]] start in final   -- Generate a random field. initField :: Int -> Int -> Double -> Rand StdGen Field initField w h threshold = do frnd <- fmap (\rv -> if rv<threshold then ' ' else '#') <$> getRandoms return $ listArray ((0,0), (w-1, h-1)) frnd   -- Get a list of "leaks" from the bottom of a field. leaks :: Field -> [Bool] leaks f = let ((xLo,_),(xHi,yHi)) = bounds f in [f!(x,yHi)=='.'| x <- [xLo..xHi]]   -- Run test once; Return bool indicating success or failure. oneTest :: Int -> Int -> Double -> Rand StdGen Bool oneTest w h threshold = or.leaks.percolate <$> initField w h threshold   -- Run test multple times; Return the number of tests that pass. multiTest :: Int -> Int -> Int -> Double -> Rand StdGen Double multiTest testCount w h threshold = do results <- replicateM testCount $ oneTest w h threshold let leakyCount = length $ filter id results return $ fromIntegral leakyCount / fromIntegral testCount   -- Display a field with walls and leaks. showField :: Field -> IO () showField a = do let ((xLo,yLo),(xHi,yHi)) = bounds a mapM_ print [ [ a!(x,y) | x <- [xLo..xHi]] | y <- [yLo..yHi]]   main :: IO () main = do g <- getStdGen let w = 15 h = 15 threshold = 0.6 (startField, g2) = runRand (initField w h threshold) g   putStrLn ("Unpercolated field with " ++ show threshold ++ " threshold.") putStrLn "" showField startField   putStrLn "" putStrLn "Same field after percolation." putStrLn "" showField $ percolate startField   let testCount = 10000 densityCount = 10   putStrLn "" putStrLn ( "Results of running percolation test " ++ show testCount ++ " times with thresholds ranging from 0/" ++ show densityCount ++ " to " ++ show densityCount ++ "/" ++ show densityCount ++ " .")   let densities = [0..densityCount] tests = sequence [multiTest testCount w h v | density <- densities, let v = fromIntegral density / fromIntegral densityCount ] results = zip densities (evalRand tests g2) mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) density densityCount x | (density,x) <- results]
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
#Ada
Ada
generic N: positive; package Generic_Perm is subtype Element is Positive range 1 .. N; type Permutation is array(Element) of Element;   procedure Set_To_First(P: out Permutation; Is_Last: out Boolean); procedure Go_To_Next(P: in out Permutation; Is_Last: out Boolean); end Generic_Perm;
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class PerfectShuffle { static void Main() { foreach (int input in new [] {8, 24, 52, 100, 1020, 1024, 10000}) { int[] numbers = Enumerable.Range(1, input).ToArray(); Console.WriteLine($"{input} cards: {ShuffleThrough(numbers).Count()}"); }   IEnumerable<T[]> ShuffleThrough<T>(T[] original) { T[] copy = (T[])original.Clone(); do { yield return copy = Shuffle(copy); } while (!Enumerable.SequenceEqual(original, copy)); } }   public static T[] Shuffle<T>(T[] array) { if (array.Length % 2 != 0) throw new ArgumentException("Length must be even."); int half = array.Length / 2; T[] result = new T[array.Length]; for (int t = 0, l = 0, r = half; l < half; t+=2, l++, r++) { result[t] = array[l]; result[t+1] = array[r]; } return result; }   }
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.
#GLSL
GLSL
  float rand(vec2 c){ return fract(sin(dot(c.xy ,vec2(12.9898,78.233))) * 43758.5453); }   float noise(vec2 p, float freq ){ float unit = screenWidth/freq; vec2 ij = floor(p/unit); vec2 xy = mod(p,unit)/unit; //xy = 3.*xy*xy-2.*xy*xy*xy; xy = .5*(1.-cos(PI*xy)); float a = rand((ij+vec2(0.,0.))); float b = rand((ij+vec2(1.,0.))); float c = rand((ij+vec2(0.,1.))); float d = rand((ij+vec2(1.,1.))); float x1 = mix(a, b, xy.x); float x2 = mix(c, d, xy.x); return mix(x1, x2, xy.y); }   float pNoise(vec2 p, int res){ float persistance = .5; float n = 0.; float normK = 0.; float f = 4.; float amp = 1.; int iCount = 0; for (int i = 0; i<50; i++){ n+=amp*noise(p, f); f*=2.; normK+=amp; amp*=persistance; if (iCount == res) break; iCount++; } float nf = n/normK; return nf*nf*nf*nf; }  
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
#Draco
Draco
proc nonrec gcd(word a, b) word: word c; while b ~= 0 do c := a; a := b; b := c % b od; a corp   proc nonrec totient(word n) word: word r, i; r := 0; for i from 1 upto n-1 do if gcd(n,i) = 1 then r := r+1 fi od; r corp   proc nonrec perfect(word n) bool: word sum, x; sum := 0; x := n; while x := totient(x); sum := sum + x; x ~= 1 do od; sum = n corp   proc nonrec main() void: word seen, n; seen := 0; n := 3; while seen < 20 do if perfect(n) then write(n, " "); seen := seen + 1 fi; n := n + 2 od corp
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
#Factor
Factor
USING: formatting kernel lists lists.lazy math math.primes.factors ;   : perfect? ( n -- ? ) [ 0 ] dip dup [ dup 2 < ] [ totient tuck [ + ] 2dip ] until drop = ;   20 1 lfrom [ perfect? ] lfilter ltake list>array "%[%d, %]\n" printf
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
#Factor
Factor
USING: formatting grouping io kernel math qw random sequences vectors ; IN: rosetta-code.playing-cards   CONSTANT: pips qw{ A 2 3 4 5 6 7 8 9 10 J Q K } CONSTANT: suits qw{ ♥ ♣ ♦ ♠ }   : <deck> ( -- vec ) 52 <iota> >vector ;   : card>str ( n -- str ) 13 /mod [ suits nth ] [ pips nth ] bi* prepend ;   : print-deck ( seq -- ) 13 group [ [ card>str "%-4s" printf ] each nl ] each ;   <deck>  ! make new deck randomize  ! shuffle the deck dup pop drop ! deal from the deck (and discard) print-deck  ! print the deck
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
#Elixir
Elixir
defmodule Pi do def calc, do: calc(1,0,1,1,3,3,0)   defp calc(q,r,t,k,n,l,c) when c==50 do IO.write "\n" calc(q,r,t,k,n,l,0) end defp calc(q,r,t,k,n,l,c) when (4*q + r - t) < n*t do IO.write n calc(q*10, 10*(r-n*t), t, k, div(10*(3*q+r), t) - 10*n, l, c+1) end defp calc(q,r,t,k,_n,l,c) do calc(q*k, (2*q+r)*l, t*l, k+1, div(q*7*k+2+r*l, t*l), l+2, c) end end   Pi.calc
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
#M2000_Interpreter
M2000 Interpreter
  Module GamePig { Print "Game of Pig" dice=-1 res$="" Player1points=0 Player1sum=0 Player2points=0 Player2sum=0 HaveWin=False score() \\ for simulation, feed the keyboard buffer with R and H simulate$=String$("R", 500) For i=1 to 100 Insert Random(1,Len(simulate$)) simulate$="H" Next i Keyboard simulate$ \\ end simulation while res$<>"Q" { Print "Player 1 turn" PlayerTurn(&Player1points, &player1sum) if res$="Q" then exit Player1sum+=Player1points Score() Print "Player 2 turn" PlayerTurn(&Player2points,&player2sum) if res$="Q" then exit Player2sum+=Player2points Score() } If HaveWin then { Score() If Player1Sum>Player2sum then { Print "Player 1 Win" } Else Print "Player 2 Win" }   Sub Rolling() dice=random(1,6) Print "dice=";dice End Sub Sub PlayOrQuit() Print "R -Roling Q -Quit" Repeat { res$=Ucase$(Key$) } Until Instr("RQ", res$)>0 End Sub Sub PlayAgain() Print "R -Roling H -Hold Q -Quit" Repeat { res$=Ucase$(Key$) } Until Instr("RHQ", res$)>0 End Sub Sub PlayerTurn(&playerpoints, &sum) PlayOrQuit() If res$="Q" then Exit Sub playerpoints=0 Rolling() While dice<>1 and res$="R" { playerpoints+=dice if dice>1 and playerpoints+sum>100 then { sum+=playerpoints HaveWin=True res$="Q" } Else { PlayAgain() if res$="R" then Rolling() } } if dice=1 then playerpoints=0 End Sub Sub Score() Print "Player1 points="; Player1sum Print "Player2 points="; Player2sum End Sub } GamePig  
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.
#Factor
Factor
USING: lists lists.lazy math.bitwise math.primes math.ranges prettyprint sequences ;   : pernicious? ( n -- ? ) bit-count prime? ;   25 0 lfrom [ pernicious? ] lfilter ltake list>array .  ! print first 25 pernicious numbers 888,888,877 888,888,888 [a,b] [ pernicious? ] filter .  ! print pernicious numbers in range
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
#REXX
REXX
/*REXX program finds and displays Pierpont primes of the first and second kinds. */ parse arg n . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/ numeric digits n /*ensure enough decimal digs (bit int).*/ big= copies(9, digits() ) /*BIG: used as a max number (a limit).*/ @.= '2nd'; @.1= '1st' do t=1 to -1 by -2; usum= 0; vsum= 0; s= 0 /*T is 1, then -1.*/ #= 0 /*number of Pierpont primes (so far). */ $=; do j=0 until #>=n /*$: the list " " " " */ if usum<=s then usum= get(2, 3); if vsum<=s then vsum= get(3, 2) s= min(vsum, usum); if \isPrime(s) then iterate /*get min; Not prime? */ #= # + 1; $= $ s /*bump counter; append.*/ end /*j*/ say w= length(word($, #) ) /*biggest prime length.*/ say center(n " Pierpont primes of the " @.t ' kind', max(10 *(w+1), 80), "═")   do p=1 by 10 to #; _=; do k=p for 10; _= _ right( word($, k), w) end /*k*/ if _\=='' then say substr( strip(_, "T"), 2) end /*p*/ end /*t*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ isPrime: procedure; parse arg x '' -1 _; if x<17 then return wordpos(x,"2 3 5 7 11 13")>0 if _==5 then return 0; if x//2==0 then return 0 /*not prime. */ if x//3==0 then return 0; if x//7==0 then return 0 /* " " */ do j=11 by 6 until j*j>x /*skip ÷ 3's.*/ if x//j==0 then return 0; if x//(j+2)==0 then return 0 /*not prime. */ end /*j*/; return 1 /*it's prime.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ get: parse arg c1,c2; m=big; do ju=0; pu= c1**ju; if pu+t>s then return min(m, pu+t) do jv=0; pv= c2**jv; if pv >s then iterate ju _= pu*pv + t; if _ >s then m= min(_, m) end /*jv*/ end /*ju*/ /*see the RETURN (above). */
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Hare
Hare
use fmt; use math::random; use datetime;   export fn main() void = { const array = ["one", "two", "three", "four", "five"]; const seed = datetime::now(); const seed = datetime::nsec(&seed); let r = math::random::init(seed: u32);   fmt::printfln("{}", array[math::random::u32n(&r, len(array): u32)])!; };
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Haskell
Haskell
import System.Random (randomRIO)   pick :: [a] -> IO a pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1)   x <- pick [1, 2, 3]
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Yabasic
Yabasic
for i = 1 to 99 if isPrime(i) print str$(i), " "; next i print end   sub isPrime(v) if v < 2 return False if mod(v, 2) = 0 return v = 2 if mod(v, 3) = 0 return v = 3 d = 5 while d * d <= v if mod(v, d) = 0 then return False else d = d + 2 : fi wend return True end sub
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
#IS-BASIC
IS-BASIC
100 PROGRAM "ReverseS.bas" 110 LET S$="Rosetta Code Pharse Reversal" 120 PRINT S$ 130 PRINT REVERSE$(S$) 140 PRINT REVERSEW$(S$) 150 PRINT REVERSEC$(S$) 160 DEF REVERSE$(S$) 170 LET T$="" 180 FOR I=LEN(S$) TO 1 STEP-1 190 LET T$=T$&S$(I) 200 NEXT 210 LET REVERSE$=T$ 220 END DEF 230 DEF REVERSEW$(S$) 240 LET T$="":LET PE=LEN(S$) 250 FOR PS=PE TO 1 STEP-1 260 IF PS=1 OR S$(PS)=" " THEN LET T$=T$&" ":LET T$=T$&LTRIM$(S$(PS:PE)):LET PE=PS-1 270 NEXT 280 LET REVERSEW$=LTRIM$(T$) 290 END DEF 300 DEF REVERSEC$(S$) 310 LET T$="":LET PS=1 320 FOR PE=1 TO LEN(S$) 330 IF PE=LEN(S$) OR S$(PE)=" " THEN LET T$=T$&" ":LET T$=T$&REVERSE$(RTRIM$(S$(PS:PE))):LET PS=PE+1 340 NEXT 350 LET REVERSEC$=LTRIM$(T$) 360 END DEF
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
#J
J
getWords=: (' '&splitstring) :. (' '&joinstring) reverseString=: |. reverseWords=: |.&.>&.getWords reverseWordOrder=: |.&.getWords
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
#FreeBASIC
FreeBASIC
' version 08-04-2017 ' compile with: fbc -s console   Sub Subfactorial(a() As ULongInt)   Dim As ULong i Dim As ULongInt num   For i = 0 To UBound(a) num = num * i If (i And 1) = 1 Then num -= 1 Else num += 1 End If a(i) = num Next   End Sub   ' Heap's algorithm non-recursive Function perms_derange(n As ULong, flag As Long = 0) As ULongInt ' fast upto n < 12 If n = 0 Then Return 1   Dim As ULong i, j, c1, count Dim As ULong a(0 To n -1), c(0 To n -1)   For j = 0 To n -1 a(j) = j Next   While i < n If c(i) < i Then If (i And 1) = 0 Then Swap a(0), a(i) Else Swap a(c(i)), a(i) End If For j = 0 To n -1 If a(j) = j Then j = 99 Next If j < 99 Then count += 1 If flag = 0 Then c1 += 1 For j = 0 To n -1 Print a(j); Next If c1 > 12 Then Print : c1 = 0 Else Print " "; End If End If End If c(i) += 1 i = 0 Else c(i) = 0 i += 1 End If Wend If flag = 0 AndAlso c1 <> 0 Then Print Return count   End Function   ' ------=< MAIN >=------   Dim As ULong i, n = 4 Dim As ULongInt subfac(20)   Subfactorial(subfac())   Print "permutations derangements for n = "; n i = perms_derange(n) Print "count returned = "; i; " , !"; n; " calculated = "; subfac(n)   Print Print "count counted subfactorial" Print "---------------------------" For i = 0 To 9 Print Using " ###: ######## ########"; i; perms_derange(i, 1); subfac(i) Next For i = 10 To 20 Print Using " ###: ###################"; i; subfac(i) Next   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every write("Permutations of length ",n := !A) do every p := permute(n) do write("\t",showList(p[1])," -> ",right(p[2],2)) end   procedure permute(n) items := [[]] every (j := 1 to n, new_items := []) do { every item := items[i := 1 to *items] do { if *item = 0 then put(new_items, [j]) else if i%2 = 0 then every k := 1 to *item+1 do { new_item := item[1:k] ||| [j] ||| item[k:0] put(new_items, new_item) } else every k := *item+1 to 1 by -1 do { new_item := item[1:k] ||| [j] ||| item[k:0] put(new_items, new_item) } } items := new_items } suspend (i := 0, [!items, if (i+:=1)%2 = 0 then 1 else -1]) end   procedure showList(A) every (s := "[") ||:= image(!A)||", " return s[1:-2]||"]" end
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.
#Nim
Nim
import strformat   const data = [85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98]   func pick(at, remain, accu, treat: int): int = if remain == 0: return if accu > treat: 1 else: 0 return pick(at - 1, remain - 1, accu + data[at - 1], treat) + (if at > remain: pick(at - 1, remain, accu, treat) else: 0)     var treat = 0 var le, gt = 0 var total = 1.0 for i in countup(0, 8): treat += data[i] for i in countdown(19, 11): total *= float(i) for i in countdown(9, 1): total /= float(i)   gt = pick(19, 9, 0, treat) le = int(total - float(gt)) echo fmt"<= : {100.0 * float(le) / total:.6f}% {le}" echo fmt" > : {100.0 * float(gt) / total:.6f}% {gt}"
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.
#Perl
Perl
#!/usr/bin/perl use warnings; use strict;   use List::Util qw{ sum };     sub means { my @groups = @_; return map sum(@$_) / @$_, @groups; }     sub following { my $pattern = shift; my $orig_count = grep $_, @$pattern; my $count; do { my $i = $#{$pattern}; until (0 > $i) { $pattern->[$i] = $pattern->[$i] ? 0 : 1; last if $pattern->[$i]; --$i; } $count = grep $_, @$pattern; } until $count == $orig_count or not $count; undef @$pattern unless $count; }     my @groups; my $i = 0; while (<DATA>) { chomp; $i++, next if /^$/; push @{ $groups[$i] }, $_; }   my @orig_means = means(@groups); my $orig_cmp = $orig_means[0] - $orig_means[1];   my $pattern = [ (0) x @{ $groups[0] }, (1) x @{ $groups[1] } ];   my @cmp = (0) x 3; while (@$pattern) { my @perms = map { my $g = $_; [ (@{ $groups[0] }, @{ $groups[1] } ) [ grep $pattern->[$_] == $g, 0 .. $#{$pattern} ] ]; } 0, 1; my @means = means(@perms); $cmp[ ($means[0] - $means[1]) <=> $orig_cmp ]++; } continue { following($pattern); } my $all = sum(@cmp); my $length = length $all; for (0, -1, 1) { printf "%-7s %${length}d %6.3f%%\n", (qw(equal greater less))[$_], $cmp[$_], 100 * $cmp[$_] / $all; }     __DATA__ 85 88 75 66 25 29 83 39 97   68 41 10 49 16 65 32 92 28 98