task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Wren
Wren
import "/ioutil" for Input import "/str" for Str import "random" for Random   var name1 = Input.text("Player 1 - Enter your name : ").trim() name1 = (name1 == "") ? "PLAYER1" : Str.upper(name1) var name2 = Input.text("Player 2 - Enter your name : ").trim() name2 = (name2 == "") ? "PLAYER2" : Str.upper(name2) var names ...
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...
#Picat
Picat
go =>   println(take_n(pernicious_number,25,1)), println([J : J in 888888877..888888888, pernicious_number(J)]), nl.   % Get the first N numbers that satisfies function F, starting with S take_n(F,N,S) = L => I = S, C = 0, L = [], while(C < N) if call(F,I) then L := L ++ [I], C := C + 1 ...
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...
#PicoLisp
PicoLisp
(de pernicious? (N) (prime? (cnt = (chop (bin N)) '("1" .))) )
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#ReScript
ReScript
let fruits = ["apple", "banana", "coconut", "orange", "lychee"]   let pickRand = arr => { let len = Js.Array.length(arr) let i = Js.Math.random_int(0, len) arr[i] }   Js.log(pickRand(fruits))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#REXX
REXX
/*REXX program picks a random element from a list (tongue in cheek, a visual pun).*/ _= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium' _=_ 'magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium' _=_ 'scandium titanium vanadium chromium manganese iro...
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...
#Tcl
Tcl
set s "rosetta code phrase reversal" # Reverse all characters puts [string reverse $s] # Reverse characters in each word puts [lmap word $s {string reverse $word}] # Reverse the words but not the characters puts [lreverse $s]
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#UNIX_Shell
UNIX Shell
s1="rosetta code phrase reversal" echo "Original string ----------------------> "$s1   echo -n "1.) Reverse the string ---------------> " echo $s1|rev   echo -n "2.) Reverse characters of each word --> " echo $s1|tr " " "\n"|rev|tr "\n" " ";echo   echo -n "3.) Reverse word order ---------------> " word_num=$(echo $s1|w...
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...
#Ruby
Ruby
def derangements(n) ary = (1 .. n).to_a ary.permutation.select do |perm| ary.zip(perm).all? {|a,b| a != b} end end   def subfact(n) case n when 0 then 1 when 1 then 0 else (n-1)*(subfact(n-1) + subfact(n-2)) end end   puts "derangements for n = 4" derangements(4).each{|d|p d}   puts "\n n derange ...
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...
#Ruby
Ruby
require 'raster_graphics'   class RGBColour # the difference between two colours def -(a_colour) (@red - a_colour.red).abs + (@green - a_colour.green).abs + (@blue - a_colour.blue).abs end end   class Pixmap # the difference between two images def -(a_pixmap) if @width != a_pixmap.width or @he...
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...
#Elena
Elena
import system'routines; import system'math; import extensions;   extension extension { isPerfect() = new Range(1, self - 1).selectBy:(n => (self.mod:n == 0).iif(n,0) ).summarize(new Integer()) == self; }   public program() { for(int n := 1, n < 10000, n += 1) { if(n.isPerfect()) ...
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...
#Elixir
Elixir
defmodule RC do def is_perfect(1), do: false def is_perfect(n) when n > 1 do Enum.sum(factor(n, 2, [1])) == n end   defp factor(n, i, factors) when n < i*i , do: factors defp factor(n, i, factors) when n == i*i , do: [i | factors] defp factor(n, i, factors) when rem(n,i)==0, do: factor(n, i+1, [i, ...
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...
#EDSAC_order_code
EDSAC order code
  [Permutations task for Rosetta Code.] [EDSAC program, Initial Orders 2.]   T51K P200F [G parameter: start address of subroutines] T47K P100F [M parameter: start address of main routine]   [====================== G parameter: Subroutines =====================] E25K TG GK [Constants used in the sub...
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 ...
#Racket
Racket
#lang racket/base (require racket/list)   (define (perfect-shuffle l) (define-values (as bs) (split-at l (/ (length l) 2))) (foldr (λ (a b d) (list* a b d)) null as bs))   (define (perfect-shuffles-needed n) (define-values (_ rv) (for/fold ((d (perfect-shuffle (range n))) (i 1)) ((_ (in-naturals...
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 ...
#Raku
Raku
sub perfect-shuffle (@deck) { my $mid = @deck / 2; flat @deck[0 ..^ $mid] Z @deck[$mid .. *]; }   for 8, 24, 52, 100, 1020, 1024, 10000 -> $size { my @deck = ^$size; my $n; repeat until [<] @deck { $n++; @deck = perfect-shuffle @deck; }   printf "%5d cards: %4d\n", $size, $n;...
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Nim
Nim
import random, strutils   type Suit* = enum ♥, ♦, ♣, ♠   Rank* {.pure.} = enum Ace = (1, "A") Two = (2, "2") Three = (3, "3") Four = (4, "4") Five = (5, "5") Six = (6, "6") Seven = (7, "7") Eight = (8, "8") Nine = (9, "9") Ten = (10, "10") Jack = (11, "J") Queen = (12...
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 ......
#Nanoquery
Nanoquery
q = 1; r = 0; t = 1 k = 1; n = 3; l = 3   nn = null; nr = null first = true   while true if (((4 * q) + r) - t) < (n * t) print n if first print "." first = false end nr = int(10 * (r - (n * t))) n = int((10 * ((3 * q) + r)) / t) - (10 * n) q *= 10 r = nr else nr = int(((2 * q) + r) * l) nn = ...
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...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations integer Player, Die, Points, Score(2); [Score(0):= 0; Score(1):= 0; \starting scores for each player Player:= 1; \second player repeat Player:= if Player = 1 then 0 else 1; \next player Points:= 0; ...
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...
#PL.2FI
PL/I
  pern: procedure options (main); declare (i, n) fixed binary (31);   n = 3; do i = 1 to 25, 888888877 to 888888888; if i = 888888877 then do; n = i ; put skip; end; do while ( ^is_prime ( tally(bit(n), '1'b) ) ); n = n + 1; end; put edit( trim(n), ' ') (a); n = n + 1; ...
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...
#Plain_English
Plain English
To decide if a number is pernicious: Find a population count of the number. If the population count is prime, say yes. Say no.   To find a population count of a number: Privatize the number. Loop. If the number is 0, exit. Bitwise and the number with the number minus 1. Bump the population count. Repeat.   To run: Star...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Ring
Ring
  aList = "abcdefghij" for i = 1 to 10 letter = random(9) + 1 if letter > 0 see aList[letter] + nl ok next  
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Ruby
Ruby
  %w(north east south west).sample # => "west" (1..100).to_a.sample(2) # => [17, 79]
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#VBA
VBA
  Option Explicit   Sub Main_Phrase_Reversals() Const PHRASE As String = "rosetta code phrase reversal" Debug.Print "Original String  : " & PHRASE Debug.Print "Reverse String  : " & Reverse_String(PHRASE) Debug.Print "Reverse each individual word : " & Reverse_each_individual_word(P...
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...
#Scala
Scala
def derangements(n: Int) = (1 to n).permutations.filter(_.zipWithIndex.forall{case (a, b) => a - b != 1})   def subfactorial(n: Long): Long = n match { case 0 => 1 case 1 => 0 case _ => (n - 1) * (subfactorial(n - 1) + subfactorial(n - 2)) }   println(s"Derangements for n = 4") println(derangements(4) mkString ...
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...
#Rust
Rust
extern crate image;   use image::{GenericImageView, Rgba};   fn diff_rgba3(rgba1 : Rgba<u8>, rgba2 : Rgba<u8>) -> i32 { (rgba1[0] as i32 - rgba2[0] as i32).abs() + (rgba1[1] as i32 - rgba2[1] as i32).abs() + (rgba1[2] as i32 - rgba2[2] as i32).abs() }   fn main() { let img1 = image::open("Lenna100.jpg")...
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...
#Sidef
Sidef
require('Imager')   func img_diff(a, b) {   func from_file(name) { %s|Imager|.new(file => name) }   func size(img) { (img.getwidth, img.getheight) }   func pixel_diff(p1, p2) { [p1.rgba] »-« [p2.rgba] -> map { .abs }.sum }   func read_pixel(img, x, y) { img.g...
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...
#Erlang
Erlang
is_perfect(X) -> X == lists:sum([N || N <- lists:seq(1,X-1), X rem N == 0]).
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE}   make do test := <<2, 5, 1>> permute (test, 1) end   test: ARRAY [INTEGER]   permute (a: ARRAY [INTEGER]; k: INTEGER) -- All permutations of 'a'. require count_positive: a.count > 0 k_valid_index: k > 0 local t: INTEGER do if k = a....
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 ...
#REXX
REXX
/*REXX program performs a "perfect shuffle" for a number of even numbered decks. */ parse arg X /*optional list of test cases from C.L.*/ if X='' then X=8 24 52 100 1020 1024 10000 /*Not specified? Then use the default.*/ w=length(word(X, words(X))) ...
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...
#OCaml
OCaml
type pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace let pips = [Two; Three; Four; Five; Six; Seven; Eight; Nine; Ten; Jack; Queen; King; Ace] type suit = Diamonds | Spades | Hearts | Clubs let suits = [Diamonds; Spades; Hearts; Clubs] type card = ...
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 ......
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary import java.math.BigInteger   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg places . if places = '' then places = -1   TWO = BigInt...
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...
#zkl
zkl
const WIN=100, PLAYERS=2; players,safeScores:=Walker.cycle([0..PLAYERS-1]), PLAYERS.pump(List(),0); rollDie:=(1).random.fp(7); yes,player,score,S:=T("","y"),players.next(),0,0; tally:='wrap(player,score){ w:=safeScores[player]+=score; (w>=WIN) };   while(True){ print("Player %d: (%d, %d). Rolling? (y/n) ".fmt(player...
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...
#PowerShell
PowerShell
  function pop-count($n) { (([Convert]::ToString($n, 2)).toCharArray() | where {$_ -eq '1'}).count }   function isPrime ($n) { if ($n -eq 1) {$false} elseif ($n -eq 2) {$true} elseif ($n -eq 3) {$true} else{ $m = [Math]::Floor([Math]::Sqrt($n)) (@(2..$m | where {($_ -lt $n) -and (...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Run_BASIC
Run BASIC
list$ = "a,b,c,d,e,f,g,h,i,j" letter = rnd(1) * 10 print "Selected letter:"; word$(list$,letter,",")
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Rust
Rust
extern crate rand;   use rand::Rng;   fn main() { let array = [5,1,2,5,6,7,8,1,2,4,5]; let mut rng = rand::thread_rng();   println!("{}", rng.choose(&array).unwrap()); }
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#VBScript
VBScript
  Phrase = "rosetta code phrase reversal"   WScript.StdOut.Write "Original String  : " & Phrase WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse String  : " & RevString(Phrase) WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse String Each Word : " & RevStringEachWord(Phrase) WScript.StdOut.W...
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...
#Vlang
Vlang
  fn main() { str := 'rosetta code phrase reversal' words := str.fields() println('Original: $str') println('Reverse: ${str.reverse()}') println('Char-Word Reverse: ${words.map(it.reverse()).join(' ')}') println('Word Reverse: ${words.reverse().join(' ')}') }
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#SuperCollider
SuperCollider
( d = { |array, n| Routine { n = n ?? { array.size.factorial }; n.do { |i| var permuted = array.permute(i); if(array.every { |each, i| permuted[i] != each }) { permuted.yield }; } }; }; f = { |n| d.((0..n-1)) }; x = f.(4); x.all.do(_.postln); ""; )
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Tcl
Tcl
package require Tcl 8.5; # for arbitrary-precision integers package require struct::list; # for permutation enumerator   proc derangements lst { # Special case if {![llength $lst]} {return {{}}} set result {} for {set perm [struct::list firstperm $lst]} {[llength $perm]} \ {set perm [struct::list...
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...
#Swift
Swift
func pixelValues(fromCGImage imageRef: CGImage?) -> [UInt8]? { var width = 0 var height = 0 var pixelValues: [UInt8]?   if let imageRef = imageRef { width = imageRef.width height = imageRef.height let bitsPerComponent = imageRef.bitsPerComponent let bytesPerRow = imageRef...
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...
#Tcl
Tcl
package require Tk   proc imageDifference {img1 img2} { if { [image width $img1] != [image width $img2] || [image height $img1] != [image height $img2] } then { return -code error "images are different size" } set diff 0 for {set x 0} {$x<[image width $img1]} {incr x} { for {set y 0} {$y<[image ...
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...
#ERRE
ERRE
PROGRAM PERFECT   PROCEDURE PERFECT(N%->OK%) LOCAL I%,S% S%=1 FOR I%=2 TO SQR(N%)-1 DO IF N% MOD I%=0 THEN S%+=I%+N% DIV I% END FOR IF I%=SQR(N%) THEN S%+=I% OK%=(N%=S%) END PROCEDURE   BEGIN PRINT(CHR$(12);) ! CLS FOR N%=2 TO 10000 STEP 2 DO PERFECT(N%->OK%) ...
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...
#Elixir
Elixir
defmodule RC do def permute([]), do: [[]] def permute(list) do for x <- list, y <- permute(list -- [x]), do: [x|y] end end   IO.inspect RC.permute([1, 2, 3])
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Ruby
Ruby
def perfect_shuffle(deck_size = 52) deck = (1..deck_size).to_a original = deck.dup half = deck_size / 2 1.step do |i| deck = deck.first(half).zip(deck.last(half)).flatten return i if deck == original end end   [8, 24, 52, 100, 1020, 1024, 10000].each {|i| puts "Perfect shuffles required for 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 ...
#Rust
Rust
extern crate itertools;   fn shuffle<T>(mut deck: Vec<T>) -> Vec<T> { let index = deck.len() / 2; let right_half = deck.split_off(index); itertools::interleave(deck, right_half).collect() }   fn main() { for &size in &[8, 24, 52, 100, 1020, 1024, 10_000] { let original_deck: Vec<_> = (0..size).c...
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...
#PARI.2FGP
PARI/GP
name(n)=Str(["A",2,3,4,5,6,7,8,9,10,"J","Q","K"][(n+3)>>2],["h","d","s","c"][n%4+1]); newdeck()={ v=vector(52,i,i); }; deal()={ my(n=name(v[1])); v=vecextract(v,2^#v-2); n }; printdeck(){ apply(name,v) }; shuffle()={ forstep(n=#v,2,-1, my(i=random(n)+1,t=v[i]); v[i]=v[n]; v[n]=t ); v };
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Nim
Nim
import bigints   var tmp1, tmp2, tmp3, acc, k = initBigInt(0) den, num, k2 = initBigInt(1)   proc extractDigit(): int32 = if num > acc: return -1   tmp3 = num shl 1 + num + acc tmp1 = tmp3 div den tmp2 = tmp3 mod den + num   if tmp2 >= den: return -1   result = int32(tmp1.limbs[0])   proc elimin...
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...
#PureBasic
PureBasic
  EnableExplicit   Procedure.i SumBinaryDigits(Number) If Number < 0 : number = -number : EndIf; convert negative numbers to positive Protected sum = 0 While Number > 0 sum + Number % 2 Number / 2 Wend ProcedureReturn sum EndProcedure   Procedure.i IsPrime(Number) If Number <= 1 ProcedureReturn...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Scala
Scala
val a = (1 to 10).toList   println(scala.util.Random.shuffle(a).head)
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln(rand([] ("foo", "bar", "baz"))); end func;
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Sidef
Sidef
var arr = %w(north east south west); say arr.rand; say arr.rand(2).dump;
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Wren
Wren
var s = "rosetta code phrase reversal" System.print("Input  : %(s)") System.print("String reversed  : %(s[-1..0])") System.print("Each word reversed  : %(s.split(" ").map { |w| w[-1..0] }.join(" "))") System.print("Word order reversed : %(s.split(" ")[-1..0].join(" "))")
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Yabasic
Yabasic
phrase$ = "Rosetta Code Phrase Reversal"   dim word$(1)   n = token(phrase$, word$())   print phrase$   for i = n to 1 step -1 print reverse$(word$(i)), " "; next   print   for i = n to 1 step -1 print word$(i), " "; next   print   for i = 1 to n print reverse$(word$(i)), " "; next   print   sub reverse$(w$...
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...
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigInt   var permute // recursive permute = Fn.new { |input| if (input.count == 1) return [input] var perms = [] var toInsert = input[0] for (perm in permute.call(input[1..-1])) { for (i in 0..perm.count) { var newPerm = perm.toList ...
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...
#Vedit_macro_language
Vedit macro language
Chdir("|(USER_MACRO)\Rosetta\data") File_Open("Lenna50.bmp", BROWSE) #10 = Buf_Num // #10 = buffer for 1st image File_Open("Lenna100.bmp", BROWSE) #20 = Buf_Num // #20 = buffer for 2nd image   Goto_Pos(10) // offset to pixel data Goto_Pos(Cur_Char + Cur_Char(1)*256) Buf_Switch(#10) Goto_Pos(10) Goto_Pos(Cur_...
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...
#F.23
F#
let perf n = n = List.fold (+) 0 (List.filter (fun i -> n % i = 0) [1..(n-1)])   for i in 1..10000 do if (perf i) then printfn "%i is perfect" i
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Erlang
Erlang
-module(permute). -export([permute/1]).   permute([]) -> [[]]; permute(L) -> [[X|Y] || X<-L, Y<-permute(L--[X])].
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Scala
Scala
object PerfectShuffle extends App { private def sizes = Seq(8, 24, 52, 100, 1020, 1024, 10000)   private def perfectShuffle(size: Int): Int = { require(size % 2 == 0, "Card deck must be even")   val (half, a) = (size / 2, Array.range(0, size)) val original = a.clone var count = 1 while (true) { ...
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 ...
#Scilab
Scilab
function New=PerfectShuffle(Nitems,Nturns) if modulo(Nitems,2)==0 then X=1:Nitems; for c=1:Nturns X=matrix(X,Nitems/2,2)'; X=X(:); end New=X'; end endfunction   Result=[]; Q=[8, 24, 52, 100, 1020, 1024, 10000]; for n=Q Same=0; T=0; Compare=[]; ...
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...
#Pascal
Pascal
package Playing_Card_Deck;   use strict;   @Playing_Card_Deck::suits = qw [Diamonds Clubs Hearts Spades]; @Playing_Card_Deck::pips = qw [Two Three Four Five Six Seven Eight Nine Ten Jack King Queen Ace]; # I choose to fully qualify these names rather than declare them # with "our" to keep them from escaping i...
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 ......
#OCaml
OCaml
open Creal;;   let block = 100 in let segment n = let s = to_string pi (n*block) in String.sub s ((n-1)*block) block in let counter = ref 1 in while true do print_string (segment !counter); flush stdout; incr counter done
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Python
Python
>>> def popcount(n): return bin(n).count("1")   >>> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61} >>> p, i = [], 0 >>> while len(p) < 25: if popcount(i) in primes: p.append(i) i += 1     >>> p [3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 31,...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Smalltalk
Smalltalk
x := #(1 2 3) atRandom.
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#SuperCollider
SuperCollider
[1, 2, 3].choose
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#zkl
zkl
zkl: var str="rosetta code phrase reversal" rosetta code phrase reversal   zkl: str.reverse() #1 lasrever esarhp edoc attesor   zkl: str.split().apply("reverse").concat(" ") #2 string to list to string attesor edoc esarhp lasrever   zkl: str.split().reverse().concat(" ") #3 reversal phrase code rosetta
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#zkl
zkl
fcn subFact(n){ if(n==0) return(1); if(n==1) return(0); (n-1)*(self.fcn(n-1) + self.fcn(n-2)); }   fcn derangements(n){ // All deranged permutations of the integers 0..n-1 inclusive enum:=[0..n-1].pump(List); Utils.Helpers.permuteW(enum).filter('wrap(perm){ perm.zipWith('==,enum).sum(0) == 0 ...
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...
#Wren
Wren
import "graphics" for Canvas, Color, ImageData import "dome" for Window   class PercentageDifference { construct new(width, height, image1, image2) { Window.title = "Perecentage difference between images" Window.resize(width, height) Canvas.resize(width, height) _img1 = ImageData.loa...
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...
#Factor
Factor
USING: kernel math math.primes.factors sequences ; IN: rosettacode.perfect-numbers   : perfect? ( n -- ? ) [ divisors sum ] [ 2 * ] bi = ;
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#FALSE
FALSE
[0\1[\$@$@-][\$@$@$@$@\/*=[@\$@+@@]?1+]#%=]p: 45p;!." "28p;!. { 0 -1 }
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Euphoria
Euphoria
function reverse(sequence s, integer first, integer last) object x while first < last do x = s[first] s[first] = s[last] s[last] = x first += 1 last -= 1 end while return s end function   function nextPermutation(sequence s) integer pos, last object x ...
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 ...
#Sidef
Sidef
func perfect_shuffle(deck) { deck/2 -> zip.flat }   [8, 24, 52, 100, 1020, 1024, 10000].each { |size| var deck = @(1..size) var shuffled = deck   var n = (1..Inf -> lazy.first { (shuffled = perfect_shuffle(shuffled)) == deck })   printf("%5d cards: %4d\n", size, n) }
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Swift
Swift
func perfectShuffle<T>(_ arr: [T]) -> [T]? { guard arr.count & 1 == 0 else { return nil }   let half = arr.count / 2 var res = [T]()   for i in 0..<half { res.append(arr[i]) res.append(arr[i + half]) }   return res }   let decks = [ Array(1...8), Array(1...24), Array(1...52), Array(1.....
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...
#Perl
Perl
package Playing_Card_Deck;   use strict;   @Playing_Card_Deck::suits = qw [Diamonds Clubs Hearts Spades]; @Playing_Card_Deck::pips = qw [Two Three Four Five Six Seven Eight Nine Ten Jack King Queen Ace]; # I choose to fully qualify these names rather than declare them # with "our" to keep them from escaping i...
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 ......
#Oforth
Oforth
: calcPiDigits | q r t k n l | 1 ->q 0 ->r 1 ->t 1 ->k 3 ->n 3 -> l   while( true ) [ 4 q * r + t - n t * < ifTrue: [ n print r n t * - 10 * 3 q * r + 10 * t / n 10 * - ->n ->r q 10 * ->q ] else: [ 2 q * r + l * 7 k * q * 2 + r l * + t l...
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...
#Quackery
Quackery
[ $ "rosetta/seive.qky" loadfile $ "rosetta/popcount.qky" loadfile ] now!   ( i.e. using the code at ) ( http://rosettacode.org/wiki/Sieve_of_Eratosthenes and ) ( http://rosettacode.org/wiki/Population_count )   29 eratosthenes ( Precompute as many p...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Swift
Swift
import Darwin   let myList = [1, 2, 4, 5, 62, 234, 1, -1] print(myList[Int(arc4random_uniform(UInt32(myList.count)))])
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Tcl
Tcl
proc randelem {list} { lindex $list [expr {int(rand()*[llength $list])}] } set x [randelem {1 2 3 4 5}]
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#zkl
zkl
fcn imageDiff(img1,img2){ if(img1.w!=img2.w or img1.h!=img2.h) throw(Exception.ValueError("width/height of the images must match!")); img1.data.howza(0).walker().zip(img2.data.howza(0)) // lazy bytes, not strings .reduce(fcn(totalDiff,[(a,b)]){ totalDiff + (a - b).abs() },0) .toFloat()/img1.w/img1.h/3...
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...
#Forth
Forth
: perfect? ( n -- ? ) 1 over 2/ 1+ 2 ?do over i mod 0= if i + then loop = ;
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Fortran
Fortran
FUNCTION isPerfect(n) LOGICAL :: isPerfect INTEGER, INTENT(IN) :: n INTEGER :: i, factorsum   isPerfect = .FALSE. factorsum = 1 DO i = 2, INT(SQRT(REAL(n))) IF(MOD(n, i) == 0) factorsum = factorsum + i + (n / i) END DO IF (factorsum == n) isPerfect = .TRUE. END FUNCTION isPerfect
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#F.23
F#
  let rec insert left x right = seq { match right with | [] -> yield left @ [x] | head :: tail -> yield left @ [x] @ right yield! insert (left @ [head]) x tail }   let rec perms permute = seq { match permute with | [] -> yield [] | head :: tail -> yield! Seq....
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 ...
#Tcl
Tcl
namespace eval shuffle {   proc perfect {deck} { if {[llength $deck]%2} { return -code error "Deck must be of even length!" } set split [expr {[llength $deck]/2}] set top [lrange $deck 0 $split-1] set btm [lrange $deck $split end] foreach a $top b $btm { ...
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...
#Phix
Phix
-- demo\rosetta\Playing_cards.exw function deal(sequence deck, integer nhands, integer ncards) sequence hands = repeat({},nhands) for n=1 to ncards do for h=1 to nhands do hands[h] &= deck[1] deck = deck[2..$] end for end for return {deck,hands} end function --consol...
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 ......
#Ol
Ol
  ; 'numbers' is count of numbers or #false for eternal pleasure. (define (pi numbers) (let loop ((q 1) (r 0) (t 1) (k 1) (n 3) (l 3) (numbers numbers)) (unless (eq? numbers 0) (if (< (- (+ (* 4 q) r) t) (* n t)) (begin (display n) (loop (* q 10) ...
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...
#Racket
Racket
#lang racket (require math/number-theory rnrs/arithmetic/bitwise-6)   (define pernicious? (compose prime? bitwise-bit-count))   (define (dnl . strs) (for-each displayln strs))   (define (show-sequence seq) (string-join (for/list ((v (in-values*-sequence seq))) (~a ((if (list? v) car values) v))) ", "))   (dnl "Tas...
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...
#Raku
Raku
sub is-pernicious(Int $n --> Bool) { is-prime [+] $n.base(2).comb; }   say (grep &is-pernicious, 0 .. *)[^25]; say grep &is-pernicious, 888_888_877 .. 888_888_888;
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT list="John'Paul'George'Ringo'Peter'Paul'Mary'Obama'Putin" sizeList=SIZE(list) selectedNr=RANDOM_NUMBERS (1,sizeList,1) selectedItem=SELECT(list,#selectednr) PRINT "Selecting term ",selectedNr," in the list, which was ",selectedItem
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#TXR
TXR
@(do (defun randelem (seq) [seq (random nil (length seq))])) @(bind x @(randelem #("a" "b" "c" "d")))
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#UNIX_Shell
UNIX Shell
list=(these are some words) printf '%s\n' "${list[RANDOM%${#list[@]}]}"
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPerfect(n As Integer) As Boolean If n < 2 Then Return False If n Mod 2 = 1 Then Return False '' we can assume odd numbers are not perfect Dim As Integer sum = 1, q For i As Integer = 2 To Sqr(n) If n Mod i = 0 Then sum += i q = n \ i If q > i Then sum...
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...
#Factor
Factor
program permutations   implicit none integer, parameter :: value_min = 1 integer, parameter :: value_max = 3 integer, parameter :: position_min = value_min integer, parameter :: position_max = value_max integer, dimension (position_min : position_max) :: permutation   call generate (position_min)   contai...
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 ...
#VBA
VBA
Option Explicit   Sub Main() Dim T, Arr, X As Long, C As Long Arr = Array(8, 24, 52, 100, 1020, 1024, 10000) For X = LBound(Arr) To UBound(Arr) C = 0 Call PerfectShuffle(T, CLng(Arr(X)), C) Debug.Print Right(String(19, " ") & "For " & Arr(X) & " cards => ", 19) & C & " shuffles needed." Er...
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...
#PHP
PHP
class Card { // if unable to save as UTF-8, use other, non-UTF-8, symbols here protected static $suits = array( '♠', '♥', '♦', '♣' );   protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );   protected $suit;   protected $suitOrder;   protected $pip; ...
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 ......
#PARI.2FGP
PARI/GP
pi()={ my(x=Pi,n=0,t); print1("3."); while(1, if(n>=default(realprecision), default(realprecision,default(realprecision)*2); x=Pi ); print1(floor(x*10^n++)%10) ) };
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#REXX
REXX
╔════════════════════════════════════════════════════════════════════════════════════════╗ ╠═════ How the ─── popCount ─── function works (working from the inner─most level): ═════╣ ║ ║ ║ arg(1) obtains the value of the 1st argum...
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...
#Ring
Ring
  # Project : Pernicious numbers   see "The first 25 pernicious numbers:" + nl nr = 0 for n=1 to 50 sum = 0 str = decimaltobase(n, 2) for m=1 to len(str) if str[m] = "1" sum = sum + 1 ok next if isprime(sum) nr = nr + 1 see "" + n + " " ok if nr = 25 ...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Ursa
Ursa
# generate a stream (ursa equivalent of a list) decl string<> str append "these" "are" "some" "values" str   decl ursa.util.random r out str<(r.getint (size str))> endl console
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#VBA
VBA
  Option Explicit   Sub Main_Pick_Random_Element() Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty")) End Sub   Function Pick_Random_Element(myArray) Randomize Timer Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray)))) End Function ...
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Frink
Frink
isPerfect = {|n| sum[allFactors[n, true, false]] == n} println[select[1 to 1000, isPerfect]]
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#FunL
FunL
def perfect( n ) = sum( d | d <- 1..n if d|n ) == 2n   println( (1..500).filter(perfect) )
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Fortran
Fortran
program permutations   implicit none integer, parameter :: value_min = 1 integer, parameter :: value_max = 3 integer, parameter :: position_min = value_min integer, parameter :: position_max = value_max integer, dimension (position_min : position_max) :: permutation   call generate (position_min)   contai...