task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#C
C
#include<stdlib.h> #include<stdio.h>   long totient(long n){ long tot = n,i;   for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; }   if(i==2) i=1; }   if(n>1) tot-=tot/n;   return tot; }   long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,s...
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...
#E
E
defmodule Card do defstruct pip: nil, suit: nil end   defmodule Playing_cards do @pips ~w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]a @suits ~w[Clubs Hearts Spades Diamonds]a @pip_value Enum.with_index(@pips) @suit_value Enum.with_index(@suits)   def deal( n_cards, deck ), do: Enum.split( deck, n_cards )...
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 ......
#D
D
import std.stdio, std.conv, std.string;   struct PiDigits { immutable uint nDigits;   int opApply(int delegate(ref string /*chunk of pi digit*/) dg){ // Maximum width for correct output, for type ulong. enum size_t width = 9;   enum ulong scale = 10UL ^^ width; enum ulong initDig...
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Python
Python
  def perta(atomic) -> (int, int):   NOBLES = 2, 10, 18, 36, 54, 86, 118 INTERTWINED = 0, 0, 0, 0, 0, 57, 89 INTERTWINING_SIZE = 14 LINE_WIDTH = 18   prev_noble = 0 for row, noble in enumerate(NOBLES): if atomic <= noble: # we are at the good row. We now need to determine the column ...
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...
#Julia
Julia
  type PigPlayer name::String score::Int strat::Function end   function PigPlayer(a::String) PigPlayer(a, 0, pig_manual) end   function scoreboard(pps::Array{PigPlayer,1}) join(map(x->@sprintf("%s has %d", x.name, x.score), pps), " | ") end   function pig_manual(pps::Array{PigPlayer,1}, pdex::Intege...
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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make -- Test of is_pernicious_number. local test: LINKED_LIST [INTEGER] i: INTEGER do create test.make from i := 1 until test.count = 25 loop if is_pernicious_number (i) then test.extend (i) end i := i + 1 end acros...
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
Permutations/Rank of a permutation
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers 0.. ( n − 1 ) {\disp...
#Tcl
Tcl
# A functional swap routine proc swap {v idx1 idx2} { lset v $idx2 [lindex $v $idx1][lset v $idx1 [lindex $v $idx2];subst ""] }   # Fill the integer array <vec> with the permutation at rank <rank> proc computePermutation {vecName rank} { upvar 1 $vecName vec if {![info exist vec] || ![llength $vec]} return ...
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...
#Python
Python
import random   # Copied from https://rosettacode.org/wiki/Miller-Rabin_primality_test#Python def is_Prime(n): """ Miller-Rabin primality test.   A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. """ if n!=int(n): return False ...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Gambas
Gambas
Public Sub Main() Dim sList As String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]   Print sList[Rand(0, 11)]   End
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#GAP
GAP
a := [2, 9, 4, 7, 5, 3]; Random(a);
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#VBScript
VBScript
Function IsPrime(n) If n = 2 Then IsPrime = True ElseIf n <= 1 Or n Mod 2 = 0 Then IsPrime = False Else IsPrime = True For i = 3 To Int(Sqr(n)) Step 2 If n Mod i = 0 Then IsPrime = False Exit For End If Next End If End Function   For n = 1 To 50 If IsPrime(n) Then WScript.StdOut.Write n &...
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...
#Go
Go
package main   import ( "fmt" "strings" )   const phrase = "rosetta code phrase reversal"   func revStr(s string) string { rs := make([]rune, len(s)) i := len(s) for _, r := range s { i-- rs[i] = r } return string(rs[i:]) }   func main() { fmt.Println("Reversed: ", revStr(phrase))   ws := strings...
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...
#Elixir
Elixir
defmodule Permutation do def derangements(n) do list = Enum.to_list(1..n) Enum.filter(permutation(list), fn perm -> Enum.zip(list, perm) |> Enum.all?(fn {a,b} -> a != b end) end) end   def subfact(0), do: 1 def subfact(1), do: 0 def subfact(n), do: (n-1) * (subfact(n-1) + subfact(n-2))   d...
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 ...
#Forth
Forth
S" fsl-util.fs" REQUIRED S" fsl/dynmem.seq" REQUIRED   cell darray p{   : sgn DUP 0 > IF DROP 1 ELSE 0 < IF -1 ELSE 0 THEN THEN ; : arr-swap {: addr1 addr2 | tmp -- :} addr1 @ TO tmp addr2 @ addr1 ! tmp addr2 ! ; : perms {: n xt | my-i k s -- :} & p{ n 1+ }malloc malloc-fail? ABORT" perms ::...
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 ...
#FreeBASIC
FreeBASIC
' version 31-03-2017 ' compile with: fbc -s console   Sub perms(n As ULong)   Dim As Long p(n), i, k, s = 1   For i = 1 To n p(i) = -i Next   Do Print "Perm: [ "; For i = 1 To n Print Abs(p(i)); " "; Next Print "] Sign: "; s   k = 0 For...
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...
#J
J
require'stats' trmt=: 0.85 0.88 0.75 0.66 0.25 0.29 0.83 0.39 0.97 ctrl=: 0.68 0.41 0.1 0.49 0.16 0.65 0.32 0.92 0.28 0.98 difm=: -&mean result=: trmt difm ctrl all=: trmt(#@[ ({. difm }.) |:@([ (comb ~.@,"1 i.@])&# ,) { ,) ctrl smoutput 'under: ','%',~":100*mean all <: result smoutput 'over: ','%',~":100*mean all > r...
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...
#Java
Java
public class PermutationTest { private static final int[] data = new int[]{ 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };   private static int pick(int at, int remain, int accu, int treat) { if (remain == 0) return (accu > treat) ? 1 : 0; retur...
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...
#Ada
Ada
type Count is mod 2**64;
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...
#D
D
import std.stdio, std.algorithm, std.random, std.math, std.array, std.range, std.ascii;   alias Cell = ubyte; alias Grid = Cell[][]; enum Cell notClustered = 1; // Filled cell, but not in a cluster.   Grid initialize(Grid grid, in double prob, ref Xorshift rng) nothrow { foreach (row; grid) foreach (...
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...
#360_Assembly
360 Assembly
* Perfect numbers 15/05/2016 PERFECTN CSECT USING PERFECTN,R13 prolog SAVEAREA B STM-SAVEAREA(R15) " DC 17F'0' " STM STM R14,R12,12(R13) " ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 ...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   // cell states #define FILL 1 #define RWALL 2 // right wall #define BWALL 4 // bottom wall   typedef unsigned int c_t;   c_t *cells, *start, *end; int m, n;   void make_grid(double p, int x, int y) { int i, j, thresh = RAND_MAX * p; m = x, n = y;   ...
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...
#EchoLisp
EchoLisp
  ;; count 1-runs - The vector is not stored (define (runs p n) (define ct 0) (define run-1 #t) (for ([i n]) (if (< (random) p) (set! run-1 #t) ;; 0 case (begin ;; 1 case (when run-1 (set! ct (1+ ct))) (set! run-1 #f)))) (// ct n))   ;; mean of t counts (define (t...
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...
#FreeBASIC
FreeBASIC
#define SOLID "#" #define EMPTY " " #define WET "v"   Dim Shared As String grid() Dim Shared As Integer last, lastrow, m, n   Sub make_grid(x As Integer, y As Integer, p As Double) m = x n = y Redim Preserve grid(x*(y+1)+1) last = Len(grid) Dim As Integer lastrow = last-n Dim As Integer i, j  ...
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...
#ABAP
ABAP
data: lv_flag type c, lv_number type i, lt_numbers type table of i.   append 1 to lt_numbers. append 2 to lt_numbers. append 3 to lt_numbers.   do. perform permute using lt_numbers changing lv_flag. if lv_flag = 'X'. exit. endif. loop at lt_numbers into lv_number. write (1) lv_number no-gap ...
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 ...
#APL
APL
faro ← ∊∘⍉(2,2÷⍨≢)⍴⊢ count ← {⍺←⍵ ⋄ ⍺≡r←⍺⍺ ⍵:1 ⋄ 1+⍺∇r} (⊢,[1.5] (faro count ⍳)¨) 8 24 52 100 1020 1024 10000
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 ...
#Arturo
Arturo
perfectShuffle: function [deckSize][ deck: 1..deckSize original: new deck halfDeck: deckSize/2   i: 1 while [true][ deck: flatten couple first.n: halfDeck deck last.n: halfDeck deck if deck = original -> return i i: i+1 ] ]   loop [8 24 52 100 1020 1024 10000] 's -> p...
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 ...
#Fortran
Fortran
  PROGRAM PERLIN IMPLICIT NONE INTEGER :: i INTEGER, DIMENSION(0:511) :: p INTEGER, DIMENSION(0:255), PARAMETER :: 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...
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
#C.2B.2B
C++
#include <cassert> #include <iostream> #include <vector>   class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) conti...
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...
#Elixir
Elixir
defmodule Card do defstruct pip: nil, suit: nil end   defmodule Playing_cards do @pips ~w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]a @suits ~w[Clubs Hearts Spades Diamonds]a @pip_value Enum.with_index(@pips) @suit_value Enum.with_index(@suits)   def deal( n_cards, deck ), do: Enum.split( deck, n_cards )...
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 ......
#Delphi
Delphi
  unit Pi_BBC_Main;   interface   uses Classes, Controls, Forms, Dialogs, StdCtrls;   type TForm1 = class(TForm) btnRunSpigotAlgo: TButton; memScreen: TMemo; procedure btnRunSpigotAlgoClick(Sender: TObject); procedure FormCreate(Sender: TObject); private fScreenWidth : integer; fLineBuffer...
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Raku
Raku
my $b = 18; my @offset = 16, 10, 10, (2×$b)+1, (-2×$b)-15, (2×$b)+1, (-2×$b)-15; my @span = flat ^8 Zxx <1 3 8 44 15 17 15 15>;   for <1 2 29 42 57 58 72 89 90 103> -> $n { printf "%3d: %2d, %2d\n", $n, map {$_+1}, ($n-1 + [+] @offset.head(@span[$n-1])).polymod($b).reverse; }
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Wren
Wren
import "./fmt" for Fmt   var limits = [3..10, 11..18, 19..36, 37..54, 55..86, 87..118]   var periodicTable = Fn.new { |n| if (n < 1 || n > 118) Fiber.abort("Atomic number is out of range.") if (n == 1) return [1, 1] if (n == 2) return [1, 18] if (n >= 57 && n <= 71) return [8, n - 53] if (n >= 89 &...
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...
#Kotlin
Kotlin
// version 1.1.2   fun main(Args: Array<String>) { print("Player 1 - Enter your name : ") val name1 = readLine()!!.trim().let { if (it == "") "PLAYER 1" else it.toUpperCase() } print("Player 2 - Enter your name : ") val name2 = readLine()!!.trim().let { if (it == "") "PLAYER 2" else it.toUpperCase() } ...
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...
#Elixir
Elixir
  defmodule SieveofEratosthenes do def init(lim) do find_primes(2,lim,(2..lim)) end   def find_primes(count,lim,nums) when (count * count) > lim do nums end   def find_primes(count,lim,nums) when (count * count) <= lim do e = Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count)) find_primes(c...
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
Permutations/Rank of a permutation
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers 0.. ( n − 1 ) {\disp...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var swap = Fn.new { |a, i, j| var t = a[i] a[i] = a[j] a[j] = t }   var mrUnrank1 // recursive mrUnrank1 = Fn.new { |rank, n, vec| if (n < 1) return var q = (rank/n).floor var r = rank % n swap.call(vec, r, n - 1) mrUnrank1.call(q, n - 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...
#Quackery
Quackery
[ stack ] is pierponts [ stack ] is kind [ stack ] is quantity   [ 1 - -2 * 1+ kind put 1+ quantity put ' [ -1 ] pierponts put ' [ 2 3 ] smoothwith [ -1 peek kind share + dup isprime not iff [ drop false ] done pierponts share -1 peek over = iff ...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}   func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(list[rand.Intn(len(list))]) }
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Groovy
Groovy
def list = [25, 30, 1, 450, 3, 78] def random = new Random();   (0..3).each { def i = random.nextInt(list.size()) println "list[${i}] == ${list[i]}" }
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Wren
Wren
import "/fmt" for Fmt   var isPrime = Fn.new { |n| if (n < 2) return false if (n%2 == 0) return n == 2 var p = 3 while (p * p <= n) { if (n%p == 0) return false p = p + 2 } return true }   var tests = [2, 5, 12, 19, 57, 61, 97] System.print("Are the following prime?") for (test i...
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Groovy
Groovy
def phaseReverse = { text, closure -> closure(text.split(/ /)).join(' ')}   def text = 'rosetta code phrase reversal' println "Original: $text" println "Reversed: ${phaseReverse(text) { it.reverse().collect { it.reverse() } } }" println "Reversed Words: ${phaseReverse(text) { it.collect { it.reverse() } } }...
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#F.23
F#
  // Generate derangements. Nigel Galloway: July 9th., 2019 let derange n= let fG n i g=let e=Array.copy n in e.[i]<-n.[g]; e.[g]<-n.[i]; e let rec derange n g α=seq{ match (α>0,n&&&(1<<<α)=0) with (true,true)->for i in [0..α-1] do if n&&&(1<<<i)=0 then let g=(fG g α i) in yield! derange (n+(1<<<i)) g (α-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 ...
#Go
Go
package permute   // Iter takes a slice p and returns an iterator function. The iterator // permutes p in place and returns the sign. After all permutations have // been generated, the iterator returns 0 and p is left in its initial order. func Iter(p []int) func() int { f := pf(len(p)) return func() int { ...
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...
#jq
jq
# combination(r) generates a stream of combinations of r items from the input array. def combination(r): if r > length or r < 0 then empty elif r == length then . else ( [.[0]] + (.[1:]|combination(r-1))), ( .[1:]|combination(r)) end;  
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...
#Julia
Julia
using Combinatorics   meandiff(a::Vector{T}, b::Vector{T}) where T <: Real = mean(a) - mean(b)   function bifurcate(a::AbstractVector, sel::Vector{T}) where T <: Integer x = a[sel] asel = trues(length(a)) asel[sel] = false y = a[asel] return x, y end   function permutation_test(...
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...
#Kotlin
Kotlin
// version 1.1.2   val data = intArrayOf( 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 )   fun pick(at: Int, remain: Int, accu: Int, treat: Int): Int { if (remain == 0) return if (accu > treat) 1 else 0 return pick(at - 1, remain - 1, accu + data[at - 1], treat) + ...
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...
#AutoHotkey
AutoHotkey
startup() dibSection := getPixels("lenna100.jpg") dibSection2 := getPixels("lenna50.jpg") ; ("File-Lenna100.jpg") pixels := dibSection.pBits pixels2 := dibSection2.pBits z := 0 loop % dibSection.width * dibSection.height * 4 { x := numget(pixels - 1, A_Index, "uchar") y := numget(pixels2 - 1, A_Index, "uchar") z += ab...
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...
#EchoLisp
EchoLisp
  (define-constant BLACK (rgb 0 0 0.6)) (define-constant WHITE -1) ;; sets pixels to clusterize to WHITE ;; returns bit-map vector (define (init-C n p ) (plot-size n n) (define C (pixels->int32-vector )) ;; get canvas bit-map (pixels-map (lambda (x y) (if (< (random) p) WHITE BLACK )) C) C )   ;; rando...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program perfectNumber64.s */ /* use Euclide Formula : if M=(2puis p)-1 is prime M * (M+1)/2 is perfect see Wikipedia */ /*******************************************/ /* Constantes file */ /*******************************************/ /* for thi...
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...
#C.2B.2B
C++
#include <cstdlib> #include <cstring> #include <iostream> #include <string>   using namespace std;   class Grid { public: Grid(const double p, const int x, const int y) : m(x), n(y) { const int thresh = static_cast<int>(RAND_MAX * p);   // Allocate two addition rows to avoid checking bounds. ...
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...
#Factor
Factor
USING: formatting fry io kernel math math.ranges math.statistics random sequences ; IN: rosetta-code.mean-run-density   : rising? ( ? ? -- ? ) [ f = ] [ t = ] bi* and ;   : count-run ( n ? ? -- m ? ) 2dup rising? [ [ 1 + ] 2dip ] when nip ;   : runs ( n p -- n ) [ 0 f ] 2dip '[ random-unit _ < count-run ] times...
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...
#Fortran
Fortran
  ! loosely translated from python. We do not need to generate and store the entire vector at once. ! compilation: gfortran -Wall -std=f2008 -o thisfile thisfile.f08   program percolation_mean_run_density implicit none integer :: i, p10, n2, n, t real :: p, limit, sim, delta data n,p,t/100,0.5,500/ write(6,'...
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...
#Go
Go
package main   import ( "bytes" "fmt" "math/rand" "time" )   func main() { const ( m, n = 15, 15 t = 1e4 minp, maxp, Δp = 0, 1, 0.1 )   rand.Seed(2) // Fixed seed for repeatable example grid g := NewGrid(.5, m, n) g.Percolate() fmt.Println(g)   rand.Seed(time.Now().UnixNano()) //...
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...
#Action.21
Action!
PROC PrintArray(BYTE ARRAY a BYTE len) BYTE i   FOR i=0 TO len-1 DO PrintB(a(i)) OD Print(" ") RETURN   BYTE FUNC NextPermutation(BYTE ARRAY a BYTE len) BYTE i,j,k,tmp   i=len-1 WHILE i>0 AND a(i-1)>a(i) DO i==-1 OD   j=i k=len-1 WHILE j<k DO tmp=a(j) a(j)=a(k) a(k)=tmp j==+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 ...
#AutoHotkey
AutoHotkey
Shuffle(cards){ n := cards.MaxIndex()/2, res := [] loop % n res.push(cards[A_Index]), res.push(cards[round(A_Index + n)]) return res }
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 ...
#C
C
/* ===> INCLUDES <============================================================*/ #include <stdlib.h> #include <stdio.h> #include <string.h>   /* ===> CONSTANTS <===========================================================*/ #define N_DECKS 7 const int kDecks[N_DECKS] = { 8, 24, 52, 100, 1020, 1024, 10000 };   /* ===> FU...
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 ...
#FreeBASIC
FreeBASIC
  #define floor(x) ((x*2.0-0.5) Shr 1) Dim Shared As Byte p(256) => { _ 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, 8...
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
#CLU
CLU
gcd = proc (a, b: int) returns (int) while b ~= 0 do a, b := b, a//b end return(a) end gcd   totient = proc (n: int) returns (int) tot: int := 0 for i: int in int$from_to(1,n-1) do if gcd(n,i)=1 then tot := tot + 1 end end return(tot) end totient   perfect = proc (n: int) ret...
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
#Cowgol
Cowgol
include "cowgol.coh";   sub gcd(a: uint16, b: uint16): (r: uint16) is while b != 0 loop r := a; a := b; b := r % b; end loop; r := a; end sub;   sub totient(n: uint16): (tot: uint16) is var i: uint16 := 1; tot := 0; while i < n loop if gcd(n,i) == 1 then ...
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
#Delphi
Delphi
  program Perfect_totient_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function totient(n: Integer): Integer; begin var tot := n; var i := 2; while i * i <= n do begin if (n mod i) = 0 then begin while (n mod i) = 0 do n := n div i; dec(tot, tot div i); end; if i...
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...
#Erlang
Erlang
  -module( playing_cards ).   -export( [deal/2, deal/3, deck/0, print/1, shuffle/1, sort_pips/1, sort_suites/1, task/0] ).   -record( card, {pip, suite} ).   -spec( deal( N_cards::integer(), Deck::[#card{}]) -> {Hand::[#card{}], Deck::[#card{}]} ). deal( N_cards, Deck ) -> lists:split( N_cards, Deck ). -spec( deal( N_h...
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 ......
#EDSAC_order_code
EDSAC order code
  [EDSAC program, Initial Orders 2. Calculates digits of pi by spigot algorithm. Easily edited to calculate digits of e (see "if pi" and "if e" in comments). Based on http://pi314.net/eng/goutte.php See also https://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml   Uses 17-bit values throughout. Arra...
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#XPL0
XPL0
proc ShowPosn(N); \Show row and column for element int N, M, A, B, I, R, C; [A:= [ 1, 2, 5, 13, 57, 72, 89, 104]; \magic numbers B:= [-1, 15, 25, 35, 72, 21, 58, 7]; I:= 7; while A(I) > N do I:= I-1; M:= N + B(I); R:= M/18 +1; C:= rem(0) +1; IntOut(0, N); Text(0, " -> "); IntOut(0, R); Text(0, ", "); IntO...
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...
#Lua
Lua
local numPlayers = 2 local maxScore = 100 local scores = { } for i = 1, numPlayers do scores[i] = 0 -- total safe score for each player end math.randomseed(os.time()) print("Enter a letter: [h]old or [r]oll?") local points = 0 -- points accumulated in current turn local p = 1 -- start with first player while true do ...
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.23
F#
open System   //Taken from https://gist.github.com/rmunn/bc49d32a586cdfa5bcab1c3e7b45d7ac let bitcount (n : int) = let count2 = n - ((n >>> 1) &&& 0x55555555) let count4 = (count2 &&& 0x33333333) + ((count2 >>> 2) &&& 0x33333333) let count8 = (count4 + (count4 >>> 4)) &&& 0x0f0f0f0f (count8 * 0x01010101...
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
Permutations/Rank of a permutation
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers 0.. ( n − 1 ) {\disp...
#zkl
zkl
fcn computePermutation(items,rank){ // in place permutation of items foreach n in ([items.len()..1,-1]){ r:=rank%n; rank/=n; items.swap(r,n-1); } items }
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...
#Raku
Raku
use ntheory:from<Perl5> <is_prime>;   sub pierpont ($kind is copy = 1) { fail "Unknown type: $kind. Must be one of 1 (default) or 2" if $kind !== 1|2; $kind = -1 if $kind == 2; my $po3 = 3; my $add-one = 3; my @iterators = [1,2,4,8 … *].iterator, [3,9,27 … *].iterator; my @head = @iterators».pul...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#GW-BASIC
GW-BASIC
10 RANDOMIZE TIMER  : REM set random number seed to something arbitrary 20 DIM ARR(10)  : REM initialise array 30 FOR I = 1 TO 10 40 ARR(I) = I*I  : REM squares of the integers is OK as a demo 50 NEXT I 60 C = 1 + INT(RND*10)  : REM get a random index from 1 to 10 inclusive 70 PRINT ARR(...
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#XPL0
XPL0
func Prime(N); \Return 'true' if N is a prime number int N; int I; [if N <= 1 then return false; for I:= 2 to sqrt(N) do if rem(N/I) = 0 then return false; return true; ];   int Num; repeat Num:= IntIn(0); Text(0, if Prime(Num) then "is " else "not "); Text(0, "prime^M^J"); until ...
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...
#Haskell
Haskell
reverseString, reverseEachWord, reverseWordOrder :: String -> String reverseString = reverse   reverseEachWord = wordLevel (fmap reverse)   reverseWordOrder = wordLevel reverse   wordLevel :: ([String] -> [String]) -> String -> String wordLevel f = unwords . f . words   main :: IO () main = (putStrLn . unlines) $ [...
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...
#Factor
Factor
USING: combinators formatting io kernel math math.combinatorics prettyprint sequences ; IN: rosetta-code.derangements   : !n ( n -- m ) { { 0 [ 1 ] } { 1 [ 0 ] } [ [ 1 - !n ] [ 2 - !n + ] [ 1 - * ] tri ] } case ;   : derangements ( n -- seq ) <iota> dup [ [ = ] 2map [ f = ] all? ] wi...
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 ...
#Haskell
Haskell
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [-1, 1]) . foldr aux [[]] where aux x items = do (f, item) <- zip (repeat id) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x : l) : ((y :) <$> insertEv x ys)   main :: IO () main = do putStrLn "3 i...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Global data(), treat=0 data()=(85, 88, 75, 66, 25, 29, 83, 39, 97,68, 41, 10, 49, 16, 65, 32, 92, 28, 98) Function pick(at, remain, accu) { If remain Else =If(accu>treat->1,0):Exit =pick(at-1,remain-1,accu+data(at-1))+If(at>remain->pick(at-1, remain, accu),0)...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
"<=: " <> ToString[#1] <> " " <> ToString[100. #1/#2] <> "%\n >: " <> ToString[#2 - #1] <> " " <> ToString[100. (1 - #1/#2)] <> "%" &[ Count[Total /@ Subsets[Join[#1, #2], {Length@#1}], n_ /; n <= Total@#1], Binomial[Length@#1 + Length@#2, Length@#1]] &[{85, 88, 75, 66, 25, 29, 83, 39, 97}, {68, 41...
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...
#BBC_BASIC
BBC BASIC
hbm1% = FNloadimage("C:lenna50.jpg") hbm2% = FNloadimage("C:lenna100.jpg")   SYS "CreateCompatibleDC", @memhdc% TO hdc1% SYS "CreateCompatibleDC", @memhdc% TO hdc2%   SYS "SelectObject", hdc1%, hbm1% SYS "SelectObject", hdc2%, hbm2%   diff% = 0 FOR y% = 0 TO 511 F...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> /* #include "imglib.h" */   #define RED_C 0 #define GREEN_C 1 #define BLUE_C 2 #define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])   int main(int argc, char **argv) { image im1, im2; double totalDiff = 0.0; unsigned int x, y;   if ( ...
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...
#Factor
Factor
USING: combinators formatting generalizations kernel math math.matrices random sequences ; IN: rosetta-code.mean-cluster-density   CONSTANT: p 0.5 CONSTANT: iterations 5   : rand-bit-matrix ( n probability -- matrix ) dupd [ random-unit > 1 0 ? ] curry make-matrix ;   : flood-fill ( x y matrix -- ) 3dup ?nth ?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...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   var ( n_range = []int{4, 64, 256, 1024, 4096} M = 15 N = 15 )   const ( p = .5 t = 5 NOT_CLUSTERED = 1 cell2char = " #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" )   func newgri...
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...
#Action.21
Action!
PROC Main() DEFINE MAXNUM="10000" CARD ARRAY pds(MAXNUM+1) CARD i,j   FOR i=2 TO MAXNUM DO pds(i)=1 OD FOR i=2 TO MAXNUM DO FOR j=i+i TO MAXNUM STEP i DO pds(j)==+i OD OD   FOR i=2 TO MAXNUM DO IF pds(i)=i THEN PrintCE(i) FI OD RETURN
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...
#D
D
import std.stdio, std.random, std.array, std.range, std.algorithm;   struct Grid { // Not enforced by runtime and type system: // a Cell must contain only the flags bits. alias Cell = uint;   enum : Cell { // Cell states (bit flags). empty = 0, filled = 1, rightWall = 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...
#FreeBASIC
FreeBASIC
Function run_test(p As Double, longitud As Integer, runs As Integer) As Double Dim As Integer r, l, cont = 0 Dim As Integer v, pv   For r = 1 To runs pv = 0 For l = 1 To longitud v = Rnd < p cont += Iif(pv < v, 1, 0) pv = v Next l Next r Re...
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...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Monad.Random import Data.Array.Unboxed import Data.List import Formatting   type Field = UArray (Int, Int) Char   -- Start percolating some seepage through a field. -- Recurse to continue percolation with new seepage. percolateR :: [(Int, Int)] -> F...
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...
#Ada
Ada
generic N: positive; package Generic_Perm is subtype Element is Positive range 1 .. N; type Permutation is array(Element) of Element;   procedure Set_To_First(P: out Permutation; Is_Last: out Boolean); procedure Go_To_Next(P: in out Permutation; Is_Last: out Boolean); end Generic_Perm;
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 ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class PerfectShuffle { static void Main() { foreach (int input in new [] {8, 24, 52, 100, 1020, 1024, 10000}) { int[] numbers = Enumerable.Range(1, input).ToArray(); Console.WriteLine($"{input} car...
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 ...
#GLSL
GLSL
  float rand(vec2 c){ return fract(sin(dot(c.xy ,vec2(12.9898,78.233))) * 43758.5453); }   float noise(vec2 p, float freq ){ float unit = screenWidth/freq; vec2 ij = floor(p/unit); vec2 xy = mod(p,unit)/unit; //xy = 3.*xy*xy-2.*xy*xy*xy; xy = .5*(1.-cos(PI*xy)); float a = rand((ij+vec2(0.,0.))); float b = rand(...
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
#Draco
Draco
proc nonrec gcd(word a, b) word: word c; while b ~= 0 do c := a; a := b; b := c % b od; a corp   proc nonrec totient(word n) word: word r, i; r := 0; for i from 1 upto n-1 do if gcd(n,i) = 1 then r := r+1 fi od; r corp   proc nonrec perfect(word n) bo...
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
#Factor
Factor
USING: formatting kernel lists lists.lazy math math.primes.factors ;   : perfect? ( n -- ? ) [ 0 ] dip dup [ dup 2 < ] [ totient tuck [ + ] 2dip ] until drop = ;   20 1 lfrom [ perfect? ] lfilter ltake list>array "%[%d, %]\n" printf
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...
#Factor
Factor
USING: formatting grouping io kernel math qw random sequences vectors ; IN: rosetta-code.playing-cards   CONSTANT: pips qw{ A 2 3 4 5 6 7 8 9 10 J Q K } CONSTANT: suits qw{ ♥ ♣ ♦ ♠ }   : <deck> ( -- vec ) 52 <iota> >vector ;   : card>str ( n -- str ) 13 /mod [ suits nth ] [ pips nth ] bi* prepend ;   : print-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 ......
#Elixir
Elixir
defmodule Pi do def calc, do: calc(1,0,1,1,3,3,0)   defp calc(q,r,t,k,n,l,c) when c==50 do IO.write "\n" calc(q,r,t,k,n,l,0) end defp calc(q,r,t,k,n,l,c) when (4*q + r - t) < n*t do IO.write n calc(q*10, 10*(r-n*t), t, k, div(10*(3*q+r), t) - 10*n, l, c+1) end defp calc(q,r,t,k,_n,l,c) do ...
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...
#M2000_Interpreter
M2000 Interpreter
  Module GamePig { Print "Game of Pig" dice=-1 res$="" Player1points=0 Player1sum=0 Player2points=0 Player2sum=0 HaveWin=False score() \\ for simulation, feed the keyboard buffer with R and H simulate$=String$("R", 500) For i=1 to 100 I...
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Factor
Factor
USING: lists lists.lazy math.bitwise math.primes math.ranges prettyprint sequences ;   : pernicious? ( n -- ? ) bit-count prime? ;   25 0 lfrom [ pernicious? ] lfilter ltake list>array .  ! print first 25 pernicious numbers 888,888,877 888,888,888 [a,b] [ pernicious? ] filter .  ! print pernicious numbers in range
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...
#REXX
REXX
/*REXX program finds and displays Pierpont primes of the first and second kinds. */ parse arg n . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/ numeric digits n ...
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Hare
Hare
use fmt; use math::random; use datetime;   export fn main() void = { const array = ["one", "two", "three", "four", "five"]; const seed = datetime::now(); const seed = datetime::nsec(&seed); let r = math::random::init(seed: u32);   fmt::printfln("{}", array[math::random::u32n(&r, len(array): u32)])!; };
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Haskell
Haskell
import System.Random (randomRIO)   pick :: [a] -> IO a pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1)   x <- pick [1, 2, 3]
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Yabasic
Yabasic
for i = 1 to 99 if isPrime(i) print str$(i), " "; next i print end   sub isPrime(v) if v < 2 return False if mod(v, 2) = 0 return v = 2 if mod(v, 3) = 0 return v = 3 d = 5 while d * d <= v if mod(v, d) = 0 then return False else d = d + 2 : fi wend return True end sub
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...
#IS-BASIC
IS-BASIC
100 PROGRAM "ReverseS.bas" 110 LET S$="Rosetta Code Pharse Reversal" 120 PRINT S$ 130 PRINT REVERSE$(S$) 140 PRINT REVERSEW$(S$) 150 PRINT REVERSEC$(S$) 160 DEF REVERSE$(S$) 170 LET T$="" 180 FOR I=LEN(S$) TO 1 STEP-1 190 LET T$=T$&S$(I) 200 NEXT 210 LET REVERSE$=T$ 220 END DEF 230 DEF REVERSEW$(S$) 240 L...
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#J
J
getWords=: (' '&splitstring) :. (' '&joinstring) reverseString=: |. reverseWords=: |.&.>&.getWords reverseWordOrder=: |.&.getWords
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...
#FreeBASIC
FreeBASIC
' version 08-04-2017 ' compile with: fbc -s console   Sub Subfactorial(a() As ULongInt)   Dim As ULong i Dim As ULongInt num   For i = 0 To UBound(a) num = num * i If (i And 1) = 1 Then num -= 1 Else num += 1 End If a(i) = num Next   End Su...
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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every write("Permutations of length ",n := !A) do every p := permute(n) do write("\t",showList(p[1])," -> ",right(p[2],2)) end   procedure permute(n) items := [[]] every (j := 1 to n, new_items := []) do { every item := items[i := 1 to *items] do { if *item = 0 t...
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...
#Nim
Nim
import strformat   const data = [85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98]   func pick(at, remain, accu, treat: int): int = if remain == 0: return if accu > treat: 1 else: 0 return pick(at - 1, remain - 1, accu + data[at - 1], treat) + ...
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...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict;   use List::Util qw{ sum };     sub means { my @groups = @_; return map sum(@$_) / @$_, @groups; }     sub following { my $pattern = shift; my $orig_count = grep $_, @$pattern; my $count; do { my $i = $#{$pattern}; until (0 > $i) { ...