task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Swift
Swift
public func totient(n: Int) -> Int { var n = n var i = 2 var tot = n   while i * i <= n { if n % i == 0 { while n % i == 0 { n /= i }   tot -= tot / i }   if i == 2 { i = 1 }   i += 2 }   if n > 1 { tot -= tot / n }   return tot }   public struct PerfectTotients: Sequence, IteratorProtocol { private var m = 1   public init() { }   public mutating func next() -> Int? { while true { defer { m += 1 }   var tot = m var sum = 0   while tot != 1 { tot = totient(n: tot) sum += tot }   if sum == m { return m } } } }   print("The first 20 perfect totient numbers are:") print(Array(PerfectTotients().prefix(20)))
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card must have a pip value and a suit value which constitute the unique value of the card. Related tasks: Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser Go Fish
#Logo
Logo
make "suits {Diamonds Hearts Clubs Spades} make "pips {Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King}   to card :n output (sentence item 1 + modulo :n 13 :pips "of item 1 + int quotient :n 13 :suits) end   to new.deck make "deck listtoarray iseq 0 51 make "top 1 end   to swap :i :j :a localmake "t item :i :a setitem :i :a item :j :a setitem :j :a :t end to shuffle.deck for [i [count :deck] 2] [swap 1 + random :i :i :deck] end   to show.deck for [i :top [count :deck]] [show card item :i :deck] end   to deal.card show card item :top :deck make "top :top + 1 end   new.deck shuffle.deck repeat 5 [deal.card]
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
#Kotlin
Kotlin
// version 1.1.2   import java.math.BigInteger   val ZERO = BigInteger.ZERO val ONE = BigInteger.ONE val TWO = BigInteger.valueOf(2L) val THREE = BigInteger.valueOf(3L) val FOUR = BigInteger.valueOf(4L) val SEVEN = BigInteger.valueOf(7L) val TEN = BigInteger.TEN   fun calcPi() { var nn: BigInteger var nr: BigInteger var q = ONE var r = ZERO var t = ONE var k = ONE var n = THREE var l = THREE var first = true while (true) { if (FOUR * q + r - t < n * t) { print(n) if (first) { print ("."); first = false } nr = TEN * (r - n * t) n = TEN * (THREE * q + r) / t - TEN * n q *= TEN r = nr } else { nr = (TWO * q + r) * l nn = (q * SEVEN * k + TWO + r * l) / (t * l) q *= k t *= l l += TWO k += ONE n = nn r = nr } } }   fun main(args: Array<String>) = calcPi()
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
#Run_BASIC
Run BASIC
numPlayers = 2 maxScore = 100 dim safeScore(numPlayers)   [loop] for player = 1 to numPlayers score = 0   while safeScore(player) < maxScore input "Player ";player;" Rolling? (Y) ";rolling$ if upper$(rolling$) = "Y" then rolled = int(rnd(0) * 5) + 1 print "Player ";player;" rolled ";rolled if rolled = 1 then print "Bust! you lose player ";player;" but still keep your previous score of ";safeScore(plater) exit while end if score = score + rolled else safeScore(player) = safeScore(player) + score end if wend next player goto [loop] [winner] print "Player ";plater;" wins with a score of ";safeScore(player)
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pernicious number. Task display the first   25   pernicious numbers   (in decimal). display all pernicious numbers between   888,888,877   and   888,888,888   (inclusive). display each list of integers on one line   (which may or may not include a title). See also Sequence   A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences. Rosetta Code entry   population count, evil numbers, odious numbers.
#Nim
Nim
import strutils   proc count(s: string; sub: char): int = var i = 0 while true: i = s.find(sub, i) if i < 0: break inc i inc result   proc popcount(n: int): int = n.toBin(64).count('1')   const primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61}   var p: seq[int] var i = 0 while p.len < 25: if popcount(i) in primes: p.add i inc i   echo p   p = @[] i = 888_888_877 while i <= 888_888_888: if popcount(i) in primes: p.add i inc i   echo p
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Picat
Picat
go =>    % single element println(choice=choice(10)), % single element    % From a list of numbers L = 1..10, println([choice(L) : _ in 1..10]),    % From a string S = "pickrandomelement", println([choice(S) : _ in 1..10]), nl.   % Pick a random number from 1..N choice(N) = random(1,N), integer(N) => true.   % Pick a random element from a list L. choice(List) = List[choice(List.length)], list(List) => true.
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#PicoLisp
PicoLisp
(get Lst (rand 1 (length Lst)))
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
#Racket
Racket
#lang racket/base (require (only-in srfi/13 string-reverse) (only-in racket/string string-split string-join))   (define (phrase-reversal s) (list (string-reverse s) (string-join (map string-reverse (string-split s))) (string-join (reverse (string-split s)))))   (for-each displayln (phrase-reversal "rosetta code phrase reversal"))
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
#Raku
Raku
my $s = 'rosetta code phrase reversal';   put 'Input  : ', $s; put 'String reversed  : ', $s.flip; put 'Each word reversed  : ', $s.words».flip; put 'Word-order reversed : ', $s.words.reverse;
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n. Task Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer). Generate and show all the derangements of 4 integers using the above routine. Create a function that calculates the subfactorial of n, !n. Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive. Optional stretch goal   Calculate    !20 Related tasks   Anagrams/Deranged anagrams   Best shuffle   Left_factorials Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PureBasic
PureBasic
  Procedure.q Subfactoral(n) If n=0:ProcedureReturn 1:EndIf If n=1:ProcedureReturn 0:EndIf ProcedureReturn (Subfactoral(n-1)+Subfactoral(n-2))*(n-1) EndProcedure   factFile.s="factorials.txt" tempFile.s="temp.txt" drngFile.s="derangements.txt" DeleteFile(factFile.s) DeleteFile(tempFile.s) DeleteFile(drngFile.s)   n=4   ; create our storage file f.s=factFile.s If CreateFile(0,f.s) WriteStringN(0,"1.2") WriteStringN(0,"2.1") CloseFile(0) Else Debug "not createfile :"+f.s EndIf   showfactorial=#False   If showfactorial ; cw("nfactorial n ="+str(n)) Debug "nfactorial n ="+Str(n) EndIf   ; build up the factorial combinations For l=1 To n-2 Gosub nfactorial Next   ; extract the derangements ; cw("derangements["+str(perm(n))+"] for n="+str(n)) Debug "derangements["+Str(Subfactoral(n))+"] for n="+Str(n) Gosub derangements ; cw("") Debug ""   ; show the first 20 derangements For i=0 To 20 Debug "derangements["+Str(Subfactoral(i))+"] for n="+Str(i) Next   End   derangements: x=0 If ReadFile(0,factFile.s) And CreateFile(1,drngFile.s) Repeat r.s = ReadString(0) cs=CountString(r.s,".") If cs hit=0 t.s="" ; scan for numbers at their index For i=1 To cs+1 s.s=StringField(r.s,i,".") t.s+s.s+"." If Val(s.s)=i:hit+1:EndIf Next t.s=RTrim(t.s,".") ; show only those which are valid If Not hit x+1 ; cw(t.s+" "+str(x)) Debug t.s+" "+Str(x) WriteStringN(1,t.s+" "+Str(x)) EndIf EndIf Until Eof(0) CloseFile(0) CloseFile(1) Else Debug "not readfile :"+factFile.s Debug "not createfile :"+drngFile.s EndIf ; cw("") Debug "" Return   nfactorial: x=0 If ReadFile(0,factFile.s) And CreateFile(1,tempFile.s) Repeat r.s = ReadString(0) cs=CountString(r.s,".") If cs For j=1 To cs+2 t.s="" For i=1 To cs+1 s.s=StringField(r.s,i,".") If i=j t.s+"."+Str(cs+2)+"."+s.s Else t.s+"."+s.s EndIf Next If j=cs+2:t.s+"."+Str(cs+2):EndIf t.s=Trim(t.s,".") x+1 If cs+2=n And showfactorial ; cw(t.s+" "+str(x)) Debug t.s+" "+Str(x) EndIf WriteStringN(1,t.s) Next EndIf Until Eof(0) CloseFile(0) CloseFile(1) Else Debug "not readfile :"+factFile.s Debug "not createfile :"+tempFile.s EndIf CopyFile(tempFile.s,factFile.s) DeleteFile(tempFile.s) Return  
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#Wren
Wren
var johnsonTrotter = Fn.new { |n| var p = List.filled(n, 0) // permutation var q = List.filled(n, 0) // inverse permutation for (i in 0...n) p[i] = q[i] = i var d = List.filled(n, -1) // direction = 1 or -1 var sign = 1 var perms = [] var signs = []   var permute // recursive closure permute = Fn.new { |k| if (k >= n) { perms.add(p.toList) signs.add(sign) sign = sign * -1 return } permute.call(k + 1) for (i in 0...k) { var z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] = q[k] + d[k] permute.call(k + 1) } d[k] = d[k] * -1 } permute.call(0) return [perms, signs] }   var printPermsAndSigns = Fn.new { |perms, signs| var i = 0 for (perm in perms) { System.print("%(perm) -> sign = %(signs[i])") i = i + 1 } }   var res = johnsonTrotter.call(3) var perms = res[0] var signs = res[1] printPermsAndSigns.call(perms, signs) System.print() res = johnsonTrotter.call(4) perms = res[0] signs = res[1] printPermsAndSigns.call(perms, signs)
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%
#Perl
Perl
use Image::Imlib2;   my $img1 = Image::Imlib2->load('Lenna50.jpg') || die; my $img2 = Image::Imlib2->load('Lenna100.jpg') || die;   my $w = $img1->width; my $h = $img1->height;   my $sum = 0;   for my $x (0..$w-1) { for my $y (0..$h-1) { my ($r1, $g1, $b1) = $img1->query_pixel($x, $y); my ($r2, $g2, $b2) = $img2->query_pixel($x, $y); $sum += abs($r1-$r2) + abs($g1-$g2) + abs($b1-$b2); } }   printf "%% difference = %.4f\n", 100 * $sum / ($w * $h * 3 * 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.
#Common_Lisp
Common Lisp
(defun perfectp (n) (= n (loop for i from 1 below n when (= 0 (mod n i)) sum 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
#CoffeeScript
CoffeeScript
# Returns a copy of an array with the element at a specific position # removed from it. arrayExcept = (arr, idx) -> res = arr[0..] res.splice idx, 1 res   # The actual function which returns the permutations of an array-like # object (or a proper array). permute = (arr) -> arr = Array::slice.call arr, 0 return [[]] if arr.length == 0   permutations = (for value,idx in arr [value].concat perm for perm in permute arrayExcept arr, idx)   # Flatten the array before returning it. [].concat 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
#Nim
Nim
import sequtils, strutils   proc newValList(size: Positive): seq[int] = if (size and 1) != 0: raise newException(ValueError, "size must be even.") result = toSeq(1..size)     func shuffled(list: seq[int]): seq[int] = result.setLen(list.len) let half = list.len div 2 for i in 0..<half: result[2 * i] = list[i] result[2 * i + 1] = list[half + i]     for size in [8, 24, 52, 100, 1020, 1024, 10000]: let initList = newValList(size) var valList = initList var count = 0 while true: inc count valList = shuffled(valList) if valList == initList: break echo ($size).align(5), ": ", ($count).align(4)
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
#Oforth
Oforth
: shuffle(l) l size 2 / dup l left swap l right zip expand ; : nbShuffles(l) 1 l while( shuffle dup l <> ) [ 1 under+ ] drop ;
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Swift
Swift
import Foundation   struct Perlin { private static let permutation = [ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 ]   private static let p = (0..<512).map({i -> Int in if i < 256 { return permutation[i] } else { return permutation[i - 256] } })   private static func fade(_ t: Double) -> Double { t * t * t * (t * (t * 6 - 15) + 10) }   private static func lerp(_ t: Double, _ a: Double, _ b: Double) -> Double { a + t * (b - a) }   private static func grad(_ hash: Int, _ x: Double, _ y: Double, _ z: Double) -> Double { let h = hash & 15 let u = h < 8 ? x : y let v = h < 4 ? y : h == 12 || h == 14 ? x : z   return (h & 1 == 0 ? u : -u) + (h & 2 == 0 ? v : -v) }   static func noise(x: Double, y: Double, z: Double) -> Double { let xi = Int(x) & 255 let yi = Int(y) & 255 let zi = Int(z) & 255   let xx = x - floor(x) let yy = y - floor(y) let zz = z - floor(z)   let u = fade(xx) let v = fade(yy) let w = fade(zz)   let a = p[xi] + yi let aa = p[a] + zi let b = p[xi + 1] + yi let ba = p[b] + zi let ab = p[a + 1] + zi let bb = p[b + 1] + zi   return lerp(w, lerp(v, lerp(u, grad(p[aa], xx, yy, zz), grad(p[ba], xx - 1, yy, zz)), lerp(u, grad(p[ab], xx, yy - 1, zz), grad(p[bb], xx - 1, yy - 1, zz))), lerp(v, lerp(u, grad(p[aa + 1], xx, yy, zz - 1), grad(p[ba + 1], xx - 1, yy, zz - 1)), lerp(u, grad(p[ab + 1], xx, yy - 1, zz - 1), grad(p[bb + 1], xx - 1, yy - 1, zz - 1)))) } }   print(Perlin.noise(x: 3.14, y: 42, z: 7))
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Wren
Wren
var totient = Fn.new { |n| var tot = n var i = 2 while (i*i <= n) { if (n%i == 0) { while(n%i == 0) n = (n/i).floor tot = tot - (tot/i).floor } if (i == 2) i = 1 i = i + 2 } if (n > 1) tot = tot - (tot/n).floor return tot }   var perfect = [] var n = 1 while (perfect.count < 20) { var tot = n var sum = 0 while (tot != 1) { tot = totient.call(tot) sum = sum + tot } if (sum == n) perfect.add(n) n = n + 2 } System.print("The first 20 perfect totient numbers are:") System.print(perfect)
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card must have a pip value and a suit value which constitute the unique value of the card. Related tasks: Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser Go Fish
#Lua
Lua
  suits = {"Clubs", "Diamonds", "Hearts", "Spades"} faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"} --a stack is a set of cards. a stack of length 1 acts as a card; the stack constructor only creates decks.   stack = setmetatable({ --shuffles a stack __unm = function(z) local ret = {} for i = #z, 1, -1 do ret[#ret + 1] = table.remove(z,math.random(i)) end return setmetatable(ret, stack) end, --puts two stacks together __add = function(z, z2) for i = 1, #z2 do z[#z+1] = table.remove(z2) end return z end, --removes n cards from a stack and returns a stack of those cards __sub = function(z, n) local ret = {} for i = 1, n do ret[i] = table.remove(z) end return setmetatable(ret, stack) end, --breaks a stack into n equally sized stacks and returns them all deal = function(z, n) local ret = {} for i = 1, #z/n do ret[i] = table.remove(z) end if n > 1 then return setmetatable(ret, stack), stack.deal(z,n-1) else return setmetatable(ret, stack) end end, --returns a and b as strings, concatenated together. Simple enough, right? __concat = function(a, b) if getmetatable(a) == stack then return stack.stackstring(a) .. b else return a .. stack.stackstring(b) end end, stackstring = function(st, ind) ind = ind or 1 if not st[ind] then return "" end return st[ind] and (faces[math.ceil(st[ind]/4)] .. " of " .. suits[st[ind]%4+1] .. "\n" .. stack.stackstring(st, ind+1)) or "" end}, { --creates a deck __call = function(z) local ret = {} for i = 1, 52 do ret[i] = i end return -setmetatable(ret,z) end})   print(stack() .. "\n") a, b, c, d = stack.deal(stack(), 4) print(a .. "\n\n\n") print(b + c .. "\n\n\n") print(d - 4 .. "") print(-b .. "")  
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
#Lasso
Lasso
#!/usr/bin/lasso9   define generatePi => { yield currentCapture   local(r = array(), i, k, b, d, c = 0, x) with i in generateSeries(1, 2800) do #r->insert(2000) with k in generateSeries(2800, 1, -14) do { #d = 0 #i = #k while(true) => { #d += #r->get(#i) * 10000 #b = 2 * #i - 1 #r->get(#i) = #d % #b #d /= #b #i--  !#i ? loop_abort #d *= #i } #x = (#c + #d / 10000) yield (#k == 2800 ? ((#x * 0.001)->asstring(-precision = 3)) | #x->asstring(-padding=4, -padChar='0')) #c = #d % 10000 } }   local(pi_digits) = generatePi loop(200) => { stdout(#pi_digits()) }
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   1   loses the player's total points   for that turn   and their turn finishes with play passing to the next player. Holding:   the player's score for that round is added to their total and becomes safe from the effects of throwing a   1   (one).   The player's turn finishes with play passing to the next player. Task Create a program to score for, and simulate dice throws for, a two-person game. Related task   Pig the dice game/Player
#Rust
Rust
use rand::prelude::*;   fn main() { println!("Beginning game of Pig...");   let mut players = vec![ Player::new(String::from("PLAYER (1) ONE")), Player::new(String::from("PLAYER (2) TWO")), ];   'game: loop { for player in players.iter_mut() { if player.cont() { println!("\n# {} has {:?} Score", player.name, player.score); player.resolve(); } else { println!("\n{} wins!", player.name); break 'game; } } }   println!("Thanks for playing!"); }   type DiceRoll = u32; type Score = u32; type Name = String;   enum Action { Roll, Hold, }   #[derive(PartialEq)] enum TurnStatus { Continue, End, }   struct Player { name: Name, score: Score, status: TurnStatus, }   impl Player { fn new(name: Name) -> Player { Player { name, score: 0, status: TurnStatus::Continue, } }   fn roll() -> DiceRoll { // Simple 1d6 dice. let sides = rand::distributions::Uniform::new(1, 6); rand::thread_rng().sample(sides) }   fn action() -> Action { // Closure to determine userinput as action. let command = || -> Option<char> { let mut cmd: String = String::new(); match std::io::stdin().read_line(&mut cmd) { Ok(c) => c.to_string(), Err(err) => panic!("Error: {}", err), };   cmd.to_lowercase().trim().chars().next() };   'user_in: loop { match command() { Some('r') => break 'user_in Action::Roll, Some('h') => break 'user_in Action::Hold, Some(invalid) => println!("{} is not a valid command!", invalid), None => println!("Please input a command!"), } } }   fn turn(&mut self) -> Score { let one = |die: DiceRoll| { println!("[DICE] Dice result is: {:3}!", die); println!("[DUMP] Dumping Score! Sorry!"); println!("###### ENDING TURN ######"); };   let two_to_six = |die: DiceRoll, score: Score, player_score: Score| { println!("[DICE] Dice result is: {:3}!", die); println!("[ROLL] Total Score: {:3}!", (score + die)); println!("[HOLD] Possible Score: {:3}!", (score + die + player_score)); };   let mut score: Score = 0; 'player: loop { println!("# {}'s Turn", self.name); println!("###### [R]oll ######\n###### --OR-- ######\n###### [H]old ######");   match Player::action() { Action::Roll => match Player::roll() { 0 | 7..=u32::MAX => panic!("outside dice bounds!"), die @ 1 => { one(die); self.status = TurnStatus::End; break 'player 0; } die @ 2..=6 => { two_to_six(die, score, self.score); self.status = TurnStatus::Continue; score += die } }, Action::Hold => { self.status = TurnStatus::End; break 'player score; } } } }   fn resolve(&mut self) { self.score += self.turn() }   fn cont(&self) -> bool { self.score <= 100 || self.status == TurnStatus::Continue } }
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.
#Panda
Panda
fun prime(a) type integer->integer a where count{{a.factor}}==2 fun pernisc(a) type integer->integer a where sum{{a.radix:2 .char.integer}}.integer.prime   1..36.pernisc 888888877..888888888.pernisc
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#PL.2FI
PL/I
declare t(0:9) character (1) static initial ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); put ( t(10*random()) );
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Powershell
Powershell
  1..100 | Get-Random -Count 3  
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
s='rosetta code phrase reversal' r1=reverse(s) r2='' Do i=1 To words(s) r2=r2 reverse(word(s,i)) End r2=strip(r2) r3='' Do i=words(s) To 1 By -1 r3=r3 word(s,i) End r3=strip(r3) Say "input  : " s say "string reversed  : " r1 say "each word reversed  : " r2 say "word-order reversed : " r3
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
#Ring
Ring
  aString = "Welcome to the Ring Language" bString = "" see reverseString(aString)   func reverseString cString for i= len(cString) to 1 step -1 bString = bString + cString[i] next return bString  
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
#Python
Python
from itertools import permutations import math     def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) )   def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError()   def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l   if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print("  %s" % (d,))   print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n)))   n = 20 print("\n!%i = %i" % (n, subfact(n)))
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#XPL0
XPL0
include c:\cxpl\codes;   proc PERMS(N); int N; \number of elements int I, K, S, T, P; [P:= Reserve((N+1)*4); for I:= 0 to N do P(I):= -I; \initialize facing left (also set P(0)=0) S:= 1; repeat Text(0, "Perm: [ "); for I:= 1 to N do [IntOut(0, abs(P(I))); ChOut(0, ^ )]; Text(0, "] Sign: "); IntOut(0, S); CrLf(0);   K:= 0; \find largest mobile element for I:= 2 to N do \for left-facing elements if P(I) < 0 and abs(P(I)) > abs(P(I-1)) and \ greater than neighbor abs(P(I)) > abs(P(K)) then K:= I; \ get largest element for I:= 1 to N-1 do \for right-facing elements if P(I) > 0 and abs(P(I)) > abs(P(I+1)) and \ greater than neighbor abs(P(I)) > abs(P(K)) then K:= I; \ get largest element if K # 0 then \mobile element found [for I:= 1 to N do \reverse elements > K if abs(P(I)) > abs(P(K)) then P(I):= P(I)*-1; I:= K + (if P(K)<0 then -1 else 1); T:= P(K); P(K):= P(I); P(I):= T; \swap K with element looked at S:= -S; \alternate signs ]; until K = 0; \no mobile element remains ];   [PERMS(3); CrLf(0); PERMS(4); ]
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement. References Steinhaus–Johnson–Trotter algorithm Johnson-Trotter Algorithm Listing All Permutations Heap's algorithm [1] Tintinnalogia Related tasks   Matrix arithmetic   Gray code
#zkl
zkl
fcn permute(seq) { insertEverywhere := fcn(x,list){ //(x,(a,b))-->((x,a,b),(a,x,b),(a,b,x)) (0).pump(list.len()+1,List,'wrap(n){list[0,n].extend(x,list[n,*]) })}; insertEverywhereB := fcn(x,t){ //--> insertEverywhere().reverse() [t.len()..-1,-1].pump(t.len()+1,List,'wrap(n){t[0,n].extend(x,t[n,*])})};   seq.reduce('wrap(items,x){ f := Utils.Helpers.cycle(insertEverywhereB,insertEverywhere); items.pump(List,'wrap(item){f.next()(x,item)}, T.fp(Void.Write,Void.Write)); },T(T)); }
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%
#Phix
Phix
-- demo\rosetta\Percentage_difference_between_images.exw without js -- (file i/o) include ppm.e function split_colour(integer c) return sq_div(sq_and_bits(c, {#FF0000,#FF00,#FF}), {#010000,#0100,#01}) end function function percentage_diff(sequence img1, img2) if length(img1)!=length(img2) or length(img1[1])!=length(img2[1]) then return "sizes do not match" end if atom diff = 0 for i=1 to length(img1) do for j=1 to length(img1[i]) do integer {r1,g1,b1} = split_colour(img1[i,j]), {r2,g2,b2} = split_colour(img2[i,j]) diff += abs(r1-r2)+abs(g1-g2)+abs(b1-b2) end for end for return 100*diff/(length(img1)*length(img1[1]))/3/255 end function sequence img1 = read_ppm("Lenna50.ppm"), img2 = read_ppm("Lenna100.ppm") ?percentage_diff(img1,img2) {} = wait_key()
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.
#D
D
import std.stdio, std.algorithm, std.range;   bool isPerfectNumber1(in uint n) pure nothrow in { assert(n > 0); } body { return n == iota(1, n - 1).filter!(i => n % i == 0).sum; }   void main() { iota(1, 10_000).filter!isPerfectNumber1.writeln; }
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
#Common_Lisp
Common Lisp
(defun permute (list) (if list (mapcan #'(lambda (x) (mapcar #'(lambda (y) (cons x y)) (permute (remove x list)))) list) '(()))) ; else   (print (permute '(A B Z)))
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: original: 1 2 3 4 5 6 7 8 after 1st shuffle: 1 5 2 6 3 7 4 8 after 2nd shuffle: 1 3 5 7 2 4 6 8 after 3rd shuffle: 1 2 3 4 5 6 7 8 The Task Write a function that can perform a perfect shuffle on an even-sized list of values. Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. Test Cases input (deck size) output (number of shuffles required) 8 3 24 11 52 8 100 30 1020 1018 1024 10 10000 300
#PARI.2FGP
PARI/GP
magic(v)=vector(#v,i,v[if(i%2,1,#v/2)+i\2]); shuffles_slow(n)=my(v=[1..n],o=v,s=1);while((v=magic(v))!=o,s++);s; shuffles(n)=znorder(Mod(2,n-1)); vector(5000,n,shuffles_slow(2*n))
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Tcl
Tcl
namespace eval perlin { proc noise {x y z} { # Find unit cube that contains point. set X [expr {int(floor($x)) & 255}] set Y [expr {int(floor($y)) & 255}] set Z [expr {int(floor($z)) & 255}]   # Find relative x,y,z of point in cube. set x [expr {$x - floor($x)}] set y [expr {$y - floor($y)}] set z [expr {$z - floor($z)}]   # Compute fade curves for each of x,y,z. set u [expr {fade($x)}] set v [expr {fade($y)}] set w [expr {fade($z)}]   # Hash coordinates of the 8 cube corners... variable p set A [expr {p($X) + $Y}] set AA [expr {p($A) + $Z}] set AB [expr {p($A+1) + $Z}] set B [expr {p($X+1) + $Y}] set BA [expr {p($B) + $Z}] set BB [expr {p($B+1) + $Z}]   # And add blended results from 8 corners of cube return [expr { lerp($w, lerp($v, lerp($u, grad(p($AA), $x, $y, $z ), grad(p($BA), $x-1, $y, $z )), lerp($u, grad(p($AB), $x, $y-1, $z ), grad(p($BB), $x-1, $y-1, $z ))), lerp($v, lerp($u, grad(p($AA+1), $x, $y, $z-1 ), grad(p($BA+1), $x-1, $y, $z-1 )), lerp($u, grad(p($AB+1), $x, $y-1, $z-1 ), grad(p($BB+1), $x-1, $y-1, $z-1 )))) }] }   namespace eval tcl::mathfunc { proc p {idx} {lindex $::perlin::permutation $idx} proc fade {t} {expr { $t**3 * ($t * ($t * 6 - 15) + 10) }} proc lerp {t a b} {expr { $a + $t * ($b - $a) }} proc grad {hash x y z} { # Convert low 4 bits of hash code into 12 gradient directions set h [expr { $hash & 15 }] set u [expr { $h<8 ? $x : $y }] set v [expr { $h<4 ? $y : ($h==12 || $h==14) ? $x : $z }] expr { (($h&1)==0 ? $u : -$u) + (($h&2)==0 ? $v : -$v) } } }   apply {{} { binary scan [binary format H* [join { 97A0895B5A0F830DC95F6035C2E907E18C24671E458E086325F0150A17BE0694F7 78EA4B001AC53E5EFCDBCB75230B2039B12158ED953857AE147D88ABA844AF4AA5 47868B301BA64D929EE7536FE57A3CD385E6DC695C29372EF528F4668F3641193F A101D85049D14C84BBD05912A9C8C4878274BC9F56A4646DC6ADBA034034D9E2FA 7C7B05CA2693767EFF5255D4CFCE3BE32F103A11B6BD1C2ADFB7AAD577F898022C 9AA346DD99659BA72BAC09811627FD13626C6E4F71E0E8B2B97068DAF661E4FB22 F2C1EED2900CBFB3A2F1513391EBF90EEF6B31C0D61FB5C76A9DB854CCB0737932 2D7F0496FE8AECCD5DDE72431D1848F38D80C34E42D73D9CB4 } ""]] cu* p variable ::perlin::permutation [concat $p $p] }} }   puts [perlin::noise 3.14 42 7]
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#zkl
zkl
var totients=List.createLong(10_000,0); // cache fcn totient(n){ if(phi:=totients[n]) return(phi); totients[n]=[1..n].reduce('wrap(p,k){ p + (n.gcd(k)==1) }) } fcn perfectTotientW{ // -->iterator (1).walker(*).tweak(fcn(z){ parts,n := 0,z; while(n!=1){ parts+=( n=totient(n) ) } if(parts==z) z else Void.Skip; }) }
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
#M2000_Interpreter
M2000 Interpreter
  Module PlayCards { Font "Arial" ' Ensure characters exist for Suits Cls 15,0 Pen 0 Inventory Suits = "♠":=0, "♥":=4, "♦":=4, "♣":=0 'suit -> color Inventory Cards = "two":=2, "three":=3, "four":=4, "five":=5 Append Cards, "six":=6, "seven":=7, "eight":=8, "nine":=9 Append Cards, "ten":=10, "jack":=10, "queen":=10, "king":=10, "ace":=1 DealerMoney=0 PrintCardOnly = Lambda Suits, Cards (k, nl=True)-> { For k { Pen Suits(.suit!) { If nl then { Print Part @(10), Eval$(Suits, .suit)+Eval$(Cards, .card) Print } Else Print Eval$(Suits, .suit)+Eval$(Cards, .card), } } } ' Using a stack object StackPack = Stack Module AppendArray (N, A) { Stack N {Data !A} } Class OneCard { suit=-1, Card Class: Module OneCard { \\ ? for optional reading read ? .suit, .card } } Decks=1 Dim Pack(Len(Cards)*Len(Suits)*Decks) k=0 \\ fill cards to Pack() For times=1 To Decks { N=each(Suits) While N { M=each(Cards) While M { Pack(k)=OneCard(N^, M^) k++ } } } DisplayAll() ' in order Suffle() DisplayAll() ' at random positions Print Card=OneCard() Print "Cards in Deck:";Len(StackPack) For i=1 to 60 { NextCard() Print "Get Card:"; Call PrintCardOnly(Card) Print Print "Cards in Deck:";Len(StackPack) DisplayDeck() Print }   Sub Suffle() Print Local N=Len(Pack())-1, N2, i, j, total=N*4+4, cur=1 For j=1 To 4 { For i=0 To N { If cur Mod 4=3 Then Print Over format$("Suffle {0:0}%",cur/total*100) N2=random(0, N) While N2=i {N2=random(0, N)} Swap Pack(i), Pack(N2) cur++ } } AppendArray StackPack, Pack() Print End Sub Sub DisplayDeck() local m=each(StackPack) While m { Call PrintCardOnly(StackItem(m), False) } End Sub Sub DisplayAll() For k=0 To Len(Pack())-1 { PrintCard(k) } End Sub Sub PrintCard(k) For Pack(k) { Pen Suits(.suit!) { Print Eval$(Suits, .suit)+Eval$(Cards, .card), } } End Sub Sub NextCard() If Len(StackPack)=0 Then { Suffle() Stack StackPack { Drop Random(0, 51) } } Stack StackPack { Read Card } End Sub } PlayCards  
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
#Liberty_BASIC
Liberty BASIC
ndigits = 0   q = 1 r = 0 t = q k = q n = 3 L = n   first = 666 ' ANY non-zero =='true' in LB.   while ndigits <100 if ( 4 *q +r -t) <( n *t) then print n; ndigits =ndigits +1 if not( ndigits mod 40) then print: print " "; if first =666 then first = 0: print "."; nr =10 *( r -n *t) n =int( ( (10 *( 3 *q +r)) /t) -10 *n) q =q *10 r =nr else nr =( 2 *q +r) *L nn =(q *( 7 *k +2) +r *L) /( t *L) q =q *k t =t *L L =L +2 k =k +1 n =int( nn) r =nr end if scan wend   end
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   1   loses the player's total points   for that turn   and their turn finishes with play passing to the next player. Holding:   the player's score for that round is added to their total and becomes safe from the effects of throwing a   1   (one).   The player's turn finishes with play passing to the next player. Task Create a program to score for, and simulate dice throws for, a two-person game. Related task   Pig the dice game/Player
#Scala
Scala
object PigDice extends App { private val (maxScore, nPlayers) = (100, 2) private val rnd = util.Random   private case class Game(gameOver: Boolean, idPlayer: Int, score: Int, stickedScores: Vector[Int])   @scala.annotation.tailrec private def loop(play: Game): Unit = play match { case Game(true, _, _, _) => case Game(false, gPlayer, gScore, gStickedVals) => val safe = gStickedVals(gPlayer) val stickScore = safe + gScore val gameOver = stickScore >= maxScore   def nextPlayer = (gPlayer + 1) % nPlayers   def gamble: Game = play match { case Game(_: Boolean, lPlayer: Int, lScore: Int, lStickedVals: Vector[Int]) => val rolled: Int = rnd.nextInt(6) + 1   println(s" Rolled $rolled") if (rolled == 1) { println(s" Bust! You lose $lScore but keep ${lStickedVals(lPlayer)}\n") play.copy(idPlayer = nextPlayer, score = 0) } else play.copy(score = lScore + rolled) }   def stand: Game = play match { case Game(_, lPlayer, _, lStickedVals) =>   println( (if (gameOver) s"\n\nPlayer $lPlayer wins with a score of" else " Sticking with") + s" $stickScore.\n")   Game(gameOver, nextPlayer, 0, lStickedVals.updated(lPlayer, stickScore)) }   if (!gameOver && Seq("y", "").contains( io.StdIn.readLine(f" Player $gPlayer%d: ($safe%d, $gScore%d) Rolling? ([y]/n): ").toLowerCase) ) loop(gamble )else loop(stand) }   loop(Game(gameOver = false, 0, 0, Array.ofDim[Int](nPlayers).toVector)) }
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.
#PARI.2FGP
PARI/GP
pern(n)=isprime(hammingweight(n)) select(pern, [1..36]) select(pern,[888888877..888888888])
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Prolog
Prolog
  ?- random_member(M, [a, b, c, d, e, f, g, h, i, j]). M = i.  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#PureBasic
PureBasic
Procedure.s pickRandomElement(List source.s()) Protected x = ListSize(source())   If x > 0 SelectElement(source(), Random(x - 1)) ;element numbering is zero - based ProcedureReturn source() EndIf EndProcedure   ;initialize list elements DataSection elements: Data.s "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" EndDataSection   #elementCount = 10 NewList item.s()   Restore elements Define i For i = 1 To #elementCount AddElement(item()) Read.s item() Next   If OpenConsole() Print("Source list: ") ForEach item() Print(item() + " ") Next PrintN(#CRLF$)   Print("Random picks from list: ") For i = 1 To 10 Print(pickRandomElement(item()) + " ") Next   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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
#Ruby
Ruby
str = "rosetta code phrase reversal"   puts str.reverse # Reversed string. puts str.split.map(&:reverse).join(" ") # Words reversed. puts str.split.reverse.join(" ") # Word order reversed.
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Rust
Rust
fn reverse_string(string: &str) -> String { string.chars().rev().collect::<String>() }   fn reverse_words(string: &str) -> String { string .split_whitespace() .map(|x| x.chars().rev().collect::<String>()) .collect::<Vec<String>>() .join(" ") }   fn reverse_word_order(string: &str) -> String { string .split_whitespace() .rev() .collect::<Vec<&str>>() .join(" ") }   #[cfg(test)] mod tests { use super::*;   #[test] fn test_reverse_string() { let string = "rosetta code phrase reversal"; assert_eq!( reverse_string(string.clone()), "lasrever esarhp edoc attesor" ); }   #[test] fn test_reverse_words() { let string = "rosetta code phrase reversal"; assert_eq!( reverse_words(string.clone()), "attesor edoc esarhp lasrever" ); }   #[test] fn test_reverse_word_order() { let string = "rosetta code phrase reversal"; assert_eq!( reverse_word_order(string.clone()), "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
#QBasic
QBasic
' Heap's algorithm non-recursive FUNCTION permsderange (n!, flag!) IF n = 0 THEN permsderange = 1   DIM a!(0 TO n), c!(0 TO n)   FOR j = 0 TO n - 1: a(j) = j: NEXT j   WHILE i < n IF c(i) < i THEN IF (i AND 1) = 0 THEN SWAP a(0), a(i) ELSE SWAP a(c(i)), a(i) END IF FOR j = 0 TO n - 1 IF a(j) = j THEN j = 99 NEXT j IF j < 99 THEN count = count + 1 IF flag = 0 THEN c1 = c1 + 1 FOR j = 0 TO n - 1 PRINT a(j); NEXT j IF c1 > 12 THEN PRINT : c1 = 0 ELSE PRINT END IF END IF END IF c(i) = c(i) + 1 i = 0 ELSE c(i) = 0 i = i + 1 END IF WEND IF flag = 0 AND c1 <> 0 THEN PRINT permsderange = count END FUNCTION   SUB Subfactorial (a!()) FOR i = 0 TO UBOUND(a) num = num * i IF (i AND 1) = 1 THEN num = num - 1 ELSE num = num + 1 END IF a(i) = num NEXT i END SUB   n! = 4 DIM subfac!(7)   CALL Subfactorial(subfac())   PRINT "permutations derangements for n = "; n i! = permsderange(n, 0) PRINT "count returned ="; i; " , !"; n; " calculated ="; subfac(n)   PRINT PRINT "count counted subfactorial" PRINT "---------------------------" FOR i = 0 TO 7 PRINT USING " ###: ######## ########"; i; permsderange(i, 1); subfac(i) NEXT i
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%
#PicoLisp
PicoLisp
(call "convert" "Lenna50.jpg" (tmp "Lenna50.ppm")) (call "convert" "Lenna100.jpg" (tmp "Lenna100.ppm"))   (let (Total 0 Diff 0) (in (tmp "Lenna50.ppm") (in (tmp "Lenna100.ppm") (while (rd 1) (inc 'Diff (*/ (abs (- @ (in -1 (rd 1)))) 1000000 255 ) ) (inc 'Total) ) ) ) (prinl "Difference is " (format (*/ Diff Total) 4) " percent") )
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%
#PureBasic
PureBasic
#URL1="http://rosettacode.org/mw/images/3/3c/Lenna50.jpg" #URL2="http://rosettacode.org/mw/images/b/b6/Lenna100.jpg"   Procedure.s GetTempFileName(basename$="",Extension$=".tmp") Protected file$, i Repeat: file$=GetTemporaryDirectory()+basename$+"_"+Str(i)+Extension$: i+1 Until FileSize(file$) = -1 ; E.g. File not found ProcedureReturn file$ EndProcedure   Procedure ImageToMatrix(Image,Array P(2)) Protected Width=ImageWidth(0)-1, Height=ImageHeight(0)-1, x, y ; Scaling down Width & Height by -1 to compensate for using 0-based arrays Dim P(Width,Height) StartDrawing(ImageOutput(Image)) For x=0 To Width For y=0 To Height P(x,y)=Point(x,y) Next y Next x StopDrawing() EndProcedure   Define File1$, File2$, totalDiff, x, y, w, h   ; Load the pictures from RoettaCode InitNetwork() File1$=GetTempFileName("",".jpg"): ReceiveHTTPFile(#URL1,File1$) File2$=GetTempFileName("",".jpg"): ReceiveHTTPFile(#URL2,File2$)   ; Decode the images & clean up temporary files UseJPEGImageDecoder() LoadImage(0,File1$):LoadImage(1,File2$) DeleteFile(File1$): DeleteFile(File2$)   ; Make two 2D arrays to hold the data Dim Pic1(0,0): Dim Pic2(0,0)   ;Load the image data into the matrixes ImageToMatrix(0,Pic1()): ImageToMatrix(1,Pic2())   ; Compare the data w=ArraySize(pic1()): h=ArraySize(pic1(),2) For x=0 To w For y=0 To h totalDiff+ Abs( Red(Pic1(x,y)) - Red(Pic2(x,y))) totalDiff+ Abs(Green(Pic1(x,y)) - Green(Pic2(x,y))) totalDiff+ Abs( Blue(Pic1(x,y)) - Blue(Pic2(x,y))) Next y Next x   MessageRequester("Result","Diff= "+StrD(100*totalDiff/(255*w*h*3),3)+" %")
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.
#Dart
Dart
/* * Function to test if a number is a perfect number * A number is a perfect number if it is equal to the sum of all its divisors * Input: Positive integer n * Output: true if n is a perfect number, false otherwise */ bool isPerfect(int n){ //Generate a list of integers in the range 1 to n-1 : [1, 2, ..., n-1] List<int> range = new List<int>.generate(n-1, (int i) => i+1);   //Create a list that filters the divisors of n from range List<int> divisors = new List.from(range.where((i) => n%i == 0));   //Sum the all the divisors int sumOfDivisors = 0; for (int i = 0; i < divisors.length; i++){ sumOfDivisors = sumOfDivisors + divisors[i]; }   // A number is a perfect number if it is equal to the sum of its divisors // We return the test if n is equal to sumOfDivisors return n == sumOfDivisors; }
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
#Crystal
Crystal
puts [1, 2, 3].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
#Perl
Perl
use List::Util qw(all);   sub perfect_shuffle { my $mid = @_ / 2; map { @_[$_, $_ + $mid] } 0..($mid - 1); }   for my $size (8, 24, 52, 100, 1020, 1024, 10000) {   my @shuffled = my @deck = 1 .. $size; my $n = 0; do { $n++; @shuffled = perfect_shuffle(@shuffled) } until all { $shuffled[$_] == $deck[$_] } 0..$#shuffled;   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
#Phix
Phix
with javascript_semantics function perfect_shuffle(sequence deck) integer l = length(deck), mp = l/2, k = 1 sequence res = repeat(0,l) for i=1 to mp do res[k] = deck[i] k += 1 res[k] = deck[i+mp] k += 1 end for return res end function constant testsizes = {8, 24, 52, 100, 1020, 1024, 10000} for i=1 to length(testsizes) do sequence deck = tagset(testsizes[i]) sequence work = perfect_shuffle(deck) integer count = 1 while work!=deck do work = perfect_shuffle(work) count += 1 end while printf(1,"%5d cards: %4d\n", {testsizes[i],count}) end for
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Vlang
Vlang
import math   // vlang doesn't have globals const ( p = [151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 ] )   fn main() { println(noise(3.14, 42, 7)) }   fn noise(x1 f64, y1 f64, z1 f64) f64 { bx := int(math.floor(x1)) & 255 by := int(math.floor(y1)) & 255 bz := int(math.floor(z1)) & 255 x := x1 - math.floor(x1) y := y1 - math.floor(y1) z := z1 - math.floor(z1) u := fade(x) v := fade(y) w := fade(z) ba := p[bx] + by baa := p[ba] + bz bab := p[ba+1] + bz bb := p[bx+1] + by bba := p[bb] + bz bbb := p[bb+1] + bz return lerp(w, lerp(v, lerp(u, grad(p[baa], x, y, z), grad(p[bba], x-1, y, z)), lerp(u, grad(p[bab], x, y-1, z), grad(p[bbb], x-1, y-1, z))), lerp(v, lerp(u, grad(p[baa+1], x, y, z-1), grad(p[bba+1], x-1, y, z-1)), lerp(u, grad(p[bab+1], x, y-1, z-1), grad(p[bbb+1], x-1, y-1, z-1)))) } fn fade(t f64) f64 { return t * t * t * (t*(t*6-15) + 10) } fn lerp(t f64, a f64, b f64) f64 { return a + t*(b-a) } fn grad(hash int, x f64, y f64, z f64) f64 { // Vlang doesn't have a ternary. Ternaries can be translated directly // with if statements, but chains of if statements are often better // expressed with match statements. match hash & 15 { 0 { return x + y } 1 { return y - x } 2 { return x - y } 3 { return -x - y } 4 { return x + z } 5 { return z - x } 6{ return x - z } 7{ return -x - z } 8 { return y + z } 9 { return z - y } 10 { return y - z } 12 { return x + y } 13 { return z - y } 14 { return y - x } else { // case 11, 16: return -y - z } } }
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
#M4
M4
define(`randSeed',141592653)dnl define(`setRand', `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')dnl define(`rand_t',`eval(randSeed^(randSeed>>13))')dnl define(`random', `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')dnl define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')dnl define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl define(`_arg1', `$1')dnl define(`_foreach', `ifelse(`$2', `()', `', `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')dnl define(`new',`define(`$1[size]',0)')dnl define(`append', `define(`$1[size]',incr(defn(`$1[size]')))`'define($1[defn($1[size])],$2)') define(`deck', `new($1)foreach(`x',(Ace,2,3,4,5,6,7,8,9,10,Jack,Queen,King), `foreach(`y',(Clubs,Diamonds,Hearts,Spades), `append(`$1',`x of y')')')')dnl define(`show', `for(`x',1,defn($1[size]),`defn($1[x])ifelse(x,defn($1[size]),`',`, ')')')dnl define(`swap',`define($1[$2],defn($1[$4]))define($1[$4],$3)')dnl define(`shuffle', `for(`x',1,defn($1[size]), `swap($1,x,defn($1[x]),eval(1+random%defn($1[size])))')')dnl define(`deal', `ifelse($#,0,``$0'', `ifelse(defn($1[size]),0, `NULL', defn($1[defn($1[size])])define($1[size],decr(defn($1[size]))))')')dnl dnl deck(`b') show(`b') shuffling shuffle(`b') show(`b') deal deal(`b') deal deal(`b') show(`b')
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
#Lua
Lua
a = {} n = 1000 len = math.modf( 10 * n / 3 )   for j = 1, len do a[j] = 2 end nines = 0 predigit = 0 for j = 1, n do q = 0 for i = len, 1, -1 do x = 10 * a[i] + q * i a[i] = math.fmod( x, 2 * i - 1 ) q = math.modf( x / ( 2 * i - 1 ) ) end a[1] = math.fmod( q, 10 ) q = math.modf( q / 10 ) if q == 9 then nines = nines + 1 else if q == 10 then io.write( predigit + 1 ) for k = 1, nines do io.write(0) end predigit = 0 nines = 0 else io.write( predigit ) predigit = q if nines ~= 0 then for k = 1, nines do io.write( 9 ) end nines = 0 end end end end print( predigit )
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
#Tcl
Tcl
package require TclOO   oo::class create Player { variable me constructor {name} { set me $name } method name {} { return $me }   method wantToRoll {safeScore roundScore} {} method stuck {score} {} method busted {score} {} method won {score} {}   method rolled {who what} { if {$who ne [self]} { #puts "[$who name] rolled a $what" } } method turnend {who score} { if {$who ne [self]} { puts "End of turn for [$who name] on $score" } } method winner {who score} { if {$who ne [self]} { puts "[$who name] is a winner, on $score" } } }   proc rollDie {} { expr {1+int(rand() * 6)} } proc rotateList {var} { upvar 1 $var l set l [list {*}[lrange $l 1 end] [lindex $l 0]] } proc broadcast {players message score} { set p0 [lindex $players 0] foreach p $players { $p $message $p0 $score } }   proc pig {args} { set players $args set scores [lrepeat [llength $args] 0] while 1 { set player [lindex $players 0] set safe [lindex $scores 0] set s 0 while 1 { if {$safe + $s >= 100} { incr safe $s $player won $safe broadcast $players winner $safe return $player } if {![$player wantToRoll $safe $s]} { lset scores 0 [incr safe $s] $player stuck $safe break } set roll [rollDie] broadcast $players rolled $roll if {$roll == 1} { $player busted $safe break } incr s $roll } broadcast $players turnend $safe rotateList players rotateList scores } }
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.
#Pascal
Pascal
program pernicious; {$IFDEF FPC} {$OPTIMIZATION ON,Regvar,ASMCSE,CSE,PEEPHOLE}// 3x speed up {$ENDIF} uses sysutils;//only used for time   type tbArr = array[0..64] of byte; { PrimeTil64 : array[0..64] of byte = (0,0,2,3,0,5,0, 7,0,0,0,11,0,13,0,0,0,17,0,19,0,0,0,23,0,0,0,0,0,29,0, 31,0,0,0,0,0,37,0,0,0,41,0,43,0,0,0,47,0, 0,0,0,0,53,0,0,0,0,0,59,0, 61,0,0,0); } const PrimeTil64 : tbArr = (0,0,1,1,0,1,0, 1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0, 1,0,0,0,0,0, 1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0, 1,0,0,0);   function n_beyond_k(n,k: NativeInt):Uint64; var i : NativeInt; Begin result := 1; IF 2*k>= n then k := n-k; For i := 1 to k do Begin result := result *n DIV i; dec(n); end; end;   function popcnt32(n:Uint32):NativeUint; //https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation const K1 = $0101010101010101; K33 = $3333333333333333; K55 = $5555555555555555; KF1 = $0F0F0F0F0F0F0F0F; begin n := n- (n shr 1) AND NativeUint(K55); n := (n AND NativeUint(K33))+ ((n shr 2) AND NativeUint(K33)); n := (n + (n shr 4)) AND NativeUint(KF1); n := (n*NativeUint(K1)) SHR 24; popcnt32 := n; end;   var bit1cnt, k : LongWord; PernCnt : Uint64; Begin writeln('the 25 first pernicious numbers'); k:=1; PernCnt:=0; repeat IF PrimeTil64[popCnt32(k)] <> 0 then Begin inc(PernCnt); write(k,' ');end; inc(k); until PernCnt >= 25; writeln;   writeln('pernicious numbers in [888888877..888888888]'); For k := 888888877 to 888888888 do IF PrimeTil64[popCnt32(k)] <> 0 then write(k,' '); writeln(#13#10);   k := 8; repeat PernCnt := 0; For bit1cnt := 0 to k do Begin //i == number of Bits set,n_beyond_k(k,i) == number of arrangements IF PrimeTil64[bit1cnt] <> 0 then inc(PernCnt,n_beyond_k(k,bit1cnt)); end; writeln(PernCnt,' pernicious numbers in [0..2^',k,'-1]'); inc(k,k); until k>64; end.
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Python
Python
>>> import random >>> random.choice(['foo', 'bar', 'baz']) 'baz'
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Quackery
Quackery
[ dup size random peek ] is pick ( [ --> x )   randomise ' [ 20 33 -15 7 0 ] pick echo cr ' pick pick echo
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
#Scala
Scala
object PhraseReversals extends App { val phrase = scala.io.StdIn.readLine println(phrase.reverse) println(phrase.split(' ').map(_.reverse).mkString(" ")) println(phrase.split(' ').reverse.mkString(" ")) }
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
#Quackery
Quackery
  [ stack ] is deranges.num ( --> [ )   forward is (deranges) [ over size deranges.num share = iff [ over temp take swap nested join temp put ] else [ dup size times [ 2dup i^ pluck dip [ over size ] tuck != iff [ rot swap nested join swap (deranges) ] else [ drop 2drop ] ] ] 2drop ] resolves (deranges) ( [ [ --> )   [ dup deranges.num put [] swap times [ i^ join ] [] temp put [] swap (deranges) temp take deranges.num release ] is derangements ( n --> [ )   [ dup 0 = iff [ drop 1 ] done 1 0 rot 1 - times [ swap over + i^ 1+ * ] nip ] is sub! ( n --> n )   4 derangements witheach [ echo cr ] cr 10 times [ i^ echo sp i^ derangements size echo sp i^ sub! echo cr ] cr 20 sub! echo
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%
#Python
Python
from PIL import Image   i1 = Image.open("image1.jpg") i2 = Image.open("image2.jpg") assert i1.mode == i2.mode, "Different kinds of images." assert i1.size == i2.size, "Different sizes."   pairs = zip(i1.getdata(), i2.getdata()) if len(i1.getbands()) == 1: # for gray-scale jpegs dif = sum(abs(p1-p2) for p1,p2 in pairs) else: dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))   ncomponents = i1.size[0] * i1.size[1] * 3 print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
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.
#Delphi
Delphi
func isPerfect(num) { var sum = 0 for i in 1..<num { if !i { break } if num % i == 0 { sum += i } } return sum == num }   let max = 33550337 print("Perfect numbers from 0 to \(max):")   for x in 0..max { if isPerfect(x) { print("\(x) is 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
#Curry
Curry
  insert :: a -> [a] -> [a] insert x xs = x : xs insert x (y:ys) = y : insert x ys   permutation :: [a] -> [a] permutation [] = [] permutation (x:xs) = insert x $ permutation xs  
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
#Picat
Picat
go => member(N,[8,24,52,100,1020,1024,10_000]), println(n=N), InOut = out, % in/out shuffling println(inOut=InOut), Print = cond(N < 100, true,false), if Print then println(1..N), end, Count = show_all_shuffles(N,InOut,Print), println(count=Count), nl, fail, nl.   % % Show all the shuffles % show_all_shuffles(N,InOut) = show_all_shuffles(N,InOut,false). show_all_shuffles(N,InOut,Print) = Count => Order = 1..N, Perfect1 = perfect_shuffle(1..N,InOut), Perfect = copy_term(Perfect1), if Print == true then println(Perfect) end, Count = 1, while (Perfect != Order) Perfect := [Perfect1[Perfect[I]] : I in 1..N], if Print == true then println(Perfect) end, Count := Count + 1 end.   % % Perfect shuffle a list % % InOut = in|out % in: first card in Top half is the first card in the new deck % out: first card in Bottom half is the first card in the new deck % perfect_shuffle(List,InOut) = Perfect => [Top,Bottom] = split_deck(List,InOut), if InOut = out then Perfect = zip2(Top,Bottom) else Perfect = zip2(Bottom,Top) end.   % % split the deck in two "halves" % % For odd out shuffles, we have to adjust the % range of the top and bottom. % split_deck(L,InOut) = [Top,Bottom] => N = L.len, if InOut = out, N mod 2 = 1 then Top = 1..(N div 2)+1, Bottom = (N div 2)+2..N else Top = 1..(N div 2), Bottom = (N div 2)+1..N end.   % % If L1 and L2 has uneven lengths, we add the odd element last % in the resulting list. % zip2(L1,L2) = R => L1Len = L1.len, L2Len = L2.len, R1 = [], foreach(I in 1..min(L1Len,L2Len)) R1 := R1 ++ [L1[I],L2[I]] end, if L1Len < L2Len then R1 := R1 ++ [L2[L2Len]] elseif L1Len > L2Len then R1 := R1 ++ [L1[L1Len]] end, R = R1.
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
#PicoLisp
PicoLisp
(de perfectShuffle (Lst) (mapcan '((B A) (list A B)) (cdr (nth Lst (/ (length Lst) 2))) Lst ) )   (for N (8 24 52 100 1020 1024 10000) (let (Lst (range 1 N) L Lst Cnt 1) (until (= Lst (setq L (perfectShuffle L))) (inc 'Cnt) ) (tab (5 6) N Cnt) ) )
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#Wren
Wren
var permutation = [ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 ]   var p = (0...512).map { |i| (i < 256) ? permutation[i] : permutation[i-256] }.toList   var fade = Fn.new { |t| t * t * t * (t * (t * 6 - 15) + 10) }   var lerp = Fn.new { |t, a, b| a + t * (b - a) }   var grad = Fn.new { |hash, x, y, z| // Convert low 4 bits of hash code into 12 gradient directions var h = hash & 15 var u = (h < 8) ? x : y var v = (h < 4) ? y : (h == 12 || h == 14) ? x : z return (((h & 1) == 0) ? u : -u) + (((h & 2) == 0) ? v : -v) }   var noise = Fn.new { |x, y, z| // Find unit cube that contains point var xi = x.floor & 255 var yi = y.floor & 255 var zi = z.floor & 255   // Find relative x, y, z of point in cube var xx = x.fraction var yy = y.fraction var zz = z.fraction   // Compute fade curves for each of xx, yy, zz var u = fade.call(xx) var v = fade.call(yy) var w = fade.call(zz)   // Hash co-ordinates of the 8 cube corners // and add blended results from 8 corners of cube var a = p[xi] + yi var aa = p[a] + zi var ab = p[a + 1] + zi var b = p[xi + 1] + yi var ba = p[b] + zi var bb = p[b + 1] + zi   return lerp.call(w, lerp.call(v, lerp.call(u, grad.call(p[aa], xx, yy, zz), grad.call(p[ba], xx - 1, yy, zz)), lerp.call(u, grad.call(p[ab], xx, yy - 1, zz), grad.call(p[bb], xx - 1, yy - 1, zz))), lerp.call(v, lerp.call(u, grad.call(p[aa + 1], xx, yy, zz - 1), grad.call(p[ba + 1], xx - 1, yy, zz - 1)), lerp.call(u, grad.call(p[ab + 1], xx, yy - 1, zz - 1), grad.call(p[bb + 1], xx - 1, yy - 1, zz - 1))) ) }   System.print(noise.call(3.14, 42, 7))
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MakeDeck[] := Tuples[{{"Ace ", 2, 3 , 4 , 5, 6 , 7 , 8 , 9 , 10, "Jack" , "Queen", "King"}, {♦ , ♣, ♥ , ♠}}] DeckShuffle[deck_] := RandomSample[deck, Length@deck] DealFromDeck[] := (Print@First@deck; deck = deck[[2 ;; All]];)
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
#M2000_Interpreter
M2000 Interpreter
  Module Checkpi { Module FindPi(Digits){ Digits++ n=Int(3.32*Digits) PlusOne=Lambda N=0% -> { =N N++ } PlusTwo=Lambda N=1% -> { =N N+=2 } Dim A(n)<<PlusOne(), B(n)<<PlusTwo() Dim Ten(n), CarrierOver(n), Sum(n),Remainder(n)=2 OutPutDigits=Digits Predigits=Stack CallBack=lambda fl=true, Chars=0 (x)->{ Print x; Chars++ If fl then Print "." : Print " "; : fl=false : Chars=0 : exit If Chars=50 then { Print Print " "; Chars=0 Refresh } else.if (Chars mod 5)=0 then { Print " "; Refresh } \\ explicitly refresh output layer, using Fast ! mode of speed } Print "Pi="; While Digits { NextDigit(&CallBack, &Digits) } print Refresh Sub NextDigit(&f, &D) CarrierOver=0 For k=n-1 to 1 { Ten(k)=Remainder(k)*10% CarrierOver(k)=CarrierOver Sum(k)=Ten(k)+CarrierOver(k) q=Sum(k) div B(k) Remainder(k)=Sum(k)-B(k)*q CarrierOver=A(k)*q } Ten(0)=Remainder(0)*10% CarrierOver(0)=CarrierOver Sum(0)=Ten(0)+CarrierOver(0) q=Sum(0) div 10% Remainder(0)=Sum(0)-10%*q if q<>9 and q<>10 then { Stack Predigits { While not empty { Call f(Number) if D>0 then D-- If D=0 then flush ' empty stack } Push q } } else.if q=9 Then { Stack Predigits { Data q } } else { Stack Predigits { While not empty { Call f((Number+1) mod 10) if D>0 then D-- If D=0 then flush ' empty stack } Push 0 } } End Sub } \\ reduce time to share with OS \\ Need explicitly use of refresh output layer (M2000 console) \\ Slow for a screen refresh per statement and give more time to OS Rem Set Slow \\ Fast is normal screen refresh, per Refresh time, and give standard time to OS Rem Set Fast \\ Fast ! use Refresh for screen refresh, and give less time o OS than standard \\ Esc key work when Refresh executed (and OS get little time) Set Fast ! FindPi 4 FindPi 28 Print Pi ' pi in M2000 is Decimal type with 29 digits (1 plus 28 after dot, is same as FindPi 28) Refresh FindPi 50 } Flush ' empty stack of values CheckPi List ' no variables exist Modules ? ' current module exist Stack ' Stack of values ' has to be empty, we didn't use current stack for values.  
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
#VBA
VBA
  Option Explicit   Sub Main_Pig() Dim Scs() As Byte, Ask As Integer, Np As Boolean, Go As Boolean Dim Cp As Byte, Rd As Byte, NbP As Byte, ScBT As Byte 'You can adapt these Const, but don't touch the "¤¤¤¤" Const INPTXT As String = "Enter number of players : " Const INPTITL As String = "Numeric only" Const ROL As String = "Player ¤¤¤¤ rolls the die." Const MSG As String = "Do you want to ""hold"" : " Const TITL As String = "Total if you keep : " Const RES As String = "The die give you : ¤¤¤¤ points." Const ONE As String = "The die give you : 1 point. Sorry!" & vbCrLf & "Next player." Const WIN As String = "Player ¤¤¤¤ win the Pig Dice Game!" Const STW As Byte = 100   Randomize Timer NbP = Application.InputBox(INPTXT, INPTITL, 2, Type:=1) ReDim Scs(1 To NbP) Cp = 1 Do ScBT = 0 Do MsgBox Replace(ROL, "¤¤¤¤", Cp) Rd = Int((Rnd * 6) + 1) If Rd > 1 Then MsgBox Replace(RES, "¤¤¤¤", Rd) ScBT = ScBT + Rd If Scs(Cp) + ScBT >= STW Then Go = True Exit Do End If Ask = MsgBox(MSG & ScBT, vbYesNo, TITL & Scs(Cp) + ScBT) If Ask = vbYes Then Scs(Cp) = Scs(Cp) + ScBT Np = True End If Else MsgBox ONE Np = True End If Loop Until Np If Not Go Then Np = False Cp = Cp + 1 If Cp > NbP Then Cp = 1 End If Loop Until Go MsgBox Replace(WIN, "¤¤¤¤", Cp) End Sub  
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.
#Perl
Perl
sub is_pernicious { my $n = shift; my $c = 2693408940; # primes < 32 as set bits while ($n) { $c >>= 1; $n &= ($n - 1); } $c & 1; }   my ($i, @p) = 0; while (@p < 25) { push @p, $i if is_pernicious($i); $i++; }   print join ' ', @p; print "\n"; ($i, @p) = (888888877,); while ($i < 888888888) { push @p, $i if is_pernicious($i); $i++; }   print join ' ', @p;
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#R
R
# a vector (letters are builtin) letters # [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" # [20] "t" "u" "v" "w" "x" "y" "z"   # picking one element sample(letters, 1) # [1] "n"   # picking some elements with repetition, and concatenating to get a word paste(sample(letters, 10, rep=T), collapse="") # [1] "episxgcgmt"
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Racket
Racket
  #lang racket (define (pick-item l) (list-ref l (random (length l))))  
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var string: phrase is "rosetta code phrase reversal"; var string: word is ""; var array string: wordList is 0 times ""; begin writeln("The original phrase:" rpad 27 <& phrase); writeln("Reverse the entire phrase:" rpad 27 <& reverse(phrase)); for word range split(phrase, ' ') do wordList &:= reverse(word); end for; writeln("Reverse words, same order:" rpad 27 <& join(wordList, ' ')); wordList := 0 times ""; for word range split(phrase, ' ') do wordList := [] (word) & wordList; end for; writeln("Reverse order, same words:" rpad 27 <& join(wordList, ' ')); end func;
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
#SenseTalk
SenseTalk
set phrase to "rosetta code phrase reversal" put phrase reversed put (the reverse of each word of phrase) joined by space put (each word of phrase) reversed joined by space  
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
#Sidef
Sidef
var str = "rosetta code phrase reversal";   say str.reverse; # reversed string say str.words.map{.reverse}.join(' '); # words reversed say str.words.reverse.join(' '); # word order reversed
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
#Racket
Racket
  #lang racket   (define (all-misplaced? l) (for/and ([x (in-list l)] [n (in-naturals 1)]) (not (= x n))))   ;; 1. Create a named function to generate derangements of the integers 0..n-1. (define (derangements n) (define (all-misplaced? l1 l2) (or (null? l1) (and (not (eq? (car l1) (car l2))) (all-misplaced? (cdr l1) (cdr l2))))) (define l (range n)) (for/list ([p (permutations l)] #:when (all-misplaced? p l)) p))   ;; 2. Generate and show all the derangements of 4 integers using the above ;; routine. (derangements 4) ;; -> '((1 0 3 2) (3 0 1 2) (1 3 0 2) (2 0 3 1) (2 3 0 1) ;; (3 2 0 1) (1 2 3 0) (2 3 1 0) (3 2 1 0))   ;; 3. Create a function that calculates the subfactorial of n, !n. (define (sub-fact n) (if (< n 2) (- 1 n) (* (+ (sub-fact (- n 1)) (sub-fact (- n 2))) (sub1 n))))   ;; 4. Print and show a table of the counted number of derangements of n vs. the ;; calculated !n for n from 0..9 inclusive. (for ([i 10]) (printf "~a ~a ~a\n" i (~a #:width 7 #:align 'right (length (derangements i))) (sub-fact i))) ;; Output: ;; 0 1 1 ;; 1 0 0 ;; 2 1 1 ;; 3 2 2 ;; 4 9 9 ;; 5 44 44 ;; 6 265 265 ;; 7 1854 1854 ;; 8 14833 14833 ;; 9 133496 133496   ;; Extra: !20 (sub-fact 20) ;; -> 895014631192902121  
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
#Raku
Raku
sub derangements(@l) { @l.permutations.grep(-> @p { none(@p Zeqv @l) }) }   sub prefix:<!>(Int $n) { (1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n] }   say 'derangements([1, 2, 3, 4])'; say derangements([1, 2, 3, 4]), "\n";   say 'n == !n == derangements(^n).elems'; for 0 .. 9 -> $n { say "!$n == { !$n } == { derangements(^$n).elems }" }
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%
#Racket
Racket
#lang racket (require racket/draw)   (define (percentage-difference bitmap1 bitmap2) (define width (send bitmap1 get-width)) (define height (send bitmap1 get-height)) (define buffer1 (make-bytes (* width height 4))) (define buffer2 (make-bytes (* width height 4))) (send (send bitmap1 make-dc) get-argb-pixels 0 0 width height buffer1) (send (send bitmap2 make-dc) get-argb-pixels 0 0 width height buffer2) (/ (* 100.0 (for/fold ((difference 0)) ((i (in-naturals)) (x1 (in-bytes buffer1)) (x2 (in-bytes buffer2))) (if (zero? (remainder i 4)) difference (+ difference (abs (- x1 x2)))))) width height 3 256))   (define lenna50 (read-bitmap "lenna50.jpg")) (define lenna100 (read-bitmap "lenna100.jpg"))   (percentage-difference lenna50 lenna100) ;-> 1.7749329408009846
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%
#Raku
Raku
use GD::Raw;   my $fh1 = fopen('./Lenna50.jpg', "rb") or die; my $img1 = gdImageCreateFromJpeg($fh1); my $fh2 = fopen('./Lenna100.jpg', "rb") or die; my $img2 = gdImageCreateFromJpeg($fh2);   my $img1X = gdImageSX($img1); my $img1Y = gdImageSY($img1); my $img2X = gdImageSX($img2); my $img2Y = gdImageSY($img2);   ($img1X == $img2X and $img1Y == $img2Y) or die "Image dimensions must match.";   my $diff = 0; my ($px1, $px2); loop (my $i = 0; $i < $img1X; $i++) { loop (my $j = 0; $j < $img1Y; $j++) {   $px1 = gdImageGetPixel($img1, $i, $j); $px2 = gdImageGetPixel($img2, $i, $j);   $diff += abs(gdImageRed($img1, $px1) - gdImageRed($img2, $px2)); $diff += abs(gdImageGreen($img1, $px1) - gdImageGreen($img2, $px2)); $diff += abs(gdImageBlue($img1, $px1) - gdImageBlue($img2, $px2)); } }   say "%difference = ", $diff/($img1X*$img1Y*3*255)*100;   gdImageDestroy($img1); gdImageDestroy($img2);  
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.
#Dyalect
Dyalect
func isPerfect(num) { var sum = 0 for i in 1..<num { if !i { break } if num % i == 0 { sum += i } } return sum == num }   let max = 33550337 print("Perfect numbers from 0 to \(max):")   for x in 0..max { if isPerfect(x) { print("\(x) is perfect") } }
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.
#E
E
pragma.enable("accumulator") def isPerfectNumber(x :int) { var sum := 0 for d ? (x % d <=> 0) in 1..!x { sum += d if (sum > x) { return false } } return sum <=> x }
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
#D
D
T[][] permutations(T)(T[] items) pure nothrow { T[][] result;   void perms(T[] s, T[] prefix=[]) nothrow { if (s.length) foreach (immutable i, immutable c; s) perms(s[0 .. i] ~ s[i+1 .. $], prefix ~ c); else result ~= prefix; }   perms(items); return result; }   version (permutations1_main) { void main() { import std.stdio; writefln("%(%s\n%)", [1, 2, 3].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
#Python
Python
  import doctest import random     def flatten(lst): """ >>> flatten([[3,2],[1,2]]) [3, 2, 1, 2] """ return [i for sublst in lst for i in sublst]   def magic_shuffle(deck): """ >>> magic_shuffle([1,2,3,4]) [1, 3, 2, 4] """ half = len(deck) // 2 return flatten(zip(deck[:half], deck[half:]))   def after_how_many_is_equal(shuffle_type,start,end): """ >>> after_how_many_is_equal(magic_shuffle,[1,2,3,4],[1,2,3,4]) 2 """   start = shuffle_type(start) counter = 1 while start != end: start = shuffle_type(start) counter += 1 return counter   def main(): doctest.testmod()   print("Length of the deck of cards | Perfect shuffles needed to obtain the same deck back") for length in (8, 24, 52, 100, 1020, 1024, 10000): deck = list(range(length)) shuffles_needed = after_how_many_is_equal(magic_shuffle,deck,deck) print("{} | {}".format(length,shuffles_needed))     if __name__ == "__main__": main()    
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
#Quackery
Quackery
[ [] swap times [ i^ join ] ] is deck ( n --> [ )   [ dup size 2 / split swap witheach [ swap i^ 2 * stuff ] ] is weave ( [ --> [ )   [ 0 swap deck dup [ rot 1+ unrot weave 2dup = until ] 2drop ] is shuffles ( n --> n )   ' [ 8 24 52 100 1020 1024 10000 ]   witheach [ say "A deck of " dup echo say " cards needs " shuffles echo say " shuffles." cr ]
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#XPL0
XPL0
func real Noise; real X, Y, Z; real U, V, W; int IX, IY, IZ, P(512), A, AA, AB, B, BA, BB;   func real Fade; real T; return T*T*T * (T*(T*6.-15.) + 10.);   func real Lerp; real T, A, B; return A + T*(B-A);   func real Grad; int Hash; real X, Y, Z; int H; real U, V; [H:= Hash & $0F; \convert low 4 bits of hash code U:= if H<8 then X else Y; \ into 12 gradient directions V:= if H<4 then Y else if H=12 or H=14 then X else Z; return (if (H&1) = 0 then U else -U) + (if (H&2) = 0 then V else -V); ];   proc Final; int Permutation, I; [Permutation:= [ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180]; for I:= 0 to 255 do [P(I):= Permutation(I); P(256+I):= P(I); ]; ];   [Final; IX:= fix(Floor(X)) & $FF; \find unit cube that IY:= fix(Floor(Y)) & $FF; \ contains point IZ:= fix(Floor(Z)) & $FF; X:= X - Floor(X); \find relative X,Y,Z Y:= Y - Floor(Y); \ of point in cube Z:= Z - Floor(Z); U:= Fade(X); \compute fade curves V:= Fade(Y); \ for each of X,Y,Z W:= Fade(Z); A:= P(IX )+IY; AA:= P(A)+IZ; AB:= P(A+1)+IZ; \hash coordinates of B:= P(IX+1)+IY; BA:= P(B)+IZ; BB:= P(B+1)+IZ; \ the 8 cube corners,   return Lerp(W, Lerp(V, Lerp(U, Grad(P(AA ), X , Y , Z ), \and add Grad(P(BA ), X-1., Y , Z )), \blended Lerp(U, Grad(P(AB ), X , Y-1., Z ), \results Grad(P(BB ), X-1., Y-1., Z ))), \from 8 Lerp(V, Lerp(U, Grad(P(AA+1), X , Y , Z-1.), \corners Grad(P(BA+1), X-1., Y , Z-1.)), \of cube Lerp(U, Grad(P(AB+1), X , Y-1., Z-1.), Grad(P(BB+1), X-1., Y-1., Z-1.)))); ];   [Format(1, 17); RlOut(0, Noise(3.14, 42., 7.)); ]
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
#MiniScript
MiniScript
suits = ["Spades", "Clubs", "Hearts", "Diamonds"] pips = ["Ace","Two","Three","Four","Five","Six","Seven", "Eight","Nine","Ten","Jack","Queen","King"]   Card = {} Card.str = function() return self.pip + " of " + self.suit + " (value: " + self.value + ")" end function   //Build Deck deck = [] for s in suits.indexes for p in pips.indexes card = new Card card.suit = suits[s] card.pip = pips[p] card.value = s * 100 + p deck.push card end for end for   draw = function(count=7) hand = [] for i in range(1, count) hand.push deck.pop end for return hand end function   display = function(stack) for card in stack print card.str end for end function   print "Deck created. Cards in Deck: " + deck.len   deck.shuffle print "Deck Shuffled"   hand = draw print "First hand: " display hand   print print deck.len + " cards left in deck:" display 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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
WriteString[$Output, "3."]; For[i = -1, True, i--, WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]];
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
#Vlang
Vlang
import rand import rand.seed import os fn main() { rand.seed(seed.time_seed_array(2)) //Set seed to current time   mut player_scores := [0, 0] mut turn := 0 mut current_score := 0   for { player := turn % player_scores.len   answer := os.input("Player $player [${player_scores[player]}, $current_score], (H)old, (R)oll or (Q)uit: ").to_lower()   match answer { "h"{ //Hold player_scores[player] += current_score print(" Player $player now has a score of ${player_scores[player]}.\n")   if player_scores[player] >= 100 { println(" Player $player wins!!!") return }   current_score = 0 turn += 1 } "r"{ //Roll roll := rand.int_in_range(1, 7) or {1}   if roll == 1 { println(" Rolled a 1. Bust!\n") current_score = 0 turn += 1 } else { println(" Rolled a ${roll}.") current_score += roll } } "q"{ //Quit return } else{ //Incorrent input println(" Please enter one of the given inputs.") } } } println("Player ${(turn-1)%player_scores.len} 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.
#Phix
Phix
with javascript_semantics function pernicious(integer n) return is_prime(sum(int_to_bits(n,32))) end function sequence s = {} integer n = 1 while length(s)<25 do if pernicious(n) then s &= n end if n += 1 end while pp(s) s = {} for i=888_888_877 to 888_888_888 do if pernicious(i) then s &= i end if end for pp(s)
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Raku
Raku
say (1, 2, 3).pick;
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Red
Red
>> random/only collect [repeat i 10 [keep i]]
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
#Smalltalk
Smalltalk
|str| str := 'rosetta code phrase reversal'.   Transcript showCR:(str reversed). Transcript showCR:(((str splitBy:$ ) collect:#reversed) join:$ ). Transcript showCR:(((str splitBy:$ ) reversed) 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
#Swift
Swift
  func reverseString(s:String)->String{ var temp = [Character]() for i in s.characters{ temp.append(i) } var j=s.characters.count-1 for i in s.characters{ temp[j]=i j-=1 } return String(temp) }   func reverseWord(s:String)->String{ var temp = [Character]() var result:String="" for i in s.characters{ if i==" "{ result += "\(reverseString(s:String(temp))) " temp=[Character]() } else { temp.append(i) } if i==s[s.index(before: s.endIndex)]{ result += (reverseString(s:String(temp))) } } return result }   func flipString(s:String)->String{ return reverseWord(s:reverseString(s:s)) } print(str) print(reverseString(s:str)) print(reverseWord(s:str)) print(flipString(s:str))  
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
#REXX
REXX
/*REXX program generates all permutations of N derangements and subfactorial # */ numeric digits 1000 /*be able to handle large subfactorials*/ parse arg N .; if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/ d= derangeSet(N) /*go and build the derangements set. */ say d 'derangements for' N "items are:" say do i=1 for d /*display the derangements for N items.*/ say right('derangement', 22) right(i, length(d) ) '───►' $.i end /*i*/ say /* [↓] count and calculate subfact !L.*/ do L=0 to 2; d= derangeSet(L) say L 'items: derangement count='right(d, 6)",  !"L'='right( !s(L), 6) end /*L*/ say say right('!20=' , 22)  !s( 20) say right('!200=', 22)  !s(200) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ !s: _=1; do j=1 for arg(1); if j//2 then _= j*_ - 1; else _=j*_ + 1 end /*j*/; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ derangeSet: procedure expose $.; parse arg x; $.=; #=0; p=x-1 if x==0 then return 1; if x==1 then return 0 @.1=2; @.2=1 /*populate 1st derangement.*/ do i=3 to x; @.i=i; end /*i*/ /* " the rest of 'em.*/ parse value @.p @.x with @.x @.p; call .buildD x /*swap & build.*/ /*build others.*/ do while .nextD(x, 0); call .buildD x; end; return # /*──────────────────────────────────────────────────────────────────────────────────────*/ .buildD: do j=1 for arg(1); if @.j==j then return; end #=#+1; do j=1 for arg(1); $.#= $.# @.j; end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ .nextD: procedure expose @.; parse arg n,i   do k=n-1 by -1 for n-1; kp=k+1; if @.k<@.kp then do; i=k; leave; end end /*k*/   do j=i+1 while j<n; parse value @.j @.n with @.n @.j; n=n-1 end /*j*/ if i==0 then return 0 do m=i+1 while @.m<@.i; end /*m*/ /* [↓] swap two values. */ parse value @.m @.i with @.i @.m; return 1
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%
#REBOL
REBOL
rebol [ Title: "Percent Image Difference" URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images ]   ; Load from local storage. Un/comment as preferred. ; a: load-image %lenna50.jpg ; b: load-image %lenna100.jpg   ; Download from rosettacode.org. a: load-image http://rosettacode.org/mw/images/3/3c/Lenna50.jpg b: load-image http://rosettacode.org/mw/images/b/b6/Lenna100.jpg   if a/size <> b/size [print "Image dimensions must match." halt]   ; Compute difference. REBOL has built-in image processing as part of ; its GUI package that I can take advantage of here:   diff: to-image layout/tight [image a effect [difference b]]   ; Calculate deviation. I use 'repeat' to rip through the image pixels ; (it knows how to deal with images) and sum, then average. Note that ; I can treat the image like an array to get number of pixels.   t: 0 repeat p diff [t: t + p/1 + p/2 + p/3] print rejoin ["Difference: " 100 * t / (255 * 3 * length? diff) "%"]   ; Optional: Since I now have a difference image, I may as well show ; it. Use the buttons or keys 'a', 'b' and 'd' to switch between the ; various images.   flip: func [ "Change to new image and label." name [word!] "Image to switch to." ][x/text: rejoin ["Image " name] x/image: get name show x]   ; Because the differences between the images are very small, I enhance ; the diff with a high contrast to make the result easier to ; see. Comment this out for the "pure" image.   diff: to-image layout/tight [image diff effect [contrast 100]]   view l: layout [ x: image diff across button "a" #"a" [flip 'a] button "b" #"b" [flip 'b] button "difference" #"d" [flip 'diff] ]
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.
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make do io.put_string (" 6 is perfect...%T") io.put_boolean (is_perfect_number (6)) io.new_line io.put_string (" 77 is perfect...%T") io.put_boolean (is_perfect_number (77)) io.new_line io.put_string ("128 is perfect...%T") io.put_boolean (is_perfect_number (128)) io.new_line io.put_string ("496 is perfect...%T") io.put_boolean (is_perfect_number (496)) end   is_perfect_number (n: INTEGER): BOOLEAN -- Is 'n' a perfect number? require n_positive: n > 0 local sum: INTEGER do across 1 |..| (n - 1) as c loop if n \\ c.item = 0 then sum := sum + c.item end end Result := sum = n end   end  
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Delphi
Delphi
program TestPermutations;   {$APPTYPE CONSOLE}   type TItem = Integer; // declare ordinal type for array item TArray = array[0..3] of TItem;   const Source: TArray = (1, 2, 3, 4);   procedure Permutation(K: Integer; var A: TArray); var I, J: Integer; Tmp: TItem;   begin for I:= Low(A) + 1 to High(A) + 1 do begin J:= K mod I; Tmp:= A[J]; A[J]:= A[I - 1]; A[I - 1]:= Tmp; K:= K div I; end; end;   var A: TArray; I, K, Count: Integer; S, S1, S2: ShortString;   begin Count:= 1; I:= Length(A); while I > 1 do begin Count:= Count * I; Dec(I); end;   S:= ''; for K:= 0 to Count - 1 do begin A:= Source; Permutation(K, A); S1:= ''; for I:= Low(A) to High(A) do begin Str(A[I]:1, S2); S1:= S1 + S2; end; S:= S + ' ' + S1; if Length(S) > 40 then begin Writeln(S); S:= ''; end; end;   if Length(S) > 0 then Writeln(S); Readln; 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
#R
R
wave.shuffle <- function(n) { deck <- 1:n ## create the original deck new.deck <- c(matrix(data = deck, ncol = 2, byrow = TRUE)) ## shuffle the deck once counter <- 1 ## track the number of loops ## defining a loop that shuffles the new deck until identical with the original one ## and in the same time increses the counter with 1 per loop while (!identical(deck, new.deck)) { ## logical condition new.deck <- c(matrix(data = new.deck, ncol = 2, byrow = TRUE)) ## shuffle counter <- counter + 1 ## add 1 to the number of loops } return(counter) ## final result - total number of loops until the condition is met } test.values <- c(8, 24, 52, 100, 1020, 1024, 10000) ## the set of the test values test <- sapply(test.values, wave.shuffle) ## apply the wave.shuffle function on each element names(test) <- test.values ## name the result test ## print the result out
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d {\displaystyle \mathbb {R} ^{d}}   into   R {\displaystyle \mathbb {R} }   with an integer   d {\displaystyle d}   which can be arbitrarily large but which is usually   2,   3,   or   4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012. Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
#zkl
zkl
class [static] ImprovedNoise{ // a container, not an object fcn noise(xyz){ xyz=vm.arglist.apply("toFloat"); X,Y,Z:= // FIND UNIT CUBE THAT CONTAINS POINT. xyz.apply(fcn(x){ x.floor().toInt().bitAnd(255) }); xyz= // FIND RELATIVE X,Y,Z OF POINT IN CUBE. xyz.apply(fcn(x){ x - x.floor() }); u,v,w:= xyz.apply(fade); // COMPUTE FADE CURVES FOR EACH OF X,Y,Z. A,AA,AB:= p[X ]+Y, p[A]+Z, p[A+1]+Z; // HASH COORDINATES OF B,BA,BB:= p[X+1]+Y, p[B]+Z, p[B+1]+Z; // THE 8 CUBE CORNERS, x,y,z:=xyz; lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD grad(p[BA ], x-1, y , z )), // BLENDED lerp(u, grad(p[AB ], x , y-1, z ), // RESULTS grad(p[BB ], x-1, y-1, z ))),// FROM 8 lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), // CORNERS grad(p[BA+1], x-1, y , z-1 )), // OF CUBE lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } fcn [private] fade(t){ t*t*t*(t*(t*6 - 15) + 10) } fcn [private] lerp(t,a,b){ a + t*(b - a) } fcn [private] grad(hash,x,y,z){ h:=hash.bitAnd(15); // CONVERT LO 4 BITS OF HASH CODE u:=(if(h<8) x else y); // INTO 12 GRADIENT DIRECTIONS. v:=(if(h<4) y else ((h==12 or h==14) and x or z)); (if(h.isEven) u else -u) + (if(h.bitAnd(2)==0) v else -v) } var [const,private] permutation=Data(Void, 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180), p=Data(Void,permutation,permutation); }
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
#MUMPS
MUMPS
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
#MATLAB_.2F_Octave
MATLAB / Octave
pi