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/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.23 | C# | using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
... |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I ... | #C.23 | C# | using System;
using System.Linq;
namespace PentominoTiling
{
class Program
{
static readonly char[] symbols = "FILNPTUVWXYZ-".ToCharArray();
static readonly int nRows = 8;
static readonly int nCols = 8;
static readonly int target = 12;
static readonly int blank = 12;
... |
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... | #Haskell | Haskell | {-# language FlexibleContexts #-}
import Data.List
import Data.Maybe
import System.Random
import Control.Monad.State
import Text.Printf
import Data.Set (Set)
import qualified Data.Set as S
type Matrix = [[Bool]]
type Cell = (Int, Int)
type Cluster = Set (Int, Int)
clusters :: Matrix -> [Cluster]
clusters m = unfol... |
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... | #Ada | Ada | function Is_Perfect(N : Positive) return Boolean is
Sum : Natural := 0;
begin
for I in 1..N - 1 loop
if N mod I = 0 then
Sum := Sum + I;
end if;
end loop;
return Sum = N;
end Is_Perfect; |
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... | #Go | Go | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
const (
m, n = 10, 10
t = 1000
minp, maxp, Δp = 0.1, 0.99, 0.1
)
// Purposely don't seed for a repeatable example grid:
g := NewGrid(.5, m, n)
g.Percolate()
fmt.Println(g)
rand.Seed(time.Now().UnixNa... |
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... | #Go | Go | package main
import (
"fmt"
"math/rand"
)
var (
pList = []float64{.1, .3, .5, .7, .9}
nList = []int{1e2, 1e3, 1e4, 1e5}
t = 100
)
func main() {
for _, p := range pList {
theory := p * (1 - p)
fmt.Printf("\np: %.4f theory: %.4f t: %d\n", p, theory, t)
fmt.Print... |
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... | #J | J | groups=:[: +/\ 2 </\ 0 , *
ooze=: [ >. [ +&* [ * [: ; groups@[ <@(* * 2 < >./)/. +
percolate=: ooze/\.@|.^:2^:_@(* (1 + # {. 1:))
trial=: percolate@([ >: ]?@$0:)
simulate=: %@[ * [: +/ (2 e. {:)@trial&15 15"0@# |
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... | #Julia | Julia | using Printf, Distributions
newgrid(p::Float64, M::Int=15, N::Int=15) = rand(Bernoulli(p), M, N)
function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int)
NOT_VISITED = 1 # const
N, M = size(grid)
dirs = [[1, 0], [-1, 0], [0, 1], [1, 0]]
# fill cell
grid[r, c] = indx
# is the bottom... |
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... | #Aime | Aime | void
f1(record r, ...)
{
if (~r) {
for (text s in r) {
r.delete(s);
rcall(f1, -2, 0, -1, s);
r[s] = 0;
}
} else {
ocall(o_, -2, 1, -1, " ", ",");
o_newline();
}
}
main(...)
{
record r;
ocall(r_put, -2, 1, -1, r, 0);
f1(r);
... |
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.2B.2B | C++ |
#include <iostream>
#include <algorithm>
#include <vector>
int pShuffle( int t ) {
std::vector<int> v, o, r;
for( int x = 0; x < t; x++ ) {
o.push_back( x + 1 );
}
r = o;
int t2 = t / 2 - 1, c = 1;
while( true ) {
v = r;
r.clear();
for( int x = t2; x >... |
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
... | #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(noise(3.14, 42, 7))
}
func noise(x, y, z float64) float64 {
X := int(math.Floor(x)) & 255
Y := int(math.Floor(y)) & 255
Z := int(math.Floor(z)) & 255
x -= math.Floor(x)
y -= math.Floor(y)
z -= math.Floor(z)
u :=... |
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
| #FreeBASIC | FreeBASIC | #include"totient.bas"
dim as uinteger found = 0, curr = 3, sum, toti
while found < 20
sum = totient(curr)
toti = sum
do
toti = totient(toti)
sum += toti
loop while toti <> 1
if sum = curr then
print sum
found += 1
end if
curr += 1
wend |
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
| #Go | Go | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
... |
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... | #Fantom | Fantom |
enum class Suit { clubs, diamonds, hearts, spades }
enum class Pips { ace, two, three, four, five,
six, seven, eight, nine, ten, jack, queen, king
}
class Card
{
readonly Suit suit
readonly Pips pips
new make (Suit suit, Pips pips)
{
this.suit = suit
this.pips = pips
}
override Str toStr ... |
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 ...... | #Erlang | Erlang | % Implemented by Arjun Sunel
-module(pi_calculation).
-export([main/0]).
main() ->
pi(1,0,1,1,3,3,0).
pi(Q,R,T,K,N,L,C) ->
if C=:=50 ->
io:format("\n"),
pi(Q,R,T,K,N,L,0) ;
true ->
if
(4*Q + R-T) < (N*T) ->
io:format("~p",[N]),
P = 10*(R-N*T),
pi(Q*10 , P, T , K , ((10*(3*Q+R)) div... |
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... | #Maple | Maple | pig := proc()
local Points, pointsThisTurn, answer, rollNum, i, win;
randomize();
Points := [0, 0];
win := [false, 0];
while not win[1] do
for i to 2 do
if not win[1] then
printf("Player %a's turn.\n", i);
answer := "";
pointsThisTurn := 0;
while not answer = "HOLD" do
while not answer = ... |
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... | #Forth | Forth | : popcount { n -- u }
0
begin
n 0<>
while
n n 1- and to n
1+
repeat ;
\ primality test for 0 <= n <= 63
: prime? ( n -- ? )
1 swap lshift 0x28208a20a08a28ac and 0<> ;
: pernicious? ( n -- ? )
popcount prime? ;
: first_n_pernicious_numbers { n -- }
." First " n . ." pernicious numbers:" c... |
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... | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
pierpont = []
limit1 = 18
limit2 = 8505000
limit3 = 50
limit4 = 21
limit5 = 30500000
for n = 0 to limit1
for m = 0 to limit1
num = pow(2,n)*pow(3,m) + 1
if isprime(num) and num < limit2
add(pierpont,num)
ok
if num > limit2
... |
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... | #Ruby | Ruby | require 'gmp'
def smooth_generator(ar)
return to_enum(__method__, ar) unless block_given?
next_smooth = 1
queues = ar.map{|num| [num, []] }
loop do
yield next_smooth
queues.each {|m, queue| queue << next_smooth * m}
next_smooth = queues.collect{|m, queue| queue.first}.min
queues.each{|m, queu... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
L := [1,2,3] # a list
x := ?L # random element
end |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #J | J | ({~ ?@#) 'abcdef'
b |
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
... | #zkl | zkl | fcn isPrime(n){
if(n.isEven or n<2) return(n==2);
(not [3..n.toFloat().sqrt().toInt(),2].filter1('wrap(m){n%m==0}))
} |
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... | #Java | Java | import java.util.Arrays;
public class PhraseRev{
private static String reverse(String x){
return new StringBuilder(x).reverse().toString();
}
private static <T> T[] reverse(T[] x){
T[] rev = Arrays.copyOf(x, x.length);
for(int i = x.length - 1; i >= 0; i--){
rev[x.length - 1 - i] = x[i];
}
return re... |
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... | #GAP | GAP | # All of this is built-in
Derangements([1 .. 4]);
# [ [ 2, 1, 4, 3 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 3, 1, 4, 2 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ],
# [ 4, 1, 2, 3 ], [ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ] ]
Size(last);
# 9
NrDerangements([1 .. 4]);
# 9
# An imple... |
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 ... | #J | J | bfsjt0=: _1 - i.
lookingat=: 0 >. <:@# <. i.@# + *
next=: | >./@:* | > | {~ lookingat
bfsjtn=: (((] <@, ] + *@{~) | i. next) C. ] * _1 ^ next < |)^:(*@next) |
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 ... | #Java | Java | package org.rosettacode.java;
import java.util.Arrays;
import java.util.stream.IntStream;
public class HeapsAlgorithm {
public static void main(String[] args) {
Object[] array = IntStream.range(0, 4)
.boxed()
.toArray();
HeapsAlgorithm algorithm = new HeapsAlgorithm();
algorithm.recursive(array);
... |
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... | #Phix | Phix | constant data = {85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 }
function pick(int at, int remain, int accu, int treat)
if remain=0 then return iff(accu>treat?1:0) end if
return pick(at-1, remain-1, accu+data[at], treat) +
iff(at>remain?pick(at-1, remai... |
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.2B.2B | C++ | #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( a... |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I ... | #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
var F = [][]int{
{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},
{1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},
{1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},
{1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},
}
v... |
http://rosettacode.org/wiki/Percolation/Mean_cluster_density | Percolation/Mean cluster density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
c
{\disp... | #J | J | congeal=: |.@|:@((*@[*>.)/\.)^:4^:_ |
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... | #Julia | Julia | using Printf, Distributions
newgrid(p::Float64, r::Int, c::Int=r) = rand(Bernoulli(p), r, c)
function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int)
NOT_CLUSTERED = 1 # const
N, M = size(grid)
dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
# fill cell
grid[r, c] = indx
# check for each d... |
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... | #Kotlin | Kotlin | // version 1.2.10
import java.util.Random
val rand = Random()
const val RAND_MAX = 32767
lateinit var map: IntArray
var w = 0
var ww = 0
const val ALPHA = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const val ALEN = ALPHA.length - 3
fun makeMap(p: Double) {
val thresh = (p * RAND_MAX).toInt()... |
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... | #ALGOL_60 | ALGOL 60 |
begin
comment - return p mod q;
integer procedure mod(p, q);
value p, q; integer p, q;
begin
mod := p - q * entier(p / q);
end;
comment - return true if n is perfect, otherwise false;
boolean procedure isperfect(n);
value n; integer n;
begin
integer sum, f1, f2;
sum := 1;
f1 := 1;
for f1 := f1 + 1 w... |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Luca... | #ALGOL_68 | ALGOL 68 | PROC is perfect = (INT candidate)BOOL: (
INT sum :=1;
FOR f1 FROM 2 TO ENTIER ( sqrt(candidate)*(1+2*small real) ) WHILE
IF candidate MOD f1 = 0 THEN
sum +:= f1;
INT f2 = candidate OVER f1;
IF f2 > f1 THEN
sum +:= f2
FI
FI;
# WHILE # sum <= candidate DO
SKIP
OD;
sum... |
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... | #Haskell | Haskell | {-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Control.Monad.Random
import Data.Array.Unboxed
import Data.List
import Formatting
data Field = Field { f :: UArray (Int, Int) Char
, hWall :: UArray (Int, Int) Bool
, vWall :: UArray (Int, Int) Bool
... |
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... | #Haskell | Haskell | import Control.Monad.Random
import Control.Applicative
import Text.Printf
import Control.Monad
import Data.Bits
data OneRun = OutRun | InRun deriving (Eq, Show)
randomList :: Int -> Double -> Rand StdGen [Int]
randomList n p = take n . map f <$> getRandomRs (0,1)
where f n = if (n > p) then 0 else 1
countRuns x... |
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... | #Kotlin | Kotlin | // version 1.2.10
import java.util.Random
val rand = Random()
const val RAND_MAX = 32767
const val NUL = '\u0000'
val x = 15
val y = 15
var grid = StringBuilder((x + 1) * (y + 1) + 1)
var cell = 0
var end = 0
var m = 0
var n = 0
fun makeGrid(p: Double) {
val thresh = (p * RAND_MAX).toInt()
m = x
n =... |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Uni... | #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
COMMENT REQUIRED BY "prelude_permutations.a68"
MODE PERMDATA = ~;
PROVIDES:
# PERMDATA*=~* #
# perm*=~ list* #
END COMMENT
MODE PERMDATALIST = REF[]PERMDATA;
MODE PERMDATALISTYIELD = PROC(PERMDATALIST)VOID;
# Generate permutations of the input data list of data list #
PROC perm gen per... |
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 ... | #Clojure | Clojure | (defn perfect-shuffle [deck]
(let [half (split-at (/ (count deck) 2) deck)]
(interleave (first half) (last half))))
(defn solve [deck-size]
(let [original (range deck-size)
trials (drop 1 (iterate perfect-shuffle original))
predicate #(= original %)]
(println (format "%5s: %s" deck-size
... |
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 ... | #Common_Lisp | Common Lisp | (defun perfect-shuffle (deck)
(let* ((half (floor (length deck) 2))
(left (subseq deck 0 half))
(right (nthcdr half deck)))
(mapcan #'list left right)))
(defun solve (deck-size)
(loop with original = (loop for n from 1 to deck-size collect n)
for trials from 1
for deck = orig... |
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
... | #J | J | band=:17 b.
ImprovedNoise=:3 :0
'x y z'=. y
X=. (<. x) band 255
Y=. (<. y) band 255
Z=. (<. z) band 255
x=. x-<.!.0 x
y=. y-<.!.0 y
z=. z-<.!.0 z
u=. fade x
v=. fade y
w=. fade z
A=. (p{~X)+Y
AA=.(p{~A)+Z
AB=.(p{~A+1)+Z
B=. (p{~X+1)+Y
BA=.(p{~B)+Z
BB=.(p{~B+1)+Z
t1=. (grad(p{~BB+1),(... |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #Haskell | Haskell | perfectTotients :: [Int]
perfectTotients =
filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate φ)) [2 ..]
φ :: Int -> Int
φ = memoize (\n -> length (filter ((1 ==) . gcd n) [1 .. n]))
memoize :: (Int -> a) -> (Int -> a)
memoize f = (!!) (f <$> [0 ..])
main :: IO ()
main = print $ take 20 perfectTot... |
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... | #Forth | Forth | require random.fs \ RANDOM ( n -- 0..n-1 ) is called CHOOSE in other Forths
create pips s" A23456789TJQK" mem,
create suits s" DHCS" mem, \ diamonds, hearts, clubs, spades
: .card ( c -- )
13 /mod swap
pips + c@ emit
suits + c@ emit ;
create deck 52 allot
variable dealt
: new-deck
52 0 ... |
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 ...... | #F.23 | F# | let rec g q r t k n l = seq {
if 4I*q+r-t < n*t
then
yield n
yield! (g (10I*q) (10I*(r-n*t)) t k ((10I*(3I*q+r))/t - 10I*n) l)
else
yield! (g (q*k) ((2I*q+r)*l) (t*l) (k+1I) ((q*(7I*k+2I)+r*l)/(t*l)) (l+2I))
}
let π = (g 1I 0I 1I 1I 3I 3I)
Seq.take 1 π |> Seq.iter (printf "%A.")
... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DynamicModule[{score, players = {1, 2}, roundscore = 0,
roll}, (score@# = 0) & /@ players;
Panel@Dynamic@
Column@{Grid[
Prepend[{#, score@#} & /@ players, {"Player", "Score"}],
Background -> {None, 2 -> Gray}], roundscore,
If[ValueQ@roll, Row@{"Rolled ", roll}, ""],
If[IntegerQ@roundsco... |
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... | #Fortran | Fortran | program pernicious
implicit none
integer :: i, n
i = 1
n = 0
do
if(isprime(popcnt(i))) then
write(*, "(i0, 1x)", advance = "no") i
n = n + 1
if(n == 25) exit
end if
i = i + 1
end do
write(*,*)
do i = 888888877, 888888888
if(isprime(popcnt(i))) write(*, "(i0, 1x)",... |
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... | #Sidef | Sidef | func smooth_generator(primes) {
var s = primes.len.of { [1] }
{
var n = s.map { .first }.min
{ |i|
s[i].shift if (s[i][0] == n)
s[i] << (n * primes[i])
} * primes.len
n
}
}
func pierpont_primes(n, k = 1) {
var g = smooth_generator([2,3])
1..I... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Java | Java | import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; // if done multiple times, the Random object should be re-used |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #JavaScript | JavaScript | var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)]; |
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... | #JavaScript | JavaScript | (function (p) {
return [
p.split('').reverse().join(''),
p.split(' ').map(function (x) {
return x.split('').reverse().join('');
}).join(' '),
p.split(' ').reverse().join(' ')
].join('\n');
})('rosetta code phrase reversal'); |
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... | #Go | Go | package main
import (
"fmt"
"math/big"
)
// task 1: function returns list of derangements of n integers
func dList(n int) (r [][]int) {
a := make([]int, n)
for i := range a {
a[i] = i
}
// recursive closure permutes a
var recurse func(last int)
recurse = func(last int) {
... |
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 ... | #jq | jq | # The helper function, _recurse, is tail-recursive and therefore in
# versions of jq with TCO (tail call optimization) there is no
# overhead associated with the recursion.
def permutations:
def abs: if . < 0 then -. else . end;
def sign: if . < 0 then -1 elif . == 0 then 0 else 1 end;
def swap(i;j): .[i] as $i... |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs ... | #Julia | Julia |
function johnsontrottermove!(ints, isleft)
len = length(ints)
function ismobile(pos)
if isleft[pos] && (pos > 1) && (ints[pos-1] < ints[pos])
return true
elseif !isleft[pos] && (pos < len) && (ints[pos+1] < ints[pos])
return true
end
false
end
fu... |
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... | #PicoLisp | PicoLisp | (load "@lib/simul.l") # For 'subsets'
(scl 2)
(de _stat (A)
(let (LenA (length A) SumA (apply + A))
(-
(*/ SumA LenA)
(*/ (- SumAB SumA) (- LenAB LenA)) ) ) )
(de permutationTest (A B)
(let
(AB (append A B)
SumAB (apply + AB)
LenAB (length AB)
Tobs ... |
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... | #PureBasic | PureBasic |
Define.f meanTreated,meanControl,diffInMeans
Define.f actualmeanTreated,actualmeanControl,actualdiffInMeans
Dim poolA(19)
poolA(1) =85 ; first 9 the treated
poolA(2) =88
poolA(3) =75
poolA(4) =66
poolA(5) =25
poolA(6) =29
poolA(7) =83
poolA(8) =39
poolA(9) =97
poolA(10) =68 ; last 10 the control
poolA(11) =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... | #Common_Lisp | Common Lisp | (require 'cl-jpeg)
;;; the JPEG library uses simple-vectors to store data. this is insane!
(defun compare-images (file1 file2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(multiple-value-bind (image1 height width) (jpeg:decode-image file1)
(let ((image2 (jpeg:decode-image file2)))
(loop for i of-... |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I ... | #Java | Java | package pentominotiling;
import java.util.*;
public class PentominoTiling {
static final char[] symbols = "FILNPTUVWXYZ-".toCharArray();
static final Random rand = new Random();
static final int nRows = 8;
static final int nCols = 8;
static final int blank = 12;
static int[][] grid = 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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | (*Calculate C_n / n^2 for n=1000, 2000, ..., 10 000*)
In[1]:= Table[N[Max@MorphologicalComponents[
RandomVariate[BernoulliDistribution[.5], {n, n}],
CornerNeighbors -> False]/n^2], {n, 10^3, 10^4, 10^3}]
(*Find the average*)
In[2]:= % // MeanAround
(*Show a 15x15 matrix with each cluster given an increme... |
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... | #Nim | Nim | import random, sequtils, strformat
const
N = 15
T = 5
P = 0.5
NotClustered = 1
Cell2Char = " #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
NRange = [4, 64, 256, 1024, 4096]
type Grid = seq[seq[int]]
proc newGrid(n: Positive; p: float): Grid =
result = newSeqWith(n, newSeq[int](n))
for r... |
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... | #Perl | Perl | $fill = 'x';
$D{$_} = $i++ for qw<DeadEnd Up Right Down Left>;
sub deq { defined $_[0] && $_[0] eq $_[1] }
sub perctest {
my($grid) = @_;
generate($grid);
my $block = 1;
for my $y (0..$grid-1) {
for my $x (0..$grid-1) {
fill($x, $y, $block++) if $perc[$y][$x] eq $fill
}
... |
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... | #ALGOL_W | ALGOL W | begin
% returns true if n is perfect, false otherwise %
% n must be > 0 %
logical procedure isPerfect ( integer value candidate ) ;
begin
integer sum;
sum := 1;
for f1 := 2 until round( sqrt( candid... |
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... | #Julia | Julia | using Printf, Distributions
struct Grid
cells::BitArray{2}
hwall::BitArray{2}
vwall::BitArray{2}
end
function Grid(p::AbstractFloat, m::Integer=10, n::Integer=10)
cells = fill(false, m, n)
hwall = rand(Bernoulli(p), m + 1, n)
vwall = rand(Bernoulli(p), m, n + 1)
vwall[:, 1] = true
vwal... |
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... | #Kotlin | Kotlin | // version 1.2.10
import java.util.Random
val rand = Random()
const val RAND_MAX = 32767
// cell states
const val FILL = 1
const val RWALL = 2 // right wall
const val BWALL = 4 // bottom wall
val x = 10
val y = 10
var grid = IntArray(x * (y + 2))
var cells = 0
var end = 0
var m = 0
var n = 0
fun makeGrid(p... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
t := integer(A[2]) | 500
write(left("p",8)," ",left("n",8)," ",left("p(1-p)",10)," ",left("SimK(p)",10))
every (p := 0.1 | 0.3 | 0.5 | 0.7 | 0.9, n := 1000 | 2000 | 3000) do {
Ka := 0.0
every !t do {
every (v := "", !n) do v ||:= |((?0.1 > p,"0")|"1")
... |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #Nim | Nim | import random, sequtils, strformat, strutils
type Grid = seq[string] # Row first, i.e. [y][x].
const
Full = '.'
Used = '#'
Empty = ' '
proc newGrid(p: float; xsize, ysize: Positive): Grid =
result = newSeqWith(ysize, newString(xsize))
for row in result.mitems:
for cell in row.mitems:
cel... |
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... | #Perl | Perl | my $block = '▒';
my $water = '+';
my $pore = ' ';
my $grid = 15;
my @site;
$D{$_} = $i++ for qw<DeadEnd Up Right Down Left>;
sub deq { defined $_[0] && $_[0] eq $_[1] }
sub percolate {
my($prob) = shift || 0.6;
$site[0] = [($pore) x $grid];
for my $y (1..$grid) {
for my $x (0..$grid-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... | #Amazing_Hopper | Amazing Hopper |
/* hopper-JAMBO - a flavour of Amazing Hopper! */
#include <jambo.h>
Main
leng=0
Void(lista)
Set("la realidad","escapa","a los sentidos"), Apnd list(lista)
Length(lista), Move to(leng)
Toksep(" ")
Printnl( lista )
Set(1) Gosub(Permutar)
End-Return
Subrutines
Define( Permutar, pos )
If ( Sub(le... |
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 ... | #D | D | import std.stdio;
void main() {
auto sizes = [8, 24, 52, 100, 1020, 1024, 10_000];
foreach(s; sizes) {
writefln("%5s : %5s", s, perfectShuffle(s));
}
}
int perfectShuffle(int size) {
import std.exception : enforce;
enforce(size%2==0);
import std.algorithm : copy, equal;
import ... |
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
... | #Java | Java | // JAVA REFERENCE IMPLEMENTATION OF IMPROVED NOISE - COPYRIGHT 2002 KEN PERLIN.
public final class ImprovedNoise {
static public double noise(double x, double y, double z) {
int X = (int)Math.floor(x) & 255, // FIND UNIT CUBE THAT
Y = (int)Math.floor(y) & 255, // C... |
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
| #J | J |
Until =: conjunction def 'u^:(0 -: v)^:_'
Filter =: (#~`)(`:6)
totient =: 5&p:
totient_chain =: [: }. (, totient@{:)Until(1={:)
ptnQ =: (= ([: +/ totient_chain))&>
|
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
| #Java | Java |
import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Integ... |
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... | #Fortran | Fortran | MODULE Cards
IMPLICIT NONE
TYPE Card
CHARACTER(5) :: value
CHARACTER(8) :: suit
END TYPE Card
TYPE(Card) :: deck(52), hand(52)
TYPE(Card) :: temp
CHARACTER(5) :: pip(13) = (/"Two ", "Three", "Four ", "Five ", "Six ", "Seven", "Eight", "Nine ", "Ten ", &
"Jack "... |
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 ...... | #Factor | Factor | USING: combinators.extras io kernel locals math prettyprint ;
IN: rosetta-code.pi
:: calc-pi-digits ( -- )
1 0 1 1 3 3 :> ( q! r! t! k! n! l! ) [
4 q * r + t - n t * < [
n pprint flush
r n t * - 10 *
3 q * r + 10 * t /i n 10 * - n! r!
q 10 * q!
] [
... |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and th... | #MiniScript | MiniScript | // Pig the Dice for two players.
Player = {}
Player.score = 0
Player.doTurn = function()
rolls = 0
pot = 0
print self.name + "'s Turn!"
while true
if self.score + pot >= goal then
print " " + self.name.upper + " WINS WITH " + (self.score + pot) + "!"
inp = "H"
e... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #FreeBASIC | FreeBASIC |
' FreeBASIC v1.05.0 win64
Function SumBinaryDigits(number As Integer) As Integer
If number < 0 Then number = -number ' convert negative numbers to positive
Var sum = 0
While number > 0
sum += number Mod 2
number \= 2
Wend
Return sum
End Function
Function IsPrime(number As Integer) As Boolean
I... |
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... | #Swift | Swift | import BigInt
import Foundation
public func pierpoint(n: Int) -> (first: [BigInt], second: [BigInt]) {
var primes = (first: [BigInt](repeating: 0, count: n), second: [BigInt](repeating: 0, count: n))
primes.first[0] = 2
var count1 = 1, count2 = 0
var s = [BigInt(1)]
var i2 = 0, i3 = 0, k = 1
var n2 = ... |
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... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var pierpont = Fn.new { |n, first|
var p = [ List.filled(n, null), List.filled(n, null) ]
for (i in 0...n) {
p[0][i] = BigInt.zero
p[1][i] = BigInt.zero
}
p[0][0] = BigInt.two
var count = 0
var count1 = 1
var count2 = 0
va... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #jq | jq | < /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Julia | Julia | array = [1,2,3]
rand(array) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #K | K | 1?"abcdefg"
,"e" |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaini... | #jq | jq | def reverse_string: explode | reverse | implode;
"rosetta code phrase reversal"
| split(" ") as $words
| "0. input: \(.)",
"1. string reversed: \(reverse_string)",
"2. each word reversed: \($words | map(reverse_string) | join(" "))",
"3. word-order reversed: \($words | reverse | 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... | #Julia | Julia |
s = "rosetta code phrase reversal"
println("The original phrase.")
println(" ", s)
println("Reverse the string.")
t = reverse(s)
println(" ", t)
println("Reverse each individual word in the string.")
t = join(map(reverse, split(s, " ")), " ")
println(" ", t)
println("Reverse the order of each word of th... |
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... | #Groovy | Groovy | def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
def subfact
subfact = { BigInteger n -> (n == 0) ? 1 : (n == 1) ? 0 : ((n-1) * (subfact(n-1) + subfact(n-2))) }
def derangement = { List l ->
def d = []
if (l) l.eachPermutation { p -> if ([p,l].transpose().every{ pp, ll -> pp != ll }) ... |
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 ... | #Kotlin | Kotlin | // version 1.1.2
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
val p = IntArray(n) { it } // permutation
val q = IntArray(n) { it } // inverse permutation
val d = IntArray(n) { -1 } // direction = 1 or -1
var sign = 1
val perms = mutableListOf<IntArray>()
val signs = mutable... |
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... | #Python | Python | from itertools import combinations as comb
def statistic(ab, a):
sumab, suma = sum(ab), sum(a)
return ( suma / len(a) -
(sumab -suma) / (len(ab) - len(a)) )
def permutationTest(a, b):
ab = a + b
Tobs = statistic(ab, a)
under = 0
for count, perm in enumerate(comb(ab, len(a)), 1):... |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two... | #D | D | import std.stdio, std.exception, std.range, std.math, bitmap;
void main() {
Image!RGB i1, i2;
i1 = i1.loadPPM6("Lenna50.ppm");
i2 = i2.loadPPM6("Lenna100.ppm");
enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");
real dif = 0.0;
foreach (p, q; zip(i1.image, i2.image))
di... |
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... | #E | E | def imageDifference(a, b) {
require(a.width() == b.width())
require(a.height() == b.height())
def X := 0..!(a.width())
def Y := 0..!(a.height())
var sumByteDiff := 0
for y in Y {
for x in X {
def ca := a[x, y]
def cb := b[x, y]
sumByteDiff += (ca.rb() - cb.rb()).abs() \
... |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I ... | #Julia | Julia | using Random
struct GridPoint x::Int; y::Int end
const nrows, ncols, target = 8, 8, 12
const grid = fill('*', nrows, ncols)
const shapeletters = ['F', 'I', 'L', 'N', 'P', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
const shapevec = [
[(1,-1, 1,0, 1,1, 2,1), (0,1, 1,-1, 1,0, 2,0),
(1,0 , 1,1, 1,2, 2,1), (1,0, 1,1... |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I ... | #Kotlin | Kotlin | // Version 1.1.4-3
import java.util.Random
val F = arrayOf(
intArrayOf(1, -1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 2, 0),
intArrayOf(1, 0, 1, 1, 1, 2, 2, 1), intArrayOf(1, 0, 1, 1, 2, -1, 2, 0),
intArrayOf(1, -2, 1, -1, 1, 0, 2, -1), intArrayOf(0, 1, 1, 1, 1, 2, 2, 1),
intArrayOf(1, -1,... |
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... | #Phix | Phix | with javascript_semantics
sequence grid
integer w, ww
procedure make_grid(atom p)
ww = w*w
grid = repeat(0,ww)
for i=1 to ww do
grid[i] = -(rnd()<p)
end for
end procedure
constant alpha = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZ"&
"abcdefghijklmnopqrstuvwxyz"
procedure show_cluster... |
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... | #AppleScript | AppleScript | -- PERFECT NUMBERS -----------------------------------------------------------
-- perfect :: integer -> bool
on perfect(n)
-- isFactor :: integer -> bool
script isFactor
on |λ|(x)
n mod x = 0
end |λ|
end script
-- quotient :: number -> number
script quotient
... |
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... | #Nim | Nim | import random, sequtils, strformat, tables
type
Cell = object
full: bool
right, down: bool # True if open to the right (x+1) or down (y+1).
Grid = seq[seq[Cell]] # Row first, i.e. [y][x].
proc newGrid(p: float; xsize, ysize: Positive): Grid =
result = newSeqWith(ysize, newSeq[Cell](xsize... |
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... | #Perl | Perl | my @bond;
my $grid = 10;
my $water = '▒';
$D{$_} = $i++ for qw<DeadEnd Up Right Down Left>;
sub percolate {
generate(shift || 0.6);
fill(my $x = 1,my $y = 0);
my @stack;
while () {
if (my $dir = direction($x,$y)) {
push @stack, [$x,$y];
($x,$y) = move($dir, $x, $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... | #J | J |
NB. translation of python
NB. 'N P T' =: 100 0.5 500 NB. hypothetical example values, to aid comprehension...
newv =: (> ?@(#&0))~ NB. generate a random binary vector. Use: N newv P
runs =: {: + [: +/ 1 0&E. NB. add the tail to the sum of 1 0 occurrences Use: runs V
m... |
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... | #Phix | Phix | with javascript_semantics
string grid
integer m, n, last, lastrow
enum SOLID = '#', EMPTY=' ', WET = 'v'
procedure make_grid(integer x, y, atom p)
m = x
n = y
grid = repeat('\n',x*(y+1)+1)
last = length(grid)
lastrow = last-n
for i=0 to x-1 do
for j=1 to y do
grid[1+i*(y+... |
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... | #APL | APL |
⍝ Builtin version, takes a vector:
⎕CY'dfns'
perms←{↓⍵[pmat ≢⍵]} ⍝ pmat always gives lexicographically ordered permutations.
⍝ Recursive fast implementation, courtesy of dzaima from The APL Orchard:
dpmat←{1=⍵:,⊂,0 ⋄ (⊃,/)¨(⍳⍵)⌽¨⊂(⊂(!⍵-1)⍴⍵-1),⍨∇⍵-1}
perms2←{↓⍵[1+⍉↑dpmat ≢⍵]}
|
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 ... | #Delphi | Delphi |
program Perfect_shuffle;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TDeck = record
Cards: TArray<Integer>;
Len: Integer;
constructor Create(deckSize: Integer); overload;
constructor Create(deck: TDeck); overload;
procedure shuffleDeck();
class operator Equal(a, b: TDeck): boolean;... |
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
... | #Julia | Julia | const permutation = UInt8[
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233,
7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219,
203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174,
20, 125, 136, 171, 168,... |
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
... | #Kotlin | Kotlin | // version 1.1.3
object Perlin {
private val permutation = intArrayOf(
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, 20... |
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
| #JavaScript | JavaScript | (() => {
'use strict';
// main :: IO ()
const main = () =>
showLog(
take(20, perfectTotients())
);
// perfectTotients :: Generator [Int]
function* perfectTotients() {
const
phi = memoized(
n => length(
filter(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.