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/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\disp...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new() var RAND_MAX = 32767   var list = [] var w = 0 var ww = 0   var ALPHA = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" var ALEN = ALPHA.count - 3   var makeList = Fn.new { |p| var thresh = (p * RAND_MAX).truncate ww = w * w ...
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   Luca...
#Axiom
Axiom
perfect?(n:Integer):Boolean == reduce(+,divisors n) = 2*n
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Swift
Swift
let randMax = 32767.0 let filled = 1 let rightWall = 2 let bottomWall = 4   final class Percolate { let height: Int let width: Int   private var grid: [Int] private var end: Int   init(height: Int, width: Int) { self.height = height self.width = width self.end = width self.grid = [Int](repeat...
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Tcl
Tcl
package require Tcl 8.6   # Structure the bond percolation system as a class oo::class create BondPercolation { variable hwall vwall cells M N constructor {width height probability} { set M $height set N $width for {set i 0} {$i <= $height} {incr i} { for {set j 0;set walls {}} {$j < $width} {incr j} { ...
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\disp...
#Perl
Perl
sub R { my ($n, $p) = @_; my $r = join '', map { rand() < $p ? 1 : 0 } 1 .. $n; 0+ $r =~ s/1+//g; }   use constant t => 100;   printf "t= %d\n", t; for my $p (qw(.1 .3 .5 .7 .9)) { printf "p= %f, K(p)= %f\n", $p, $p*(1-$p); for my $n (qw(10 100 1000)) { my $r; $r += R($n, $p) for 1 .. ...
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Tcl
Tcl
package require Tcl 8.6   oo::class create SitePercolation { variable cells w h constructor {width height probability} { set w $width set h $height for {set cells {}} {[llength $cells] < $h} {lappend cells $row} { for {set row {}} {[llength $row] < $w} {lappend row $cell} { set cell [expr {rand() < $p...
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 Uni...
#AutoHotkey
AutoHotkey
#NoEnv StringCaseSense On   o := str := "Hello"   Loop { str := perm_next(str) If !str { MsgBox % clipboard := o break } o.= "`n" . str }   perm_Next(str){ p := 0, sLen := StrLen(str) Loop % sLen { If A_Index=1 continue t := SubStr(str, sLen+1-A_Index, 1) 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 ...
#FreeBASIC
FreeBASIC
function is_in_order( d() as uinteger ) as boolean 'tests if a deck is in order for i as uinteger = lbound(d) to ubound(d)-1 if d(i) > d(i+1) then return false next i return true end function   sub init_deck( d() as uinteger ) for i as uinteger = 1 to ubound(d) d(i) = i next i ...
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 ...
#Pascal
Pascal
program perlinNoise; //Perlin Noise //http://rosettacode.org/mw/index.php?title=Perlin_noise#Go uses sysutils; type float64 = double; const p{ermutation} : array[0..255] of byte = ( 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...
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
#Nim
Nim
import strformat   func totient(n: int): int = var tot = n var nn = n var i = 2 while i * i <= nn: if nn mod i == 0: while nn mod i == 0: nn = nn div i dec tot, tot div i if i == 2: i = 1 inc i, 2 if nn > 1: dec tot, tot div nn tot   var n = 1 var num = 0 echo "The ...
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
#Pascal
Pascal
program Perftotient; {$IFdef FPC} {$MODE DELPHI} {$CodeAlign proc=32,loop=1} {$IFEND} uses sysutils; const cLimit = 57395631;//177147;//4190263;//57395631;//1162261467;// //global var TotientList : array of LongWord; Sieve : Array of byte; SolList : array of LongWord; T1,T0 : INt64;   procedure SieveInit(...
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 mu...
#Hy
Hy
(import [random [shuffle]]) (setv pips (.split "2 3 4 5 6 7 8 9 10 J Q K A")) (setv suits (.split "♥ ♦ ♣ ♠")) (setv cards_per_hand 5)   (defn make_deck [pips suits] (lfor x pips y suits (+ x y)))   (defn deal_hand [num_cards deck] (setv delt (cut deck None num_cards)) (setv new_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 ......
#Go
Go
package main   import ( "fmt" "math/big" )   type lft struct { q,r,s,t big.Int }   func (t *lft) extr(x *big.Int) *big.Rat { var n, d big.Int var r big.Rat return r.SetFrac( n.Add(n.Mul(&t.q, x), &t.r), d.Add(d.Mul(&t.s, x), &t.t)) }   var three = big.NewInt(3) var four = big.New...
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 th...
#Perl
Perl
#!perl use strict; use warnings; my @players = @ARGV; @players = qw(Joe Mike); my @scores = (0) x @players; while( 1 ) { PLAYER: for my $i ( 0 .. $#players ) { my $name = $players[$i]; my $score = $scores[$i]; my $roundscore = 1 + int rand 6; print "$name, your score so far is $score.\n"; print "You rolled a...
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 pe...
#Icon_and_Unicon
Icon and Unicon
link "factors"   procedure main(A) every writes((pernicious(seq())\25||" ") | "\n") every writes((pernicious(888888877 to 888888888)||" ") | "\n") end   procedure pernicious(n) return (isprime(c1bits(n)),n) end   procedure c1bits(n) c := 0 while n > 0 do c +:= 1(n%2, n/:=2) return c end
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RandomChoice[{a, b, c}]
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#MATLAB_.2F_Octave
MATLAB / Octave
list = {'a','b','c'}; list{ceil(rand(1)*length(list))}
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, maintaini...
#MATLAB_.2F_Octave
MATLAB / Octave
  function r=revstr(s,d) slist=strsplit(s,d); for k=1:length(slist) rlist{k}=slist{k}(end:-1:1); end; fprintf(1,'%s\n',s) fprintf(1,'%s %c',slist{end:-1:1},d) fprintf(1,'\n'); fprintf(1,'%s %c',rlist{:},d) fprintf(1,'\n'); fprintf(1,'%s\n',s(end:-1:1)) end   revstr('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, maintaini...
#MiniScript
MiniScript
phrase = "rosetta code phrase reversal"   // general sequence reversal function reverse = function(seq) out = [] for i in range(seq.len-1, 0) out.push seq[i] end for if seq isa string then return out.join("") return out end function   // 1. Reverse the characters of the string. print 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. The...
#Kotlin
Kotlin
// version 1.1.2   fun <T> permute(input: List<T>): List<List<T>> { if (input.size == 1) return listOf(input) val perms = mutableListOf<List<T>>() val toInsert = input[0] for (perm in permute(input.drop(1))) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() 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 ...
#Phix
Phix
function spermutations(integer p, integer i) -- -- generate the i'th permutation of [1..p]: -- first obtain the appropriate permutation of [1..p-1], -- then insert p/move it down k(=0..p-1) places from the end. -- sequence res integer k = mod(i-1,2*p) if k>=p then k=2*p-1-k end if if p>1 then ...
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Rust
Rust
  fn main() { let treatment = vec![85, 88, 75, 66, 25, 29, 83, 39, 97]; let control = vec![68, 41, 10, 49, 16, 65, 32, 92, 28, 98];   let mut data_set = control.clone(); data_set.extend_from_slice(&treatment);   let greater = combinations(treatment.iter().sum(), treatment.len() as i64, &data_set) as...
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Scala
Scala
object PermutationTest extends App { private val data = Array(85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98) private var (total, treat) = (1.0, 0)   private def pick(at: Int, remain: Int, accu: Int, treat: Int): Int = { if (remain == 0) return if (accu > treat) 1 else 0   ...
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#Icon_and_Unicon
Icon and Unicon
link printf # for main only   procedure main() # % difference between images fn1 := "Lenna100.jpg" fn2 := "Lenna50.jpg" printf("%%difference of files %i & %i = %r\n",fn1,fn2,ImageDiff(fn1,fn2)) end   procedure ImageDiff(fn1,fn2) #: return % difference of two images img1 := open(1,"g","canvas=hidden",...
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#Raku
Raku
# 20201028 Raku programming solution   my \F = [ <1 -1 1 0 1 1 2 1>, <0 1 1 -1 1 0 2 0>, <1 0 1 1 1 2 2 1>, <1 0 1 1 2 -1 2 0>, <1 -2 1 -1 1 0 2 -1>, <0 1 1 1 1 2 2 1>, <1 -1 1 0 1 1 2 -1>, <1 -1 1 0 2 0 2 1> ];   my \I = [ <0 1 0 2 0 3 0 4>, <1 0 2 0 3 0 4 0> ];   my \L = [ <1 0 1 1 1 2 1 3>, ...
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\disp...
#zkl
zkl
const X=-1; // the sentinal that marks an untouched cell var C,N,NN,P; fcn createC(n,p){ N,P=n,p; NN=N*N; C=NN.pump(List.createLong(NN),0); // vector of ints foreach n in (NN){ C[n]=X*(Float.random(1)<=P) } // X is the sentinal } fcn showCluster{ alpha:="-ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuv...
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   Luca...
#BASIC
BASIC
FUNCTION perf(n) sum = 0 FOR i = 1 TO n - 1 IF n MOD i = 0 THEN sum = sum + i END IF NEXT i IF sum = n THEN perf = 1 ELSE perf = 0 END IF END FUNCTION
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new() var RAND_MAX = 32767   // cell states var FILL = 1 var RWALL = 2 // right wall var BWALL = 4 // bottom wall   var x = 10 var y = 10 var grid = List.filled(x * (y + 2), 0) var cells = 0 var end = 0 var m = 0 var n = 0   var makeGrid = Fn.new {...
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\disp...
#Phix
Phix
with javascript_semantics function run_test(atom p, integer len, runs) integer count = 0 for r=1 to runs do bool v, pv = false for l=1 to len do v = rnd()<p count += pv<v pv = v end for end for return count/runs/len end function procedure mai...
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new() var RAND_MAX = 32767 var EMPTY = ""   var x = 15 var y = 15 var grid = List.filled((x + 1) * (y + 1) + 1, EMPTY) var cell = 0 var end = 0 var m = 0 var n = 0   var makeGrid = Fn.new { |p| var thresh = (p * RAND_MAX).truncate m = x n ...
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 Uni...
#AWK
AWK
  # syntax: GAWK -f PERMUTATIONS.AWK [-v sep=x] [word] # # examples: # REM all permutations on one line # GAWK -f PERMUTATIONS.AWK # # REM all permutations on a separate line # GAWK -f PERMUTATIONS.AWK -v sep="\n" # # REM use a different word # GAWK -f PERMUTATIONS.AWK Gwen # # REM command used for Rosett...
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 ...
#Go
Go
package main   import "fmt"   type Deck struct { Cards []int length int }   func NewDeck(deckSize int) (res *Deck){ if deckSize % 2 != 0{ panic("Deck size must be even") } res = new(Deck) res.Cards = make([]int, deckSize) res.length = deckSize for i,_ := range res.Cards{ res.Cards[i] = i } return } func ...
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 ...
#Perl
Perl
use strict; use warnings; use experimental 'signatures';   use constant permutation => qw{ 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 17...
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
#Perl
Perl
use ntheory qw(euler_phi);   sub phi_iter { my($p) = @_; euler_phi($p) + ($p == 2 ? 0 : phi_iter(euler_phi($p))); }   my @perfect; for (my $p = 2; @perfect < 20 ; ++$p) { push @perfect, $p if $p == phi_iter($p); }   printf "The first twenty perfect totient numbers:\n%s\n", join ' ', @perfect;
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Phix
Phix
with javascript_semantics function totient(integer n) integer tot = n, i = 2 while i*i<=n do if mod(n,i)=0 then while true do n /= i if mod(n,i)!=0 then exit end if end while tot -= tot/i end if i += iff(i=2?1:2) end...
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist)   cards := 2 # cards per hand players := 5 # players to deal to   write("New deck : ", showcards(D := newcarddeck())) # create and show a new deck write("Shuffled : ", showcards(D := shuffl...
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 ......
#Groovy
Groovy
BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3 String nn boolean first = true   while (true) { (nn, first, q, r, t, k, n, l) = (4*q + r - t < n*t) \ ? ["${n}${first?'.':''}", false, 10*q, 10*(r - n*t), t , k , 10*(3*q + r)/t - 10*n , l ] \  : ['' , first, q*k , (2*q +...
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 th...
#Phix
Phix
constant numPlayers = 2, maxScore = 100 sequence scores = repeat(0,numPlayers) printf(1,"\nPig The Dice Game\n\n") integer points = 0, -- points accumulated in current turn, 0=swap turn player = 1 -- start with first player while true do integer roll = rand(6) printf(1,"Player %d, your score i...
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 pe...
#J
J
ispernicious=: 1 p: +/"1@#:
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 pe...
#Java
Java
public class Pernicious{ //very simple isPrime since x will be <= Long.SIZE public static boolean isPrime(int x){ if(x < 2) return false; for(int i = 2; i < x; i++){ if(x % i == 0) return false; } return true; }   public static int popCount(long x){ re...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Maxima
Maxima
random_element(l):= part(l, 1+random(length(l))); /* (%i1) random_element(['a, 'b, 'c]); (%o1) c */
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#.D0.9C.D0.9A-61.2F52
МК-61/52
0 П0 1 П1 2 П2 3 П3 4 П4 5   ^ СЧ * [x] ПE КИПE С/П
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, maintaini...
#MUMPS
MUMPS
set string="Rosetta Code Phrase Reversal" set str="",len=$length(string," ") for i=1:1:len set $piece(str," ",i)=$piece(string," ",len-i+1) write string,! write $reverse(string),! write str,! write $reverse(str),!
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Nim
Nim
import algorithm, sequtils, strutils   const Phrase = "rosetta code phrase reversal"   echo "Phrase: ", Phrase echo "Reversed phrase: ", reversed(Phrase).join() echo "Reversed words: ", Phrase.split().mapIt(reversed(it).join()).join(" ") echo "Reversed word order: ", reversed(Phrase.split()).join(...
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Lua
Lua
-- Return an iterator to produce every permutation of list function permute (list) local function perm (list, n) if n == 0 then coroutine.yield(list) end for i = 1, n do list[i], list[n] = list[n], list[i] perm(list, n - 1) list[i], list[n] = list[n], list[i] ...
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 ...
#PicoLisp
PicoLisp
(let (N 4 L (mapcar '((I) (list I 0)) (range 1 N) ) ) (for I L (printsp (car I)) ) (prinl) (while # find the lagest mobile integer (setq X (maxi '((I) (car (get L (car I)))) (extract '((I J) ...
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 ...
#PowerShell
PowerShell
  function output([Object[]]$A, [Int]$k, [ref]$sign) { "Perm: [$([String]::Join(', ', $A))] Sign: $($sign.Value)" }   function permutation([Object[]]$array) { function generate([Object[]]$A, [Int]$k, [ref]$sign) { if($k -eq 1) { output $A $k $sign $sign.Value = -$s...
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const array integer: treatmentGroup is [] (85, 88, 75, 66, 25, 29, 83, 39, 97); const array integer: controlGroup is [] (68, 41, 10, 49, 16, 65, 32, 92, 28, 98); const array integer: both is treatmentGroup & controlGroup;   const func integer: pick (in integer: at, in...
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Sidef
Sidef
func statistic(ab, a) { var(sumab, suma) = (ab.sum, a.sum) suma/a.size - ((sumab-suma) / (ab.size-a.size)) }   func permutationTest(a, b) { var ab = (a + b) var tobs = statistic(ab, a) var under = (var count = 0) ab.combinations(a.len, {|*perm| statistic(ab, perm) <= tobs && (under += 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...
#J
J
require 'media/image3' 'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg' 1.62559
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...
#Java
Java
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO;   public enum ImgDiffPercent { ;   public static void main(String[] args) throws IOException { // https://rosettacode.org/mw/images/3/3c/Lenna50.jpg // https://rosettacode.org/mw/i...
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Dim symbols As Char() = "XYPFTVNLUZWI█".ToCharArray(), nRows As Integer = 8, nCols As Integer = 8, target As Integer = 12, blank As Integer = 12, grid As Integer()() = New Integer(nRows - 1)() {}, placed As Boolean() = New Boolean(target - 1) {}, pens As List...
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#BBC_BASIC
BBC BASIC
FOR n% = 2 TO 10000 STEP 2 IF FNperfect(n%) PRINT n% NEXT END   DEF FNperfect(N%) LOCAL I%, S% S% = 1 FOR I% = 2 TO SQR(N%)-1 IF N% MOD I% = 0 S% += I% + N% DIV I% NEXT IF I% = SQR(N%) S% += I% = (N% = S%)
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   Luca...
#Bracmat
Bracmat
( ( perf = sum i . 0:?sum & 0:?i & whl ' ( !i+1:<!arg:?i & ( mod$(!arg.!i):0&!sum+!i:?sum | ) ) & !sum:!arg ) & 0:?n & whl ' ( !n+1:~>10000:?n & (perf$!n&out$!n|) ) );
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#zkl
zkl
// cell states const FILLED=1; // and odd const RWALL =2; // right wall const BWALL =4; // bottom wall fcn P(p,wall){ (0.0).random(1)<p and wall or 0 }   fcn makeGrid(m,n,p){ // Allocate two addition rows to avoid checking bounds. // Bottom row is also required by drippage grid:=Data(m*(n+2)); do(m){ grid...
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\disp...
#Python
Python
from __future__ import division from random import random from math import fsum   n, p, t = 100, 0.5, 500   def newv(n, p): return [int(random() < p) for i in range(n)]   def runs(v): return sum((a & ~b) for a, b in zip(v, v[1:] + [0]))   def mean_run_density(n, p): return runs(newv(n, p)) / n   for p10 i...
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#zkl
zkl
fcn makeGrid(m,n,p){ grid:=Data((m+1)*(n+1)); // first row and right edges are buffers grid.write(" "*m); grid.write("\r"); do(n){ do(m){ grid.write(((0.0).random(1)<p) and "+" or "."); } // cell is porous or not grid.write("\n"); } grid } fcn ff(grid,x,m){ // walk across row looking for a ...
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 Uni...
#BASIC256
BASIC256
arraybase 1 n = 4 : cont = 0 dim a(n) dim c(n)   for j = 1 to n a[j] = j next j   do for i = 1 to n print a[i]; next print " ";   i = n cont += 1 if cont = 12 then print cont = 0 else print " "; end if   do i -= 1 until (i = 0) or (a[i]...
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Haskell
Haskell
shuffle :: [a] -> [a] shuffle lst = let (a,b) = splitAt (length lst `div` 2) lst in foldMap (\(x,y) -> [x,y]) $ zip a b   findCycle :: Eq a => (a -> a) -> a -> [a] findCycle f x = takeWhile (/= x) $ iterate f (f x)   main = mapM_ report [ 8, 24, 52, 100, 1020, 1024, 10000 ] where report n = putSt...
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 ...
#Phix
Phix
with javascript_semantics constant ph = x"97 A0 89 5B 5A 0F 83 0D C9 5F 60 35 C2 E9 07 E1"& x"8C 24 67 1E 45 8E 08 63 25 F0 15 0A 17 BE 06 94"& x"F7 78 EA 4B 00 1A C5 3E 5E FC DB CB 75 23 0B 20"& x"39 B1 21 58 ED 95 38 57 AE 14 7D 88 AB A8 44 AF"& x"4A A5 47 86 8B...
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
#PicoLisp
PicoLisp
(gc 16) (de gcd (A B) (until (=0 B) (let M (% A B) (setq A B B M) ) ) (abs A) ) (de totient (N) (let C 0 (for I N (and (=1 (gcd N I)) (inc 'C)) ) C ) ) (de totients (NIL) (let (C 0 N 1) (while (> 20 C) (let (Cur N S 0) (while (> Cur 1) ...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#PILOT
PILOT
C :z=0  :n=3 *num C :s=0  :x=n *perfect C :t=0  :i=1 *totient C :a=x  :b=i *gcd C :c=a-b*(a/b)  :a=b  :b=c J (b>0):*gcd C (a=1):t=t+1 C :i=i+1 J (i<=x-1):*totient C :x=t  :s=s+x J (x<>1):*perfect T (s=n):#n C (s=n):z=z+1 C :n=n+2 J (z<20):*num E :
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 mu...
#J
J
NB. playingcards.ijs NB. Defines a Rosetta Code playing cards class NB. Multiple decks may be used, one for each instance of this class.   coclass 'rcpc' NB. Rosetta Code playing cards class   NB. Class objects Ranks=: _2 ]\ ' A 2 3 4 5 6 7 8 910 J Q K' Suits=: ucp '♦♣♥♠' DeckPrototype=: (] #: i.@:*/)Ranks ,&# Suits...
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 ......
#Haskell
Haskell
pi_ = g (1, 0, 1, 1, 3, 3) where g (q, r, t, k, n, l) = if 4 * q + r - t < n * t then n : g ( 10 * q , 10 * (r - n * t) , t , k , div (10 * (3 * q + r)) t - 10 * n , l) else g ...
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 th...
#PHP
PHP
error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING ));   define('MAXSCORE', 100); define('PLAYERCOUNT', 2);   $confirm = array('Y', 'y', '');   while (true) { printf(' Player %d: (%d, %d) Rolling? (Yn) ', $player, $safeScore[$player], $score); if ($safeScore[$player] + $score < MAXSCORE && ...
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 pe...
#jq
jq
# is_prime is designed to work with jq 1.4 def is_prime: if . == 2 then true else 2 < . and . % 2 == 1 and . as $in | (($in + 1) | sqrt) as $m | (((($m - 1) / 2) | floor) + 1) as $max | reduce range(1; $max) as $i (true; if . then ($in % ((2 * $i) + 1)) > 0 else false end) e...
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 pe...
#Julia
Julia
using Primes   ispernicious(n::Integer) = isprime(count_ones(n)) nextpernicious(n::Integer) = begin n += 1; while !ispernicious(n) n += 1 end; return n end function perniciouses(n::Int) rst = Vector{Int}(n) rst[1] = 3 for i in 2:n rst[i] = nextpernicious(rst[i-1]) end return rst end pernicio...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Nanoquery
Nanoquery
import Nanoquery.Util list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} println list[new(Random).getInt(len(list))]
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#NetLogo
NetLogo
;; from list containnig only literals and literal constants user-message one-of [ 1 3 "rooster" blue ] ;; from list containing variables and reporters user-message one-of (list (red + 2) turtles (patch 0 0) )
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   iArray = [ 1, 2, 3, 4, 5 ] -- a traditional array iList = Arrays.asList(iArray) -- a Java Collection "List" object iWords = '1 2 3 4 5' -- a list as a string of space delimited words     v1 = iArray[Random().nextInt(iA...
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, maintaini...
#Oforth
Oforth
"rosetta code phrase reversal" reverse println "rosetta code phrase reversal" words map(#reverse) unwords println "rosetta code phrase reversal" words reverse unwords println
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, maintaini...
#Perl
Perl
use feature 'say'; my $s = "rosetta code phrase reversal";   say "0. Input  : ", $s; say "1. String reversed  : ", scalar reverse $s; say "2. Each word reversed  : ", join " ", reverse split / /, reverse $s; say "3. Word-order reversed : ", join " ", reverse split / /,$s;   # Or, using a regex: say "2. ...
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. The...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
  Needs["Combinatorica`"] derangements[n_] := Derangements[Range[n]] derangements[4] Table[{NumberOfDerangements[i], Subfactorial[i]}, {i, 9}] // TableForm Subfactorial[20]
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#Python
Python
from operator import itemgetter   DEBUG = False # like the built-in __debug__   def spermutations(n): """permutations by swapping. Yields: perm, sign""" sign = 1 p = [[i, 0 if i == 0 else -1] # [num, direction] for i in range(n)]   if DEBUG: print ' #', p yield tuple(pp[0] for pp in p), sig...
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Tcl
Tcl
package require Tcl 8.5   # Difference of means; note that the first list must be the concatenation of # the two lists (because this is cheaper to work with). proc statistic {AB A} { set sumAB [tcl::mathop::+ {*}$AB] set sumA [tcl::mathop::+ {*}$A] expr { $sumA / double([llength $A]) - ($sumAB - $sumA) / ...
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...
#JavaScript
JavaScript
function getImageData(url, callback) { var img = document.createElement('img'); var canvas = document.createElement('canvas');   img.onload = function () { canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); callback(ctx.getImageData(0, 0, img....
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#Wren
Wren
import "random" for Random import "/trait" for Stepped   var F = [ [1, -1, 1, 0, 1, 1, 2, 1], [0, 1, 1, -1, 1, 0, 2, 0], [1, 0, 1, 1, 1, 2, 2, 1], [1, 0, 1, 1, 2, -1, 2, 0], [1, -2, 1, -1, 1, 0, 2, -1], [0, 1, 1, 1, 1, 2, 2, 1], [1, -1, 1, 0, 1, 1, 2, -1], [1, -1, 1, 0, 2, 0, 2, 1] ]   va...
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   Luca...
#Burlesque
Burlesque
Jfc++\/2.*==
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\disp...
#Racket
Racket
#lang racket (require racket/fixnum) (define t (make-parameter 100))   (define (Rn v) (define (inner-Rn rv idx b-1) (define b (fxvector-ref v idx)) (define rv+ (if (and (= b 1) (= b-1 0)) (add1 rv) rv)) (if (zero? idx) rv+ (inner-Rn rv+ (sub1 idx) b))) (inner-Rn 0 (sub1 (fxvector-length v)) 0))   (defin...
http://rosettacode.org/wiki/Percolation/Mean_run_density
Percolation/Mean run density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let v {\disp...
#REXX
REXX
/* REXX */ Numeric Digits 20 Call random(,12345) /* make the run reproducable */ pList = '.1 .3 .5 .7 .9' nList = '1e2 1e3 1e4 1e5' t = 100 Do While plist<>'' Parse Var plist p plist theory=p*(1-p) Say ' ' Say 'p:' format(p,2,4)' theory:'format(theory,2,4)' t:'format(t,4) Say ' n sim ...
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 Uni...
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion set arr=ABCD set /a n=4 :: echo !arr! call :permu  %n% arr goto:eof   :permu num &arr setlocal if %1 equ 1 call echo(!%2! & exit /b set /a "num=%1-1,n2=num-1" set arr=!%2! for /L %%c in (0,1,!n2!) do ( call:permu !num! arr set /a n1="num&1" if !n1! equ 0 (call:s...
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 ...
#J
J
shuf=: /: $ /:@$ 0 1"_
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Java
Java
import java.util.Arrays; import java.util.stream.IntStream;   public class PerfectShuffle {   public static void main(String[] args) { int[] sizes = {8, 24, 52, 100, 1020, 1024, 10_000}; for (int size : sizes) System.out.printf("%5d : %5d%n", size, perfectShuffle(size)); }   stat...
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 ...
#PureBasic
PureBasic
; Perlin_noise ; http://www.rosettacode.org   DataSection STARTDATA: Data.i 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,...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#PL.2FI
PL/I
perfectTotient: procedure options(main); gcd: procedure(aa, bb) returns(fixed); declare (aa, bb, a, b, c) fixed; a = aa; b = bb; do while(b ^= 0); c = a; a = b; b = mod(c, b); end; return(a); end gcd;   totient: procedure(n...
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Java
Java
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
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 ......
#Icon_and_Unicon
Icon and Unicon
procedure pi (q, r, t, k, n, l) first := "yes" repeat { # infinite loop if (4*q+r-t < n*t) then { suspend n if (\first) := &null then suspend "." # compute and update variables for next cycle nr := 10*(r-n*t) n := ((10*(3*q+r)) / t) - 10*n q *:= 10 r := nr } else { ...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Python
Python
#!/usr/bin/python3   ''' See: http://en.wikipedia.org/wiki/Pig_(dice)   This program scores and throws the dice for a two player game of Pig   '''   from random import randint   playercount = 2 maxscore = 100 safescore = [0] * playercount player = 0 score=0   while max(safescore) < maxscore: rolling = input("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 pe...
#Kotlin
Kotlin
// version 1.0.5-2   fun isPrime(n: Int): Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d : Int = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#NewLISP
NewLISP
  (define (pick-random-element R) (nth (rand (length R)) R))  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Nim
Nim
import random randomize()   let ls = @["foo", "bar", "baz"] echo sample(ls)
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, maintaini...
#Phix
Phix
with javascript_semantics constant test = "rosetta code phrase reversal", fmt = """ The original phrase as given:  %s 1. Reverse the entire phrase:  %s 2. Reverse words, same order:  %s 3. Reverse order, same words:  %s """ printf(1,fmt,{test, reverse(test), join(apply(split(test),r...
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. The...
#Nim
Nim
import algorithm, sequtils, strformat, strutils, tables   iterator derangements[T](a: openArray[T]): seq[T] = var perm = @a while true: if not perm.nextPermutation(): break block checkDerangement: for i, val in a: if perm[i] == val: break checkDerangement yield perm   proc `!`(n: 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 ...
#Racket
Racket
  #lang racket   (define (add-at l i x) (if (zero? i) (cons x l) (cons (car l) (add-at (cdr l) (sub1 i) x))))   (define (permutations l) (define (loop l) (cond [(null? l) '(())] [else (for*/list ([(p i) (in-indexed (loop (cdr l)))] [i ((if (odd? i) identity reverse) ...
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 ...
#Raku
Raku
sub insert($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. +@xs) } sub order($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }   multi perms([]) { [] => +1 }   multi perms([$x, *@xs]) { perms(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(+1,-1) xx * }   .say for perms([0..2]);
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Ursala
Ursala
#import std #import nat #import flo   treatment_group = <85,88,75,66,25,29,83,39,97> control_group = <68,41,10,49,16,65,32,92,28,98>   f = # returns the fractions of alternative mean differences above and below the actual   float~*; -+ vid^~G(plus,~&)+ (not fleq@rlX)*|@htX; ~~ float+ length, minus*+ mean^~*C/~&...
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Wren
Wren
import "/fmt" for Fmt   var data = [85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98]   var pick // recursive pick = Fn.new { |at, remain, accu, treat| if (remain == 0) return (accu > treat) ? 1 : 0 return pick.call(at-1, remain-1, accu + data[at-1], treat) + ((at > remain) ...
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...
#Julia
Julia
using Images, FileIO, Printf   absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue)) function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T size(A) != size(B) && throw(ArgumentError("images must be same-size")) s = zero(T) for (a, b) in zip(A, B) ...
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...
#Kotlin
Kotlin
// version 1.2.10   import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO import kotlin.math.abs   fun getDifferencePercent(img1: BufferedImage, img2: BufferedImage): Double { val width = img1.width val height = img1.height val width2 = img2.width val height2 = img2.height...
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#zkl
zkl
fcn printResult { foreach row in (grid){ row.apply(symbols.get).concat(" ").println() } } fcn tryPlaceOrientation(o, R,C, shapeIndex){ foreach ro,co in (o){ r,c:=R+ro, C+co; if(r<0 or r>=nRows or c<0 or c>=nCols or grid[r][c]!=-1) return(False); } grid[R][C]=shapeIndex; foreach ro,co in (o){ grid[R+ro...