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/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 of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Clojure | Clojure |
(defn permutation-swaps
"List of swap indexes to generate all permutations of n elements"
[n]
(if (= n 2) `((0 1))
(let [old-swaps (permutation-swaps (dec n))
swaps-> (partition 2 1 (range n))
swaps<- (reverse swaps->)]
(mapcat (fn [old-swap side]
(case side
:first swaps<-
:right (conj swaps<- old-swap)
:left (conj swaps-> (map inc old-swap))))
(conj old-swaps nil)
(cons :first (cycle '(:left :right)))))))
(defn swap [v [i j]]
(-> v
(assoc i (nth v j))
(assoc j (nth v i))))
(defn permutations [n]
(let [permutations (reduce
(fn [all-perms new-swap]
(conj all-perms (swap (last all-perms)
new-swap)))
(vector (vec (range n)))
(permutation-swaps n))
output (map vector
permutations
(cycle '(1 -1)))]
output))
(doseq [n [2 3 4]]
(dorun (map println (permutations n))))
|
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 subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Delphi | Delphi |
program Permutation_test;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure Comb(n, m: Integer; emit: TProc<TArray<Integer>>);
var
s: TArray<Integer>;
last: Integer;
procedure rc(i, next: Integer);
begin
for var j := next to n - 1 do
begin
s[i] := j;
if i = last then
emit(s)
else
rc(i + 1, j + 1);
end;
end;
begin
SetLength(s, m);
last := m - 1;
rc(0, 0);
end;
begin
var tr: TArray<Integer> := [85, 88, 75, 66, 25, 29, 83, 39, 97];
var ct: TArray<Integer> := [68, 41, 10, 49, 16, 65, 32, 92, 28, 98];
// collect all results in a single list
var all: TArray<Integer> := concat(tr, ct);
// compute sum of all data, useful as intermediate result
var sumAll := 0;
for var r in all do
inc(sumAll, r);
// closure for computing scaled difference.
// compute results scaled by len(tr)*len(ct).
// this allows all math to be done in integers.
var sd :=
function(trc: TArray<Integer>): Integer
begin
var sumTr := 0;
for var x in trc do
inc(sumTr, all[x]);
result := sumTr * length(ct) - (sumAll - sumTr) * length(tr);
end;
// compute observed difference, as an intermediate result
var a: TArray<Integer>;
SetLength(a, length(tr));
for var i := 0 to High(a) do
a[i] := i;
var sdObs := sd(a);
// iterate over all combinations. for each, compute (scaled)
// difference and tally whether leq or gt observed difference.
var nLe, nGt: Integer;
comb(length(all), length(tr),
procedure(c: TArray<Integer>)
begin
if sd(c) > sdObs then
inc(nGt)
else
inc(nle);
end);
// print results as percentage
var pc := 100 / (nLe + nGt);
writeln(format('differences <= observed: %f%%', [nle * pc]));
writeln(format('differences > observed: %f%%', [ngt * pc]));
{$IFNDEF UNIX} readln; {$ENDIF}
end. |
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
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int p[512];
double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
double lerp(double t, double a, double b) { return a + t * (b - a); }
double grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h<8 ? x : y,
v = h<4 ? y : h==12||h==14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
double noise(double x, double y, double z) {
int X = (int)floor(x) & 255,
Y = (int)floor(y) & 255,
Z = (int)floor(z) & 255;
x -= floor(x);
y -= floor(y);
z -= floor(z);
double u = fade(x),
v = fade(y),
w = fade(z);
int 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;
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}
void loadPermutation(char* fileName){
FILE* fp = fopen(fileName,"r");
int permutation[256],i;
for(i=0;i<256;i++)
fscanf(fp,"%d",&permutation[i]);
fclose(fp);
for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];
}
int main(int argC,char* argV[])
{
if(argC!=5)
printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>");
else{
loadPermutation(argV[1]);
printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));
}
return 0;
}
|
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program totientPerfect.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 20
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessNumber: .asciz " @ "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
mov r4,#2 @ start number
mov r6,#0 @ line counter
mov r7,#0 @ result counter
1:
mov r0,r4
mov r5,#0 @ totient sum
2:
bl totient @ compute totient
add r5,r5,r0 @ add totient
cmp r0,#1
beq 3f
b 2b
3:
cmp r5,r4 @ compare number and totient sum
bne 4f
mov r0,r4 @ display result if equals
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrszMessNumber
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
add r7,r7,#1
add r6,r6,#1 @ increment indice line display
cmp r6,#5 @ if = 5 new line
bne 4f
mov r6,#0
ldr r0,iAdrszCarriageReturn
bl affichageMess
4:
add r4,r4,#1 @ increment number
cmp r7,#MAXI @ maxi ?
blt 1b @ and loop
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrszMessNumber: .int szMessNumber
/******************************************************************/
/* compute totient of number */
/******************************************************************/
/* r0 contains number */
totient:
push {r1-r5,lr} @ save registers
mov r4,r0 @ totient
mov r5,r0 @ save number
mov r1,#0 @ for first divisor
1: @ begin loop
mul r3,r1,r1 @ compute square
cmp r3,r5 @ compare number
bgt 4f @ end
add r1,r1,#2 @ next divisor
mov r0,r5
bl division
cmp r3,#0 @ remainder null ?
bne 3f
2: @ begin loop 2
mov r0,r5
bl division
cmp r3,#0
moveq r5,r2 @ new value = quotient
beq 2b
mov r0,r4 @ totient
bl division
sub r4,r4,r2 @ compute new totient
3:
cmp r1,#2 @ first divisor ?
moveq r1,#1 @ divisor = 1
b 1b @ and loop
4:
cmp r5,#1 @ final value > 1
ble 5f
mov r0,r4 @ totient
mov r1,r5 @ divide by value
bl division
sub r4,r4,r2 @ compute new totient
5:
mov r0,r4
100:
pop {r1-r5,pc} @ restaur registers
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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 must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #CoffeeScript | CoffeeScript | #translated from JavaScript example
class Card
constructor: (@pip, @suit) ->
toString: => "#{@pip}#{@suit}"
class Deck
pips = '2 3 4 5 6 7 8 9 10 J Q K A'.split ' '
suits = '♣ ♥ ♠ ♦'.split ' '
constructor: (@cards) ->
if not @cards?
@cards = []
for suit in suits
for pip in pips
@cards.push new Card(pip, suit)
toString: => "[#{@cards.join(', ')}]"
shuffle: =>
for card, i in @cards
randomCard = parseInt @cards.length * Math.random()
@cards[i] = @cards.splice(randomCard, 1, card)[0]
deal: -> @cards.shift() |
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 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #C.2B.2B | C++ | #include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
class Gospers
{
cpp_int q, r, t, i, n;
public:
// use Gibbons spigot algorith based on the Gospers series
Gospers() : q{1}, r{0}, t{1}, i{1}
{
++*this; // move to the first digit
}
// the ++ prefix operator will move to the next digit
Gospers& operator++()
{
n = (q*(27*i-12)+5*r) / (5*t);
while(n != (q*(675*i-216)+125*r)/(125*t))
{
r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);
q = i*(2*i-1)*q;
t = 3*(3*i+1)*(3*i+2)*t;
i++;
n = (q*(27*i-12)+5*r) / (5*t);
}
q = 10*q;
r = 10*r-10*n*t;
return *this;
}
// the dereference operator will give the current digit
int operator*()
{
return (int)n;
}
};
int main()
{
Gospers g;
std::cout << *g << "."; // print the first digit and the decimal point
for(;;) // run forever
{
std::cout << *++g; // increment to the next digit and print
}
} |
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 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #FutureBasic | FutureBasic |
include "NSLog.incl"
local fn PeriodicTable( n as NSInteger ) as CFDictionaryRef
NSInteger i, row = 0, start = 0, finish, limits(6,6)
CFDictionaryRef dict = NULL
if n < 1 or n > 118 then NSLog( @"Atomic number is out of range." ) : exit fn
if n == 1 then dict = @{@"row":@1, @"col":@1} : exit fn
if n == 2 then dict = @{@"row":@1, @"col":@18} : exit fn
if n >= 57 and n <= 71 then dict = @{@"row":@8, @"col":fn NumberWithInteger( n - 53 )} : exit fn
if n >= 89 and n <= 103 then dict = @{@"row":@9, @"col":fn NumberWithInteger( n - 85 )} : exit fn
limits(0,0) = 3 : limits(0,1) = 10
limits(1,0) = 11 : limits(1,1) = 18
limits(2,0) = 19 : limits(2,1) = 36
limits(3,0) = 37 : limits(3,1) = 54
limits(4,0) = 55 : limits(4,1) = 86
limits(5,0) = 87 : limits(5,1) = 118
for i = 0 to 5
if ( n >= limits(i,0) and n <= limits(i,1) )
row = i + 2
start = limits(i,0)
finish = limits(i,1)
break
end if
next
if ( n < start + 2 or row == 4 or row == 5 )
dict = @{@"row":fn NumberWithInteger(row), @"col":fn NumberWithInteger( n - start + 1 )} : exit fn
end if
dict = @{@"row":fn NumberWithInteger(row), @"col":fn NumberWithInteger( n - finish + 18 )}
end fn = dict
local fn BuildTable
NSInteger i, count
CFArrayRef numbers = @[@1, @2, @29, @42, @57, @58, @59, @71, @72, @89, @90, @103, @113]
count = fn ArrayCount( numbers )
for i = 0 to count -1
CFDictionaryRef coordinates = fn PeriodicTable( fn NumberIntegerValue( numbers[i] ) )
NSLog( @"Atomic number %3d -> (%d, %d)", fn NumberIntegerValue( numbers[i] ), fn NumberIntegerValue( coordinates[@"row"] ), fn NumberIntegerValue( coordinates[@"col"] ) )
next
end fn
fn BuildTable
HandleEvents
|
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 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #Go | Go | package main
import (
"fmt"
"log"
)
var limits = [][2]int{
{3, 10}, {11, 18}, {19, 36}, {37, 54}, {55, 86}, {87, 118},
}
func periodicTable(n int) (int, int) {
if n < 1 || n > 118 {
log.Fatal("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 && n <= 103 {
return 9, n - 85
}
var row, start, end int
for i := 0; i < len(limits); i++ {
limit := limits[i]
if n >= limit[0] && n <= limit[1] {
row, start, end = i+2, limit[0], limit[1]
break
}
}
if n < start+2 || row == 4 || row == 5 {
return row, n - start + 1
}
return row, n - end + 18
}
func main() {
for _, n := range []int{1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113} {
row, col := periodicTable(n)
fmt.Printf("Atomic number %3d -> %d, %-2d\n", n, row, col)
}
} |
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 the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Pig.bas"
110 RANDOMIZE
120 STRING PLAYER$(1 TO 2)*28
130 NUMERIC POINTS(1 TO 2),VICTORY(1 TO 2)
140 LET WINNINGSCORE=100
150 TEXT 40:PRINT "Let's play Pig!";CHR$(241):PRINT
160 FOR I=1 TO 2
170 PRINT "Player";I
180 INPUT PROMPT "Whats your name? ":PLAYER$(I)
190 LET POINTS(I)=0:LET VICTORY(I)=0:PRINT
200 NEXT
210 DO
220 CALL TAKETURN(1)
230 IF NOT VICTORY(1) THEN CALL TAKETURN(2)
240 LOOP UNTIL VICTORY(1) OR VICTORY(2)
250 IF VICTORY(1) THEN
260 CALL CONGRAT(1)
270 ELSE
280 CALL CONGRAT(2)
290 END IF
300 DEF TAKETURN(P)
310 LET NEWPOINTS=0
320 SET #102:INK 3:PRINT :PRINT "It's your turn, " PLAYER$(P);"!":PRINT "So far, you have";POINTS(P);"points in all."
330 SET #102:INK 1:PRINT "Do you want to roll the die? (y/n)"
340 LET KEY$=ANSWER$
350 DO WHILE KEY$="y"
360 LET ROLL=RND(6)+1
370 IF ROLL=1 THEN
380 LET NEWPOINTS=0:LET KEY$="n"
390 PRINT "Oh no! You rolled a 1! No new points after all."
400 ELSE
410 LET NEWPOINTS=NEWPOINTS+ROLL
420 PRINT "You rolled a";ROLL:PRINT "That makes";NEWPOINTS;"new points so far."
430 PRINT "Roll again? (y/n)"
440 LET KEY$=ANSWER$
450 END IF
460 LOOP
470 IF NEWPOINTS=0 THEN
480 PRINT PLAYER$(P);" still has";POINTS(P);"points."
490 ELSE
500 LET POINTS(P)=POINTS(P)+NEWPOINTS:LET VICTORY(P)=POINTS(P)>=WINNINGSCORE
510 END IF
520 END DEF
530 DEF CONGRAT(P)
540 SET #102:INK 3:PRINT :PRINT "Congratulations ";PLAYER$(P);"!"
550 PRINT "You won with";POINTS(P);"points.":SET #102:INK 1
560 END DEF
570 DEF ANSWER$
580 LET K$=""
590 DO
600 LET K$=LCASE$(INKEY$)
610 LOOP UNTIL K$="y" OR K$="n"
620 LET ANSWER$=K$
630 END DEF |
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 pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #CLU | CLU | % The population count of an integer is never going to be
% higher than the amount of bits in it (max 64)
% so we can get away with a very simple primality test.
is_prime = proc (n: int) returns (bool)
if n<=2 then return(n=2) end
if n//2=0 then return(false) end
for i: int in int$from_to_by(n+2, n/2, 2) do
if n//i=0 then return(false) end
end
return(true)
end is_prime
% Find the population count of a number
pop_count = proc (n: int) returns (int)
c: int := 0
while n > 0 do
c := c + n // 2
n := n / 2
end
return(c)
end pop_count
% Is N pernicious?
pernicious = proc (n: int) returns (bool)
return(is_prime(pop_count(n)))
end pernicious
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, "First 25 pernicious numbers: ")
n: int := 1
seen: int := 0
while seen<25 do
if pernicious(n) then
stream$puts(po, int$unparse(n) || " ")
seen := seen + 1
end
n := n + 1
end
stream$putl(po, "\nPernicious numbers between 888,888,877 and 888,888,888:")
for i: int in int$from_to(888888877,888888888) do
if pernicious(i) then
stream$puts(po, int$unparse(i) || " ")
end
end
end start_up |
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 pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. PERNICIOUS-NUMBERS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 AMOUNT PIC 99.
03 CAND PIC 9(9).
03 POPCOUNT PIC 99.
03 POP-N PIC 9(9).
03 FILLER REDEFINES POP-N.
05 FILLER PIC 9(8).
05 FILLER PIC 9.
88 ODD VALUES 1, 3, 5, 7, 9.
03 DSOR PIC 99.
03 DIV-RSLT PIC 99V99.
03 FILLER REDEFINES DIV-RSLT.
05 FILLER PIC 99.
05 FILLER PIC 99.
88 DIVISIBLE VALUE ZERO.
03 PRIME-FLAG PIC X.
88 PRIME VALUE '*'.
01 FORMAT.
03 SIZE-FLAG PIC X.
88 SMALL VALUE 'S'.
88 LARGE VALUE 'L'.
03 SMALL-NUM PIC ZZ9.
03 LARGE-NUM PIC Z(9)9.
03 OUT-STR PIC X(80).
03 OUT-PTR PIC 99.
PROCEDURE DIVISION.
BEGIN.
PERFORM SMALL-PERNICIOUS.
PERFORM LARGE-PERNICIOUS.
STOP RUN.
INIT-OUTPUT-VARS.
MOVE ZERO TO AMOUNT.
MOVE 1 TO OUT-PTR.
MOVE SPACES TO OUT-STR.
SMALL-PERNICIOUS.
PERFORM INIT-OUTPUT-VARS.
MOVE 'S' TO SIZE-FLAG.
PERFORM ADD-PERNICIOUS
VARYING CAND FROM 1 BY 1 UNTIL AMOUNT IS EQUAL TO 25.
DISPLAY OUT-STR.
LARGE-PERNICIOUS.
PERFORM INIT-OUTPUT-VARS.
MOVE 'L' TO SIZE-FLAG.
PERFORM ADD-PERNICIOUS
VARYING CAND FROM 888888877 BY 1
UNTIL CAND IS GREATER THAN 888888888.
DISPLAY OUT-STR.
ADD-NUM.
ADD 1 TO AMOUNT.
IF SMALL,
MOVE CAND TO SMALL-NUM,
STRING SMALL-NUM DELIMITED BY SIZE INTO OUT-STR
WITH POINTER OUT-PTR.
IF LARGE,
MOVE CAND TO LARGE-NUM,
STRING LARGE-NUM DELIMITED BY SIZE INTO OUT-STR
WITH POINTER OUT-PTR.
ADD-PERNICIOUS.
PERFORM FIND-POPCOUNT.
PERFORM CHECK-PRIME.
IF PRIME, PERFORM ADD-NUM.
FIND-POPCOUNT.
MOVE ZERO TO POPCOUNT.
MOVE CAND TO POP-N.
PERFORM COUNT-BIT UNTIL POP-N IS EQUAL TO ZERO.
COUNT-BIT.
IF ODD, ADD 1 TO POPCOUNT.
DIVIDE 2 INTO POP-N.
CHECK-PRIME.
IF POPCOUNT IS LESS THAN 2,
MOVE SPACE TO PRIME-FLAG
ELSE
MOVE '*' TO PRIME-FLAG.
PERFORM CHECK-DSOR VARYING DSOR FROM 2 BY 1
UNTIL NOT PRIME OR DSOR IS NOT LESS THAN POPCOUNT.
CHECK-DSOR.
DIVIDE POPCOUNT BY DSOR GIVING DIV-RSLT.
IF DIVISIBLE, MOVE SPACE TO PRIME-FLAG. |
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
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Racket | Racket |
#lang racket (require math)
(define-syntax def (make-rename-transformer #'match-define-values))
(define (perm xs n)
(cond [(empty? xs) '()]
[else (def (q r) (quotient/remainder n (factorial (sub1 (length xs)))))
(def (a (cons c b)) (split-at xs q))
(cons c (perm (append a b) r))]))
(define (rank ys)
(cond [(empty? ys) 0]
[else (def ((cons x0 xs)) ys)
(+ (rank xs)
(* (for/sum ([x xs] #:when (< x x0)) 1)
(factorial (length xs))))]))
|
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
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Raku | Raku | use v6;
sub rank2inv ( $rank, $n = * ) {
$rank.polymod( 1 ..^ $n );
}
sub inv2rank ( @inv ) {
[+] @inv Z* [\*] 1, 1, * + 1 ... *
}
sub inv2perm ( @inv, @items is copy = ^@inv.elems ) {
my @perm;
for @inv.reverse -> $i {
@perm.append: @items.splice: $i, 1;
}
@perm;
}
sub perm2inv ( @perm ) { #not in linear time
(
{ @perm[++$ .. *].grep( * < $^cur ).elems } for @perm;
).reverse;
}
for ^6 {
my @row.push: $^rank;
for ( *.&rank2inv(3) , &inv2perm, &perm2inv, &inv2rank ) -> &code {
@row.push: code( @row[*-1] );
}
say @row;
}
my $perms = 4; #100;
my $n = 12; #144;
say 'Via BigInt rank';
for ( ( ^([*] 1 .. $n) ).pick($perms) ) {
say $^rank.&rank2inv($n).&inv2perm;
};
say 'Via inversion vectors';
for ( { my $i=0; inv2perm (^++$i).roll xx $n } ... * ).unique( with => &[eqv] ).[^$perms] {
.say;
};
say 'Via Raku method pick';
for ( { [(^$n).pick(*)] } ... * ).unique( with => &[eqv] ).head($perms) {
.say
};
|
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 called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Nim | Nim | import math, strutils
func isPrime(n: int): bool =
## Check if "n" is prime by trying successive divisions.
## "n" is supposed not to be a multiple of 2 or 3.
var d = 5
var delta = 2
while d <= int(sqrt(n.toFloat)):
if n mod d == 0: return false
inc d, delta
delta = 6 - delta
result = true
func isProduct23(n: int): bool =
## Check if "n" has only 2 and 3 for prime divisors
## (i.e. that "n = 2^u * 3^v").
var n = n
while (n and 1) == 0: n = n shr 1
while n mod 3 == 0: n = n div 3
result = n == 1
iterator pierpont(maxCount: Positive; k: int): int =
## Yield the Pierpoint primes of first or second kind according
## to the value of "k" (+1 for first kind, -1 for second kind).
yield 2
yield 3
var n = 5
var delta = 2 # 2 and 4 alternatively to skip the multiples of 2 and 3.
yield n
var count = 3
while count < maxCount:
inc n, delta
delta = 6 - delta
if isProduct23(n - k) and isPrime(n):
inc count
yield n
template pierpont1*(maxCount: Positive): int = pierpont(maxCount, +1)
template pierpont2*(maxCount: Positive): int = pierpont(maxCount, -1)
when isMainModule:
echo "First 50 Pierpont primes of the first kind:"
var count = 0
for n in pierpont1(50):
stdout.write ($n).align(9)
inc count
if count mod 10 == 0: stdout.write '\n'
echo ""
echo "First 50 Pierpont primes of the second kind:"
count = 0
for n in pierpont2(50):
stdout.write ($n).align(9)
inc count
if count mod 10 == 0: stdout.write '\n' |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Euphoria | Euphoria | constant s = {'a', 'b', 'c'}
puts(1,s[rand($)]) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #F.23 | F# | let list = ["a"; "b"; "c"; "d"; "e"]
let rand = new System.Random()
printfn "%s" list.[rand.Next(list.Length)] |
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
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #UNIX_Shell | UNIX Shell | function primep {
typeset n=$1 p=3
(( n == 2 )) && return 0 # 2 is prime.
(( n & 1 )) || return 1 # Other evens are not prime.
(( n >= 3 )) || return 1
# Loop for odd p from 3 to sqrt(n).
# Comparing p * p <= n can overflow.
while (( p <= n / p )); do
# If p divides n, then n is not prime.
(( n % p )) || return 1
(( p += 2 ))
done
return 0 # Yes, n is prime.
} |
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, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Emacs_Lisp | Emacs Lisp | (defun reverse-sep (words sep)
(mapconcat 'identity (reverse (split-string words sep)) sep))
(defun reverse-chars (line)
(reverse-sep line ""))
(defun reverse-words (line)
(reverse-sep line " "))
(defvar line "rosetta code phrase reversal")
(with-output-to-temp-buffer "*reversals*"
(princ (reverse-chars line))
(terpri)
(princ (mapconcat 'identity (mapcar #'reverse-chars
(split-string line)) " "))
(terpri)
(princ (reverse-words line))
(terpri)) |
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.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.23 | C# |
using System;
class Derangements
{
static int n = 4;
static int [] buf = new int [n];
static bool [] used = new bool [n];
static void Main()
{
for (int i = 0; i < n; i++) used [i] = false;
rec(0);
}
static void rec(int ind)
{
for (int i = 0; i < n; i++)
{
if (!used [i] && i != ind)
{
used [i] = true;
buf [ind] = i;
if (ind + 1 < n) rec(ind + 1);
else Console.WriteLine(string.Join(",", buf));
used [i] = false;
}
}
}
}
|
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 of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Common_Lisp | Common Lisp | (defstruct (directed-number (:conc-name dn-))
(number nil :type integer)
(direction nil :type (member :left :right)))
(defmethod print-object ((dn directed-number) stream)
(ecase (dn-direction dn)
(:left (format stream "<~D" (dn-number dn)))
(:right (format stream "~D>" (dn-number dn)))))
(defun dn> (dn1 dn2)
(declare (directed-number dn1 dn2))
(> (dn-number dn1) (dn-number dn2)))
(defun dn-reverse-direction (dn)
(declare (directed-number dn))
(setf (dn-direction dn) (ecase (dn-direction dn)
(:left :right)
(:right :left))))
(defun make-directed-numbers-upto (upto)
(let ((numbers (make-array upto :element-type 'integer)))
(dotimes (n upto numbers)
(setf (aref numbers n) (make-directed-number :number (1+ n) :direction :left)))))
(defun max-mobile-pos (numbers)
(declare ((vector directed-number) numbers))
(loop with pos-limit = (1- (length numbers))
with max-value and max-pos
for num across numbers
for pos from 0
do (ecase (dn-direction num)
(:left (when (and (plusp pos) (dn> num (aref numbers (1- pos)))
(or (null max-value) (dn> num max-value)))
(setf max-value num
max-pos pos)))
(:right (when (and (< pos pos-limit) (dn> num (aref numbers (1+ pos)))
(or (null max-value) (dn> num max-value)))
(setf max-value num
max-pos pos))))
finally (return max-pos)))
(defun permutations (upto)
(loop with numbers = (make-directed-numbers-upto upto)
for max-mobile-pos = (max-mobile-pos numbers)
for sign = 1 then (- sign)
do (format t "~A sign: ~:[~;+~]~D~%" numbers (plusp sign) sign)
while max-mobile-pos
do (let ((max-mobile-number (aref numbers max-mobile-pos)))
(ecase (dn-direction max-mobile-number)
(:left (rotatef (aref numbers (1- max-mobile-pos))
(aref numbers max-mobile-pos)))
(:right (rotatef (aref numbers max-mobile-pos)
(aref numbers (1+ max-mobile-pos)))))
(loop for n across numbers
when (dn> n max-mobile-number)
do (dn-reverse-direction n)))))
(permutations 3)
(permutations 4) |
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 subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Elixir | Elixir | defmodule Permutation do
def statistic(ab, a) do
sumab = Enum.sum(ab)
suma = Enum.sum(a)
suma / length(a) - (sumab - suma) / (length(ab) - length(a))
end
def test(a, b) do
ab = a ++ b
tobs = statistic(ab, a)
{under, count} = Enum.reduce(comb(ab, length(a)), {0,0}, fn perm, {under, count} ->
if statistic(ab, perm) <= tobs, do: {under+1, count+1},
else: {under , count+1}
end)
under * 100.0 / count
end
defp comb(_, 0), do: [[]]
defp comb([], _), do: []
defp comb([h|t], m) do
(for l <- comb(t, m-1), do: [h|l]) ++ comb(t, m)
end
end
treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]
controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
under = Permutation.test(treatmentGroup, controlGroup)
:io.fwrite "under = ~.2f%, over = ~.2f%~n", [under, 100-under] |
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 subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #GAP | GAP | a := [85, 88, 75, 66, 25, 29, 83, 39, 97];
b := [68, 41, 10, 49, 16, 65, 32, 92, 28, 98];
# Compute a decimal approximation of a rational
Approx := function(x, d)
local neg, a, b, n, m, s;
if x < 0 then
x := -x;
neg := true;
else
neg := false;
fi;
a := NumeratorRat(x);
b := DenominatorRat(x);
n := QuoInt(a, b);
a := RemInt(a, b);
m := 10^d;
s := "";
if neg then
Append(s, "-");
fi;
Append(s, String(n));
n := Size(s) + 1;
Append(s, String(m + QuoInt(a*m, b)));
s[n] := '.';
return s;
end;
PermTest := function(a, b)
local c, d, p, q, u, v, m, n, k, diff, all;
p := Size(a);
q := Size(b);
v := Concatenation(a, b);
n := p + q;
m := Binomial(n, p);
diff := Sum(a)/p - Sum(b)/q;
all := [1 .. n];
k := 0;
for u in Combinations(all, p) do
c := List(u, i -> v[i]);
d := List(Difference(all, u), i -> v[i]);
if Sum(c)/p - Sum(d)/q > diff then
k := k + 1;
fi;
od;
return [Approx((1 - k/m)*100, 3), Approx(k/m*100, 3)];
end;
# in order, % less or greater than original diff
PermTest(a, b);
[ "87.197", "12.802" ] |
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
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) / Float(FF'FF)
V (p, t) = (0.5, 500)
F newv(n, p)
R (0 .< n).map(i -> Int(nonrandom() < @p))
F runs(v)
R sum(zip(v, v[1..] [+] [0]).map((a, b) -> (a [&] (-)b)))
F mean_run_density(n, p)
R runs(newv(n, p)) / Float(n)
L(p10) (1.<10).step(2)
p = p10 / 10
V limit = p * (1 - p)
print(‘’)
L(n2) (10.<16).step(2)
V n = 2 ^ n2
V sim = sum((0 .< t).map(i -> mean_run_density(@n, :p))) / t
print(‘t=#3 p=#.2 n=#5 p(1-p)=#.3 sim=#.3 delta=#.1%’.format(
t, p, n, limit, sim, I limit {abs(sim - limit) / limit * 100} E sim * 100)) |
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
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) / Float(FF'FF)
V (M, nn, t) = (15, 15, 100)
V cell2char = ‘ #abcdefghijklmnopqrstuvwxyz’
V NOT_VISITED = 1
T PercolatedException
(Int, Int) t
F (t)
.t = t
F newgrid(p)
R (0 .< :nn).map(n -> (0 .< :M).map(m -> Int(nonrandom() < @@p)))
F pgrid(cell, percolated)
L(n) 0 .< :nn
print(‘#.) ’.format(n % 10)‘’(0 .< :M).map(m -> :cell2char[@cell[@n][m]]).join(‘ ’))
I percolated != (-1, -1)
V where = percolated[0]
print(‘!) ’(‘ ’ * where)‘’:cell2char[cell[:nn - 1][where]])
F walk_maze(m, n, &cell, indx) -> N
cell[n][m] = indx
I n < :nn - 1 & cell[n + 1][m] == :NOT_VISITED
walk_maze(m, n + 1, &cell, indx)
E I n == :nn - 1
X PercolatedException((m, indx))
I m & cell[n][m - 1] == :NOT_VISITED
walk_maze(m - 1, n, &cell, indx)
I m < :M - 1 & cell[n][m + 1] == :NOT_VISITED
walk_maze(m + 1, n, &cell, indx)
I n & cell[n - 1][m] == :NOT_VISITED
walk_maze(m, n - 1, &cell, indx)
F check_from_top(&cell) -> (Int, Int)?
V (n, walk_index) = (0, 1)
X.try
L(m) 0 .< :M
I cell[n][m] == :NOT_VISITED
walk_index++
walk_maze(m, n, &cell, walk_index)
X.catch PercolatedException ex
R ex.t
R N
V sample_printed = 0B
[Float = Int] pcount
L(p10) 11
V p = p10 / 10.0
pcount[p] = 0
L(tries) 0 .< t
V cell = newgrid(p)
(Int, Int)? percolated = check_from_top(&cell)
I percolated != N
pcount[p]++
I !sample_printed
print("\nSample percolating #. x #., p = #2.2 grid\n".format(M, nn, p))
pgrid(cell, percolated)
sample_printed = 1B
print("\n p: Fraction of #. tries that percolate through\n".format(t))
L(p, c) sorted(pcount.items())
print(‘#.1: #.’.format(p, c / Float(t))) |
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
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #Common_Lisp | Common Lisp | ;;;; Translation from: Java
(declaim (optimize (speed 3) (debug 0)))
(defconstant +p+
(let ((permutation
#(151 160 137 91 90 15
131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23
190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33
88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166
77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244
102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196
135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123
5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42
223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9
129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228
251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107
49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254
138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180))
(aux (make-array 512 :element-type 'fixnum)))
(dotimes (i 256 aux)
(setf (aref aux i) (aref permutation i))
(setf (aref aux (+ 256 i)) (aref permutation i)))))
(defun fade (te)
(declare (type double-float te))
(the double-float (* te te te (+ (* te (- (* te 6) 15)) 10))))
(defun lerp (te a b)
(declare (type double-float te a b))
(the double-float (+ a (* te (- b a)))))
(defun grad (hash x y z)
(declare (type fixnum hash)
(type double-float x y z))
(let* ((h (logand hash 15)) ;; convert lo 4 bits of hash code into 12 gradient directions
(u (if (< h 8) x y))
(v (cond ((< h 4)
y)
((or (= h 12) (= h 14))
x)
(t z))))
(the
double-float
(+
(if (zerop (logand h 1)) u (- u))
(if (zerop (logand h 2)) v (- v))))))
(defun noise (x y z)
(declare (type double-float x y z))
;; find unit cube that contains point.
(let ((cx (logand (floor x) 255))
(cy (logand (floor y) 255))
(cz (logand (floor z) 255)))
;; find relative x, y, z of point in cube.
(let ((x (- x (floor x)))
(y (- y (floor y)))
(z (- z (floor z))))
;; compute fade curves for each of x, y, z.
(let ((u (fade x))
(v (fade y))
(w (fade z)))
;; hash coordinates of the 8 cube corners,
(let* ((ca (+ (aref +p+ cx) cy))
(caa (+ (aref +p+ ca) cz))
(cab (+ (aref +p+ (1+ ca)) cz))
(cb (+ (aref +p+ (1+ cx)) cy))
(cba (+ (aref +p+ cb) cz))
(cbb (+ (aref +p+ (1+ cb)) cz)))
;; ... and add blended results from 8 corners of cube
(the double-float
(lerp w
(lerp v
(lerp u
(grad (aref +p+ caa) x y z)
(grad (aref +p+ cba) (1- x) y z))
(lerp u
(grad (aref +p+ cab) x (1- y) z)
(grad (aref +p+ cbb) (1- x) (1- y) z)))
(lerp v
(lerp u
(grad (aref +p+ (1+ caa)) x y (1- z))
(grad (aref +p+ (1+ cba)) (1- x) y (1- z)))
(lerp u
(grad (aref +p+ (1+ cab)) x (1- y) (1- z))
(grad (aref +p+ (1+ cbb)) (1- x) (1- y) (1- z)))))))))))
(print (noise 3.14d0 42d0 7d0))
|
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
| #Arturo | Arturo | totient: function [n][
tt: new n
nn: new n
i: new 2
while [nn >= i ^ 2][
if zero? nn % i [
while [zero? nn % i]->
'nn / i
'tt - tt/i
]
if i = 2 ->
i: new 1
'i + 2
]
if nn > 1 ->
'tt - tt/nn
return tt
]
x: new 1
num: new 0
while [num < 20][
tot: new x
s: new 0
while [tot <> 1][
tot: totient tot
's + tot
]
if s = x [
prints ~"|x| "
inc 'num
]
'x + 2
]
print "" |
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
| #AutoHotkey | AutoHotkey | MsgBox, 262144, , % result := perfect_totient(20)
perfect_totient(n){
count := sum := tot := 0, str:= "", m := 1
while (count < n) {
tot := m, sum := 0
while (tot != 1) {
tot := totient(tot)
sum += tot
}
if (sum = m) {
str .= m ", "
count++
}
m++
}
return Trim(str, ", ")
}
totient(n) {
tot := n, i := 2
while (i*i <= n) {
if !Mod(n, i) {
while !Mod(n, i)
n /= i
tot -= tot / i
}
if (i = 2)
i := 1
i+=2
}
if (n > 1)
tot -= tot / n
return tot
} |
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 must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Common_Lisp | Common Lisp | (defconstant +suits+
'(club diamond heart spade)
"Card suits are the symbols club, diamond, heart, and spade.")
(defconstant +pips+
'(ace 2 3 4 5 6 7 8 9 10 jack queen king)
"Card pips are the numbers 2 through 10, and the symbols ace, jack,
queen and king.")
(defun make-deck (&aux (deck '()))
"Returns a list of cards, where each card is a cons whose car is a
suit and whose cdr is a pip."
(dolist (suit +suits+ deck)
(dolist (pip +pips+)
(push (cons suit pip) deck))))
(defun shuffle (list)
"Returns a shuffling of list, by sorting it with a random
predicate. List may be modified."
(sort list #'(lambda (x y)
(declare (ignore x y))
(zerop (random 2))))) |
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 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Clojure | Clojure | (ns pidigits
(:gen-class))
(def calc-pi
; integer division rounding downwards to -infinity
(let [div (fn [x y] (long (Math/floor (/ x y))))
; Computations performed after yield clause in Python code
update-after-yield (fn [[q r t k n l]]
(let [nr (* 10 (- r (* n t)))
nn (- (div (* 10 (+ (* 3 q) r)) t) (* 10 n))
nq (* 10 q)]
[nq nr t k nn l]))
; Update of else clause in Python code: if (< (- (+ (* 4 q) r) t) (* n t))
update-else (fn [[q r t k n l]]
(let [nr (* (+ (* 2 q) r) l)
nn (div (+ (* q 7 k) 2 (* r l)) (* t l))
nq (* k q)
nt (* l t)
nl (+ 2 l)
nk (+ 1 k)]
[nq nr nt nk nn nl]))
; Compute the lazy sequence of pi digits translating the Python code
pi-from (fn pi-from [[q r t k n l]]
(if (< (- (+ (* 4 q) r) t) (* n t))
(lazy-seq (cons n (pi-from (update-after-yield [q r t k n l]))))
(recur (update-else [q r t k n l]))))]
; Use Clojure big numbers to perform the math (avoid integer overflow)
(pi-from [1N 0N 1N 1N 3N 3N])))
;; Indefinitely Output digits of pi, with 40 characters per line
(doseq [[i q] (map-indexed vector calc-pi)]
(when (= (mod i 40) 0)
(println))
(print q))
|
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 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #J | J | PT=: (' ',.~[;._2) {{)n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 H He
2 Li Be B C N O F Ne
3 Na Mg Al Si P S Cl Ar
4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr
5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe
6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn
7 Fr Ra - Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og
8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu
9 Aktinoidi- Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr
}}
ptrc=: {{
tokens=. (#~ (3>#)@> * */@(tolower~:toupper)@>) ~.,;:,PT
ndx=. (>' ',L:0' ',L:0~tokens) {.@I.@E."1 ,PT
Lantanoidi=. ndx{+/\'*'=,PT
Aktinoidi=. ndx{+/\'-'=,PT
j=. 13|3*Lantanoidi+3*Aktinoidi
k=. {:$PT
0,}."1/:~j,.(<.ndx%k),.1+(/:~@~. i. ])k|ndx
}}
rowcol=: ptrc'' |
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 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #Julia | Julia | const limits = [3:10, 11:18, 19:36, 37:54, 55:86, 87:118]
function periodic_table(n)
(n < 1 || n > 118) && error("Atomic number is out of range.")
n == 1 && return [1, 1]
n == 2 && return [1, 18]
57 <= n <= 71 && return [8, n - 53]
89 <= n <= 103 && return [9, n - 85]
row, limitstart, limitstop = 0, 0, 0
for i in eachindex(limits)
if limits[i].start <= n <= limits[i].stop
row, limitstart, limitstop = i + 1, limits[i].start, limits[i].stop
break
end
end
return (n < limitstart + 2 || row == 4 || row == 5) ?
[row, n - limitstart + 1] : [row, n - limitstop + 18]
end
for n in [1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113]
rc = periodic_table(n)
println("Atomic number ", lpad(n, 3), " -> ($(rc[1]), $(rc[2]))")
end
|
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #J | J | require'general/misc/prompt' NB. was require'misc' in j6
status=:3 :0
'pid cur tot'=. y
player=. 'player ',":pid
potential=. ' potential: ',":cur
total=. ' total: ',":tot
smoutput player,potential,total
)
getmove=:3 :0
whilst.1~:+/choice do.
choice=.'HRQ' e. prompt '..Roll the dice or Hold or Quit? [R or H or Q]: '
end.
choice#'HRQ'
)
NB. simulate an y player game of pig
pigsim=:3 :0
smoutput (":y),' player game of pig'
scores=.y#0
while.100>>./scores do.
for_player.=i.y do.
smoutput 'begining of turn for player ',":pid=.1+I.player
current=. 0
whilst. (1 ~: roll) *. 'R' = move do.
status pid, current, player+/ .*scores
if.'R'=move=. getmove'' do.
smoutput 'rolled a ',":roll=. 1+?6
current=. (1~:roll)*current+roll end. end.
scores=. scores+(current*player)+100*('Q'e.move)*-.player
smoutput 'player scores now: ',":scores end. end.
smoutput 'player ',(":1+I.scores>:100),' wins'
) |
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 pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Common_Lisp | Common Lisp | (format T "~{~a ~}~%"
(loop for n = 1 then (1+ n)
when (primep (logcount n))
collect n into numbers
when (= (length numbers) 25)
return numbers))
(format T "~{~a ~}~%"
(loop for n from 888888877 to 888888888
when (primep (logcount n))
collect n)) |
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
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #REXX | REXX | /*REXX program displays permutations of N number of objects (1, 2, 3, ···). */
parse arg N y seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 4 /*Not specified? Then use the default.*/
if y=='' | y=="," then y= 17 /* " " " " " " */
if datatype(seed,'W') then call random ,,seed /*can make RANDOM numbers repeatable. */
permutes= permSets(N) /*returns N! (number of permutations).*/
w= length(permutes) /*used for aligning the SAY output. */
@.=
do p=0 for permutes /*traipse through each of the permutes.*/
z= permSets(N, p) /*get which of the permutation it is.*/
say 'for' N "items, permute rank" right(p,w) 'is: ' z
@.p= z /*define a rank permutation in @ array.*/
end /*p*/
say /* [↓] displays a particular perm rank*/
say ' the permutation rank of' y "is: " @.y /*display a particular permutation rank*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
permSets: procedure expose @. #; #= 0; parse arg x,r,c; c= space(c); xm= x -1
do j=1 for x; @.j= j-1; end /*j*/
_=0; do u=2 for xm; _= _ @.u; end /*u*/
if r==# then return _; if c==_ then return #
do while .permSets(x,0); #= #+1; _= @.1
do v=2 for xm; _= _ @.v; end /*v*/
if r==# then return _; if c==_ then return #
end /*while···*/
return #+1
/*──────────────────────────────────────────────────────────────────────────────────────*/
.permSets: procedure expose @.; parse arg p,q; pm= p-1
do k=pm by -1 for pm; kp= k+1; if @.k<@.kp then do; q=k; leave; end
end /*k*/
do j=q+1 while j<p; parse value @.j @.p with @.p @.j; p= p-1
end /*j*/
if q==0 then return 0
do p=q+1 while @.p<@.q
end /*p*/
parse value @.p @.q with @.q @.p
return 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 called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use bigint try=>"GMP";
use ntheory qw<is_prime>;
# index of mininum value in list
sub min_index { my $b = $_[my $i = 0]; $_[$_] < $b && ($b = $_[$i = $_]) for 0..$#_; $i }
sub iter1 { my $m = shift; my $e = 0; return sub { $m ** $e++; } }
sub iter2 { my $m = shift; my $e = 1; return sub { $m * ($e *= 2) } }
sub pierpont {
my($max ) = shift || die 'Must specify count of primes to generate.';
my($kind) = @_ ? shift : 1;
die "Unknown type: $kind. Must be one of 1 (default) or 2" unless $kind == 1 || $kind == 2;
$kind = -1 if $kind == 2;
my $po3 = 3;
my $add_one = 3;
my @iterators;
push @iterators, iter1(2);
push @iterators, iter1(3); $iterators[1]->();
my @head = ($iterators[0]->(), $iterators[1]->());
my @pierpont;
do {
my $key = min_index(@head);
my $min = $head[$key];
push @pierpont, $min + $kind if is_prime($min + $kind);
$head[$key] = $iterators[$key]->();
if ($min >= $add_one) {
push @iterators, iter2($po3);
$add_one = $head[$#iterators] = $iterators[$#iterators]->();
$po3 *= 3;
}
} until @pierpont == $max;
@pierpont;
}
my @pierpont_1st = pierpont(250,1);
my @pierpont_2nd = pierpont(250,2);
say "First 50 Pierpont primes of the first kind:";
my $fmt = "%9d"x10 . "\n";
for my $row (0..4) { printf $fmt, map { $pierpont_1st[10*$row + $_] } 0..9 }
say "\nFirst 50 Pierpont primes of the second kind:";
for my $row (0..4) { printf $fmt, map { $pierpont_2nd[10*$row + $_] } 0..9 }
say "\n250th Pierpont prime of the first kind: " . $pierpont_1st[249];
say "\n250th Pierpont prime of the second kind: " . $pierpont_2nd[249]; |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Factor | Factor | ( scratchpad ) { "a" "b" "c" "d" "e" "f" } random .
"a" |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Falcon | Falcon |
lst = [1, 3, 5, 8, 10]
> randomPick(lst)
|
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
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Ursala | Ursala | #import std
#import nat
prime = ~<{0,1}&& -={2,3}!| ~&h&& (all remainder)^Dtt/~& iota@K31 |
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, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor |
USE: splitting
: splitp ( str -- seq ) " " split ;
: printp ( seq -- ) " " join print ;
: reverse-string ( str -- ) reverse print ;
: reverse-words ( str -- ) splitp [ reverse ] map printp ;
: reverse-phrase ( str -- ) splitp reverse printp ;
"rosetta code phrase reversal" [ reverse-string ] [ reverse-words ] [ reverse-phrase ] tri
|
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, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fortran | Fortran | DO WHILE (L1.LE.L .AND. ATXT(L1).LE." ")
L1 = L1 + 1
END DO |
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.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Clojure | Clojure | (ns derangements.core
(:require [clojure.set :as s]))
(defn subfactorial [n]
(case n
0 1
1 0
(* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2))))))
(defn no-fixed-point
"f : A -> B must be a biyective function written as a hash-map, returns
all g : A -> B such that (f(a) = b) => not(g(a) = b)"
[f]
(case (count f)
0 [{}]
1 []
(let [g (s/map-invert f)
a (first (keys f))
a' (f a)]
(mapcat
(fn [b'] (let [b (g b')
f' (dissoc f a b)]
(concat (map #(reduce conj % [[a b'] [b a']])
(no-fixed-point f'))
(map #(conj % [a b'])
(no-fixed-point (assoc f' b a'))))))
(filter #(not= a' %) (keys g))))))
(defn derangements [xs]
{:pre [(= (count xs) (count (set xs)))]}
(map (fn [f] (mapv f xs))
(no-fixed-point (into {} (map vector xs xs)))))
(defn -main []
(do
(doall (map println (derangements [0,1,2,3])))
(doall (map #(println (str (subfactorial %) " " (count (derangements (range %)))))
(range 10)))
(println (subfactorial 20))))
|
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #D | D | import std.algorithm, std.array, std.typecons, std.range;
struct Spermutations(bool doCopy=true) {
private immutable uint n;
alias TResult = Tuple!(int[], int);
int opApply(in int delegate(in ref TResult) nothrow dg) nothrow {
int result;
int sign = 1;
alias Int2 = Tuple!(int, int);
auto p = n.iota.map!(i => Int2(i, i ? -1 : 0)).array;
TResult aux;
aux[0] = p.map!(pi => pi[0]).array;
aux[1] = sign;
result = dg(aux);
if (result)
goto END;
while (p.any!q{ a[1] }) {
// Failed to use std.algorithm here, too much complex.
auto largest = Int2(-100, -100);
int i1 = -1;
foreach (immutable i, immutable pi; p)
if (pi[1])
if (pi[0] > largest[0]) {
i1 = i;
largest = pi;
}
immutable n1 = largest[0],
d1 = largest[1];
sign *= -1;
int i2;
if (d1 == -1) {
i2 = i1 - 1;
p[i1].swap(p[i2]);
if (i2 == 0 || p[i2 - 1][0] > n1)
p[i2][1] = 0;
} else if (d1 == 1) {
i2 = i1 + 1;
p[i1].swap(p[i2]);
if (i2 == n - 1 || p[i2 + 1][0] > n1)
p[i2][1] = 0;
}
if (doCopy) {
aux[0] = p.map!(pi => pi[0]).array;
} else {
foreach (immutable i, immutable pi; p)
aux[0][i] = pi[0];
}
aux[1] = sign;
result = dg(aux);
if (result)
goto END;
foreach (immutable i3, ref pi; p) {
immutable n3 = pi[0],
d3 = pi[1];
if (n3 > n1)
pi[1] = (i3 < i2) ? 1 : -1;
}
}
END: return result;
}
}
Spermutations!doCopy spermutations(bool doCopy=true)(in uint n) {
return typeof(return)(n);
}
version (permutations_by_swapping1) {
void main() {
import std.stdio;
foreach (immutable n; [3, 4]) {
writefln("\nPermutations and sign of %d items", n);
foreach (const tp; n.spermutations)
writefln("Perm: %s Sign: %2d", tp[]);
}
}
} |
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 subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #FreeBASIC | FreeBASIC |
Dim Shared datos(18) As Integer => {85, 88, 75, 66, 25, 29, 83, 39, 97,_
68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
Function pick(at As Integer, remain As Integer, accu As Integer, treat As Integer) As Integer
If remain = 0 Then
If accu > treat Then Return 1 Else Return 0
End If
Dim a As Integer
If at > remain Then a = pick(at-1, remain, accu, treat) Else a = 0
Return pick(at-1, remain-1, accu+datos(at), treat) + a
End Function
Dim As Integer treat = 0, le, gt, total = 1, i
For i = 1 To 9
treat += datos(i)
Next i
For i = 19 To 11 Step -1
total *= i
Next i
For i = 9 To 1 Step -1
total /= i
Next i
gt = pick(19, 9, 0, treat)
le = total - gt
Print Using "<= : ##.######% #####"; 100*le/total; le
Print Using " > : ##.######% #####"; 100*gt/total; gt
Sleep
|
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
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #C | C | #include <stdio.h>
#include <stdlib.h>
// just generate 0s and 1s without storing them
double run_test(double p, int len, int runs)
{
int r, x, y, i, cnt = 0, thresh = p * RAND_MAX;
for (r = 0; r < runs; r++)
for (x = 0, i = len; i--; x = y)
cnt += x < (y = rand() < thresh);
return (double)cnt / runs / len;
}
int main(void)
{
double p, p1p, K;
int ip, n;
puts( "running 1000 tests each:\n"
" p\t n\tK\tp(1-p)\t diff\n"
"-----------------------------------------------");
for (ip = 1; ip < 10; ip += 2) {
p = ip / 10., p1p = p * (1 - p);
for (n = 100; n <= 100000; n *= 10) {
K = run_test(p, n, 1000);
printf("%.1f\t%6d\t%.4f\t%.4f\t%+.4f (%+.2f%%)\n",
p, n, K, p1p, K - p1p, (K - p1p) / p1p * 100);
}
putchar('\n');
}
return 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
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *cell, *start, *end;
int m, n;
void make_grid(int x, int y, double p)
{
int i, j, thresh = p * RAND_MAX;
m = x, n = y;
end = start = realloc(start, (x+1) * (y+1) + 1);
memset(start, 0, m + 1);
cell = end = start + m + 1;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
*end++ = rand() < thresh ? '+' : '.';
*end++ = '\n';
}
end[-1] = 0;
end -= ++m; // end is the first cell of bottom row
}
int ff(char *p) // flood fill
{
if (*p != '+') return 0;
*p = '#';
return p >= end || ff(p+m) || ff(p+1) || ff(p-1) || ff(p-m);
}
int percolate(void)
{
int i;
for (i = 0; i < m && !ff(cell + i); i++);
return i < m;
}
int main(void)
{
make_grid(15, 15, .5);
percolate();
puts("15x15 grid:");
puts(cell);
puts("\nrunning 10,000 tests for each case:");
double p;
int ip, i, cnt;
for (ip = 0; ip <= 10; ip++) {
p = ip / 10.;
for (cnt = i = 0; i < 10000; i++) {
make_grid(15, 15, p);
cnt += percolate();
}
printf("p=%.1f: %.4f\n", p, cnt / 10000.);
}
return 0;
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #11l | 11l | V a = [1, 2, 3]
L
print(a)
I !a.next_permutation()
L.break |
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 repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #11l | 11l | F flatten(lst)
[Int] r
L(sublst) lst
L(i) sublst
r [+]= i
R r
F magic_shuffle(deck)
V half = deck.len I/ 2
R flatten(zip(deck[0 .< half], deck[half ..]))
F after_how_many_is_equal(start, end)
V deck = magic_shuffle(start)
V counter = 1
L deck != end
deck = magic_shuffle(deck)
counter++
R counter
print(‘Length of the deck of cards | Perfect shuffles needed to obtain the same deck back’)
L(length) (8, 24, 52, 100, 1020, 1024, 10000)
V deck = Array(0 .< length)
V shuffles_needed = after_how_many_is_equal(deck, deck)
print(‘#<5 | #.’.format(length, shuffles_needed)) |
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
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #D | D | import std.stdio, std.math;
struct PerlinNoise {
private static double fade(in double t) pure nothrow @safe @nogc {
return t ^^ 3 * (t * (t * 6 - 15) + 10);
}
private static double lerp(in double t, in double a, in double b)
pure nothrow @safe @nogc {
return a + t * (b - a);
}
private static double grad(in ubyte hash,
in double x, in double y, in double z)
pure nothrow @safe @nogc {
// Convert lo 4 bits of hash code into 12 gradient directions.
immutable h = hash & 0xF;
immutable double u = (h < 8) ? x : y,
v = (h < 4) ? y : (h == 12 || h == 14 ? x : z);
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
static immutable ubyte[512] p;
static this() pure nothrow @safe @nogc {
static immutable permutation = cast(ubyte[256])x"97 A0 89 5B 5A
0F 83 0D C9 5F 60 35 C2 E9 07 E1 8C 24 67 1E 45 8E 08 63 25
F0 15 0A 17 BE 06 94 F7 78 EA 4B 00 1A C5 3E 5E FC DB CB 75
23 0B 20 39 B1 21 58 ED 95 38 57 AE 14 7D 88 AB A8 44 AF 4A
A5 47 86 8B 30 1B A6 4D 92 9E E7 53 6F E5 7A 3C D3 85 E6 DC
69 5C 29 37 2E F5 28 F4 66 8F 36 41 19 3F A1 01 D8 50 49 D1
4C 84 BB D0 59 12 A9 C8 C4 87 82 74 BC 9F 56 A4 64 6D C6 AD
BA 03 40 34 D9 E2 FA 7C 7B 05 CA 26 93 76 7E FF 52 55 D4 CF
CE 3B E3 2F 10 3A 11 B6 BD 1C 2A DF B7 AA D5 77 F8 98 02 2C
9A A3 46 DD 99 65 9B A7 2B AC 09 81 16 27 FD 13 62 6C 6E 4F
71 E0 E8 B2 B9 70 68 DA F6 61 E4 FB 22 F2 C1 EE D2 90 0C BF
B3 A2 F1 51 33 91 EB F9 0E EF 6B 31 C0 D6 1F B5 C7 6A 9D B8
54 CC B0 73 79 32 2D 7F 04 96 FE 8A EC CD 5D DE 72 43 1D 18
48 F3 8D 80 C3 4E 42 D7 3D 9C B4";
// Two copies of permutation.
p[0 .. permutation.length] = permutation[];
p[permutation.length .. $] = permutation[];
}
/// x0, y0 and z0 can be any real numbers, but the result is
/// zero if they are all integers.
/// The result is probably in [-1.0, 1.0].
static double opCall(in double x0, in double y0, in double z0)
pure nothrow @safe @nogc {
// Find unit cube that contains point.
immutable ubyte X = cast(int)x0.floor & 0xFF,
Y = cast(int)y0.floor & 0xFF,
Z = cast(int)z0.floor & 0xFF;
// Find relative x,y,z of point in cube.
immutable x = x0 - x0.floor,
y = y0 - y0.floor,
z = z0 - z0.floor;
// Compute fade curves for each of x,y,z.
immutable u = fade(x),
v = fade(y),
w = fade(z);
// Hash coordinates of the 8 cube corners.
immutable 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;
// And add blended results from 8 corners of cube.
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1),
grad(p[BA+1], x-1, y , z-1)),
lerp(u, grad(p[AB+1], x , y-1, z-1),
grad(p[BB+1], x-1, y-1, z-1))));
}
}
void main() {
writefln("%1.17f", PerlinNoise(3.14, 42, 7));
/*
// Generate a demo image using the Gray Scale task module.
import grayscale_image;
enum N = 200;
auto im = new Image!Gray(N, N);
foreach (immutable y; 0 .. N)
foreach (immutable x; 0 .. N) {
immutable p = PerlinNoise(x / 30.0, y / 30.0, 0.1);
im[x, y] = Gray(cast(ubyte)((p + 1) / 2 * 256));
}
im.savePGM("perlin_noise.pgm");
*/
} |
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
| #AWK | AWK |
# syntax: GAWK -f PERFECT_TOTIENT_NUMBERS.AWK
BEGIN {
i = 20
printf("The first %d perfect totient numbers:\n%s\n",i,perfect_totient(i))
exit(0)
}
function perfect_totient(n, count,m,str,sum,tot) {
for (m=1; count<n; m++) {
tot = m
sum = 0
while (tot != 1) {
tot = totient(tot)
sum += tot
}
if (sum == m) {
str = str m " "
count++
}
}
return(str)
}
function totient(n, i,tot) {
tot = n
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)
}
|
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
| #BASIC | BASIC | 10 DEFINT A-Z
20 N=3
30 S=N: T=0
40 X=S: S=0
50 FOR I=1 TO X-1
60 A=X: B=I
70 IF B>0 THEN C=A: A=B: B=C MOD B: GOTO 70
80 IF A=1 THEN S=S+1
90 NEXT
100 T=T+S
110 IF S>1 GOTO 40
120 IF T=N THEN PRINT N,: Z=Z+1
130 N=N+2
140 IF Z<20 GOTO 30 |
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 must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #D | D | import std.stdio, std.typecons, std.algorithm, std.traits, std.array,
std.range, std.random;
enum Pip {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, Queen, King, Ace}
enum Suit {Diamonds, Spades, Hearts, Clubs}
alias Card = Tuple!(Pip, Suit);
auto newDeck() pure nothrow @safe {
return cartesianProduct([EnumMembers!Pip], [EnumMembers!Suit]);
}
alias shuffleDeck = randomShuffle;
Card dealCard(ref Card[] deck) pure nothrow @safe @nogc {
immutable card = deck.back;
deck.popBack;
return card;
}
void show(in Card[] deck) @safe {
writefln("Deck:\n%(%s\n%)\n", deck);
}
void main() /*@safe*/ {
auto d = newDeck.array;
d.show;
d.shuffleDeck;
while (!d.empty)
d.dealCard.writeln;
} |
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 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Common_Lisp | Common Lisp | (defun pi-spigot ()
(labels
((g (q r t1 k n l)
(cond
((< (- (+ (* 4 q) r) t1)
(* n t1))
(princ n)
(g (* 10 q)
(* 10 (- r (* n t1)))
t1
k
(- (floor (/ (* 10 (+ (* 3 q) r))
t1))
(* 10 n))
l))
(t
(g (* q k)
(* (+ (* 2 q) r) l)
(* t1 l)
(+ k 1)
(floor (/ (+ (* q (+ (* 7 k) 2))
(* r l))
(* t1 l)))
(+ l 2))))))
(g 1 0 1 1 3 3))) |
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 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[FindPeriodGroup]
FindPeriodGroup[n_Integer] := Which[57 <= n <= 70,
{8, n - 53}
,
89 <= n <= 102,
{9, n - 85}
,
1 <= n <= 118,
{ElementData[n, "Period"], ElementData[n, "Group"]}
,
True,
Missing["Element does not exist"]
]
Row[{"Element ", #, " -> ", FindPeriodGroup[#]}] & /@ {1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113} // Column
Graphics[Text[#, {1, -1} Reverse@FindPeriodGroup[#]] & /@ Range[118]] |
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 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #Perl | Perl | use strict;
use warnings; no warnings 'uninitialized';
use feature 'say';
use List::Util <sum head>;
sub divmod { int $_[0]/$_[1], $_[0]%$_[1] }
my $b = 18;
my(@offset,@span,$cnt);
push @span, ($cnt++) x $_ for <1 3 8 44 15 17 15 15>;
@offset = (16, 10, 10, (2*$b)+1, (-2*$b)-15, (2*$b)+1, (-2*$b)-15);
for my $n (<1 2 29 42 57 58 72 89 90 103 118>) {
printf "%3d: %2d, %2d\n", $n, map { $_+1 } divmod $n-1 + sum(head $span[$n-1], @offset), $b;
} |
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 the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Java | Java | import java.util.*;
public class PigDice {
public static void main(String[] args) {
final int maxScore = 100;
final int playerCount = 2;
final String[] yesses = {"y", "Y", ""};
int[] safeScore = new int[2];
int player = 0, score = 0;
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
while (true) {
System.out.printf(" Player %d: (%d, %d) Rolling? (y/n) ", player,
safeScore[player], score);
if (safeScore[player] + score < maxScore
&& Arrays.asList(yesses).contains(sc.nextLine())) {
final int rolled = rnd.nextInt(6) + 1;
System.out.printf(" Rolled %d\n", rolled);
if (rolled == 1) {
System.out.printf(" Bust! You lose %d but keep %d\n\n",
score, safeScore[player]);
} else {
score += rolled;
continue;
}
} else {
safeScore[player] += score;
if (safeScore[player] >= maxScore)
break;
System.out.printf(" Sticking with %d\n\n", safeScore[player]);
}
score = 0;
player = (player + 1) % playerCount;
}
System.out.printf("\n\nPlayer %d wins with a score of %d",
player, safeScore[player]);
}
} |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #D | D | void main() {
import std.stdio, std.algorithm, std.range, core.bitop;
immutable pernicious = (in uint n) => (2 ^^ n.popcnt) & 0xA08A28AC;
uint.max.iota.filter!pernicious.take(25).writeln;
iota(888_888_877, 888_888_889).filter!pernicious.writeln;
} |
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
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Ring | Ring |
# Project : Permutations/Rank of a permutation
list = [0, 1, 2, 3]
for perm = 0 to 23
str = ""
for i = 1 to len(list)
str = str + list[i] + ", "
next
see nl
str = left(str, len(str)-2)
see "(" + str + ") -> " + perm
nextPermutation(list)
next
func nextPermutation(a)
elementcount = len(a)
if elementcount < 1 then return ok
pos = elementcount-1
while a[pos] >= a[pos+1]
pos -= 1
if pos <= 0 permutationReverse(a, 1, elementcount)
return
ok
end
last = elementcount
while a[last] <= a[pos]
last -= 1
end
temp = a[pos]
a[pos] = a[last]
a[last] = temp
permutationReverse(a, pos+1, elementcount)
func permutationReverse(a, first, last)
while first < last
temp = a[first]
a[first] = a[last]
a[last] = temp
first = first + 1
last = last - 1
end
|
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
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Ruby | Ruby | class Permutation
include Enumerable
attr_reader :num_elements, :size
def initialize(num_elements)
@num_elements = num_elements
@size = fact(num_elements)
end
def each
return self.to_enum unless block_given?
(0...@size).each{|i| yield unrank(i)}
end
def unrank(r) # nonrecursive version of Myrvold Ruskey unrank2 algorithm.
pi = (0...num_elements).to_a
(@num_elements-1).downto(1) do |n|
s, r = r.divmod(fact(n))
pi[n], pi[s] = pi[s], pi[n]
end
pi
end
def rank(pi) # nonrecursive version of Myrvold Ruskey rank2 algorithm.
pi = pi.dup
pi1 = pi.zip(0...pi.size).sort.map(&:last)
(pi.size-1).downto(0).inject(0) do |memo,i|
pi[i], pi[pi1[i]] = pi[pi1[i]], (s = pi[i])
pi1[s], pi1[i] = pi1[i], pi1[s]
memo += s * fact(i)
end
end
private
def fact(n)
n.zero? ? 1 : n.downto(1).inject(:*)
end
end |
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 called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Phix | Phix | -- demo/rosetta/Pierpont_primes.exw
with javascript_semantics
include mpfr.e
function pierpont(integer n)
sequence p = {{mpz_init(2)},{}},
s = {mpz_init(1)}
integer i2 = 1, i3 = 1
mpz {n2, n3, t} = mpz_inits(3)
atom t1 = time()+1
while min(length(p[1]),length(p[2])) < n do
mpz_mul_si(n2,s[i2],2)
mpz_mul_si(n3,s[i3],3)
if mpz_cmp(n2,n3)<0 then
mpz_set(t,n2)
i2 += 1
else
mpz_set(t,n3)
i3 += 1
end if
if mpz_cmp(t,s[$]) > 0 then
s = append(s, mpz_init_set(t))
mpz_add_ui(t,t,1)
if length(p[1]) < n and mpz_prime(t) then
p[1] = append(p[1],mpz_init_set(t))
end if
mpz_sub_ui(t,t,2)
if length(p[2]) < n and mpz_prime(t) then
p[2] = append(p[2],mpz_init_set(t))
end if
end if
if time()>t1 then
printf(1,"Found: 1st:%d/%d, 2nd:%d/%d\r",
{length(p[1]),n,length(p[2]),n})
t1 = time()+1
end if
end while
return p
end function
--constant limit = 2000 -- 2 mins
--constant limit = 1000 -- 8.1s
constant limit = 250 -- 0.1s
atom t0 = time()
sequence p = pierpont(limit)
constant fs = {"first","second"}
for i=1 to length(fs) do
printf(1,"First 50 Pierpont primes of the %s kind:\n",{fs[i]})
for j=1 to 50 do
printf(1,"%8s ", {mpz_get_str(p[i][j])})
if mod(j,10)=0 then printf(1,"\n") end if
end for
printf(1,"\n")
end for
constant t = {250,1000,2000}
for i=1 to length(t) do
integer ti = t[i]
if ti>limit then exit end if
for j=1 to length(fs) do
string zs = shorten(mpz_get_str(p[j][ti]))
printf(1,"%dth Pierpont prime of the %s kind: %s\n",{ti,fs[j],zs})
end for
printf(1,"\n")
end for
printf(1,"Took %s\n", elapsed(time()-t0))
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Fortran | Fortran | program pick_random
implicit none
integer :: i
integer :: a(10) = (/ (i, i = 1, 10) /)
real :: r
call random_seed
call random_number(r)
write(*,*) a(int(r*size(a)) + 1)
end program |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Free_Pascal | Free Pascal | ' FB 1.05.0 Win64
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Randomize
Dim randInt As Integer
For i As Integer = 1 To 5
randInt = Int(Rnd * 10)
Print a(randInt)
Next
Sleep |
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
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #V | V | [prime?
2
[[dup * >] [true] [false] ifte [% 0 >] dip and]
[succ]
while
dup * <]. |
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, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub split (s As Const String, sepList As Const String, result() As String)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1) = Mid(s, position(i - 1) + 1, length)
Next
End Sub
Function reverse(s As Const String) As String
If s = "" Then Return ""
Dim t As String = s
Dim length As Integer = Len(t)
For i As Integer = 0 to length\2 - 1
Swap t[i], t[length - 1 - i]
Next
Return t
End Function
Dim s As String = "rosetta code phrase reversal"
Dim a() As String
Dim sepList As String = " "
Print "Original string => "; s
Print "Reversed string => "; reverse(s)
Print "Reversed words => ";
split s, sepList, a()
For i As Integer = LBound(a) To UBound(a)
Print reverse(a(i)); " ";
Next
Print
Print "Reversed order => ";
For i As Integer = UBound(a) To LBound(a) Step -1
Print a(i); " ";
Next
Print : Print
Print "Press any key to quit"
Sleep |
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.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #D | D | import std.stdio, std.algorithm, std.typecons, std.conv,
std.range, std.traits;
T factorial(T)(in T n) pure nothrow @safe @nogc {
Unqual!T result = 1;
foreach (immutable i; 2 .. n + 1)
result *= i;
return result;
}
T subfact(T)(in T n) pure nothrow @safe @nogc {
if (0 <= n && n <= 2)
return n != 1;
return (n - 1) * (subfact(n - 1) + subfact(n - 2));
}
auto derangements(in size_t n, in bool countOnly=false)
pure nothrow @safe {
size_t[] seq = n.iota.array;
auto ori = seq.idup;
size_t[][] all;
size_t cnt = n == 0;
foreach (immutable tot; 0 .. n.factorial - 1) {
size_t j = n - 2;
while (seq[j] > seq[j + 1])
j--;
size_t k = n - 1;
while (seq[j] > seq[k])
k--;
seq[k].swap(seq[j]);
size_t r = n - 1;
size_t s = j + 1;
while (r > s) {
seq[s].swap(seq[r]);
r--;
s++;
}
j = 0;
while (j < n && seq[j] != ori[j])
j++;
if (j == n) {
if (countOnly)
cnt++;
else
all ~= seq.dup;
}
}
return tuple(all, cnt);
}
void main() @safe {
"Derangements for n = 4:".writeln;
foreach (const d; 4.derangements[0])
d.writeln;
"\nTable of n vs counted vs calculated derangements:".writeln;
foreach (immutable i; 0 .. 10)
writefln("%s %-7s%-7s", i, derangements(i, 1)[1], i.subfact);
writefln("\n!20 = %s", 20L.subfact);
} |
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 of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #EchoLisp | EchoLisp |
(lib 'list)
(for/fold (sign 1) ((σ (in-permutations 4)) (count 100))
(printf "perm: %a count:%4d sign:%4d" σ count sign) (* sign -1))
perm: (0 1 2 3) count: 0 sign: 1
perm: (0 1 3 2) count: 1 sign: -1
perm: (0 3 1 2) count: 2 sign: 1
perm: (3 0 1 2) count: 3 sign: -1
perm: (3 0 2 1) count: 4 sign: 1
perm: (0 3 2 1) count: 5 sign: -1
perm: (0 2 3 1) count: 6 sign: 1
perm: (0 2 1 3) count: 7 sign: -1
perm: (2 0 1 3) count: 8 sign: 1
perm: (2 0 3 1) count: 9 sign: -1
perm: (2 3 0 1) count: 10 sign: 1
perm: (3 2 0 1) count: 11 sign: -1
perm: (3 2 1 0) count: 12 sign: 1
perm: (2 3 1 0) count: 13 sign: -1
perm: (2 1 3 0) count: 14 sign: 1
perm: (2 1 0 3) count: 15 sign: -1
perm: (1 2 0 3) count: 16 sign: 1
perm: (1 2 3 0) count: 17 sign: -1
perm: (1 3 2 0) count: 18 sign: 1
perm: (3 1 2 0) count: 19 sign: -1
perm: (3 1 0 2) count: 20 sign: 1
perm: (1 3 0 2) count: 21 sign: -1
perm: (1 0 3 2) count: 22 sign: 1
perm: (1 0 2 3) count: 23 sign: -1
|
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 subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Go | Go | package main
import "fmt"
var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}
var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
func main() {
// collect all results in a single list
all := make([]int, len(tr)+len(ct))
copy(all, tr)
copy(all[len(tr):], ct)
// compute sum of all data, useful as intermediate result
var sumAll int
for _, r := range all {
sumAll += r
}
// closure for computing scaled difference.
// compute results scaled by len(tr)*len(ct).
// this allows all math to be done in integers.
sd := func(trc []int) int {
var sumTr int
for _, x := range trc {
sumTr += all[x]
}
return sumTr*len(ct) - (sumAll-sumTr)*len(tr)
}
// compute observed difference, as an intermediate result
a := make([]int, len(tr))
for i, _ := range a {
a[i] = i
}
sdObs := sd(a)
// iterate over all combinations. for each, compute (scaled)
// difference and tally whether leq or gt observed difference.
var nLe, nGt int
comb(len(all), len(tr), func(c []int) {
if sd(c) > sdObs {
nGt++
} else {
nLe++
}
})
// print results as percentage
pc := 100 / float64(nLe+nGt)
fmt.Printf("differences <= observed: %f%%\n", float64(nLe)*pc)
fmt.Printf("differences > observed: %f%%\n", float64(nGt)*pc)
}
// combination generator, copied from combination task
func comb(n, m int, emit func([]int)) {
s := make([]int, m)
last := m - 1
var rc func(int, int)
rc = func(i, next int) {
for j := next; j < n; j++ {
s[i] = j
if i == last {
emit(s)
} else {
rc(i+1, j+1)
}
}
return
}
rc(0, 0)
} |
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
{\displaystyle c}
be a 2D boolean square matrix of
n
×
n
{\displaystyle n\times n}
values of either 1 or 0 where the
probability of any value being 1 is
p
{\displaystyle p}
, (and of 0 is therefore
1
−
p
{\displaystyle 1-p}
).
We define a cluster of 1's as being a group of 1's connected vertically or
horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either
0
{\displaystyle 0}
or by the limits of the matrix.
Let the number of such clusters in such a randomly constructed matrix be
C
n
{\displaystyle C_{n}}
.
Percolation theory states that
K
(
p
)
{\displaystyle K(p)}
(the mean cluster density) will satisfy
K
(
p
)
=
C
n
/
n
2
{\displaystyle K(p)=C_{n}/n^{2}}
as
n
{\displaystyle n}
tends to infinity. For
p
=
0.5
{\displaystyle p=0.5}
,
K
(
p
)
{\displaystyle K(p)}
is found numerically to approximate
0.065770
{\displaystyle 0.065770}
...
Task
Show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
for
p
=
0.5
{\displaystyle p=0.5}
and
for values of
n
{\displaystyle n}
up to at least
1000
{\displaystyle 1000}
.
Any calculation of
C
n
{\displaystyle C_{n}}
for finite
n
{\displaystyle n}
is subject to randomness, so an approximation should be
computed as the average of
t
{\displaystyle t}
runs, where
t
{\displaystyle t}
≥
5
{\displaystyle 5}
.
For extra credit, graphically show clusters in a
15
×
15
{\displaystyle 15\times 15}
,
p
=
0.5
{\displaystyle p=0.5}
grid.
Show your output here.
See also
s-Cluster on Wolfram mathworld. | #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R (:seed >> 16) / Float(FF'FF)
V nn = 15
V tt = 5
V pp = 0.5
V NotClustered = 1
V Cell2Char = ‘ #abcdefghijklmnopqrstuvwxyz’
V NRange = [4, 64, 256, 1024, 4096]
F newGrid(n, p)
R (0 .< n).map(i -> (0 .< @n).map(i -> Int(nonrandom() < @@p)))
F walkMaze(&grid, m, n, idx) -> N
grid[n][m] = idx
I n < grid.len - 1 & grid[n + 1][m] == NotClustered
walkMaze(&grid, m, n + 1, idx)
I m < grid[0].len - 1 & grid[n][m + 1] == NotClustered
walkMaze(&grid, m + 1, n, idx)
I m > 0 & grid[n][m - 1] == NotClustered
walkMaze(&grid, m - 1, n, idx)
I n > 0 & grid[n - 1][m] == NotClustered
walkMaze(&grid, m, n - 1, idx)
F clusterCount(&grid)
V walkIndex = 1
L(n) 0 .< grid.len
L(m) 0 .< grid[0].len
I grid[n][m] == NotClustered
walkIndex++
walkMaze(&grid, m, n, walkIndex)
R walkIndex - 1
F clusterDensity(n, p)
V grid = newGrid(n, p)
R clusterCount(&grid) / Float(n * n)
F print_grid(grid)
L(row) grid
print(L.index % 10, end' ‘) ’)
L(cell) row
print(‘ ’Cell2Char[cell], end' ‘’)
print()
V grid = newGrid(nn, 0.5)
print(‘Found ’clusterCount(&grid)‘ clusters in this ’nn‘ by ’nn" grid\n")
print_grid(grid)
print()
L(n) NRange
V sum = 0.0
L 0 .< tt
sum += clusterDensity(n, pp)
V sim = sum / tt
print(‘t = #. p = #.2 n = #4 sim = #.5’.format(tt, pp, n, sim)) |
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
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #C.2B.2B | C++ | #include <algorithm>
#include <random>
#include <vector>
#include <iostream>
#include <numeric>
#include <iomanip>
using VecIt = std::vector<int>::const_iterator ;
//creates vector of length n, based on probability p for 1
std::vector<int> createVector( int n, double p ) {
std::vector<int> result( n ) ;
std::random_device rd ;
std::mt19937 gen( rd( ) ) ;
std::uniform_real_distribution<> dis( 0 , 1 ) ;
for ( int i = 0 ; i < n ; i++ ) {
double number = dis( gen ) ;
if ( number <= p )
result[ i ] = 1 ;
else
result[ i ] = 0 ;
}
return result ;
}
//find number of 1 runs in the vector
int find_Runs( const std::vector<int> & numberVector ) {
int runs = 0 ;
VecIt found = numberVector.begin( ) ;
while ( ( found = std::find( found , numberVector.end( ) , 1 ) )
!= numberVector.end( ) ) {
runs++ ;
while ( found != numberVector.end( ) && ( *found == 1 ) )
std::advance( found , 1 ) ;
if ( found == numberVector.end( ) )
break ;
}
return runs ;
}
int main( ) {
std::cout << "t = 100\n" ;
std::vector<double> p_values { 0.1 , 0.3 , 0.5 , 0.7 , 0.9 } ;
for ( double p : p_values ) {
std::cout << "p = " << p << " , K(p) = " << p * ( 1 - p ) << std::endl ;
for ( int n = 10 ; n < 100000 ; n *= 10 ) {
std::vector<double> runsFound ;
for ( int i = 0 ; i < 100 ; i++ ) {
std::vector<int> ones_and_zeroes = createVector( n , p ) ;
runsFound.push_back( find_Runs( ones_and_zeroes ) / static_cast<double>( n ) ) ;
}
double average = std::accumulate( runsFound.begin( ) , runsFound.end( ) , 0.0 ) / runsFound.size( ) ;
std::cout << " R(" << std::setw( 6 ) << std::right << n << ", p) = " << average << std::endl ;
}
}
return 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
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #D | D | import std.stdio, std.random, std.array, std.datetime;
enum size_t nCols = 15,
nRows = 15,
nSteps = 11, // Probability granularity.
nTries = 20_000; // Simulation tries.
enum Cell : char { empty = ' ', filled = '#', visited = '.' }
alias Grid = Cell[nCols][nRows];
void initialize(ref Grid grid, in double probability, ref Xorshift rng) {
foreach (ref row; grid)
foreach (ref cell; row)
cell = (rng.uniform01 < probability) ? Cell.empty : Cell.filled;
}
void show(in ref Grid grid) @safe {
writefln("%(|%(%c%)|\n%)|", grid);
}
bool percolate(ref Grid grid) pure nothrow @safe @nogc {
bool walk(in size_t r, in size_t c) nothrow @safe @nogc {
enum bottom = nRows - 1;
grid[r][c] = Cell.visited;
if (r < bottom && grid[r + 1][c] == Cell.empty) { // Down.
if (walk(r + 1, c))
return true;
} else if (r == bottom)
return true;
if (c && grid[r][c - 1] == Cell.empty) // Left.
if (walk(r, c - 1))
return true;
if (c < nCols - 1 && grid[r][c + 1] == Cell.empty) // Right.
if (walk(r, c + 1))
return true;
if (r && grid[r - 1][c] == Cell.empty) // Up.
if (walk(r - 1, c))
return true;
return false;
}
enum startR = 0;
foreach (immutable c; 0 .. nCols)
if (grid[startR][c] == Cell.empty)
if (walk(startR, c))
return true;
return false;
}
void main() {
static struct Counter {
double prob;
size_t count;
}
StopWatch sw;
sw.start;
enum probabilityStep = 1.0 / (nSteps - 1);
Counter[nSteps] counters;
foreach (immutable i, ref co; counters)
co.prob = i * probabilityStep;
Grid grid;
bool sampleShown = false;
auto rng = Xorshift(unpredictableSeed);
foreach (ref co; counters) {
foreach (immutable _; 0 .. nTries) {
grid.initialize(co.prob, rng);
if (grid.percolate) {
co.count++;
if (!sampleShown) {
writefln("Percolating sample (%dx%d, probability =%5.2f):",
nCols, nRows, co.prob);
grid.show;
sampleShown = true;
}
}
}
}
sw.stop;
writefln("\nFraction of %d tries that percolate through:", nTries);
foreach (const co; counters)
writefln("%1.3f %1.3f", co.prob, co.count / double(nTries));
writefln("\nSimulations and grid printing performed" ~
" in %3.2f seconds.", sw.peek.msecs / 1000.0);
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #360_Assembly | 360 Assembly | * Permutations 26/10/2015
PERMUTE CSECT
USING PERMUTE,R15 set base register
LA R9,TMP-A n=hbound(a)
SR R10,R10 nn=0
LOOP LA R10,1(R10) nn=nn+1
LA R11,PG pgi=@pg
LA R6,1 i=1
LOOPI1 CR R6,R9 do i=1 to n
BH ELOOPI1
LA R2,A-1(R6) @a(i)
MVC 0(1,R11),0(R2) output a(i)
LA R11,1(R11) pgi=pgi+1
LA R6,1(R6) i=i+1
B LOOPI1
ELOOPI1 XPRNT PG,80
LR R6,R9 i=n
LOOPUIM BCTR R6,0 i=i-1
LTR R6,R6 until i=0
BE ELOOPUIM
LA R2,A-1(R6) @a(i)
LA R3,A(R6) @a(i+1)
CLC 0(1,R2),0(R3) or until a(i)<a(i+1)
BNL LOOPUIM
ELOOPUIM LR R7,R6 j=i
LA R7,1(R7) j=i+1
LR R8,R9 k=n
LOOPWJ CR R7,R8 do while j<k
BNL ELOOPWJ
LA R2,A-1(R7) r2=@a(j)
LA R3,A-1(R8) r3=@a(k)
MVC TMP,0(R2) tmp=a(j)
MVC 0(1,R2),0(R3) a(j)=a(k)
MVC 0(1,R3),TMP a(k)=tmp
LA R7,1(R7) j=j+1
BCTR R8,0 k=k-1
B LOOPWJ
ELOOPWJ LTR R6,R6 if i>0
BNP ILE0
LR R7,R6 j=i
LA R7,1(R7) j=i+1
LOOPWA LA R2,A-1(R7) @a(j)
LA R3,A-1(R6) @a(i)
CLC 0(1,R2),0(R3) do while a(j)<a(i)
BNL AJGEAI
LA R7,1(R7) j=j+1
B LOOPWA
AJGEAI LA R2,A-1(R7) r2=@a(j)
LA R3,A-1(R6) r3=@a(i)
MVC TMP,0(R2) tmp=a(j)
MVC 0(1,R2),0(R3) a(j)=a(i)
MVC 0(1,R3),TMP a(i)=tmp
ILE0 LTR R6,R6 until i<>0
BNE LOOP
XR R15,R15 set return code
BR R14 return to caller
A DC C'ABCD' <== input
TMP DS C temp for swap
PG DC CL80' ' buffer
YREGS
END PERMUTE |
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 repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #Action.21 | Action! | DEFINE MAXDECK="5000"
PROC Order(INT ARRAY deck INT count)
INT i
FOR i=0 TO count-1
DO
deck(i)=i
OD
RETURN
BYTE FUNC IsOrdered(INT ARRAY deck INT count)
INT i
FOR i=0 TO count-1
DO
IF deck(i)#i THEN
RETURN (0)
FI
OD
RETURN (1)
PROC Shuffle(INT ARRAY src,dst INT count)
INT i,i1,i2
i=0 i1=0 i2=count RSH 1
WHILE i<count
DO
dst(i)=src(i1) i==+1 i1==+1
dst(i)=src(i2) i==+1 i2==+1
OD
RETURN
PROC Test(INT ARRAY deck,deck2 INT count)
INT ARRAY tmp
INT n
Order(deck,count)
n=0
DO
Shuffle(deck,deck2,count)
tmp=deck deck=deck2 deck2=tmp
n==+1
Poke(77,0) ;turn off the attract mode
PrintF("%I cards -> %I iterations%E",count,n)
Put(28) ;move cursor up
UNTIL IsOrdered(deck,count)
OD
PutE()
RETURN
PROC Main()
INT ARRAY deck(MAXDECK),deck2(MAXDECK)
INT ARRAY counts=[8 24 52 100 1020 1024 MAXDECK]
INT i
FOR i=0 TO 6
DO
Test(deck,deck2,counts(i))
OD
RETURN |
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 repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #Ada | Ada | with ada.text_io;use ada.text_io;
procedure perfect_shuffle is
function count_shuffle (half_size : Positive) return Positive is
subtype index is Natural range 0..2 * half_size - 1;
subtype index_that_move is index range index'first+1..index'last-1;
type deck is array (index) of index;
initial, d, next : deck;
count : Natural := 1;
begin
for i in index loop initial (i) := i; end loop;
d := initial;
loop
for i in index_that_move loop
next (i) := (if d (i) mod 2 = 0 then d(i)/2 else d(i)/2 + half_size);
end loop;
exit when next (index_that_move)= initial(index_that_move);
d := next;
count := count + 1;
end loop;
return count;
end count_shuffle;
test : array (Positive range <>) of Positive := (8, 24, 52, 100, 1020, 1024, 10_000);
begin
for size of test loop
put_line ("For" & size'img & " cards, there are "& count_shuffle (size / 2)'img & " shuffles needed.");
end loop;
end perfect_shuffle; |
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
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #Delphi | Delphi | x floor >integer 255 bitand :> X
y floor >integer 255 bitand :> Y
z floor >integer 255 bitand :> Z |
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
| #BASIC256 | BASIC256 | found = 0
curr = 3
while found < 20
sum = Totient(curr)
toti = sum
while toti <> 1
toti = Totient(toti)
sum += toti
end while
if sum = curr then
print sum
found += 1
end if
curr += 1
end while
end
function GCD(n, d)
if n = 0 then return d
if d = 0 then return n
if n > d then return GCD(d, (n mod d))
return GCD(n, (d mod n))
end function
function Totient(n)
phi = 0
for m = 1 to n
if GCD(m, n) = 1 then phi += 1
next m
return phi
end function |
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
| #BCPL | BCPL | get "libhdr"
let gcd(a,b) = b=0 -> a, gcd(b, a rem b)
let totient(n) = valof
$( let r = 0
for i=1 to n-1
if gcd(n,i) = 1 then r := r + 1
resultis r
$)
let perfect(n) = valof
$( let sum = 0 and x = n
$( x := totient(x)
sum := sum + x
$) repeatuntil x = 1
resultis sum = n
$)
let start() be
$( let seen = 0 and n = 3
while seen < 20
$( if perfect(n)
$( writef("%N ", n)
seen := seen + 1
$)
n := n + 2
$)
wrch('*N')
$) |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Delphi | Delphi | program Cards;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
type
TPip = (pTwo, pThree, pFour, pFive, pSix, pSeven, pEight, pNine, pTen, pJack, pQueen, pKing, pAce);
TSuite = (sDiamonds, sSpades, sHearts, sClubs);
const
cPipNames: array[TPip] of string = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A');
cSuiteNames: array[TSuite] of string = ('Diamonds', 'Spades', 'Hearts', 'Clubs');
type
TCard = class
private
FSuite: TSuite;
FPip: TPip;
public
constructor Create(aSuite: TSuite; aPip: TPip);
function ToString: string; override;
property Pip: TPip read FPip;
property Suite: TSuite read FSuite;
end;
TDeck = class
private
FCards: TList;
public
constructor Create;
destructor Destroy; override;
procedure Shuffle;
function Deal: TCard;
function ToString: string; override;
end;
{ TCard }
constructor TCard.Create(aSuite: TSuite; aPip: TPip);
begin
FSuite := aSuite;
FPip := aPip;
end;
function TCard.ToString: string;
begin
Result := Format('%s of %s', [cPipNames[Pip], cSuiteNames[Suite]])
end;
{ TDeck }
constructor TDeck.Create;
var
pip: TPip;
suite: TSuite;
begin
FCards := TList.Create;
for suite := Low(TSuite) to High(TSuite) do
for pip := Low(TPip) to High(TPip) do
FCards.Add(TCard.Create(suite, pip));
end;
function TDeck.Deal: TCard;
begin
Result := FCards[0];
FCards.Delete(0);
end;
destructor TDeck.Destroy;
var
i: Integer;
c: TCard;
begin
for i := FCards.Count - 1 downto 0 do begin
c := FCards[i];
FCards.Delete(i);
c.Free;
end;
FCards.Free;
inherited;
end;
procedure TDeck.Shuffle;
var
i, j: Integer;
temp: TCard;
begin
Randomize;
for i := FCards.Count - 1 downto 0 do begin
j := Random(FCards.Count);
temp := FCards[j];
FCards.Delete(j);
FCards.Add(temp);
end;
end;
function TDeck.ToString: string;
var
i: Integer;
begin
for i := 0 to FCards.Count - 1 do
Writeln(TCard(FCards[i]).ToString);
end;
begin
with TDeck.Create do
try
Shuffle;
ToString;
Writeln;
with Deal do
try
Writeln(ToString);
finally
Free;
end;
finally
Free;
end;
Readln;
end. |
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 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Crystal | Crystal | require "big"
def pi
q, r, t, k, n, l = [1, 0, 1, 1, 3, 3].map { |n| BigInt.new(n) }
dot_written = false
loop do
if 4*q + r - t < n*t
yield n
unless dot_written
yield '.'
dot_written = true
end
nr = 10*(r - n*t)
n = ((10*(3*q + r)) / t) - 10*n
q *= 10
r = nr
else
nr = (2*q + r) * l
nn = (q*(7*k + 2) + r*l) / (t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
end
end
end
pi { |digit_or_dot| print digit_or_dot; STDOUT.flush }
|
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 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #Phix | Phix | with javascript_semantics
constant match_wp = false
function prc(integer n)
constant t = {0,2,10,18,36,54,86,118,119}
integer row = abs(binary_search(n,t,true))-1,
col = n-t[row]
if col>1+(row>1) then
col = 18-(t[row+1]-n)
if match_wp then
if col<=2 then return {row+2,col+14} end if
else -- matches above ascii:
if col<=2+(row>5) then return {row+2,col+15} end if
end if
end if
return {row,col}
end function
sequence pt = repeat(repeat(" ",19),10)
pt[1][2..$] = apply(true,sprintf,{{"%3d"},tagset(18)}) -- column headings
for i=1 to 9 do pt[i+1][1] = sprintf("%3d",i) end for -- row numbers
for i=1 to 118 do
integer {r,c} = prc(i)
pt[r+1][c+1] = sprintf("%3d",i)
end for
if not match_wp then -- (ascii only:)
pt[7][4] = " L*"
pt[8][4] = " A*"
pt[9][2..4] = {"Lanthanide:"}
pt[10][2..4] = {" Actinide:"}
end if
printf(1,"%s\n",{join(apply(true,join,{pt,{"|"}}),"\n")})
|
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 the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #JavaScript | JavaScript | let players = [
{ name: '', score: 0 },
{ name: '', score: 0 }
];
let curPlayer = 1,
gameOver = false;
players[0].name = prompt('Your name, player #1:').toUpperCase();
players[1].name = prompt('Your name, player #2:').toUpperCase();
function roll() { return 1 + Math.floor(Math.random()*6) }
function round(player) {
let curSum = 0,
quit = false,
dice;
alert(`It's ${player.name}'s turn (${player.score}).`);
while (!quit) {
dice = roll();
if (dice == 1) {
alert('You roll a 1. What a pity!');
quit = true;
} else {
curSum += dice;
quit = !confirm(`
You roll a ${dice} (sum: ${curSum}).\n
Roll again?
`);
if (quit) {
player.score += curSum;
if (player.score >= 100) gameOver = true;
}
}
}
}
// main
while (!gameOver) {
if (curPlayer == 0) curPlayer = 1; else curPlayer = 0;
round(players[curPlayer]);
if (gameOver) alert(`
${players[curPlayer].name} wins (${players[curPlayer].score}).
`);
}
|
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 pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #EchoLisp | EchoLisp |
(lib 'sequences)
(define (pernicious? n) (prime? (bit-count n)))
(define pernicious (filter pernicious? [1 .. ]))
(take pernicious 25)
→ (3 5 6 7 9 10 11 12 13 14 17 18 19 20 21 22 24 25 26 28 31 33 34 35 36)
(take (filter pernicious? [888888877 .. 888888889]) #:all)
→ (888888877 888888878 888888880 888888883 888888885 888888886)
|
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
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Scala | Scala | import scala.math._
def factorial(n: Int): BigInt = {
(1 to n).map(BigInt.apply).fold(BigInt(1))(_ * _)
}
def indexToPermutation(n: Int, x: BigInt): List[Int] = {
indexToPermutation((0 until n).toList, x)
}
def indexToPermutation(ns: List[Int], x: BigInt): List[Int] = ns match {
case Nil => Nil
case _ => {
val (iBig, xNew) = x /% factorial(ns.size - 1)
val i = iBig.toInt
ns(i) :: indexToPermutation(ns.take(i) ++ ns.drop(i + 1), xNew)
}
}
def permutationToIndex[A](xs: List[A])(implicit ord: Ordering[A]): BigInt = xs match {
case Nil => BigInt(0)
case x :: rest => factorial(rest.size) * rest.count(ord.lt(_, x)) + permutationToIndex(rest)
} |
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 called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Prolog | Prolog |
?- use_module(library(heaps)).
three_smooth(Lz) :-
singleton_heap(H, 1, nothing),
lazy_list(next_3smooth, 0-H, Lz).
next_3smooth(Top-H0, N-H2, N) :-
min_of_heap(H0, Top, _), !,
get_from_heap(H0, Top, _, H1),
next_3smooth(Top-H1, N-H2, N).
next_3smooth(_-H0, N-H3, N) :-
get_from_heap(H0, N, _, H1),
N2 is N * 2,
N3 is N * 3,
add_to_heap(H1, N2, nothing, H2),
add_to_heap(H2, N3, nothing, H3).
first_kind(K) :-
three_smooth(Ns), member(N, Ns),
K is N + 1,
prime(K).
second_kind(K) :-
three_smooth(Ns), member(N, Ns),
K is N - 1,
prime(K).
show(Seq, N) :-
format("The first ~w values of ~s are: ", [N, Seq]),
once(findnsols(N, X, call(Seq, X), L)),
write(L), nl,
once(offset(249, call(Seq, TwoFifty))),
format("The 250th value of ~w is ~w~n", [Seq, TwoFifty]).
main :-
show(first_kind, 50), nl,
show(second_kind, 50), nl,
halt.
% primality checker -- Miller Rabin preceded with a round of trial divisions.
prime(N) :-
integer(N),
N > 1,
divcheck(
N,
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
139, 149],
Result),
((Result = prime, !); miller_rabin_primality_test(N)).
divcheck(_, [], unknown) :- !.
divcheck(N, [P|_], prime) :- P*P > N, !.
divcheck(N, [P|Ps], State) :- N mod P =\= 0, divcheck(N, Ps, State).
miller_rabin_primality_test(N) :-
bases(Bases, N),
forall(member(A, Bases), strong_fermat_pseudoprime(N, A)).
miller_rabin_precision(16).
bases([31, 73], N) :- N < 9_080_191, !.
bases([2, 7, 61], N) :- N < 4_759_123_141, !.
bases([2, 325, 9_375, 28_178, 450_775, 9_780_504, 1_795_265_022], N) :-
N < 18_446_744_073_709_551_616, !. % 2^64
bases(Bases, N) :-
miller_rabin_precision(T), RndLimit is N - 2,
length(Bases, T), maplist(random_between(2, RndLimit), Bases).
strong_fermat_pseudoprime(N, A) :- % miller-rabin strong pseudoprime test with base A.
succ(Pn, N), factor_2s(Pn, S, D),
X is powm(A, D, N),
((X =:= 1, !); \+ composite_witness(N, S, X)).
composite_witness(_, 0, _) :- !.
composite_witness(N, K, X) :-
X =\= N-1,
succ(Pk, K), X2 is (X*X) mod N, composite_witness(N, Pk, X2).
factor_2s(N, S, D) :- factor_2s(0, N, S, D).
factor_2s(S, D, S, D) :- D /\ 1 =\= 0, !.
factor_2s(S0, D0, S, D) :-
succ(S0, S1), D1 is D0 >> 1,
factor_2s(S1, D1, S, D).
?- main.
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Randomize
Dim randInt As Integer
For i As Integer = 1 To 5
randInt = Int(Rnd * 10)
Print a(randInt)
Next
Sleep |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Frink | Frink | a = ["one", "two", "three"]
println[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
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #VBA | VBA | Option Explicit
Sub FirstTwentyPrimes()
Dim count As Integer, i As Long, t(19) As String
Do
i = i + 1
If IsPrime(i) Then
t(count) = i
count = count + 1
End If
Loop While count <= UBound(t)
Debug.Print Join(t, ", ")
End Sub
Function IsPrime(Nb As Long) As Boolean
If Nb = 2 Then
IsPrime = True
ElseIf Nb < 2 Or Nb Mod 2 = 0 Then
Exit Function
Else
Dim i As Long
For i = 3 To Sqr(Nb) Step 2
If Nb Mod i = 0 Then Exit Function
Next
IsPrime = True
End If
End Function |
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, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Frink | Frink | a = "rosetta code phrase reversal"
println[reverse[a]]
println[join["", map["reverse", wordList[a]]]]
println[reverseWords[a]] // Built-in function
// Alternately, the above could be
// join["", reverse[wordList[a]]]
|
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, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Gambas | Gambas | Public Sub Main()
Dim sString As String = "rosetta code phrase reversal" 'The string
Dim sNewString, sTemp As String 'String variables
Dim siCount As Short 'Counter
Dim sWord As New String[] 'Word store
For siCount = Len(sString) DownTo 1 'Loop backwards through the string
sNewString &= Mid(sString, sicount, 1) 'Add each character to the new string
Next
Print "Original string = \t" & sString & "\n" & 'Print the original string
"Reversed string = \t" & sNewString 'Print the reversed string
sNewString = "" 'Reset sNewString
For Each sTemp In Split(sString, " ") 'Split the original string by the spaces
sWord.Add(sTemp) 'Add each word to sWord array
Next
For siCount = sWord.max DownTo 0 'Loop backward through each word in sWord
sNewString &= sWord[siCount] & " " 'Add each word to to sNewString
Next
Print "Reversed word order = \t" & sNewString 'Print reversed word order
sNewString = "" 'Reset sNewString
For Each sTemp In sWord 'For each word in sWord
For siCount = Len(sTemp) DownTo 1 'Loop backward through the word
sNewString &= Mid(sTemp, siCount, 1) 'Add the characters to sNewString
Next
sNewString &= " " 'Add a space at the end of each word
Next
Print "Words reversed = \t" & sNewString 'Print words reversed
End |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #EchoLisp | EchoLisp |
(lib 'list) ;; in-permutations
(lib 'bigint)
;; generates derangements by filtering out permutations
(define (derangement? nums) ;; predicate
(for/and ((n nums) (i (length nums))) (!= n i)))
(define (derangements n)
(for/list ((p (in-permutations n))) #:when (derangement? p) p))
(define (count-derangements n)
(for/sum ((p (in-permutations n))) #:when (derangement? p) 1))
;;
;; !n = (n - 1) (!(n-1) + !(n-2))
(define (!n n)
(* (1- n) (+ (!n (1- n)) (!n (- n 2)))))
(remember '!n #(1 0))
|
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 of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Elixir | Elixir | defmodule Permutation do
def by_swap(n) do
p = Enum.to_list(0..-n) |> List.to_tuple
by_swap(n, p, 1)
end
defp by_swap(n, p, s) do
IO.puts "Perm: #{inspect for i <- 1..n, do: abs(elem(p,i))} Sign: #{s}"
k = 0 |> step_up(n, p) |> step_down(n, p)
if k > 0 do
pk = elem(p,k)
i = if pk>0, do: k+1, else: k-1
p = Enum.reduce(1..n, p, fn i,acc ->
if abs(elem(p,i)) > abs(pk), do: put_elem(acc, i, -elem(acc,i)), else: acc
end)
pi = elem(p,i)
p = put_elem(p,i,pk) |> put_elem(k,pi) # swap
by_swap(n, p, -s)
end
end
defp step_up(k, n, p) do
Enum.reduce(2..n, k, fn i,acc ->
if elem(p,i)<0 and abs(elem(p,i))>abs(elem(p,i-1)) and abs(elem(p,i))>abs(elem(p,acc)),
do: i, else: acc
end)
end
defp step_down(k, n, p) do
Enum.reduce(1..n-1, k, fn i,acc ->
if elem(p,i)>0 and abs(elem(p,i))>abs(elem(p,i+1)) and abs(elem(p,i))>abs(elem(p,acc)),
do: i, else: acc
end)
end
end
Enum.each(3..4, fn n ->
Permutation.by_swap(n)
IO.puts ""
end) |
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 of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #F.23 | F# |
(*Implement Johnson-Trotter algorithm
Nigel Galloway January 24th 2017*)
module Ring
let PlainChanges (N:'n[]) = seq{
let gn = [|for n in N -> 1|]
let ni = [|for n in N -> 0|]
let gel = Array.length(N)-1
yield N
let rec _Ni g e l = seq{
match (l,g) with
|_ when l<0 -> gn.[g] <- -gn.[g]; yield! _Ni (g-1) e (ni.[g-1] + gn.[g-1])
|(1,0) -> ()
|_ when l=g+1 -> gn.[g] <- -gn.[g]; yield! _Ni (g-1) (e+1) (ni.[g-1] + gn.[g-1])
|_ -> let n = N.[g-ni.[g]+e];
N.[g-ni.[g]+e] <- N.[g-l+e]; N.[g-l+e] <- n; yield N
ni.[g] <- l; yield! _Ni gel 0 (ni.[gel] + gn.[gel])}
yield! _Ni gel 0 1
}
|
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 subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Haskell | Haskell | binomial n m = (f !! n) `div` (f !! m) `div` (f !! (n - m))
where f = scanl (*) 1 [1..]
permtest treat ctrl = (fromIntegral less) / (fromIntegral total) * 100
where
total = binomial (length avail) (length treat)
less = combos (sum treat) (length treat) avail
avail = ctrl ++ treat
combos total n a@(x:xs)
| total < 0 = binomial (length a) n
| n == 0 = 0
| n > length a = 0
| n == length a = fromEnum (total < sum a)
| otherwise = combos (total - x) (n - 1) xs
+ combos total n xs
main = let r = permtest
[85, 88, 75, 66, 25, 29, 83, 39, 97]
[68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
in do putStr "> : "; print r
putStr "<=: "; print $ 100 - 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
{\displaystyle c}
be a 2D boolean square matrix of
n
×
n
{\displaystyle n\times n}
values of either 1 or 0 where the
probability of any value being 1 is
p
{\displaystyle p}
, (and of 0 is therefore
1
−
p
{\displaystyle 1-p}
).
We define a cluster of 1's as being a group of 1's connected vertically or
horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either
0
{\displaystyle 0}
or by the limits of the matrix.
Let the number of such clusters in such a randomly constructed matrix be
C
n
{\displaystyle C_{n}}
.
Percolation theory states that
K
(
p
)
{\displaystyle K(p)}
(the mean cluster density) will satisfy
K
(
p
)
=
C
n
/
n
2
{\displaystyle K(p)=C_{n}/n^{2}}
as
n
{\displaystyle n}
tends to infinity. For
p
=
0.5
{\displaystyle p=0.5}
,
K
(
p
)
{\displaystyle K(p)}
is found numerically to approximate
0.065770
{\displaystyle 0.065770}
...
Task
Show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
for
p
=
0.5
{\displaystyle p=0.5}
and
for values of
n
{\displaystyle n}
up to at least
1000
{\displaystyle 1000}
.
Any calculation of
C
n
{\displaystyle C_{n}}
for finite
n
{\displaystyle n}
is subject to randomness, so an approximation should be
computed as the average of
t
{\displaystyle t}
runs, where
t
{\displaystyle t}
≥
5
{\displaystyle 5}
.
For extra credit, graphically show clusters in a
15
×
15
{\displaystyle 15\times 15}
,
p
=
0.5
{\displaystyle p=0.5}
grid.
Show your output here.
See also
s-Cluster on Wolfram mathworld. | #C | C | #include <stdio.h>
#include <stdlib.h>
int *map, w, ww;
void make_map(double p)
{
int i, thresh = RAND_MAX * p;
i = ww = w * w;
map = realloc(map, i * sizeof(int));
while (i--) map[i] = -(rand() < thresh);
}
char alpha[] = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
#define ALEN ((int)(sizeof(alpha) - 3))
void show_cluster(void)
{
int i, j, *s = map;
for (i = 0; i < w; i++) {
for (j = 0; j < w; j++, s++)
printf(" %c", *s < ALEN ? alpha[1 + *s] : '?');
putchar('\n');
}
}
void recur(int x, int v) {
if (x >= 0 && x < ww && map[x] == -1) {
map[x] = v;
recur(x - w, v);
recur(x - 1, v);
recur(x + 1, v);
recur(x + w, v);
}
}
int count_clusters(void)
{
int i, cls;
for (cls = i = 0; i < ww; i++) {
if (-1 != map[i]) continue;
recur(i, ++cls);
}
return cls;
}
double tests(int n, double p)
{
int i;
double k;
for (k = i = 0; i < n; i++) {
make_map(p);
k += (double)count_clusters() / ww;
}
return k / n;
}
int main(void)
{
w = 15;
make_map(.5);
printf("width=15, p=0.5, %d clusters:\n", count_clusters());
show_cluster();
printf("\np=0.5, iter=5:\n");
for (w = 1<<2; w <= 1<<14; w<<=2)
printf("%5d %9.6f\n", w, tests(5, .5));
free(map);
return 0;
} |
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 Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #11l | 11l | F perf(n)
V sum = 0
L(i) 1 .< n
I n % i == 0
sum += i
R sum == n
L(i) 1..10000
I perf(i)
print(i, end' ‘ ’) |
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
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
, assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards. Each
c
e
l
l
[
m
,
n
]
{\displaystyle \mathrm {cell} [m,n]}
is bounded by (horizontal) walls
h
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {hwall} [m,n]}
and
h
w
a
l
l
[
m
+
1
,
n
]
{\displaystyle \mathrm {hwall} [m+1,n]}
; (vertical) walls
v
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {vwall} [m,n]}
and
v
w
a
l
l
[
m
,
n
+
1
]
{\displaystyle \mathrm {vwall} [m,n+1]}
Assume that the probability of any wall being present is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
Except for the outer horizontal walls at
m
=
0
{\displaystyle m=0}
and
m
=
M
{\displaystyle m=M}
which are always present.
The task
Simulate pouring a fluid onto the top surface (
n
=
0
{\displaystyle n=0}
) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall.
The fluid does not move beyond the horizontal constraints of the grid.
The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
=
100
{\displaystyle t=100}
.
Use an
M
=
10
,
N
=
10
{\displaystyle M=10,N=10}
grid of cells for all cases.
Optionally depict fluid successfully percolating through a grid graphically.
Show all output on this page.
| #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) / Float(FF'FF)
T Grid
[[Int]] cell, hwall, vwall
F (cell, hwall, vwall)
.cell = cell
.hwall = hwall
.vwall = vwall
V (M, nn, t) = (10, 10, 100)
T PercolatedException
(Int, Int) t
F (t)
.t = t
V HVF = ([‘ .’, ‘ _’], [‘:’, ‘|’], [‘ ’, ‘#’])
F newgrid(p)
V hwall = (0 .. :nn).map(n -> (0 .< :M).map(m -> Int(nonrandom() < @@p)))
V vwall = (0 .< :nn).map(n -> (0 .. :M).map(m -> (I m C (0, :M) {1} E Int(nonrandom() < @@p))))
V cell = (0 .< :nn).map(n -> (0 .< :M).map(m -> 0))
R Grid(cell, hwall, vwall)
F pgrid(grid, percolated)
V (cell, hwall, vwall) = grid
V (h, v, f) = :HVF
L(n) 0 .< :nn
print(‘ ’(0 .< :M).map(m -> @h[@hwall[@n][m]]).join(‘’))
print(‘#.) ’.format(n % 10)‘’(0 .. :M).map(m -> @v[@vwall[@n][m]]‘’@f[I m < :M {@cell[@n][m]} E 0]).join(‘’)[0 .< (len)-1])
V n = :nn
print(‘ ’(0 .< :M).map(m -> @h[@hwall[@n][m]]).join(‘’))
I percolated != (-1, -1)
V where = percolated[0]
print(‘!) ’(‘ ’ * where)‘ ’f[1])
F flood_fill(m, n, &cell, hwall, vwall) -> N
cell[n][m] = 1
I n < :nn - 1 & !hwall[n + 1][m] & !cell[n + 1][m]
flood_fill(m, n + 1, &cell, hwall, vwall)
E I n == :nn - 1 & !hwall[n + 1][m]
X PercolatedException((m, n + 1))
I m & !vwall[n][m] & !cell[n][m - 1]
flood_fill(m - 1, n, &cell, hwall, vwall)
I m < :M - 1 & !vwall[n][m + 1] & !cell[n][m + 1]
flood_fill(m + 1, n, &cell, hwall, vwall)
I n != 0 & !hwall[n][m] & !cell[n - 1][m]
flood_fill(m, n - 1, &cell, hwall, vwall)
F pour_on_top(Grid &grid) -> (Int, Int)?
V n = 0
X.try
L(m) 0 .< :M
I grid.hwall[n][m] == 0
flood_fill(m, n, &grid.cell, grid.hwall, grid.vwall)
X.catch PercolatedException ex
R ex.t
R N
V sample_printed = 0B
[Float = Int] pcount
L(p10) 11
V p = (10 - p10) / 10.0
pcount[p] = 0
L(tries) 0 .< t
V grid = newgrid(p)
(Int, Int)? percolated = pour_on_top(&grid)
I percolated != N
pcount[p]++
I !sample_printed
print("\nSample percolating #. x #. grid".format(M, nn))
pgrid(grid, percolated ? (-1, -1))
sample_printed = 1B
print("\n p: Fraction of #. tries that percolate through".format(t))
L(p, c) sorted(pcount.items())
print(‘#.1: #.’.format(p, c / Float(t))) |
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
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #D | D | import std.stdio, std.range, std.algorithm, std.random, std.math;
enum n = 100, p = 0.5, t = 500;
double meanRunDensity(in size_t n, in double prob) {
return n.iota.map!(_ => uniform01 < prob)
.array.uniq.sum / double(n);
}
void main() {
foreach (immutable p; iota(0.1, 1.0, 0.2)) {
immutable limit = p * (1 - p);
writeln;
foreach (immutable n2; iota(10, 16, 2)) {
immutable n = 2 ^^ n2;
immutable sim = t.iota.map!(_ => meanRunDensity(n, p))
.sum / t;
writefln("t=%3d, p=%4.2f, n=%5d, p(1-p)=%5.5f, " ~
"sim=%5.5f, delta=%3.1f%%", t, p, n, limit, sim,
limit ? abs(sim - limit) / limit * 100 : sim*100);
}
}
} |
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
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #Factor | Factor | USING: arrays combinators combinators.short-circuit formatting
fry generalizations io kernel math math.matrices math.order
math.ranges math.vectors prettyprint random sequences ;
IN: rosetta-code.site-percolation
SYMBOLS: ▓ . v ;
: randomly-filled-matrix ( m n probability -- matrix )
[ random-unit > ▓ . ? ] curry make-matrix ;
: in-bounds? ( matrix loc -- ? )
[ dim { 1 1 } v- ] dip [ 0 rot between? ] 2map [ t = ] all? ;
: set-coord ( obj loc matrix -- ) [ reverse ] dip set-index ;
: get-coord ( matrix loc -- elt ) swap [ first2 ] dip nth nth ;
: (can-percolate?) ( matrix loc -- ? )
{
{ [ 2dup in-bounds? not ] [ 2drop f ] }
{ [ 2dup get-coord { v ▓ } member? ] [ 2drop f ] }
{
[ 2dup second [ dim second 1 - ] dip = ]
[ [ v ] 2dip swap set-coord t ]
}
[
2dup get-coord . =
[ [ v ] 2dip swap [ set-coord ] 2keep swap ] when
{
[ { 1 0 } v+ ] [ { 1 0 } v- ]
[ { 0 1 } v+ ] [ { 0 1 } v- ]
} [ (can-percolate?) ] map-compose 2||
]
} cond ;
: can-percolate? ( matrix -- ? )
dup dim first <iota> [ 0 2array (can-percolate?) ] with find
drop >boolean ;
: show-sample ( -- )
f [ [ can-percolate? ] keep swap ]
[ drop 15 15 0.6 randomly-filled-matrix ] do until
"Sample percolation, p = 0.6" print simple-table. ;
: percolation-rate ( p -- rate )
[ 500 1 ] dip -
'[ 15 15 _ randomly-filled-matrix can-percolate? ] replicate
[ t = ] count 500 / ;
: site-percolation ( -- )
show-sample nl "Running 500 trials at each porosity:" print
10 [1,b] [
10 / dup percolation-rate "p = %.1f: %.3f\n" printf
] each ;
MAIN: site-percolation |
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
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #Fortran | Fortran |
! loosely translated from python.
! compilation: gfortran -Wall -std=f2008 thisfile.f08
!$ a=site && gfortran -o $a -g -O0 -Wall -std=f2008 $a.f08 && $a
!100 trials per
!Fill Fraction goal(%) simulated through paths(%)
! 0 0
! 10 0
! 20 0
! 30 0
! 40 0
! 50 6
!
!
! b b b b h j m m m
! b b b b b h h m m m m m
! b b b h h h m
! b h h h h h h h
! b b h h h h h h h h h
! b b b h h h h h h h h h h
! b b @ h h h h h h h
! @ @ h h h h h h h h
! @ @ @ @ h h h h
! @ @ @ @ h h h h h h
! @ @ @ h h h h h h h
! @ @ @ h h h h h h
! @ h h h h h h
! @ h h h h h h h
! @ @ h h h h h h h h h h
! 60 59
! 70 97
! 80 100
! 90 100
! 100 100
program percolation_site
implicit none
integer, parameter :: m=15,n=15,t=100
!integer, parameter :: m=2,n=2,t=8
integer(kind=1), dimension(m, n) :: grid
real :: p
integer :: i, ip, trial, successes
logical :: success, unseen, q
data unseen/.true./
write(6,'(i3,a11)') t,' trials per'
write(6,'(a21,a30)') 'Fill Fraction goal(%)','simulated through paths(%)'
do ip=0, 10
p = ip/10.0
successes = 0
do trial = 1, t
call newgrid(grid, p)
success = .false.
do i=1, m
q = walk(grid, i) ! deliberately compute all paths
success = success .or. q
end do
if ((ip == 6) .and. unseen) then
call display(grid)
unseen = .false.
end if
successes = successes + merge(1, 0, success)
end do
write(6,'(9x,i3,24x,i3)')ip*10,nint(100*real(successes)/real(t))
end do
contains
logical function walk(grid, start)
integer(kind=1), dimension(m,n), intent(inout) :: grid
integer, intent(in) :: start
walk = rwalk(grid, 1, start, int(start+1,1))
end function walk
recursive function rwalk(grid, i, j, k) result(through)
logical :: through
integer(kind=1), dimension(m,n), intent(inout) :: grid
integer, intent(in) :: i, j
integer(kind=1), intent(in) :: k
logical, dimension(4) :: q
!out of bounds
through = .false.
if (i < 1) return
if (m < i) return
if (j < 1) return
if (n < j) return
!visited or non-pore
if (1_1 /= grid(i, j)) return
!update grid and recurse with neighbors. deny 'shortcircuit' evaluation
grid(i, j) = k
q(1) = rwalk(grid,i+0,j+1,k)
q(2) = rwalk(grid,i+0,j-1,k)
q(3) = rwalk(grid,i+1,j+0,k)
q(4) = rwalk(grid,i-1,j+0,k)
!newly discovered outlet
through = (i == m) .or. any(q)
end function rwalk
subroutine newgrid(grid, probability)
implicit none
real :: probability
integer(kind=1), dimension(m,n), intent(out) :: grid
real, dimension(m,n) :: harvest
call random_number(harvest)
grid = merge(1_1, 0_1, harvest < probability)
end subroutine newgrid
subroutine display(grid)
integer(kind=1), dimension(m,n), intent(in) :: grid
integer :: i, j, k, L
character(len=n*2) :: lineout
write(6,'(/)')
lineout = ' '
do i=1,m
do j=1,n
k = j+j
L = grid(i,j)+1
lineout(k:k) = ' @abcdefghijklmnopqrstuvwxyz'(L:L)
end do
write(6,*) lineout
end do
end subroutine display
end program percolation_site
|
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 Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program permutation64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Value : @\n"
sMessCounter: .asciz "Permutations = @ \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .quad 1,2,3
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: //entry of program
ldr x0,qAdrTableNumber //address number table
mov x1,NBELEMENTS //number of élements
mov x10,0 //counter
bl heapIteratif
mov x0,x10 //display counter
ldr x1,qAdrsZoneConv //
bl conversion10S //décimal conversion
ldr x0,qAdrsMessCounter
ldr x1,qAdrsZoneConv //insert conversion
bl strInsertAtCharInc
bl affichageMess //display message
100: //standard end of the program
mov x0,0 //return code
mov x8,EXIT //request to exit program
svc 0 //perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrsMessCounter: .quad sMessCounter
/******************************************************************/
/* permutation by heap iteratif (wikipedia) */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the eléments number */
heapIteratif:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
stp x5,x6,[sp,-16]! // save registers
stp x7,fp,[sp,-16]! // save registers
tst x1,1 // odd ?
add x2,x1,1
csel x2,x2,x1,ne // the stack must be a multiple of 16
lsl x7,x2,3 // 8 bytes by count
sub sp,sp,x7
mov fp,sp
mov x3,#0
mov x4,#0 // index
1: // init area counter
str x4,[fp,x3,lsl 3]
add x3,x3,#1
cmp x3,x1
blt 1b
bl displayTable
add x10,x10,#1
mov x3,#0 // index
2:
ldr x4,[fp,x3,lsl 3] // load count [i]
cmp x4,x3 // compare with i
bge 5f
tst x3,#1 // even ?
bne 3f
ldr x5,[x0] // yes load value A[0]
ldr x6,[x0,x3,lsl 3] // and swap with value A[i]
str x6,[x0]
str x5,[x0,x3,lsl 3]
b 4f
3:
ldr x5,[x0,x4,lsl 3] // load value A[count[i]]
ldr x6,[x0,x3,lsl 3] // and swap with value A[i]
str x6,[x0,x4,lsl 3]
str x5,[x0,x3,lsl 3]
4:
bl displayTable
add x10,x10,1
add x4,x4,1 // increment count i
str x4,[fp,x3,lsl 3] // and store on stack
mov x3,0 // raz index
b 2b // and loop
5:
mov x4,0 // raz count [i]
str x4,[fp,x3,lsl 3]
add x3,x3,1 // increment index
cmp x3,x1 // end ?
blt 2b // no -> loop
add sp,sp,x7 // stack alignement
100:
ldp x7,fp,[sp],16 // restaur 2 registers
ldp x5,x6,[sp],16 // restaur 2 registers
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,#0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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 repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #ALGOL_68 | ALGOL 68 | # returns an array of the specified length, initialised to an ascending sequence of integers #
OP DECK = ( INT length )[]INT:
BEGIN
[ 1 : length ]INT result;
FOR i TO UPB result DO result[ i ] := i OD;
result
END # DECK # ;
# in-place shuffles the deck as per the task requirements #
# LWB deck is assumed to be 1 #
PROC shuffle = ( REF[]INT deck )VOID:
BEGIN
[ 1 : UPB deck ]INT result;
INT left pos := 1;
INT right pos := ( UPB deck OVER 2 ) + 1;
FOR i FROM 2 BY 2 TO UPB result DO
result[ left pos ] := deck[ i - 1 ];
result[ right pos ] := deck[ i ];
left pos +:= 1;
right pos +:= 1
OD;
FOR i TO UPB deck DO deck[ i ] := result[ i ] OD
END # SHUFFLE # ;
# compares two integer arrays for equality #
OP = = ( []INT a, b )BOOL:
IF LWB a /= LWB b OR UPB a /= UPB b
THEN # the arrays have different bounds #
FALSE
ELSE
BOOL result := TRUE;
FOR i FROM LWB a TO UPB a WHILE result := a[ i ] = b[ i ] DO SKIP OD;
result
FI # = # ;
# compares two integer arrays for inequality #
OP /= = ( []INT a, b )BOOL: NOT ( a = b );
# returns the number of shuffles required to return a deck of the specified length #
# back to its original state #
PROC count shuffles = ( INT length )INT:
BEGIN
[] INT original deck = DECK length;
[ 1 : length ]INT shuffled deck := original deck;
INT count := 1;
WHILE shuffle( shuffled deck );
shuffled deck /= original deck
DO
count +:= 1
OD;
count
END # count shuffles # ;
# test the shuffling #
[]INT lengths = ( 8, 24, 52, 100, 1020, 1024, 10 000 );
FOR l FROM LWB lengths TO UPB lengths DO
print( ( whole( lengths[ l ], -8 ) + ": " + whole( count shuffles( lengths[ l ] ), -6 ), newline ) )
OD |
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
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #Factor | Factor | x floor >integer 255 bitand :> X
y floor >integer 255 bitand :> Y
z floor >integer 255 bitand :> Z |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.