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/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
#Wren
Wren
import "/ioutil" for Input import "/str" for Str import "random" for Random   var name1 = Input.text("Player 1 - Enter your name : ").trim() name1 = (name1 == "") ? "PLAYER1" : Str.upper(name1) var name2 = Input.text("Player 2 - Enter your name : ").trim() name2 = (name2 == "") ? "PLAYER2" : Str.upper(name2) var names = [name1, name2] var r = Random.new() var totals = [0, 0] var player = 0 while (true) { System.print("\n%(names[player])") System.print(" Your total score is currently %(totals[player])") var score = 0 while (true) { var rh = Str.lower(Input.option(" Roll or Hold r/h : ", "rhRH")) if (rh == "h") { totals[player] = totals[player] + score System.print(" Your total score is now %(totals[player])") if (totals[player] >= 100) { System.print(" So, %(names[player]), YOU'VE WON!") return } player = (player == 0) ? 1 : 0 break } var dice = r.int(1, 7) System.print(" You have thrown a %(dice)") if (dice == 1) { System.print(" Sorry, your score for this round is now 0") System.print(" Your total score remains at %(totals[player])") player = (player == 0) ? 1 : 0 break } score = score + dice System.print(" 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.
#Picat
Picat
go =>   println(take_n(pernicious_number,25,1)), println([J : J in 888888877..888888888, pernicious_number(J)]), nl.   % Get the first N numbers that satisfies function F, starting with S take_n(F,N,S) = L => I = S, C = 0, L = [], while(C < N) if call(F,I) then L := L ++ [I], C := C + 1 end, I := I + 1 end.   pop_count(N) = sum([1: I in N.to_binary_string(), I = '1']).   pernicious_number(N) => prime(pop_count(N)).
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.
#PicoLisp
PicoLisp
(de pernicious? (N) (prime? (cnt = (chop (bin N)) '("1" .))) )
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#ReScript
ReScript
let fruits = ["apple", "banana", "coconut", "orange", "lychee"]   let pickRand = arr => { let len = Js.Array.length(arr) let i = Js.Math.random_int(0, len) arr[i] }   Js.log(pickRand(fruits))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#REXX
REXX
/*REXX program picks a random element from a list (tongue in cheek, a visual pun).*/ _= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium' _=_ 'magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium' _=_ 'scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium' _=_ 'germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium' _=_ 'niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin' _=_ 'antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium' _=_ 'neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium' _=_ 'thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum' _=_ 'gold mercury thallium lead bismuth polonium astatine radon francium radium actinium' _=_ 'thorium protactinium uranium neptunium plutonium americium curium berkelium' _=_ 'californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium' _=_ 'seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium' _=_ 'flerovium moscovium livermorium tennessine oganesson ununenniym unbinvlium umbiunium'   /*───── You can't trust atoms, ─────*/ /*───── they make everything up. ─────*/   #= words(_) /*obtain the number of words in list. */ item= word(_, random(1, #) ) /*pick a random word (element) in list.*/ say 'random element: ' item /*stick a fork in it, we're all done. */
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
#Tcl
Tcl
set s "rosetta code phrase reversal" # Reverse all characters puts [string reverse $s] # Reverse characters in each word puts [lmap word $s {string reverse $word}] # Reverse the words but not the characters puts [lreverse $s]
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#UNIX_Shell
UNIX Shell
s1="rosetta code phrase reversal" echo "Original string ----------------------> "$s1   echo -n "1.) Reverse the string ---------------> " echo $s1|rev   echo -n "2.) Reverse characters of each word --> " echo $s1|tr " " "\n"|rev|tr "\n" " ";echo   echo -n "3.) Reverse word order ---------------> " word_num=$(echo $s1|wc -w) while [ $word_num != 0 ];do echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " " word_num=$(expr $word_num - 1);done;echo
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
#Ruby
Ruby
def derangements(n) ary = (1 .. n).to_a ary.permutation.select do |perm| ary.zip(perm).all? {|a,b| a != b} end end   def subfact(n) case n when 0 then 1 when 1 then 0 else (n-1)*(subfact(n-1) + subfact(n-2)) end end   puts "derangements for n = 4" derangements(4).each{|d|p d}   puts "\n n derange subfact" (0..9).each do |n| puts "%2d :%8d,%8d" % [n, derangements(n).size, subfact(n)] end   puts "\nNumber of derangements" (10..20).each do |n| puts "#{n} : #{subfact(n)}" end
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#Ruby
Ruby
require 'raster_graphics'   class RGBColour # the difference between two colours def -(a_colour) (@red - a_colour.red).abs + (@green - a_colour.green).abs + (@blue - a_colour.blue).abs end end   class Pixmap # the difference between two images def -(a_pixmap) if @width != a_pixmap.width or @height != a_pixmap.height raise ArgumentError, "can't compare images with different sizes" end sum = 0 each_pixel {|x,y| sum += self[x,y] - a_pixmap[x,y]} Float(sum) / (@width * @height * 255 * 3) end end   lenna50 = Pixmap.open_from_jpeg('Lenna50.jpg') lenna100 = Pixmap.open_from_jpeg('Lenna100.jpg')   puts "difference: %.5f%%" % (100.0 * (lenna50 - lenna100))
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.
#Elena
Elena
import system'routines; import system'math; import extensions;   extension extension { isPerfect() = new Range(1, self - 1).selectBy:(n => (self.mod:n == 0).iif(n,0) ).summarize(new Integer()) == self; }   public program() { for(int n := 1, n < 10000, n += 1) { if(n.isPerfect()) { console.printLine(n," is perfect") } };   console.readChar() }
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.
#Elixir
Elixir
defmodule RC do def is_perfect(1), do: false def is_perfect(n) when n > 1 do Enum.sum(factor(n, 2, [1])) == n end   defp factor(n, i, factors) when n < i*i , do: factors defp factor(n, i, factors) when n == i*i , do: [i | factors] defp factor(n, i, factors) when rem(n,i)==0, do: factor(n, i+1, [i, div(n,i) | factors]) defp factor(n, i, factors) , do: factor(n, i+1, factors) end   IO.inspect (for i <- 1..10000, RC.is_perfect(i), do: i)
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
#EDSAC_order_code
EDSAC order code
  [Permutations task for Rosetta Code.] [EDSAC program, Initial Orders 2.]   T51K P200F [G parameter: start address of subroutines] T47K P100F [M parameter: start address of main routine]   [====================== G parameter: Subroutines =====================] E25K TG GK [Constants used in the subroutines] [0] AF [add to address to make A order for that address] [1] SF [add to address to make S order for that address] [2] UF [(1) add to address to make U order for that address] [(2) subtract from S order to make T order, same address] [3] OF [add to A order to make T order, same address]   [----------------------------------------------------------- Subroutine to initialize an array of n short (17-bit) words to 0, 1, 2, ..., n-1 (in the address field). Parameters: 4F = address of array; 5F = n = length of array. Workspace: 0F, 1F.] [4] A3F [plant return link as usual] T19@ A4F [address of array] A2@ [make U order for that address] T1F [store U order in 1F] A5F [load n = number of elements (in address field)] S2F [make n-1] [Start of loop; works backwards, n-1 to 0] [11] UF [store array element in 0F] A1F [make order to store element in array] T15@ [plant that order in code] AF [pick up element fron 0F] [15] UF [(planted) store element in array] S2F [dec to next element] E11@ [loop if still >= 0] TF [clear acc. before return] [19] ZF [overwritten by jump back to caller]   [------------------------------------------------------------------- Subroutine to get next permutation in lexicographic order. Uses same 4-step algorithm as Wikipedia article "Permutations", but notation in comments differs from that in Wikipedia. Parameters: 4F = address of array; 5F = n = length of array. 0F is returned as 0 for success, < 0 if passed-in permutation is the last. Workspace: 0F, 1F.] [20] A3F [plant return link as usual] T103@   [Step 1: Find the largest index k such that a{k} > a{k-1}. If no such index exists, the passed-in permutation is the last.] A4F [load address of a{0}] A@ [make A order for a{0}] U1F [store as test for end of loop] A5F [make A order for a{n}] U96@ [plant in code below] S2F [make A order for a{n-1}] T43@ [plant in code below] A4F [load address of a{0}] A5F [make address of a{n}] A1@ [make S order for a{n}] T44@ [plant in code below] [Start of loop for comparing a{k} with a{k-1}] [33] TF [clear acc] A43@ [load A order for a{k}] S2F [make A order for a{k-1}] S1F [tested all yet?] G102@ [if yes, jump to failed (no more permutations)] A1F [restore accumulator after test] T43@ [plant updated A order] A44@ [dec address in S order] S2F T44@ [43] SF [(planted) load a{k-1}] [44] AF [(planted) subtract a{k}] E33@ [loop back if a{k-1} > a{k}]   [Step 2: Find the largest index j >= k such that a{j} > a{k-1}. Such an index j exists, because j = k is an instance.] TF [clear acc] A4F [load address of a{0}] A5F [make address of a{n}] A1@ [make S order for a{n}] T1F [save as test for end of loop] A44@ [load S order for a{k}] T64@ [plant in code below] A43@ [load A order for a{k-1}] T63@ [plant in code below] [Start of loop] [55] TF [clear acc] A64@ [load S order for a{j} (initially j = k)] U75@ [plant in code below] A2F [inc address (in effect inc j)] S1F [test for end of array] E66@ [jump out if so] A1F [restore acc after test] T64@ [update S order] [63] AF [(planted) load a{k-1}] [64] SF [(planted) subtract a{j}] G55@ [loop back if a{j} still > a{k-1}] [66] [Step 3: Swap a{k-1} and a{j}] TF [clear acc] A63@ [load A order for a{k-1}] U77@ [plant in code below, 2 places] U94@ A3@ [make T order for a{k-1}] T80@ [plant in code below] A75@ [load S order for a{j}] S2@ [make T order for a{j}] T78@ [plant in code below] [75] SF [(planted) load -a{j}] TF [park -a{j} in 0F] [77] AF [(planted) load a{k-1}] [78] TF [(planted) store a{j}] SF [load a{j} by subtracting -a{j}] [80] TF [(planted) store in a{k-1}]   [Step 4: Now a{k}, ..., a{n-1} are in decreasing order. Change to increasing order by repeated swapping.] [81] A96@ [counting down from a{n} (exclusive end of array)] S2F [make A order for a{n-1}] U96@ [plant in code] A3@ [make T order for a{n-1}] T99@ [plant] A94@ [counting up from a{k-1} (exclusive)] A2F [make A order for a{k}] U94@ [plant] A3@ [make T order for a{k}] U97@ [plant] S99@ [swapped all yet?] E101@ [if yes, jump to exit from subroutine] [Swapping two array elements, initially a{k} and a{n-1}] TF [clear acc] [94] AF [(planted) load 1st element] TF [park in 0F] [96] AF [(planted) load 2nd element] [97] TF [(planted) copy to 1st element] AF [load old 1st element] [99] TF [(planted) copy to 2nd element] E81@ [always loop back] [101] TF [done, return 0 in location 0F] [102] TF [return status to caller in 0F; also clears acc] [103] ZF [(planted) jump back to caller]   [==================== M parameter: Main routine ==================] [Prints all 120 permutations of the letters in 'EDSAC'.] E25K TM GK [Constants used in the main routine] [0] P900F [address of permutation array] [1] P5F [number of elements in permutation (in address field)] [Array of letters in 'EDSAC', in alphabetical order] [2] AF CF DF EF SF [7] O2@ [add to index to make O order for letter in array] [8] P12F [permutations per printed line (in address field)] [9] AF [add to address to make A order for that address] [Teleprinter characters] [10] K2048F [set letters mode] [11]  !F [space] [12] @F [carriage return] [13] &F [line feed] [14] K4096F [null]   [Entry point, with acc = 0.] [15] O10@ [set teleprinter to letters] S8@ [intialize -ve count of permutations per line] T7F [keep count in 7F] A@ [pass address of permutation array in 4F] T4F A1@ [pass number of elements in 5F] T5F [22] A22@ [call subroutine to initialize permutation array] G4G [Loop: print current permutation, then get next (if any)] [24] A4F [address] A9@ [make A order] T29@ [plant in code] S5F [initialize -ve count of array elements] [28] T6F [keep count in 6F] [29] AF [(planted) load permutation element] A7@ [make order to print letter from table] T32@ [plant in code] [32] OF [(planted) print letter from table] A29@ [inc address in permutation array] A2F T29@ A6F [inc -ve count of array elements] A2F G28@ [loop till count becomes 0] A7F [inc -ve count of perms per line] A2F E44@ [jump if end of line] O11@ [else print a space] G47@ [join common code] [44] O12@ [print CR] O13@ [print LF] S8@ [47] T7F [update -ve count of permutations in line] [48] A48@ [call subroutine for next permutation (if any)] G20G AF [test 0F: got a new permutation?] E24@ [if so, loop to print it] O14@ [no more, output null to flush teleprinter buffer] ZF [halt program] E15Z [define entry point] PF [enter with acc = 0] [end]  
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#Racket
Racket
#lang racket/base (require racket/list)   (define (perfect-shuffle l) (define-values (as bs) (split-at l (/ (length l) 2))) (foldr (λ (a b d) (list* a b d)) null as bs))   (define (perfect-shuffles-needed n) (define-values (_ rv) (for/fold ((d (perfect-shuffle (range n))) (i 1)) ((_ (in-naturals)) #:break (apply < d)) (values (perfect-shuffle d) (add1 i)))) rv)   (module+ test (require rackunit) (check-equal? (perfect-shuffle '(1 2 3 4)) '(1 3 2 4))   (define (test-perfect-shuffles-needed n e) (define psn (perfect-shuffles-needed n)) (printf "Deck size:\t~a\tShuffles needed:\t~a\t(~a)~%" n psn e) (check-equal? psn e))   (for-each test-perfect-shuffles-needed '(8 24 52 100 1020 1024 10000) '(3 11 8 30 1018 10 300)))
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
#Raku
Raku
sub perfect-shuffle (@deck) { my $mid = @deck / 2; flat @deck[0 ..^ $mid] Z @deck[$mid .. *]; }   for 8, 24, 52, 100, 1020, 1024, 10000 -> $size { my @deck = ^$size; my $n; repeat until [<] @deck { $n++; @deck = perfect-shuffle @deck; }   printf "%5d cards: %4d\n", $size, $n; }
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
#Nim
Nim
import random, strutils   type Suit* = enum ♥, ♦, ♣, ♠   Rank* {.pure.} = enum Ace = (1, "A") Two = (2, "2") Three = (3, "3") Four = (4, "4") Five = (5, "5") Six = (6, "6") Seven = (7, "7") Eight = (8, "8") Nine = (9, "9") Ten = (10, "10") Jack = (11, "J") Queen = (12, "Q") King = (13, "K")   Card* = tuple[rank: Rank; suit: Suit]   # Sequences of cards: synonyms for seq[Card]. Deck* = seq[Card] Hand* = seq[Card]   var initRandom = false # True if "randomize" has been called.     proc `$`*(c: Card): string = ## Return the representation of a card. $c.rank & $c.suit     proc initDeck*(): Deck = ## Initialize a deck. for suit in Suit: for rank in Rank: result.add (rank, suit)     proc shuffle*(cards: var seq[Card]) = ## Shuffle a list of cards (deck or hand). if not initRandom: randomize() initRandom = true random.shuffle(cards)     func `$`*(cards: seq[Card]): string = ## Return the representation of a list o cards. cards.join(" ")     func dealOne*(cards: var seq[Card]): Card = ## Deal one card from a list of cards. assert cards.len > 0 cards.pop()     ## Draw one card from a list of cards. let draw* = dealOne     func deal*(deck: var Deck; nPlayers: Positive; nCards: Positive): seq[Hand] = ## Deal "nCards" cards to "nPlayers" players. assert deck.len >= nCards * nPlayers result.setLen(nPlayers) for n in 1..nCards: for p in 0..<nPlayers: result[p].add deck.pop()     when isMainModule: import strformat   var deck = initDeck() deck.shuffle() echo "Initial deck after shuffling: " for i in 0..2: echo deck[(i * 13)..(i * 13 + 12)], " ..." echo deck[^13..^1]   echo "\nDeal eight cards for five players from the deck:" var hands = deck.deal(5, 8) for i, hand in hands: echo &"Player {i + 1} hand: ", hand echo "Remaining cards: ", deck   echo "\nAfter player 1 drew a card from the deck: " hands[0].add deck.draw() echo "Player 1 hand: ", hands[0] echo "Remaining cards: ", 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
#Nanoquery
Nanoquery
q = 1; r = 0; t = 1 k = 1; n = 3; l = 3   nn = null; nr = null first = true   while true if (((4 * q) + r) - t) < (n * t) print n if first print "." first = false end nr = int(10 * (r - (n * t))) n = int((10 * ((3 * q) + r)) / t) - (10 * n) q *= 10 r = nr else nr = int(((2 * q) + r) * l) nn = int((((q * (7 * k)) + 2) + (r * l)) / (t * l)) q *= k t *= l l += 2 k += 1 n = nn r = nr end if end while
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
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations integer Player, Die, Points, Score(2); [Score(0):= 0; Score(1):= 0; \starting scores for each player Player:= 1; \second player repeat Player:= if Player = 1 then 0 else 1; \next player Points:= 0; \points for current turn loop [Text(0, "Player "); IntOut(0, Player+1); Text(0, " is up. Roll or hold (r/h)? "); OpenI(0); \discard any chars in keyboard buffer (like CR) if ChIn(0) = ^h then quit \default is 'r' to roll else [Die:= Ran(6)+1; \roll the die Text(0, "You get "); IntOut(0, Die); CrLf(0); if Die = 1 then [Points:= 0; quit]; Points:= Points + Die; \add up points for turn Text(0, "Total points are "); IntOut(0, Points); Text(0, " for a tentative score of "); IntOut(0, Score(Player)+Points); CrLf(0); ]; ]; Score(Player):= Score(Player) + Points; \show scores Text(0, "Player 1 has "); IntOut(0, Score(0)); Text(0, " and player 2 has "); IntOut(0, Score(1)); CrLf(0); until Score(Player) >= 100; Text(0, "Player "); IntOut(0, Player+1); Text(0, " WINS!!!"); ]
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.
#PL.2FI
PL/I
  pern: procedure options (main); declare (i, n) fixed binary (31);   n = 3; do i = 1 to 25, 888888877 to 888888888; if i = 888888877 then do; n = i ; put skip; end; do while ( ^is_prime ( tally(bit(n), '1'b) ) ); n = n + 1; end; put edit( trim(n), ' ') (a); n = n + 1; end;   is_prime: procedure (n) returns (bit(1)); declare n fixed (15); declare i fixed (10);   if n < 2 then return ('0'b); if n = 2 then return ('1'b); if mod(n, 2) = 0 then return ('0'b);   do i = 3 to sqrt(n) by 2; if mod(n, i) = 0 then return ('0'b); end; return ('1'b); end is_prime;   end pern;  
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.
#Plain_English
Plain English
To decide if a number is pernicious: Find a population count of the number. If the population count is prime, say yes. Say no.   To find a population count of a number: Privatize the number. Loop. If the number is 0, exit. Bitwise and the number with the number minus 1. Bump the population count. Repeat.   To run: Start up. Show the first twenty-five pernicious numbers. Show the pernicious numbers between 888888877 and 888888888. Wait for the escape key. Shut down.   To show the first twenty-five pernicious numbers: Put 0 into a number. Put 0 into a pernicious number count. Loop. If the pernicious number count is greater than 24, write "" on the console; exit. If the number is pernicious, show the number; bump the pernicious number count. Bump the number. Repeat.   To show a number: Convert the number to a string. Write the string then " " on the console without advancing.   To show the pernicious numbers between a number and another number: Privatize the number. Subtract 1 from the number. Loop. If the number is past the other number, exit. If the number is pernicious, show the number. Repeat.
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Ring
Ring
  aList = "abcdefghij" for i = 1 to 10 letter = random(9) + 1 if letter > 0 see aList[letter] + nl ok next  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Ruby
Ruby
  %w(north east south west).sample # => "west" (1..100).to_a.sample(2) # => [17, 79]
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
#VBA
VBA
  Option Explicit   Sub Main_Phrase_Reversals() Const PHRASE As String = "rosetta code phrase reversal" Debug.Print "Original String  : " & PHRASE Debug.Print "Reverse String  : " & Reverse_String(PHRASE) Debug.Print "Reverse each individual word : " & Reverse_each_individual_word(PHRASE) Debug.Print "Reverse order of each word  : " & Reverse_the_order_of_each_word(PHRASE) End Sub   Function Reverse_String(strPhrase As String) As String Reverse_String = StrReverse(strPhrase) End Function   Function Reverse_each_individual_word(strPhrase As String) As String Dim Words, i&, strTemp$ Words = Split(strPhrase, " ") For i = 0 To UBound(Words) Words(i) = Reverse_String(CStr(Words(i))) Next i Reverse_each_individual_word = Join(Words, " ") End Function   Function Reverse_the_order_of_each_word(strPhrase As String) As String Dim Words, i&, strTemp$   Words = Split(strPhrase, " ") For i = UBound(Words) To 0 Step -1 strTemp = strTemp & " " & Words(i) Next i Reverse_the_order_of_each_word = Trim(strTemp) End Function  
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
#Scala
Scala
def derangements(n: Int) = (1 to n).permutations.filter(_.zipWithIndex.forall{case (a, b) => a - b != 1})   def subfactorial(n: Long): Long = n match { case 0 => 1 case 1 => 0 case _ => (n - 1) * (subfactorial(n - 1) + subfactorial(n - 2)) }   println(s"Derangements for n = 4") println(derangements(4) mkString "\n")   println("\n%2s%10s%10s".format("n", "derange", "subfact")) (0 to 9).foreach(n => println("%2d%10d%10d".format(n, derangements(n).size, subfactorial(n)))) (10 to 20).foreach(n => println(f"$n%2d${subfactorial(n)}%20d"))
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%
#Rust
Rust
extern crate image;   use image::{GenericImageView, Rgba};   fn diff_rgba3(rgba1 : Rgba<u8>, rgba2 : Rgba<u8>) -> i32 { (rgba1[0] as i32 - rgba2[0] as i32).abs() + (rgba1[1] as i32 - rgba2[1] as i32).abs() + (rgba1[2] as i32 - rgba2[2] as i32).abs() }   fn main() { let img1 = image::open("Lenna100.jpg").unwrap(); let img2 = image::open("Lenna50.jpg").unwrap(); let mut accum = 0; let zipper = img1.pixels().zip(img2.pixels()); for (pixel1, pixel2) in zipper { accum += diff_rgba3(pixel1.2, pixel2.2); } println!("Percent difference {}", accum as f64 * 100.0/ (255.0 * 3.0 * (img1.width() * img1.height()) as f64)); }
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%
#Sidef
Sidef
require('Imager')   func img_diff(a, b) {   func from_file(name) { %s|Imager|.new(file => name) }   func size(img) { (img.getwidth, img.getheight) }   func pixel_diff(p1, p2) { [p1.rgba] »-« [p2.rgba] -> map { .abs }.sum }   func read_pixel(img, x, y) { img.getpixel(x => x, y => y) }   var(img1, img2) = (from_file(a), from_file(b))   var(w1, h1) = size(img1) var(w2, h2) = size(img2)   if ((w1 != w2) || (h1 != h2)) { return nil }   var sum = 0 for y,x in (^h1 ~X ^w1) { sum += pixel_diff(read_pixel(img1, x, y), read_pixel(img2, x, y)) }   sum / (w1 * h1 * 255 * 3) }   say 100*img_diff('Lenna50.jpg', 'Lenna100.jpg')
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.
#Erlang
Erlang
is_perfect(X) -> X == lists:sum([N || N <- lists:seq(1,X-1), X rem N == 0]).
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE}   make do test := <<2, 5, 1>> permute (test, 1) end   test: ARRAY [INTEGER]   permute (a: ARRAY [INTEGER]; k: INTEGER) -- All permutations of 'a'. require count_positive: a.count > 0 k_valid_index: k > 0 local t: INTEGER do if k = a.count then across a as ar loop io.put_integer (ar.item) end io.new_line else across k |..| a.count as c loop t := a [k] a [k] := a [c.item] a [c.item] := t permute (a, k + 1) t := a [k] a [k] := a [c.item] a [c.item] := t end end end   end    
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#REXX
REXX
/*REXX program performs a "perfect shuffle" for a number of even numbered decks. */ parse arg X /*optional list of test cases from C.L.*/ if X='' then X=8 24 52 100 1020 1024 10000 /*Not specified? Then use the default.*/ w=length(word(X, words(X))) /*used for right─aligning the numbers. */   do j=1 for words(X); y=word(X,j) /*use numbers in the test suite (list).*/   do k=1 for y; @.k=k; end /*k*/ /*generate a deck to be used (shuffled)*/ do t=1 until eq(); call magic; end /*t*/ /*shuffle until before equals after.*/   say 'deck size:' right(y,w)"," right(t,w) 'perfect shuffles.' end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ eq: do ?=1 for y; if @.?\==? then return 0; end; return 1 /*──────────────────────────────────────────────────────────────────────────────────────*/ magic: z=0 /*set the Z pointer (used as index).*/ h=y%2 /*get the half─way (midpoint) pointer. */ do s=1 for h; z=z+1; h=h+1 /*traipse through the card deck pips. */  !.z=@.s; z=z+1 /*assign left half; then bump pointer. */  !.z=@.h /* " right " */ end /*s*/ /*perform a perfect shuffle of the deck*/   do r=1 for y; @.r=!.r; end /*re─assign to the original card deck. */ return
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
#OCaml
OCaml
type pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace let pips = [Two; Three; Four; Five; Six; Seven; Eight; Nine; Ten; Jack; Queen; King; Ace] type suit = Diamonds | Spades | Hearts | Clubs let suits = [Diamonds; Spades; Hearts; Clubs] type card = pip * suit let full_deck = Array.of_list (List.concat (List.map (fun pip -> List.map (fun suit -> (pip, suit)) suits) pips)) let shuffle deck = for i = Array.length deck - 1 downto 1 do let j = Random.int (i+1) in let temp = deck.(i) in deck.(i) <- deck.(j); deck.(j) <- temp done
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary import java.math.BigInteger   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg places . if places = '' then places = -1   TWO = BigInteger.valueOf(2) THREE = BigInteger.valueOf(3) FOUR = BigInteger.valueOf(4) SEVEN = BigInteger.valueOf(7)   q_ = BigInteger.ONE r_ = BigInteger.ZERO t_ = BigInteger.ONE k_ = BigInteger.ONE n_ = BigInteger.valueOf(3) l_ = BigInteger.valueOf(3)   nn = BigInteger nr = BigInteger   first = isTrue() digitCt = 0 loop forever if FOUR.multiply(q_).add(r_).subtract(t_).compareTo(n_.multiply(t_)) == -1 then do digitCt = digitCt + 1 if places > 0 & digitCt - 1 > places then leave say n_'\-' if first then do say '.\-' first = isFalse() end nr = BigInteger.TEN.multiply(r_.subtract(n_.multiply(t_))) n_ = BigInteger.TEN.multiply(THREE.multiply(q_).add(r_)).divide(t_).subtract(BigInteger.TEN.multiply(n_)) q_ = q_.multiply(BigInteger.TEN) r_ = nr end else do nr = TWO.multiply(q_).add(r_).multiply(l_) nn = q_.multiply((SEVEN.multiply(k_))).add(TWO).add(r_.multiply(l_)).divide(t_.multiply(l_)) q_ = q_.multiply(k_) t_ = t_.multiply(l_) l_ = l_.add(TWO) k_ = k_.add(BigInteger.ONE) n_ = nn r_ = nr end end say   return   method isTrue() private static returns boolean return (1 == 1) method isFalse() private static returns boolean return \isTrue()  
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
#zkl
zkl
const WIN=100, PLAYERS=2; players,safeScores:=Walker.cycle([0..PLAYERS-1]), PLAYERS.pump(List(),0); rollDie:=(1).random.fp(7); yes,player,score,S:=T("","y"),players.next(),0,0; tally:='wrap(player,score){ w:=safeScores[player]+=score; (w>=WIN) };   while(True){ print("Player %d: (%d, %d). Rolling? (y/n) ".fmt(player+1,S,score)); if(yes.holds(ask().strip().toLower())){ rolled:=rollDie(); println(" Rolled a %d".fmt(rolled)); if(rolled==1){ println(" Bust! You lose %d but keep %d\n".fmt(score,S)); }else{ score+=rolled; if(score + S>=WIN){ tally(player,score); break; } continue; } }else{ if(tally(player,score)) break; println(" Sticking with %d\n".fmt(safeScores[player])); } player,score,S=players.next(),0,safeScores[player]; } println("\n\nPlayer %d wins with a score of %d".fmt(player+1, safeScores[player]));
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pernicious number. Task display the first   25   pernicious numbers   (in decimal). display all pernicious numbers between   888,888,877   and   888,888,888   (inclusive). display each list of integers on one line   (which may or may not include a title). See also Sequence   A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences. Rosetta Code entry   population count, evil numbers, odious numbers.
#PowerShell
PowerShell
  function pop-count($n) { (([Convert]::ToString($n, 2)).toCharArray() | where {$_ -eq '1'}).count }   function isPrime ($n) { if ($n -eq 1) {$false} elseif ($n -eq 2) {$true} elseif ($n -eq 3) {$true} else{ $m = [Math]::Floor([Math]::Sqrt($n)) (@(2..$m | where {($_ -lt $n) -and ($n % $_ -eq 0) }).Count -eq 0) } }   $i = 0 $num = 1 $arr = while($i -lt 25) { if((isPrime (pop-count $num))) { $i++ $num } $num++ } "first 25 pernicious numbers" "$arr" "" "pernicious numbers between 888,888,877 and 888,888,888" "$(888888877..888888888 | where{isprime(pop-count $_)})"  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Run_BASIC
Run BASIC
list$ = "a,b,c,d,e,f,g,h,i,j" letter = rnd(1) * 10 print "Selected letter:"; word$(list$,letter,",")
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Rust
Rust
extern crate rand;   use rand::Rng;   fn main() { let array = [5,1,2,5,6,7,8,1,2,4,5]; let mut rng = rand::thread_rng();   println!("{}", rng.choose(&array).unwrap()); }
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
#VBScript
VBScript
  Phrase = "rosetta code phrase reversal"   WScript.StdOut.Write "Original String  : " & Phrase WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse String  : " & RevString(Phrase) WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse String Each Word : " & RevStringEachWord(Phrase) WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse Phrase  : " & RevPhrase(Phrase) WScript.StdOut.WriteLine   Function RevString(s) x = Len(s) For i = 1 To Len(s) RevString = RevString & Mid(s,x,1) x = x - 1 Next End Function   Function RevStringEachWord(s) arr = Split(s," ") For i = 0 To UBound(arr) RevStringEachWord = RevStringEachWord & RevString(arr(i)) If i < UBound(arr) Then RevStringEachWord = RevStringEachWord & " " End If Next End Function   Function RevPhrase(s) arr = Split(s," ") For i = UBound(arr) To LBound(arr) Step -1 RevPhrase = RevPhrase & arr(i) If i > LBound(arr) Then RevPhrase = RevPhrase & " " End If Next End Function  
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
#Vlang
Vlang
  fn main() { str := 'rosetta code phrase reversal' words := str.fields() println('Original: $str') println('Reverse: ${str.reverse()}') println('Char-Word Reverse: ${words.map(it.reverse()).join(' ')}') println('Word Reverse: ${words.reverse().join(' ')}') }
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
#SuperCollider
SuperCollider
( d = { |array, n| Routine { n = n ?? { array.size.factorial }; n.do { |i| var permuted = array.permute(i); if(array.every { |each, i| permuted[i] != each }) { permuted.yield }; } }; }; f = { |n| d.((0..n-1)) }; x = f.(4); x.all.do(_.postln); ""; )
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
#Tcl
Tcl
package require Tcl 8.5; # for arbitrary-precision integers package require struct::list; # for permutation enumerator   proc derangements lst { # Special case if {![llength $lst]} {return {{}}} set result {} for {set perm [struct::list firstperm $lst]} {[llength $perm]} \ {set perm [struct::list nextperm $perm]} { set skip 0 foreach a $lst b $perm { if {[set skip [string equal $a $b]]} break } if {!$skip} {lappend result $perm} } return $result }   proc deranged1to n { for {set i 1;set r {}} {$i <= $n} {incr i} {lappend r $i} return [derangements $r] }   proc countDeranged1to n { llength [deranged1to $n] }   proc subfact n { if {$n == 0} {return 1} if {$n == 1} {return 0} set o 1 set s 0 for {set i 1} {$i < $n} {incr i} { set s [expr {$i * ($o + [set o $s])}] } return $s }
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#Swift
Swift
func pixelValues(fromCGImage imageRef: CGImage?) -> [UInt8]? { var width = 0 var height = 0 var pixelValues: [UInt8]?   if let imageRef = imageRef { width = imageRef.width height = imageRef.height let bitsPerComponent = imageRef.bitsPerComponent let bytesPerRow = imageRef.bytesPerRow let totalBytes = height * bytesPerRow let bitmapInfo = imageRef.bitmapInfo   let colorSpace = CGColorSpaceCreateDeviceRGB() var intensities = [UInt8](repeating: 0, count: totalBytes)   let contextRef = CGContext(data: &intensities, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))   pixelValues = intensities }   return pixelValues }   func compareImages(image1: UIImage, image2: UIImage) -> Double? { guard let data1 = pixelValues(fromCGImage: image1.cgImage), let data2 = pixelValues(fromCGImage: image2.cgImage), data1.count == data2.count else { return nil }   let width = Double(image1.size.width) let height = Double(image1.size.height)   return zip(data1, data2) .enumerated() .reduce(0.0) { $1.offset % 4 == 3 ? $0 : $0 + abs(Double($1.element.0) - Double($1.element.1)) } * 100 / (width * height * 3.0) / 255.0 }   let image1 = UIImage(named: "Lenna50") let image2 = UIImage(named: "Lenna100")   compareImages(image1: image1, image2: image2)    
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%
#Tcl
Tcl
package require Tk   proc imageDifference {img1 img2} { if { [image width $img1] != [image width $img2] || [image height $img1] != [image height $img2] } then { return -code error "images are different size" } set diff 0 for {set x 0} {$x<[image width $img1]} {incr x} { for {set y 0} {$y<[image height $img1]} {incr y} { lassign [$img1 get $x $y] r1 g1 b1 lassign [$img2 get $x $y] r2 g2 b2 incr diff [expr {abs($r1-$r2)+abs($g1-$g2)+abs($b1-$b2)}] } } expr {$diff/double($x*$y*3*255)} }   # Package only used for JPEG loader package require Img image create photo lenna50 -file lenna50.jpg image create photo lenna100 -file lenna100.jpg puts "difference is [expr {[imageDifference lenna50 lenna100]*100.}]%" exit ;# Need explicit exit here; don't want a GUI
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.
#ERRE
ERRE
PROGRAM PERFECT   PROCEDURE PERFECT(N%->OK%) LOCAL I%,S% S%=1 FOR I%=2 TO SQR(N%)-1 DO IF N% MOD I%=0 THEN S%+=I%+N% DIV I% END FOR IF I%=SQR(N%) THEN S%+=I% OK%=(N%=S%) END PROCEDURE   BEGIN PRINT(CHR$(12);) ! CLS FOR N%=2 TO 10000 STEP 2 DO PERFECT(N%->OK%) IF OK% THEN PRINT(N%) END FOR END PROGRAM
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
#Elixir
Elixir
defmodule RC do def permute([]), do: [[]] def permute(list) do for x <- list, y <- permute(list -- [x]), do: [x|y] end end   IO.inspect RC.permute([1, 2, 3])
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#Ruby
Ruby
def perfect_shuffle(deck_size = 52) deck = (1..deck_size).to_a original = deck.dup half = deck_size / 2 1.step do |i| deck = deck.first(half).zip(deck.last(half)).flatten return i if deck == original end end   [8, 24, 52, 100, 1020, 1024, 10000].each {|i| puts "Perfect shuffles required for deck size #{i}: #{perfect_shuffle(i)}"}  
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
#Rust
Rust
extern crate itertools;   fn shuffle<T>(mut deck: Vec<T>) -> Vec<T> { let index = deck.len() / 2; let right_half = deck.split_off(index); itertools::interleave(deck, right_half).collect() }   fn main() { for &size in &[8, 24, 52, 100, 1020, 1024, 10_000] { let original_deck: Vec<_> = (0..size).collect(); let mut deck = original_deck.clone(); let mut iterations = 0; loop { deck = shuffle(deck); iterations += 1; if deck == original_deck { break; } } println!("{: >5}: {: >4}", size, iterations); } }
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
#PARI.2FGP
PARI/GP
name(n)=Str(["A",2,3,4,5,6,7,8,9,10,"J","Q","K"][(n+3)>>2],["h","d","s","c"][n%4+1]); newdeck()={ v=vector(52,i,i); }; deal()={ my(n=name(v[1])); v=vecextract(v,2^#v-2); n }; printdeck(){ apply(name,v) }; shuffle()={ forstep(n=#v,2,-1, my(i=random(n)+1,t=v[i]); v[i]=v[n]; v[n]=t ); v };
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
#Nim
Nim
import bigints   var tmp1, tmp2, tmp3, acc, k = initBigInt(0) den, num, k2 = initBigInt(1)   proc extractDigit(): int32 = if num > acc: return -1   tmp3 = num shl 1 + num + acc tmp1 = tmp3 div den tmp2 = tmp3 mod den + num   if tmp2 >= den: return -1   result = int32(tmp1.limbs[0])   proc eliminateDigit(d: int32) = acc -= den * d acc *= 10 num *= 10   proc nextTerm() = k += 1 k2 += 2 acc += num shl 1 acc *= k2 den *= k2 num *= k   var i = 0   while true: var d: int32 = -1 while d < 0: nextTerm() d = extractDigit()   stdout.write chr(ord('0') + d) inc i if i == 40: echo "" i = 0 eliminateDigit d
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.
#PureBasic
PureBasic
  EnableExplicit   Procedure.i SumBinaryDigits(Number) If Number < 0 : number = -number : EndIf; convert negative numbers to positive Protected sum = 0 While Number > 0 sum + Number % 2 Number / 2 Wend ProcedureReturn sum EndProcedure   Procedure.i IsPrime(Number) If Number <= 1 ProcedureReturn #False ElseIf Number <= 3 ProcedureReturn #True ElseIf Number % 2 = 0 Or Number % 3 = 0 ProcedureReturn #False EndIf Protected i = 5 While i * i <= Number If Number % i = 0 Or Number % (i + 2) = 0 ProcedureReturn #False EndIf i + 6 Wend ProcedureReturn #True EndProcedure   Procedure.i IsPernicious(Number) Protected popCount = SumBinaryDigits(Number) ProcedureReturn Bool(IsPrime(popCount)) EndProcedure   Define n = 1, count = 0 If OpenConsole() PrintN("The following are the first 25 pernicious numbers :") PrintN("") Repeat If IsPernicious(n) Print(RSet(Str(n), 3)) count + 1 EndIf n + 1 Until count = 25 PrintN("") PrintN("") PrintN("The pernicious numbers between 888,888,877 and 888,888,888 inclusive are : ") PrintN("") For n = 888888877 To 888888888 If IsPernicious(n) Print(RSet(Str(n), 10)) EndIf Next PrintN("") PrintN("") PrintN("Press any key to close the console") Repeat: Delay(10) : Until Inkey() <> "" CloseConsole() EndIf  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Scala
Scala
val a = (1 to 10).toList   println(scala.util.Random.shuffle(a).head)
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln(rand([] ("foo", "bar", "baz"))); end func;
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Sidef
Sidef
var arr = %w(north east south west); say arr.rand; say arr.rand(2).dump;
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
#Wren
Wren
var s = "rosetta code phrase reversal" System.print("Input  : %(s)") System.print("String reversed  : %(s[-1..0])") System.print("Each word reversed  : %(s.split(" ").map { |w| w[-1..0] }.join(" "))") System.print("Word order reversed : %(s.split(" ")[-1..0].join(" "))")
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Yabasic
Yabasic
phrase$ = "Rosetta Code Phrase Reversal"   dim word$(1)   n = token(phrase$, word$())   print phrase$   for i = n to 1 step -1 print reverse$(word$(i)), " "; next   print   for i = n to 1 step -1 print word$(i), " "; next   print   for i = 1 to n print reverse$(word$(i)), " "; next   print   sub reverse$(w$) local i, rw$   for i = len(w$) to 1 step -1 rw$ = rw$ + mid$(w$, i, 1) next   return rw$ end sub
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
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigInt   var permute // recursive permute = Fn.new { |input| if (input.count == 1) return [input] var perms = [] var toInsert = input[0] for (perm in permute.call(input[1..-1])) { for (i in 0..perm.count) { var newPerm = perm.toList newPerm.insert(i, toInsert) perms.add(newPerm) } } return perms }   var derange = Fn.new { |input| if (input.isEmpty) return [input] var perms = permute.call(input) var derangements = [] for (perm in perms) { var deranged = true for (i in 0...perm.count) { if (perm[i] == i) { deranged = false break } } if (deranged) derangements.add(perm) } return derangements }   var subFactorial // recursive subFactorial = Fn.new { |n| if (n == 0) return BigInt.one if (n == 1) return BigInt.zero return (subFactorial.call(n-1) + subFactorial.call(n-2)) * (n - 1) }   var input = [0, 1, 2, 3] var derangements = derange.call(input) System.print("There are %(derangements.count) derangements of %(input), namely:\n") System.print(derangements.join("\n"))   System.print("\nN Counted Calculated") System.print("- ------- ----------") for (n in 0..9) { var list = List.filled(n, 0) for (i in 0...n) list[i] = i var counted = derange.call(list).count Fmt.print("$d $-9d $-9i", n, counted, subFactorial.call(n)) } System.print("\n!20 = %(subFactorial.call(20))")
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%
#Vedit_macro_language
Vedit macro language
Chdir("|(USER_MACRO)\Rosetta\data") File_Open("Lenna50.bmp", BROWSE) #10 = Buf_Num // #10 = buffer for 1st image File_Open("Lenna100.bmp", BROWSE) #20 = Buf_Num // #20 = buffer for 2nd image   Goto_Pos(10) // offset to pixel data Goto_Pos(Cur_Char + Cur_Char(1)*256) Buf_Switch(#10) Goto_Pos(10) Goto_Pos(Cur_Char + Cur_Char(1)*256)   #15 = 0 // #15 = difference #16 = 0 // #16 = total number of samples While(!At_EOF) { #11 = Cur_Char; Char Buf_Switch(#20) #21 = Cur_Char; Char #15 += abs(#11-#21) #16++ Buf_Switch(#10) }   #19 = #15 / (#16*256/100000) M("Sum of diff: ") NT(#15) M("Total bytes: ") NT(#16) M("Difference: ") NT(#19/1000,LEFT+NOCR) M(".") NT(#19%1000,LEFT+NOCR) M("%\n")   Buf_Switch(#10) Buf_Quit(OK) Buf_Switch(#20) Buf_Quit(OK)
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.
#F.23
F#
let perf n = n = List.fold (+) 0 (List.filter (fun i -> n % i = 0) [1..(n-1)])   for i in 1..10000 do if (perf i) then printfn "%i is perfect" i
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
#Erlang
Erlang
-module(permute). -export([permute/1]).   permute([]) -> [[]]; permute(L) -> [[X|Y] || X<-L, Y<-permute(L--[X])].
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
#Scala
Scala
object PerfectShuffle extends App { private def sizes = Seq(8, 24, 52, 100, 1020, 1024, 10000)   private def perfectShuffle(size: Int): Int = { require(size % 2 == 0, "Card deck must be even")   val (half, a) = (size / 2, Array.range(0, size)) val original = a.clone var count = 1 while (true) { val aa = a.clone for (i <- 0 until half) { a(2 * i) = aa(i) a(2 * i + 1) = aa(i + half) } if (a.deep == original.deep) return count count += 1 } 0 }   for (size <- sizes) println(f"$size%5d : ${perfectShuffle(size)}%5d")   }
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
#Scilab
Scilab
function New=PerfectShuffle(Nitems,Nturns) if modulo(Nitems,2)==0 then X=1:Nitems; for c=1:Nturns X=matrix(X,Nitems/2,2)'; X=X(:); end New=X'; end endfunction   Result=[]; Q=[8, 24, 52, 100, 1020, 1024, 10000]; for n=Q Same=0; T=0; Compare=[]; while ~Same T=T+1; R=PerfectShuffle(n,T); Compare = find(R-(1:n)); if Compare == [] then Same = 1; end end Result=[Result;T]; end disp([Q', Result])
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
#Pascal
Pascal
package Playing_Card_Deck;   use strict;   @Playing_Card_Deck::suits = qw [Diamonds Clubs Hearts Spades]; @Playing_Card_Deck::pips = qw [Two Three Four Five Six Seven Eight Nine Ten Jack King Queen Ace]; # I choose to fully qualify these names rather than declare them # with "our" to keep them from escaping into the scope of other # packages in the same file. Another possible solution is to use # "our" or "my", but to enclose this entire package in a bare block.   sub new # Creates a new deck-object. The cards are initially neatly ordered. {my $invocant = shift; my $class = ref($invocant) || $invocant; my @cards = (); foreach my $suit (@Playing_Card_Deck::suits) {foreach my $pip (@Playing_Card_Deck::pips) {push(@cards, {suit => $suit, pip => $pip});}} return bless([@cards], $class);}   sub deal # Removes the top card of the given deck and returns it as a hash # with the keys "suit" and "pip". {return %{ shift( @{shift(@_)} ) };}   sub shuffle # Randomly permutes the cards in the deck. It uses the algorithm # described at: # http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm {our @deck; local *deck = shift; # @deck is now an alias of the invocant's referent. for (my $n = $#deck ; $n ; --$n) {my $k = int rand($n + 1); @deck[$k, $n] = @deck[$n, $k] if $k != $n;}}   sub print_cards # Prints out a description of every card in the deck, in order. {print "$_->{pip} of $_->{suit}\n" foreach @{shift(@_)};}
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ... Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions. Related Task Arithmetic-geometric mean/Calculate Pi
#OCaml
OCaml
open Creal;;   let block = 100 in let segment n = let s = to_string pi (n*block) in String.sub s ((n-1)*block) block in let counter = ref 1 in while true do print_string (segment !counter); flush stdout; incr counter done
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.
#Python
Python
>>> def popcount(n): return bin(n).count("1")   >>> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61} >>> p, i = [], 0 >>> while len(p) < 25: if popcount(i) in primes: p.append(i) i += 1     >>> p [3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 31, 33, 34, 35, 36] >>> p, i = [], 888888877 >>> while i <= 888888888: if popcount(i) in primes: p.append(i) i += 1     >>> p [888888877, 888888878, 888888880, 888888883, 888888885, 888888886] >>>
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Smalltalk
Smalltalk
x := #(1 2 3) atRandom.
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#SuperCollider
SuperCollider
[1, 2, 3].choose
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
#zkl
zkl
zkl: var str="rosetta code phrase reversal" rosetta code phrase reversal   zkl: str.reverse() #1 lasrever esarhp edoc attesor   zkl: str.split().apply("reverse").concat(" ") #2 string to list to string attesor edoc esarhp lasrever   zkl: str.split().reverse().concat(" ") #3 reversal phrase code rosetta
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n. Task Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer). Generate and show all the derangements of 4 integers using the above routine. Create a function that calculates the subfactorial of n, !n. Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive. Optional stretch goal   Calculate    !20 Related tasks   Anagrams/Deranged anagrams   Best shuffle   Left_factorials Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zkl
zkl
fcn subFact(n){ if(n==0) return(1); if(n==1) return(0); (n-1)*(self.fcn(n-1) + self.fcn(n-2)); }   fcn derangements(n){ // All deranged permutations of the integers 0..n-1 inclusive enum:=[0..n-1].pump(List); Utils.Helpers.permuteW(enum).filter('wrap(perm){ perm.zipWith('==,enum).sum(0) == 0 }); } fcn derangers(n){ // just count # of derangements enum:=[0..n-1].pump(List); Utils.Helpers.permuteW(enum).reduce('wrap(sum,perm){ sum + (perm.zipWith('==,enum).sum(0) == 0) },0); }
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two images is 1.62125%
#Wren
Wren
import "graphics" for Canvas, Color, ImageData import "dome" for Window   class PercentageDifference { construct new(width, height, image1, image2) { Window.title = "Perecentage difference between images" Window.resize(width, height) Canvas.resize(width, height) _img1 = ImageData.loadFromFile(image1) _img2 = ImageData.loadFromFile(image2) // display images side by side _img1.draw(0, 0) _img2.draw(550, 0) Canvas.print(image1, 200, 525, Color.white) Canvas.print(image2, 750, 525, Color.white) }   init() { var dpc = (getDifferencePercent(_img1, _img2) * 1e5).round / 1e5 System.print("Percentage difference between images: %(dpc)\%") }   getDifferencePercent(img1, img2) { var width = img1.width var height = img1.height var width2 = img2.width var height2 = img2.height if (width != width2 || height != height2) { var f = "(%(width), %(height)) vs. (%(width2), %(height2))" Fiber.abort("Images must have the same dimensions: %(f)") } var diff = 0 for (y in 0...height) { for (x in 0...width) { diff = diff + pixelDiff(img1.pget(x, y), img2.pget(x, y)) } } var maxDiff = 3 * 255 * width * height return 100 * diff / maxDiff }   pixelDiff(c1, c2) { (c1.r - c2.r).abs + (c1.g - c2.g).abs + (c1.b - c2.b).abs }   update() {}   draw(alpha) {} }   var Game = PercentageDifference.new(1100, 550, "Lenna50.jpg", "Lenna100.jpg")
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.
#Factor
Factor
USING: kernel math math.primes.factors sequences ; IN: rosettacode.perfect-numbers   : perfect? ( n -- ? ) [ divisors sum ] [ 2 * ] bi = ;
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.
#FALSE
FALSE
[0\1[\$@$@-][\$@$@$@$@\/*=[@\$@+@@]?1+]#%=]p: 45p;!." "28p;!. { 0 -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
#Euphoria
Euphoria
function reverse(sequence s, integer first, integer last) object x while first < last do x = s[first] s[first] = s[last] s[last] = x first += 1 last -= 1 end while return s end function   function nextPermutation(sequence s) integer pos, last object x if length(s) < 1 then return 0 end if   pos = length(s)-1 while compare(s[pos], s[pos+1]) >= 0 do pos -= 1 if pos < 1 then return -1 end if end while   last = length(s) while compare(s[last], s[pos]) <= 0 do last -= 1 end while x = s[pos] s[pos] = s[last] s[last] = x   return reverse(s, pos+1, length(s)) end function   object s s = "abcd" puts(1, s & '\t') while 1 do s = nextPermutation(s) if atom(s) then exit end if puts(1, s & '\t') end while
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
#Sidef
Sidef
func perfect_shuffle(deck) { deck/2 -> zip.flat }   [8, 24, 52, 100, 1020, 1024, 10000].each { |size| var deck = @(1..size) var shuffled = deck   var n = (1..Inf -> lazy.first { (shuffled = perfect_shuffle(shuffled)) == deck })   printf("%5d cards: %4d\n", size, n) }
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
#Swift
Swift
func perfectShuffle<T>(_ arr: [T]) -> [T]? { guard arr.count & 1 == 0 else { return nil }   let half = arr.count / 2 var res = [T]()   for i in 0..<half { res.append(arr[i]) res.append(arr[i + half]) }   return res }   let decks = [ Array(1...8), Array(1...24), Array(1...52), Array(1...100), Array(1...1020), Array(1...1024), Array(1...10000) ]   for deck in decks { var shuffled = deck var shuffles = 0   repeat { shuffled = perfectShuffle(shuffled)! shuffles += 1 } while shuffled != deck   print("Deck of \(shuffled.count) took \(shuffles) shuffles to get back to original order") }
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
#Perl
Perl
package Playing_Card_Deck;   use strict;   @Playing_Card_Deck::suits = qw [Diamonds Clubs Hearts Spades]; @Playing_Card_Deck::pips = qw [Two Three Four Five Six Seven Eight Nine Ten Jack King Queen Ace]; # I choose to fully qualify these names rather than declare them # with "our" to keep them from escaping into the scope of other # packages in the same file. Another possible solution is to use # "our" or "my", but to enclose this entire package in a bare block.   sub new # Creates a new deck-object. The cards are initially neatly ordered. {my $invocant = shift; my $class = ref($invocant) || $invocant; my @cards = (); foreach my $suit (@Playing_Card_Deck::suits) {foreach my $pip (@Playing_Card_Deck::pips) {push(@cards, {suit => $suit, pip => $pip});}} return bless([@cards], $class);}   sub deal # Removes the top card of the given deck and returns it as a hash # with the keys "suit" and "pip". {return %{ shift( @{shift(@_)} ) };}   sub shuffle # Randomly permutes the cards in the deck. It uses the algorithm # described at: # http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm {our @deck; local *deck = shift; # @deck is now an alias of the invocant's referent. for (my $n = $#deck ; $n ; --$n) {my $k = int rand($n + 1); @deck[$k, $n] = @deck[$n, $k] if $k != $n;}}   sub print_cards # Prints out a description of every card in the deck, in order. {print "$_->{pip} of $_->{suit}\n" foreach @{shift(@_)};}
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ... Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions. Related Task Arithmetic-geometric mean/Calculate Pi
#Oforth
Oforth
: calcPiDigits | q r t k n l | 1 ->q 0 ->r 1 ->t 1 ->k 3 ->n 3 -> l   while( true ) [ 4 q * r + t - n t * < ifTrue: [ n print r n t * - 10 * 3 q * r + 10 * t / n 10 * - ->n ->r q 10 * ->q ] else: [ 2 q * r + l * 7 k * q * 2 + r l * + t l * / ->n ->r k q * ->q t l * ->t l 2 + ->l k 1+ ->k ] ] ;
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.
#Quackery
Quackery
[ $ "rosetta/seive.qky" loadfile $ "rosetta/popcount.qky" loadfile ] now!   ( i.e. using the code at ) ( http://rosettacode.org/wiki/Sieve_of_Eratosthenes and ) ( http://rosettacode.org/wiki/Population_count )   29 eratosthenes ( Precompute as many primes as are required ) ( for the task. 888,888,888 is a 30 bit ) ( number less than (2^30)-1 so primes up to ) ( 29 will suffice. )   [ 1+ over - times [ dup i^ + dup popcount isprime iff [ echo sp ] else drop ] drop ] is perniciousrange ( n n --> )   25 echopopwith isprime cr   888888877 888888888 perniciousrange cr
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Swift
Swift
import Darwin   let myList = [1, 2, 4, 5, 62, 234, 1, -1] print(myList[Int(arc4random_uniform(UInt32(myList.count)))])
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Tcl
Tcl
proc randelem {list} { lindex $list [expr {int(rand()*[llength $list])}] } set x [randelem {1 2 3 4 5}]
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%
#zkl
zkl
fcn imageDiff(img1,img2){ if(img1.w!=img2.w or img1.h!=img2.h) throw(Exception.ValueError("width/height of the images must match!")); img1.data.howza(0).walker().zip(img2.data.howza(0)) // lazy bytes, not strings .reduce(fcn(totalDiff,[(a,b)]){ totalDiff + (a - b).abs() },0) .toFloat()/img1.w/img1.h/3/255; // or: .toFloat()/img1.data.len()/255 }
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.
#Forth
Forth
: perfect? ( n -- ? ) 1 over 2/ 1+ 2 ?do over i mod 0= if i + then loop = ;
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.
#Fortran
Fortran
FUNCTION isPerfect(n) LOGICAL :: isPerfect INTEGER, INTENT(IN) :: n INTEGER :: i, factorsum   isPerfect = .FALSE. factorsum = 1 DO i = 2, INT(SQRT(REAL(n))) IF(MOD(n, i) == 0) factorsum = factorsum + i + (n / i) END DO IF (factorsum == n) isPerfect = .TRUE. END FUNCTION isPerfect
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
#F.23
F#
  let rec insert left x right = seq { match right with | [] -> yield left @ [x] | head :: tail -> yield left @ [x] @ right yield! insert (left @ [head]) x tail }   let rec perms permute = seq { match permute with | [] -> yield [] | head :: tail -> yield! Seq.collect (insert [] head) (perms tail) }   [<EntryPoint>] let main argv = perms (Seq.toList argv) |> Seq.iter (fun x -> printf "%A\n" x) 0  
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#Tcl
Tcl
namespace eval shuffle {   proc perfect {deck} { if {[llength $deck]%2} { return -code error "Deck must be of even length!" } set split [expr {[llength $deck]/2}] set top [lrange $deck 0 $split-1] set btm [lrange $deck $split end] foreach a $top b $btm { lappend res $a $b } return $res }   proc cycle_length {transform deck} { set d $deck while 1 { set d [$transform $d] incr i if {$d eq $deck} {return $i} } return $i }   proc range {a {b ""}} { if {$b eq ""} { set b $a; set a 0 } set res {} while {$a < $b} { lappend res $a incr a } return $res }   }   set ::argv {} package require tcltest tcltest::test "Test perfect shuffle cycles" {} -body { lmap size {8 24 52 100 1020 1024 10000} { shuffle::cycle_length perfect [range $size] } } -result {3 11 8 30 1018 10 300}
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
#Phix
Phix
-- demo\rosetta\Playing_cards.exw function deal(sequence deck, integer nhands, integer ncards) sequence hands = repeat({},nhands) for n=1 to ncards do for h=1 to nhands do hands[h] &= deck[1] deck = deck[2..$] end for end for return {deck,hands} end function --console: procedure show_cards(sequence s) for i=1 to length(s) do integer c = s[i]-1 string sep = iff(mod(i,13)=0 or i=length(s)?"\n":" ") puts(1,"23456789TJQKA"[mod(c,13)+1]&"SHDC"[floor(c/13)+1]&sep) end for end procedure sequence deck, hands procedure console_show() for i=1 to length(hands) do printf(1,"hand%d:\n",{i}) show_cards(sort(hands[i])) end for printf(1,"remaining cards(%d):\n",{length(deck)}) show_cards(deck) end procedure --GUI: function cards_to_utf8(sequence s) sequence utf32 = {} for i=1 to length(s) do integer c = s[i] integer pip = mod(c,13) utf32 &= 0x1F0A1 + pip+(pip>10) + floor((c-1)/13)*#10 if mod(i,12)=0 and i<length(s) then utf32 &= '\n' end if end for return utf32_to_utf8(utf32) end function include pGUI.e constant FONT = sprintf(`FONT="Arial, %d"`,{92}) procedure gui_show() IupOpen() IupSetGlobal("UTF8MODE","YES") Ihandles lh = {} for i=1 to length(hands) do Ihandle l = IupLabel(sprintf("hand%d:",{i})) Ihandle h = IupLabel(cards_to_utf8(sort(hands[i])),FONT) lh &= l&h end for lh &= IupLabel("remaining cards:") lh &= IupLabel(cards_to_utf8(deck),FONT) Ihandle dlg = IupDialog(IupVbox(lh)) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure constant DECKSIZE=52 deck = shuffle(tagset(DECKSIZE)) show_cards(deck) {deck,hands} = deal(deck,2,9) console_show() gui_show()
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ... Note: this task is about   calculating   pi.   For information on built-in pi constants see Real constants and functions. Related Task Arithmetic-geometric mean/Calculate Pi
#Ol
Ol
  ; 'numbers' is count of numbers or #false for eternal pleasure. (define (pi numbers) (let loop ((q 1) (r 0) (t 1) (k 1) (n 3) (l 3) (numbers numbers)) (unless (eq? numbers 0) (if (< (- (+ (* 4 q) r) t) (* n t)) (begin (display n) (loop (* q 10) (* 10 (- r (* n t))) t k (- (div (* 10 (+ (* 3 q) r)) t) (* 10 n)) l (if numbers (- numbers 1)))) (begin (loop (* q k) (* (+ (* 2 q) r) l) (* t l) (+ k 1) (div (+ (* q (* 7 k)) 2 (* r l)) (* t l)) (+ l 2) (if numbers (- numbers 1))))))))   (pi #false)  
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.
#Racket
Racket
#lang racket (require math/number-theory rnrs/arithmetic/bitwise-6)   (define pernicious? (compose prime? bitwise-bit-count))   (define (dnl . strs) (for-each displayln strs))   (define (show-sequence seq) (string-join (for/list ((v (in-values*-sequence seq))) (~a ((if (list? v) car values) v))) ", "))   (dnl "Task requirements:" "display the first 25 pernicious numbers." (show-sequence (in-parallel (sequence-filter pernicious? (in-naturals 1)) (in-range 25))) "display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive)." (show-sequence (sequence-filter pernicious? (in-range 888888877 (add1 888888888)))))   (module+ test (require rackunit) (check-true (pernicious? 22)))
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.
#Raku
Raku
sub is-pernicious(Int $n --> Bool) { is-prime [+] $n.base(2).comb; }   say (grep &is-pernicious, 0 .. *)[^25]; say grep &is-pernicious, 888_888_877 .. 888_888_888;
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT list="John'Paul'George'Ringo'Peter'Paul'Mary'Obama'Putin" sizeList=SIZE(list) selectedNr=RANDOM_NUMBERS (1,sizeList,1) selectedItem=SELECT(list,#selectednr) PRINT "Selecting term ",selectedNr," in the list, which was ",selectedItem
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#TXR
TXR
@(do (defun randelem (seq) [seq (random nil (length seq))])) @(bind x @(randelem #("a" "b" "c" "d")))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#UNIX_Shell
UNIX Shell
list=(these are some words) printf '%s\n' "${list[RANDOM%${#list[@]}]}"
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPerfect(n As Integer) As Boolean If n < 2 Then Return False If n Mod 2 = 1 Then Return False '' we can assume odd numbers are not perfect Dim As Integer sum = 1, q For i As Integer = 2 To Sqr(n) If n Mod i = 0 Then sum += i q = n \ i If q > i Then sum += q End If Next Return n = sum End Function   Print "The first 5 perfect numbers are : " For i As Integer = 2 To 33550336 If isPerfect(i) Then Print i; " "; Next   Print Print "Press any key to quit" 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
#Factor
Factor
program permutations   implicit none integer, parameter :: value_min = 1 integer, parameter :: value_max = 3 integer, parameter :: position_min = value_min integer, parameter :: position_max = value_max integer, dimension (position_min : position_max) :: permutation   call generate (position_min)   contains   recursive subroutine generate (position)   implicit none integer, intent (in) :: position integer :: value   if (position > position_max) then write (*, *) permutation else do value = value_min, value_max if (.not. any (permutation (: position - 1) == value)) then permutation (position) = value call generate (position + 1) end if end do end if   end subroutine generate   end program permutations
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
#VBA
VBA
Option Explicit   Sub Main() Dim T, Arr, X As Long, C As Long Arr = Array(8, 24, 52, 100, 1020, 1024, 10000) For X = LBound(Arr) To UBound(Arr) C = 0 Call PerfectShuffle(T, CLng(Arr(X)), C) Debug.Print Right(String(19, " ") & "For " & Arr(X) & " cards => ", 19) & C & " shuffles needed." Erase T Next End Sub   Private Sub PerfectShuffle(tb, NbCards As Long, Count As Long) Dim arr1, arr2, StrInit As String, StrTest As String   tb = CreateArray(1, NbCards) StrInit = Join(tb, " ") Do Count = Count + 1 Call DivideArr(tb, arr1, arr2) tb = RemakeArray(arr1, arr2) StrTest = Join(tb, " ") Loop While StrTest <> StrInit End Sub   Private Function CreateArray(First As Long, Length As Long) As String() Dim i As Long, T() As String, C As Long If IsEven(Length) Then ReDim T(Length - 1) For i = First To First + Length - 1 T(C) = i C = C + 1 Next i CreateArray = T End If End Function   Private Sub DivideArr(A, B, C) Dim i As Long B = A ReDim Preserve B(UBound(A) \ 2) ReDim C(UBound(B)) For i = LBound(C) To UBound(C) C(i) = A(i + UBound(B) + 1) Next End Sub   Private Function RemakeArray(A1, A2) As String() Dim i As Long, T() As String, C As Long ReDim T((UBound(A2) * 2) + 1) For i = LBound(T) To UBound(T) - 1 Step 2 T(i) = A1(C) T(i + 1) = A2(C) C = C + 1 Next RemakeArray = T End Function   Private Function IsEven(Number As Long) As Boolean IsEven = (Number Mod 2 = 0) End Function
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
#PHP
PHP
class Card { // if unable to save as UTF-8, use other, non-UTF-8, symbols here protected static $suits = array( '♠', '♥', '♦', '♣' );   protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );   protected $suit;   protected $suitOrder;   protected $pip;   protected $pipOrder;   protected $order;   public function __construct( $suit, $pip ) { if( !in_array( $suit, self::$suits ) ) { throw new InvalidArgumentException( 'Invalid suit' ); } if( !in_array( $pip, self::$pips ) ) { throw new InvalidArgumentException( 'Invalid pip' ); }   $this->suit = $suit; $this->pip = $pip; }   public function getSuit() { return $this->suit; }   public function getPip() { return $this->pip; }   public function getSuitOrder() { // lazy evaluate suit order if( !isset( $this->suitOrder ) ) { // cache suit order $this->suitOrder = array_search( $this->suit, self::$suits ); }   return $this->suitOrder; }   public function getPipOrder() { // lazy evaluate pip order if( !isset( $this->pipOrder ) ) { // cache pip order $this->pipOrder = array_search( $this->pip, self::$pips ); }   return $this->pipOrder; }   public function getOrder() { // lazy evaluate order if( !isset( $this->order ) ) { $suitOrder = $this->getSuitOrder(); $pipOrder = $this->getPipOrder(); // cache order $this->order = $pipOrder * count( self::$suits ) + $suitOrder; }   return $this->order; }   public function compareSuit( Card $other ) { return $this->getSuitOrder() - $other->getSuitOrder(); }   public function comparePip( Card $other ) { return $this->getPipOrder() - $other->getPipOrder(); }   public function compare( Card $other ) { return $this->getOrder() - $other->getOrder(); }   public function __toString() { return $this->suit . $this->pip; }   public static function getSuits() { return self::$suits; }   public static function getPips() { return self::$pips; } }   class CardCollection implements Countable, Iterator { protected $cards = array();   protected function __construct( array $cards = array() ) { foreach( $cards as $card ) { $this->addCard( $card ); } }   /** * Countable::count() implementation */ public function count() { return count( $this->cards ); }   /** * Iterator::key() implementation */ public function key() { return key( $this->cards ); }   /** * Iterator::valid() implementation */ public function valid() { return null !== $this->key(); }   /** * Iterator::next() implementation */ public function next() { next( $this->cards ); }   /** * Iterator::current() implementation */ public function current() { return current( $this->cards ); }   /** * Iterator::rewind() implementation */ public function rewind() { reset( $this->cards ); }   public function sort( $comparer = null ) { $comparer = $comparer ?: function( $a, $b ) { return $a->compare( $b ); };   if( !is_callable( $comparer ) ) { throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' ); }   usort( $this->cards, $comparer ); return $this; }   public function toString() { return implode( ' ', $this->cards ); }   public function __toString() { return $this->toString(); }   protected function addCard( Card $card ) { if( in_array( $card, $this->cards ) ) { throw new DomainException( 'Card is already present in this collection' ); }   $this->cards[] = $card; } }   class Deck extends CardCollection { public function __construct( $shuffled = false ) { foreach( Card::getSuits() as $suit ) { foreach( Card::getPips() as $pip ) { $this->addCard( new Card( $suit, $pip ) ); } }   if( $shuffled ) { $this->shuffle(); } }   public function deal( $amount = 1, CardCollection $cardCollection = null ) { if( !is_int( $amount ) || $amount < 1 ) { throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' ); }   if( $amount > count( $this->cards ) ) { throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' ); }   $cards = array_splice( $this->cards, 0, $amount );   $cardCollection = $cardCollection ?: new CardCollection;   foreach( $cards as $card ) { $cardCollection->addCard( $card ); }   return $cardCollection; }   public function shuffle() { shuffle( $this->cards ); } }   class Hand extends CardCollection { // override CardCollection __constructor // to allow public instantiation // but disallow instantiation with cards public function __construct() {}   public function play( $position ) { if( !isset( $this->cards[ $position ] ) ) { throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' ); }   $result = array_splice( $this->cards, $position, 1 ); return $result[ 0 ]; } }
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
#PARI.2FGP
PARI/GP
pi()={ my(x=Pi,n=0,t); print1("3."); while(1, if(n>=default(realprecision), default(realprecision,default(realprecision)*2); x=Pi ); print1(floor(x*10^n++)%10) ) };
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.
#REXX
REXX
╔════════════════════════════════════════════════════════════════════════════════════════╗ ╠═════ How the ─── popCount ─── function works (working from the inner─most level): ═════╣ ║ ║ ║ arg(1) obtains the value of the 1st argument passed to the (popCount) function. ║ ║ d2x converts a decimal string ──► heXadecimal (it may have a leading zeroes).║ ║ +0 adds zero to the (above) string, removing any superfluous leading zeroes. ║ ║ translate converts all zeroes to blanks (the 2nd argument defaults to a blank). ║ ║ space removes all blanks from the character string (now only containing '1's). ║ ║ length counts the number of characters in the string. ║ ║ return returns the above value to the invoker. ║ ║ ║ ║ Note that all values in REXX are stored as (eight─bit) characters. ║ ╚════════════════════════════════════════════════════════════════════════════════════════╝
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.
#Ring
Ring
  # Project : Pernicious numbers   see "The first 25 pernicious numbers:" + nl nr = 0 for n=1 to 50 sum = 0 str = decimaltobase(n, 2) for m=1 to len(str) if str[m] = "1" sum = sum + 1 ok next if isprime(sum) nr = nr + 1 see "" + n + " " ok if nr = 25 exit ok next   func decimaltobase(nr, base) binary = 0 i = 1 while(nr != 0) remainder = nr % base nr = floor(nr/base) binary= binary + (remainder*i) i = i*10 end return string(binary)   func isprime num if (num <= 1) return 0 ok if (num % 2 = 0 and num != 2) return 0 ok for i = 3 to floor(num / 2) -1 step 2 if (num % i = 0) return 0 ok next return 1  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Ursa
Ursa
# generate a stream (ursa equivalent of a list) decl string<> str append "these" "are" "some" "values" str   decl ursa.util.random r out str<(r.getint (size str))> endl console
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#VBA
VBA
  Option Explicit   Sub Main_Pick_Random_Element() Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty")) End Sub   Function Pick_Random_Element(myArray) Randomize Timer Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray)))) End Function  
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.
#Frink
Frink
isPerfect = {|n| sum[allFactors[n, true, false]] == n} println[select[1 to 1000, isPerfect]]
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.
#FunL
FunL
def perfect( n ) = sum( d | d <- 1..n if d|n ) == 2n   println( (1..500).filter(perfect) )
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
#Fortran
Fortran
program permutations   implicit none integer, parameter :: value_min = 1 integer, parameter :: value_max = 3 integer, parameter :: position_min = value_min integer, parameter :: position_max = value_max integer, dimension (position_min : position_max) :: permutation   call generate (position_min)   contains   recursive subroutine generate (position)   implicit none integer, intent (in) :: position integer :: value   if (position > position_max) then write (*, *) permutation else do value = value_min, value_max if (.not. any (permutation (: position - 1) == value)) then permutation (position) = value call generate (position + 1) end if end do end if   end subroutine generate   end program permutations