task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#FreeBASIC
FreeBASIC
#define NSWAPS 100   type card suit : 2 as ubyte face : 4 as ubyte 'the remaining 2 bits are unused end type   dim shared as string*8 Suits(0 to 3) = {"Spades", "Clubs", "Hearts", "Diamonds"} dim shared as string*8 Faces(0 to 12) = {"Ace", "Two", "Three", "Four", "Five",_ "Six", "Seven", "Eight", "Nine...
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 ......
#Fortran
Fortran
  program pi implicit none integer,dimension(3350) :: vect integer,dimension(201) :: buffer integer :: more,karray,num,k,l,n more = 0 vect = 2 do n = 1,201 karray = 0 do l = 3350,1,-1 num = 100000*vect(l) + karray*l karray = num/(2*l - 1) vect(l) = num - karray*(2*l - 1) end ...
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...
#Nim
Nim
import random, strformat, strutils   randomize()   stdout.write "Player 1 - Enter your name : " let name1 = block: let n = stdin.readLine().strip() if n.len == 0: "PLAYER 1" else: n.toUpper stdout.write "Player 2 - Enter your name : " let name2 = block: let n = stdin.readLine()...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func pernicious(w uint32) bool { const ( ff = 1<<32 - 1 mask1 = ff / 3 mask3 = ff / 5 maskf = ff / 17 maskp = ff / 255 ) w -= w >> 1 & mask1 w = w&mask3 + w>>2&mask3 w = (w + w>>4) & maskf return 0xa08a28ac>>(w*maskp>>24)&1...
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP var [const] one=BI(1), two=BI(2), three=BI(3);   fcn pierPonts(n){ //-->((bigInt first kind primes) (bigInt second)) pps1,pps2 := List(BI(2)), List(); count1, count2, s := 1, 0, List(BI(1)); // n==2_000, s-->266_379 elements i2,i3,k := 0, 0, 1; n2,n3,t := BI(...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Klingphix
Klingphix
include ..\Utilitys.tlhy   :pickran len rand * 1 + get ;   ( 1 3.1415 "Hello world" ( "nest" "list" ) )   10 [drop pickran ?] for   " " input
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   /** * Extension function on any list that will return a random element from index 0 * to the last index */ fun <E> List<E>.getRandomElement() = this[Random().nextInt(this.size)]   /** * Extension function on any list that will return a list of unique random picks * fr...
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...
#K
K
  / Rosetta code phrase reversal / phraserev.k   reversestr: {|x} getnxtwd: {c:(&" "~'x); if[c~!0;w::x;:""];w::c[0]#x; x: ((1+c[0]) _ x)} revwords: {rw:""; while[~(x~""); x: getnxtwd x;rw,:|w;rw,:" "];:-1 _ rw} revwordorder: {rw:""; while[~(x~""); x: getnxtwd x;rw:" ",rw;rw:w,rw];:-1 _ rw}    
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Klingphix
Klingphix
include ..\Utilitys.tlhy   "Rosetta Code Phrase Reversal" dup ? dup reverse ? split dup reverse len [drop pop swap print " " print] for drop nl len [drop pop swap reverse print " " print] for drop nl nl   "End " input
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Haskell
Haskell
import Control.Monad (forM_)   import Data.List (permutations)   -- Compute all derangements of a list derangements :: Eq a => [a] -> [[a]] derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations   -- Compute the number of derangements of n elements subfactorial :: (Eq a, Num a) => a -> a subfacto...
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 ...
#Lua
Lua
_JT={} function JT(dim) local n={ values={}, positions={}, directions={}, sign=1 } setmetatable(n,{__index=_JT}) for i=1,dim do n.values[i]=i n.positions[i]=i n.directions[i]=-1 end return n end   function _JT:largestMobile() for i=#self.values,1,-1 do local loc=self.positions[i]+self.direct...
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...
#R
R
permutation.test <- function(treatment, control) { perms <- combinations(length(treatment)+length(control), length(treatment), c(treatment, control), set=FALSE) p <- mean(rowMeans(perms) <= mean(treatment)) c(under=p, over=(1-p)) }
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Racket
Racket
#lang racket/base   (define-syntax-rule (inc! x) (set! x (add1 x)))   (define (permutation-test control-gr treatment-gr) (let ([both-gr (append control-gr treatment-gr)] [threshold (apply + control-gr)] [more 0] [leq 0]) (let loop ([data both-gr] [sum 0] [needed (length control-gr)] [av...
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...
#F.23
F#
  //Percentage difference between 2 images. Nigel Galloway April 18th., 2018 let img50 = new System.Drawing.Bitmap("Lenna50.jpg") let img100 = new System.Drawing.Bitmap("Lenna100.jpg") let diff=Seq.cast<System.Drawing.Color*System.Drawing.Color>(Array2D.init img50.Width img50.Height (fun n g->(img50.GetPixel(n,g),img10...
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...
#Forth
Forth
: pixel-diff ( pixel1 pixel2 -- n ) over 255 and over 255 and - abs >r 8 rshift swap 8 rshift over 255 and over 255 and - abs >r 8 rshift swap 8 rshift - abs r> + r> + ; : bdiff ( bmp1 bmp2 -- fdiff ) 2dup bdim rot bdim d<> abort" images not comparable" 0e ( F: total di...
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 ...
#Nim
Nim
import random, sequtils, strutils   const   F = @[[1, -1, 1, 0, 1, 1, 2, 1], [0, 1, 1, -1, 1, 0, 2, 0], [1, 0, 1, 1, 1, 2, 2, 1], [1, 0, 1, 1, 2, -1, 2, 0], [1, -2, 1, -1, 1, 0, 2, -1], [0, 1, 1, 1, 1, 2, 2, 1], [1, -1, 1, 0, 1, 1, 2, -1], [1, -1, 1, 0, 2, 0, 2, 1]]   I = @[[0, 1, 0, 2, 0, 3...
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 ...
#Perl
Perl
#!/usr/bin/perl   use strict; # first open space version use warnings;   my $size = shift // 8;   sub rotate { local $_ = shift; my $ans = ''; $ans .= "\n" while s/.$/$ans .= $&; ''/gem; $ans; }   sub topattern { local $_ = shift; s/.+/ $& . ' ' x ($size - length $&)/ge; s/^\s+|\s+\z//g; [ tr/ \n...
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...
#Python
Python
from __future__ import division from random import random import string from math import fsum   n_range, p, t = (2**n2 for n2 in range(4, 14, 2)), 0.5, 5 N = M = 15   NOT_CLUSTERED = 1 # filled but not clustered cell cell2char = ' #' + string.ascii_letters   def newgrid(n, p): return [[int(random() < p) for x in ...
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...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program perfectNumber.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include...
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...
#Phix
Phix
with javascript_semantics constant w = 10, h = 10 sequence wall = join(repeat("+",w+1),"---")&"\n", cell = join(repeat("|",w+1)," ")&"\n", grid procedure new_grid(atom p) grid = split(join(repeat(wall,h+1),cell),'\n') -- now knock down some walls for i=1 to length(grid)-1 do ...
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...
#Julia
Julia
using Printf, Distributions, IterTools   newv(n::Int, p::Float64) = rand(Bernoulli(p), n) runs(v::Vector{Int}) = sum((a & ~b) for (a, b) in zip(v, IterTools.chain(v[2:end], v[1])))   mrd(n::Int, p::Float64) = runs(newv(n, p)) / n   nrep = 500   for p in 0.1:0.2:1 lim = p * (1 - p)   println() for ex in 10:2...
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...
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random() const val RAND_MAX = 32767   // just generate 0s and 1s without storing them fun runTest(p: Double, len: Int, runs: Int): Double { var cnt = 0 val thresh = (p * RAND_MAX).toInt() for (r in 0 until runs) { var x = 0 var i = len...
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...
#Python
Python
from random import random import string from pprint import pprint as pp   M, N, t = 15, 15, 100   cell2char = ' #' + string.ascii_letters NOT_VISITED = 1 # filled cell not walked   class PercolatedException(Exception): pass   def newgrid(p): return [[int(random() < p) for m in range(M)] for n in range(N)] # cel...
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...
#AppleScript
AppleScript
----------------------- PERMUTATIONS -----------------------   -- permutations :: [a] -> [[a]] on permutations(xs) script go on |λ|(xs) script h on |λ|(x) script ts on |λ|(ys) {{x} & ys} ...
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 ...
#Dyalect
Dyalect
func shuffle(arr) { if arr.Length() % 2 != 0 { throw @InvalidValue(arr.Length()) } var half = arr.Length() / 2 var result = Array.Empty(arr.Length()) var (t, l, r) = (0, 0, half)   while l < half { result[t] = arr[l] result[t+1] = arr[r] l += 1 r += 1 ...
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 ...
#EchoLisp
EchoLisp
  ;; shuffler : a permutation vector which interleaves both halves of deck (define (make-shuffler n) (let ((s (make-vector n))) (for ((i (in-range 0 n 2))) (vector-set! s i (/ i 2))) (for ((i (in-range 0 n 2))) (vector-set! s (1+ i) (+ (/ n 2) (vector-ref s i)))) s))   ;; output : (n . # of shuffles needed to ...
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 ...
#Lua
Lua
local p = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 13...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#jq
jq
  # jq optimizes the recursive call of _gcd in the following: def gcd(a;b): def _gcd: if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end; [a,b] | _gcd ;   def count(s): reduce s as $x (0; .+1);   # A perfect totient number is an integer that is equal to the sum of its iterated totients. # aka Euler's p...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Julia
Julia
using Primes   eulerphi(n) = (r = one(n); for (p,k) in factor(abs(n)) r *= p^(k-1)*(p-1) end; r)   const phicache = Dict{Int, Int}()   cachedphi(n) = (if !haskey(phicache, n) phicache[n] = eulerphi(n) end; phicache[n])   function perfecttotientseries(n) perfect = Vector{Int}() i = 1 while length(perfect) < ...
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...
#Go
Go
package cards   import ( "math/rand" )   // A Suit represents one of the four standard suites. type Suit uint8   // The four standard suites. const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 )   func (s Suit) String() string { const suites = "CDHS" // or "♣♢♡♠" return suites[s : s+1] }...
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 ......
#FreeBASIC
FreeBASIC
' version 05-07-2018 ' compile with: fbc -s console   ' unbounded spigot ' Ctrl-c to end program or close console window   #Include "gmp.bi"   Dim As UInteger num, ndigit, fp = Not 0 Dim As mpz_ptr q,r,t,k,n,l,tmp1,tmp2 q = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(q,1) r = Allocate(Len(__Mpz_struct)) : Mpz_i...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Objeck
Objeck
  class Pig { function : Main(args : String[]) ~ Nil { player_count := 2; max_score := 100; safe_score := Int->New[player_count]; player := 0; score := 0;   while(true) { safe := safe_score[player]; " Player {$player}: ({$safe}, {$score}) Rolling? (y/n) "->PrintLine(); rolling ...
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...
#Go
Go
package main   import "fmt"   func pernicious(w uint32) bool { const ( ff = 1<<32 - 1 mask1 = ff / 3 mask3 = ff / 5 maskf = ff / 17 maskp = ff / 255 ) w -= w >> 1 & mask1 w = w&mask3 + w>>2&mask3 w = (w + w>>4) & maskf return 0xa08a28ac>>(w*maskp>>24)&1...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#LabVIEW
LabVIEW
local( my array = array('one', 'two', 3) )   #myarray -> get(integer_random(#myarray -> size, 1))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Lasso
Lasso
local( my array = array('one', 'two', 3) )   #myarray -> get(integer_random(#myarray -> size, 1))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Liberty_BASIC
Liberty BASIC
list$ ="John Paul George Ringo Peter Paul Mary Obama Putin" wantedTerm =int( 10 *rnd( 1)) print "Selecting term "; wantedTerm; " in the list, which was "; word$( list$, wantedTerm, " ")
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Kotlin
Kotlin
// version 1.0.6   fun reverseEachWord(s: String) = s.split(" ").map { it.reversed() }.joinToString(" ")   fun main(args: Array<String>) { val original = "rosetta code phrase reversal" val reversed = original.reversed() println("Original string => $original") println("Reversed string => $reversed") ...
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...
#Lambdatalk
Lambdatalk
  {W.reverse word} reverses characters in a word {S.reverse words} reverses a sequence of words {S.map function words} applies a function to a sequence of words   {def S rosetta code phrase reversal} = rosetta code phrase reversal   {W.reverse {S}} -> lasrever esarhp edoc attesor {S.map W.reverse {S}} -> attesor...
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...
#J
J
derangement=: (A.&i.~ !)~ (*/ .~: # [) i. NB. task item 1 subfactorial=: ! * +/@(_1&^ % !)@i.@>: NB. task item 3
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class Derangement {   public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toStrin...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
perms[0] = {{{}, 1}}; perms[n_] := Flatten[If[#2 == 1, Reverse, # &]@ Table[{Insert[#1, n, i], (-1)^(n + i) #2}, {i, n}] & @@@ perms[n - 1], 1];
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#Nim
Nim
# iterative Boothroyd method iterator permutations*[T](ys: openarray[T]): tuple[perm: seq[T], sign: int] = var d = 1 c = newSeq[int](ys.len) xs = newSeq[T](ys.len) sign = 1   for i, y in ys: xs[i] = y yield (xs, sign)   block outter: while true: while d > 1: dec d c[d] ...
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...
#Raku
Raku
sub stats ( @test, @all ) { ([+] @test / +@test) - ([+] flat @all, (@test X* -1)) / @all - @test }   my int @treated = <85 88 75 66 25 29 83 39 97>; my int @control = <68 41 10 49 16 65 32 92 28 98>; my int @all = flat @treated, @control;   my $base = stats( @treated, @all );   my atomicint @trials[3] = 0, 0, 0;   ...
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...
#Fortran
Fortran
program ImageDifference   use RCImageBasic use RCImageIO   implicit none   integer, parameter :: input1_u = 20, & input2_u = 21   type(rgbimage) :: lenna1, lenna2 real :: totaldiff     open(input1_u, file="Lenna100.ppm", action="read") open(input2_u, file="Lenna50.ppm",...
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...
#Frink
Frink
  img1 = new image["file:Lenna50.jpg"] img2 = new image["file:Lenna100.jpg"]   [w1, h1] = img1.getSize[] [w2, h2] = img2.getSize[]   sum = 0 for x=0 to w1-1 for y=0 to h1-1 { [r1,g1,b1] = img1.getPixel[x,y] [r2,g2,b2] = img2.getPixel[x,y] sum = sum + abs[r1-r2] + abs[g1-g2] + abs[b1-b2] }   e...
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 ...
#Phix
Phix
with javascript_semantics constant pentominoes = split(""" ......I................................................................ ......I.....L......N.........................................Y......... .FF...I.....L.....NN....PP....TTT...........V.....W....X....YY.....ZZ.. FF....I.....L.....N.....PP.....T....U.U.....V...
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...
#Racket
Racket
#lang racket (require srfi/14) ; character sets   ; much faster than safe fixnum functions (require racket/require ; for fancy require clause below (filtered-in (lambda (name) (regexp-replace #rx"unsafe-" name "")) racket/unsafe/ops)  ; these aren't in racket/unsafe/ops (only-in racket/fixnum...
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...
#Raku
Raku
my @perc; my $fill = 'x';   enum Direction <DeadEnd Up Right Down Left>;   my $𝘒 = perctest(15); .fmt("%-2s").say for @perc; say "𝘱 = 0.5, 𝘕 = 15, 𝘒 = $𝘒\n";   my $trials = 5; for 10, 30, 100, 300, 1000 -> $𝘕 { my $𝘒 = ( [+] perctest($𝘕) xx $trials ) / $trials; say "𝘱 = 0.5, trials = $trials, 𝘕 = $𝘕,...
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...
#Arturo
Arturo
divisors: $[n][ select 1..(n/2)+1 'i -> 0 = n % i ] perfect?: $[n][ n = sum divisors n ]   loop 2..1000 'i [ if perfect? i -> print i ]
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#AutoHotkey
AutoHotkey
Loop, 30 { If isMersennePrime(A_Index + 1) res .= "Perfect number: " perfectNum(A_Index + 1) "`n" }   MsgBox % res   perfectNum(N) { Return 2**(N - 1) * (2**N - 1) }   isMersennePrime(N) { If (isPrime(N)) && (isPrime(2**N - 1)) Return true }   isPrime(N) { Loop, % Floor(Sqrt(N)) If (A_Index > 1 && !...
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...
#Python
Python
from collections import namedtuple from random import random from pprint import pprint as pp   Grid = namedtuple('Grid', 'cell, hwall, vwall')   M, N, t = 10, 10, 100   class PercolatedException(Exception): pass   HVF = [(' .', ' _'), (':', '|'), (' ', '#')] # Horiz, vert, fill chars   def newgrid(p): hwall = [[in...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
meanRunDensity[p_, len_, trials_] := Mean[Length[Cases[Split@#, {1, ___}]] & /@ Unitize[Chop[RandomReal[1, {trials, len}], 1 - p]]]/len   Column@Table[ Grid[Join[{{p, n, K, diff}}, Table[{q, n, x = meanRunDensity[q, n, 100] // N, q (1 - q) - x}, {n, {100, 1000, 10000, 100000}}], {}], Alignment ...
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...
#Nim
Nim
import random, strformat   const T = 100   var pList = [0.1, 0.3, 0.5, 0.7, 0.9] nList = [100, 1_000, 10_000, 100_000]   for p in pList:   let theory = p * (1 - p) echo &"\np: {p:.4f} theory: {theory:.4f} t: {T}" echo " n sim sim-theory"   for n in nList: var sum = 0 for _ in 1...
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...
#Racket
Racket
#lang racket (require racket/require (only-in racket/fixnum for*/fxvector)) (require (filtered-in (lambda (name) (regexp-replace #rx"unsafe-" name "")) racket/unsafe/ops))   (define cell-empty 0) (define cell-filled 1) (define cell-wall 2) (define cell-visited 3) (define cell-exit 4)   (d...
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...
#Raku
Raku
my $block = '▒'; my $water = '+'; my $pore = ' '; my $grid = 15; my @site;   enum Direction <DeadEnd Up Right Down Left>;   say 'Sample percolation at .6'; percolate(.6); .join.say for @site; say "\n";   my $tests = 1000; say "Doing $tests trials at each porosity:"; for .1, .2 ... 1 -> $p { printf "p = %0.1f: %0....
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...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program permutation.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a fi...
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 ...
#Elixir
Elixir
defmodule Perfect do def shuffle(n) do start = Enum.to_list(1..n) m = div(n, 2) shuffle(start, magic_shuffle(start, m), m, 1) end   defp shuffle(start, start, _, step), do: step defp shuffle(start, deck, m, step) do shuffle(start, magic_shuffle(deck, m), m, step+1) end   defp magic_shuffle(d...
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 ...
#F.23
F#
  let perfectShuffle xs = let h = (List.length xs) / 2 xs |> List.mapi (fun i x->(if i<h then i * 2 else ((i-h) * 2) + 1), x) |> List.sortBy fst |> List.map snd   let orderCount n = let xs = [1..n] let rec spin count ys = if xs=ys then count else ys |> perfectShuffle |> spin (count + 1) xs |> pe...
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 ...
#Nim
Nim
import math   const Permutation = [ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, ...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Kotlin
Kotlin
// Version 1.3.21   fun totient(n: Int): Int { var tot = n var nn = n var i = 2 while (i * i <= nn) { if (nn % i == 0) { while (nn % i == 0) nn /= i tot -= tot / i } if (i == 2) i = 1 i += 2 } if (nn > 1) tot -= tot / nn return tot }   ...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(Y,Z) ENTRY TO GCD. A = Y B = Z LOOP WHENEVER A.E.B, FUNCTION RETURN A WHENEVER A.G.B, A = A-B WHENEVER A.L.B, B = B-A TRANSFER TO LOOP END OF FUNCTION   ...
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...
#Groovy
Groovy
import groovy.transform.TupleConstructor   enum Pip { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } enum Suit { DIAMONDS, SPADES, HEARTS, CLUBS }   @TupleConstructor class Card { final Pip pip final Suit suit   String toString() { "$pip of $suit" } }   class Deck { ...
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 ......
#FunL
FunL
def compute_pi = def g( q, r, t, k, n, l ) = if 4*q + r - t < n*t n # g( 10*q, 10*(r - n*t), t, k, (10*(3*q + r))\t - 10*n, l ) else g( q*k, (2*q + r)*l, t*l, k + 1, (q*(7*k + 2) + r*l)\(t*l), l + 2 )   g( 1, 0, 1, 1, 3, 3 )   if _name_ == '-main-' print( compute_pi().head() + '.' )   if arg...
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...
#OCaml
OCaml
class player (name_init : string) = object val name = name_init val mutable total = 0 val mutable turn_score = 0 method get_name = name method get_score = total method end_turn = total <- total + turn_score; turn_score <- 0; method has_won = total >= 100; method r...
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...
#Groovy
Groovy
  class example{ static void main(String[] args){ def n=0; def counter=0; while(counter<25){ if(print(n)){ counter++;} n=n+1; } println(); def x=888888877; while(x<888888889){ print(x); x++;} } static def print(def a){ def primes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]; def c=Integer.toBinaryString(a); String d=c; d...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#LiveCode
LiveCode
put "Apple,Banana,Peach,Apricot,Pear" into fruits put item (random(the number of items of fruits)) of fruits
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Logo
Logo
pick [1 2 3]
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Lua
Lua
-- Return a copy of table t in which each string is reversed function reverseEach (t) local rev = {} for k, v in pairs(t) do rev[k] = v:reverse() end return rev end   -- Return a reversed copy of table t function tabReverse (t) local revTab = {} for i, v in ipairs(t) do revTab[#t - i + 1] = v end ...
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...
#jq
jq
def derangements:   # In order to reference the original array conveniently, define _derangements(ary): def _derangements(ary): # We cannot put the i-th element in the i-th place: def deranged: # state: [i, available] .[0] as $i | .[1] as $in | if $i == (ary|length) then [] else ...
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 ...
#ooRexx
ooRexx
/* REXX Compute permutations of things elements */ /* implementing Heap's algorithm nicely shown in */ /* https://en.wikipedia.org/wiki/Heap%27s_algorithm */ /* Recursive Algorithm */ Parse Arg things e.='' Select When things='?' Then Call help When things='' Then ...
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...
#REXX
REXX
/*REXX program performs a permutation test on N + M subjects (volunteers): */ /* ↑ ↑ */ /* │ │ */ ...
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...
#Go
Go
package main   import ( "fmt" "image/jpeg" "os" "log" "image" )   func loadJpeg(filename string) (image.Image, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close()   img, err := jpeg.Decode(f) if err != nil { return nil, err ...
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 ...
#Picat
Picat
  import sat, util. rotate(Q) = Res => % rotate right by 90 degrees NZ = len(Q[1]), NS = len(Q), Res = new_array(NZ,NS), foreach(Z in 1..NZ, S in 1..NS) Res[Z,S] = Q[S,NZ+1-Z] end.   matprint(Q) => NZ = len(Q), NS = len(Q[1]), foreach(Z in 1..NZ, S in 1..NS) printf("%d|", Q[Z,S]), if S...
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 ...
#Racket
Racket
#lang racket   (require racket/hash)   (module+ main (Pentomino-tiling))   (define n-rows 8) (define n-cols 8) (define blank '-)   (define (build-grid) (for/fold ((grid (for*/hash ((r n-rows) (c n-cols)) (values (cons r c) #f)))) ((_ 4)) (hash-set grid (cons (random n-rows) (random n-cols)) blank)))   (define (ma...
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...
#Tcl
Tcl
package require Tcl 8.6   proc determineClusters {w h p} { # Construct the grid set grid [lrepeat $h [lrepeat $w 0]] for {set i 0} {$i < $h} {incr i} { for {set j 0} {$j < $w} {incr j} { lset grid $i $j [expr {rand() < $p ? -1 : 0}] } } # Find (and count) the clusters set cl 0 for {se...
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...
#AWK
AWK
$ awk 'func perf(n){s=0;for(i=1;i<n;i++)if(n%i==0)s+=i;return(s==n)} BEGIN{for(i=1;i<10000;i++)if(perf(i))print i}' 6 28 496 8128
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Racket
Racket
#lang racket   (define has-left-wall? (lambda (x) (bitwise-bit-set? x 0))) (define has-right-wall? (lambda (x) (bitwise-bit-set? x 1))) (define has-top-wall? (lambda (x) (bitwise-bit-set? x 2))) (define has-bottom-wall? (lambda (x) (bitwise-bit-set? x 3))) (define has-fluid? (lambda (x) (bitwise-bit-set? x ...
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...
#Raku
Raku
my @bond; my $grid = 10; my $geom = $grid - 1; my $water = '▒';   enum Direction <DeadEnd Up Right Down Left>;   say 'Sample percolation at .6'; percolate .6; .join.say for @bond; say "\n";   my $tests = 100; say "Doing $tests trials at each porosity:"; for .1, .2 ... 1 -> $p { printf "p = %0.1f: %0.2f\n", $p, (sum...
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...
#Pascal
Pascal
  {$MODE objFPC}//for using result,parameter runs becomes for variable.. uses sysutils;//Format const MaxN = 100*1000;   function run_test(p:double;len,runs: NativeInt):double; var x, y, i,cnt : NativeInt; Begin result := 1/ (runs * len); cnt := 0; for runs := runs-1 downto 0 do Begin x := 0; y ...
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...
#Sidef
Sidef
class Percolate {   has block = '▒' has water = '+' has pore = ' ' has grid = 15 has site = []   enum <DeadEnd, Up, Right, Down, Left>   method direction(x, y) { ((site[y + 1][x] == pore) && Down ) || ((site[y][x - 1] == pore) && Left ) || ((site[y][x + 1] == pore)...
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...
#Arturo
Arturo
print permutate [1 2 3]
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Factor
Factor
USING: arrays formatting kernel math prettyprint sequences sequences.merged ; IN: rosetta-code.perfect-shuffle   CONSTANT: test-cases { 8 24 52 100 1020 1024 10000 }   : shuffle ( seq -- seq' ) halves 2merge ;   : shuffle-count ( n -- m ) <iota> >array 0 swap dup [ 2dup = ] [ shuffle [ 1 + ] 2dip ] do until 2dr...
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 ...
#Fortran
Fortran
MODULE PERFECT_SHUFFLE IMPLICIT NONE   CONTAINS   ! Shuffle the deck/array of integers FUNCTION SHUFFLE(NUM_ARR) INTEGER, DIMENSION(:), INTENT(IN) :: NUM_ARR INTEGER, DIMENSION(SIZE(NUM_ARR)) :: SHUFFLE INTEGER :: I, IDX   IF (MOD(SIZE(NUM_ARR), 2) .NE. 0) THE...
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 ...
#OCaml
OCaml
let permutation = [151;160;137;91;90;15; 131;13;201;95;96;53;194;233;7;225;140;36;103;30;69;142;8;99;37;240;21;10;23; 190; 6;148;247;120;234;75;0;26;197;62;94;252;219;203;117;35;11;32;57;177;33; 88;237;149;56;87;174;20;125;136;171;168; 68;175;74;165;71;134;139;48;27;166; 77;146;158;231;83;111;229;122;60;211;133;230;220...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Maple
Maple
iterated_totient := proc(n::posint, total) if NumberTheory:-Totient(n) = 1 then return total + 1; else return iterated_totient(NumberTheory:-Totient(n), total + NumberTheory:-Totient(n)); end if; end proc:   isPerfect := n -> evalb(iterated_totient(n, 0) = n):   count := 0: num_list := []: for i while count < ...
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[PerfectTotientNumberQ] PerfectTotientNumberQ[n_Integer] := Total[Rest[Most[FixedPointList[EulerPhi, n]]]] == n res = {}; i = 0; While[Length[res] < 20, i++; If[PerfectTotientNumberQ[i], AppendTo[res, i]] ] res
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Modula-2
Modula-2
MODULE PerfectTotient; FROM InOut IMPORT WriteCard, WriteLn;   CONST Amount = 20; VAR n, seen: CARDINAL;   PROCEDURE GCD(a, b: CARDINAL): CARDINAL; VAR c: CARDINAL; BEGIN WHILE b # 0 DO c := a MOD b; a := b; b := c; END; RETURN a; END GCD;   PROCEDURE Totient(n: CARDINAL): CARDINAL; ...
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...
#Haskell
Haskell
import System.Random   data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Ord, Enum, Bounded, Eq, Show)   data Suit = Diamonds | Spades | Hearts | Clubs deriving (Ord, Enum, Bounded, Eq, Show)   type Card = (Pip, Suit)   fullRange :: (Bounded a...
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 ......
#FutureBasic
FutureBasic
  include "ConsoleWindow"   dim as long kf, ks xref mf(_maxLong - 1) as long xref ms(_maxLong - 1) as long dim as long cnt, n, temp, nd dim as long col, col1 dim as long lloc, stor(50)   end globals   local mode local fn FmtStr( nn as long, s as Str255 ) as Str255 dim l as long dim as Str255 f l = s[0] select case ...
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...
#Pascal
Pascal
program Pig;   const WinningScore = 100;   type DieRoll = 1..6; Score = integer; Player = record Name: string; Points: score; Victory: Boolean end;   { Assume a 2-player game. } var Player1, Player2: Player;   function RollTheDie: DieRoll; { Return a random number 1 thru 6. } begin RollTheDie := random(...
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...
#Haskell
Haskell
module Pernicious where   isPernicious :: Integer -> Bool isPernicious num = isPrime $ toInteger $ length $ filter ( == 1 ) $ toBinary num   isPrime :: Integer -> Bool isPrime number = divisors number == [1, number] where divisors :: Integer -> [Integer] divisors number = [ m | m <- [1 .. number] , nu...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Lua
Lua
math.randomseed(os.time()) local a = {1,2,3} print(a[math.random(1,#a)])
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Maple
Maple
a := [bear, giraffe, dog, rabbit, koala, lion, fox, deer, pony]: randomNum := rand(1 ..numelems(a)): a[randomNum()];
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Maple
Maple
#reverse the string str := "rosetta code phrase reversal": print(StringTools:-Reverse(str)): #reverse each word lst := convert(StringTools:-Split(str, " "), Array): for i to numelems(lst) do lst[i] := StringTools:-Reverse(lst[i]): end do: print(StringTools:-Join(convert(lst,list)," ")): #reverse word order print(Strin...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
phrase = "Rosetta Code Phrase Reversal";   reverseWords[phrase_String] := StringJoin @@ Riffle[Reverse@StringSplit@phrase, " "]   reverseLetters[phrase_String] :=   StringJoin @@ Riffle[Map[StringJoin @@ Reverse[Characters@#] &, StringSplit@phrase], " "]   {phrase, reverseWords@phrase, reverseLetters@phrase,...
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...
#Julia
Julia
using Printf, Combinatorics   derangements(n::Int) = (perm for perm in permutations(1:n) if all(indx != p for (indx, p) in enumerate(perm)))   function subfact(n::Integer)::Integer if n in (0, 2) return 1 elseif n == 1 return 0 elseif 1 ≤ n ≤ 18 return round(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 ...
#Perl
Perl
  #!perl use strict; use warnings;   # This code uses "Even's Speedup," as described on # the Wikipedia page about the Steinhaus–Johnson– # Trotter algorithm.   # Any resemblance between this code and the Python # code elsewhere on the page is purely a coincidence, # caused by them both implementing the same algorithm....
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...
#Ruby
Ruby
def statistic(ab, a) sumab, suma = ab.inject(:+).to_f, a.inject(:+).to_f suma / a.size - (sumab - suma) / (ab.size - a.size) end   def permutationTest(a, b) ab = a + b tobs = statistic(ab, a) under = count = 0 ab.combination(a.size) do |perm| under += 1 if statistic(ab, perm) <= tobs count += 1 en...
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...
#Haskell
Haskell
import Bitmap import Bitmap.Netpbm import Bitmap.RGB   import Control.Monad import Control.Monad.ST import System.Environment (getArgs)   main = do [path1, path2] <- getArgs image1 <- readNetpbm path1 image2 <- readNetpbm path2 diff <- stToIO $ imageDiff image1 image2 putStrLn $ "Difference: " ++ sh...
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 ...
#Python
Python
from itertools import product   minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((13184...