task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and 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
| #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int PLAYERS = 2, MAX_POINTS = 100;
//--------------------------------------------------------------------------------------------------
class player
{
public:
player() { reset(); }
void reset()
{
name = "";
current_score = round_score = 0;
}
string getName() { return name; }
void setName( string n ) { name = n; }
int getCurrScore() { return current_score; }
void addCurrScore() { current_score += round_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
private:
string name;
int current_score, round_score;
};
//--------------------------------------------------------------------------------------------------
class pigGame
{
public:
pigGame() { resetPlayers(); }
void play()
{
while( true )
{
system( "cls" );
int p = 0;
while( true )
{
if( turn( p ) )
{
praise( p );
break;
}
++p %= PLAYERS;
}
string r;
cout << "Do you want to play again ( y / n )? "; cin >> r;
if( r != "Y" && r != "y" ) return;
resetPlayers();
}
}
private:
void resetPlayers()
{
system( "cls" );
string n;
for( int p = 0; p < PLAYERS; p++ )
{
_players[p].reset();
cout << "Enter name player " << p + 1 << ": "; cin >> n;
_players[p].setName( n );
}
}
void praise( int p )
{
system( "cls" );
cout << "CONGRATULATIONS " << _players[p].getName() << ", you are the winner!" << endl << endl;
cout << "Final Score" << endl;
drawScoreboard();
cout << endl << endl;
}
void drawScoreboard()
{
for( int p = 0; p < PLAYERS; p++ )
cout << _players[p].getName() << ": " << _players[p].getCurrScore() << " points" << endl;
cout << endl;
}
bool turn( int p )
{
system( "cls" );
drawScoreboard();
_players[p].zeroRoundScore();
string r;
int die;
while( true )
{
cout << _players[p].getName() << ", your round score is: " << _players[p].getRoundScore() << endl;
cout << "What do you want to do (H)old or (R)oll? "; cin >> r;
if( r == "h" || r == "H" )
{
_players[p].addCurrScore();
return _players[p].getCurrScore() >= MAX_POINTS;
}
if( r == "r" || r == "R" )
{
die = rand() % 6 + 1;
if( die == 1 )
{
cout << _players[p].getName() << ", your turn is over." << endl << endl;
system( "pause" );
return false;
}
_players[p].addRoundScore( die );
}
cout << endl;
}
return false;
}
player _players[PLAYERS];
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
pigGame pg;
pg.play();
return 0;
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #Vlang | Vlang | import os
import strings
type PlayfairOption = int
const (
no_q = 0
i_equals_j = 1
)
struct Playfair {
mut:
keyword string
pfo PlayfairOption
table [5][5]u8
}
fn (mut p Playfair) init() {
// Build table.
mut used := [26]bool{} // all elements false
if p.pfo == no_q {
used[16] = true // Q used
} else {
used[9] = true // J used
}
alphabet := p.keyword.to_upper() + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < alphabet.len; k++ {
c := alphabet[k]
if c < 'A'[0] || c > 'Z'[0] {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break // table has been filled
}
j = 0
}
}
}
}
fn (p Playfair) get_clean_text(pt string) string {
// Ensure everything is upper case.
plain_text := pt.to_upper()
// Get rid of any non-letters and insert X between duplicate letters.
mut clean_text := strings.new_builder(128)
// Safe to assume null u8 won't be present in plain_text.
mut prev_byte := `\000`
for i in 0..plain_text.len {
mut next_byte := plain_text[i]
// It appears that Q should be omitted altogether if NO_Q option is specified;
// we assume so anyway.
if next_byte < 'A'[0] || next_byte > 'Z'[0] || (next_byte == 'Q'[0] && p.pfo == no_q) {
continue
}
// If i_equals_j option specified, replace J with I.
if next_byte == 'J'[0] && p.pfo == i_equals_j {
next_byte = 'I'[0]
}
if next_byte != prev_byte {
clean_text.write_u8(next_byte)
} else {
clean_text.write_u8('X'[0])
clean_text.write_u8(next_byte)
}
prev_byte = next_byte
}
l := clean_text.len
if l%2 == 1 {
// Dangling letter at end so add another letter to complete digram.
if clean_text.str()[l-1] != 'X'[0] {
clean_text.write_u8('X'[0])
} else {
clean_text.write_u8('Z'[0])
}
}
return clean_text.str()
}
fn (p Playfair) find_byte(c u8) (int, int) {
for i in 0..5 {
for j in 0..5 {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
fn (p Playfair) encode(plain_text string) string {
clean_text := p.get_clean_text(plain_text)
mut cipher_text := strings.new_builder(128)
l := clean_text.len
for i := 0; i < l; i += 2 {
row1, col1 := p.find_byte(clean_text[i])
row2, col2 := p.find_byte(clean_text[i+1])
if row1 == row2{
cipher_text.write_u8(p.table[row1][(col1+1)%5])
cipher_text.write_u8(p.table[row2][(col2+1)%5])
} else if col1 == col2{
cipher_text.write_u8(p.table[(row1+1)%5][col1])
cipher_text.write_u8(p.table[(row2+1)%5][col2])
} else {
cipher_text.write_u8(p.table[row1][col2])
cipher_text.write_u8(p.table[row2][col1])
}
if i < l-1 {
cipher_text.write_u8(' '[0])
}
}
return cipher_text.str()
}
fn (p Playfair) decode(cipher_text string) string {
mut decoded_text := strings.new_builder(128)
l := cipher_text.len
// cipher_text will include spaces so we need to skip them.
for i := 0; i < l; i += 3 {
row1, col1 := p.find_byte(cipher_text[i])
row2, col2 := p.find_byte(cipher_text[i+1])
if row1 == row2 {
mut temp := 4
if col1 > 0 {
temp = col1 - 1
}
decoded_text.write_u8(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decoded_text.write_u8(p.table[row2][temp])
} else if col1 == col2 {
mut temp := 4
if row1 > 0 {
temp = row1 - 1
}
decoded_text.write_u8(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decoded_text.write_u8(p.table[temp][col2])
} else {
decoded_text.write_u8(p.table[row1][col2])
decoded_text.write_u8(p.table[row2][col1])
}
if i < l-1 {
decoded_text.write_u8(' '[0])
}
}
return decoded_text.str()
}
fn (p Playfair) print_table() {
println("The table to be used is :\n")
for i in 0..5 {
for j in 0..5 {
print("${p.table[i][j].ascii_str()} ")
}
println('')
}
}
fn main() {
keyword := os.input("Enter Playfair keyword : ")
mut ignore_q := ''
for ignore_q != "y" && ignore_q != "n" {
ignore_q = os.input("Ignore Q when building table y/n : ").to_lower()
}
mut pfo := no_q
if ignore_q == "n" {
pfo = i_equals_j
}
mut table := [5][5]u8{}
mut pf := Playfair{keyword, pfo, table}
pf.init()
pf.print_table()
plain_text := os.input("\nEnter plain text : ")
encoded_text := pf.encode(plain_text)
println("\nEncoded text is : $encoded_text")
decoded_text := pf.decode(encoded_text)
println("Deccoded text is : $decoded_text")
} |
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.
| #11l | 11l | F popcount(n)
R bin(n).count(‘1’)
F is_prime(n)
I n < 2
R 0B
L(i) 2 .. Int(sqrt(n))
I n % i == 0
R 0B
R 1B
V i = 0
V cnt = 0
L
I is_prime(popcount(i))
print(i, end' ‘ ’)
cnt++
I cnt == 25
L.break
i++
print()
L(i) 888888877..888888888
I is_prime(popcount(i))
print(i, 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
| #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R (:seed >> 16) / Float(FF'FF)
F mrUnrank1(&vec, rank, n)
I n < 1 {R}
V (q, r) = divmod(rank, n)
swap(&vec[r], &vec[n - 1])
mrUnrank1(&vec, q, n - 1)
F mrRank1(&vec, &inv, n)
I n < 2 {R 0}
V s = vec[n - 1]
swap(&vec[n - 1], &vec[inv[n - 1]])
swap(&inv[s], &inv[n - 1])
R s + n * mrRank1(&vec, &inv, n - 1)
F getPermutation(&vec, rank)
L(i) 0 .< vec.len {vec[i] = i}
mrUnrank1(&vec, rank, vec.len)
F getRank(vec)
V v = [0] * vec.len
V inv = [0] * vec.len
L(val) vec
v[L.index] = val
inv[val] = L.index
R mrRank1(&v, &inv, vec.len)
V tv3 = [0] * 3
L(r) 6
getPermutation(&tv3, r)
print(‘#2 -> #. -> #.’.format(r, tv3, getRank(tv3)))
print()
V tv4 = [0] * 4
L(r) 24
getPermutation(&tv4, r)
print(‘#2 -> #. -> #.’.format(r, tv4, getRank(tv4)))
print()
V tv12 = [0] * 12
L 4
V r = Int(nonrandom() * factorial(12))
getPermutation(&tv12, r)
print(‘#9 -> #. -> #.’.format(r, tv12, getRank(tv12))) |
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
| #D | D | import std.algorithm;
import std.bigint;
import std.random;
import std.stdio;
immutable PRIMES = [
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, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571,
577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761,
769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977,
];
BigInt getRandom(BigInt min, BigInt max) {
auto r = max - min;
auto hs = r.toHex;
BigInt result;
do {
string t = "0x";
for (int i = 0; i < hs.length; i++) {
t ~= "0123456789abcdef"[uniform(0, 16)];
}
result = BigInt(t) + min;
} while (result < min || max <= result);
return result;
}
//Modified from https://rosettacode.org/wiki/Miller-Rabin_primality_test#Python
bool isProbablePrime(BigInt n) {
if (n == 0 || n == 1) {
return false;
}
bool check(BigInt num) {
foreach (prime; PRIMES) {
if (num == prime) {
return true;
}
if (num % prime == 0) {
return false;
}
if (prime * prime > num) {
return true;
}
}
return true;
}
if (check(n)) {
auto large = PRIMES[$ - 1];
if (n <= large) {
return true;
}
}
int s = 0;
auto d = n - 1;
while ((d & 1) == 0) {
d >>= 1;
s++;
}
bool trialComposite(BigInt a) {
if (powmod(a, d, n) == 1) {
return false;
}
for (int i = 0; i < s; i++) {
auto t = BigInt(2) ^^ i;
if (powmod(a, t * d, n) == n - 1) {
return false;
}
}
return true;
}
for (int i = 0; i < 8; i++) {
auto a = getRandom(BigInt(2), n);
if (trialComposite(a)) {
return false;
}
}
return true;
}
BigInt[][] pierpont(int n) {
BigInt[][] p = [[], []];
for (int i = 0; i < n; i++) {
p[0] ~= BigInt(0);
p[1] ~= BigInt(0);
}
p[0][0] = 2;
int count = 0;
int count1 = 1;
int count2 = 0;
BigInt[] s = [BigInt(1)];
int i2 = 0;
int i3 = 0;
int k = 1;
BigInt n2, n3, t;
while (count < n) {
n2 = s[i2] * 2;
n3 = s[i3] * 3;
if (n2 < n3) {
t = n2;
i2++;
} else {
t = n3;
i3++;
}
if (t > s[k - 1]) {
s ~= t;
k++;
t++;
if (count1 < n && t.isProbablePrime()) {
p[0][count1] = t;
count1++;
}
t -= 2;
if (count2 < n && t.isProbablePrime()) {
p[1][count2] = t;
count2++;
}
count = min(count1, count2);
}
}
return p;
}
void main() {
auto p = pierpont(250);
writeln("First 50 Pierpont primes of the first kind:");
for (int i = 0; i < 50; i++) {
writef("%8d ", p[0][i]);
if ((i - 9) % 10 == 0) {
writeln;
}
}
writeln;
writeln("First 50 Pierpont primes of the first kind:");
for (int i = 0; i < 50; i++) {
writef("%8d ", p[1][i]);
if ((i - 9) % 10 == 0) {
writeln;
}
}
writeln;
writefln("%dth Pierpont prime of the first kind: %d", p[0].length, p[0][$ - 1]);
writefln("%dth Pierpont prime of the second kind: %d", p[1].length, p[1][$ - 1]);
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #AutoHotkey | AutoHotkey | list := ["abc", "def", "gh", "ijklmnop", "hello", "world"]
Random, randint, 1, % list.MaxIndex()
MsgBox % List[randint] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #AWK | AWK | # syntax: GAWK -f PICK_RANDOM_ELEMENT.AWK
BEGIN {
n = split("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",day_of_week,",")
srand()
x = int(n*rand()) + 1
printf("%s\n",day_of_week[x])
exit(0)
} |
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
| #SAS | SAS | data primes;
do n=1 to 1000;
link primep;
if primep then output;
end;
stop;
primep:
if n < 4 then do;
primep=n=2 or n=3;
return;
end;
primep=0;
if mod(n,2)=0 then return;
do k=3 to sqrt(n) by 2;
if mod(n,k)=0 then return;
end;
primep=1;
return;
keep n;
run; |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Python | Python | #!/usr/bin/python3
'''
See: http://en.wikipedia.org/wiki/Pig_(dice)
This program scores, throws the dice, and plays for an N player game of Pig.
'''
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
maxscore = 100
maxgames = 100000
Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')
class Player():
def __init__(self, player_index):
self.player_index = player_index
def __repr__(self):
return '%s(%i)' % (self.__class__.__name__, self.player_index)
def __call__(self, safescore, scores, game):
'Returns boolean True to roll again'
pass
class RandPlay(Player):
def __call__(self, safe, scores, game):
'Returns random boolean choice of whether to roll again'
return bool(random.randint(0, 1))
class RollTo20(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20'
return (((sum(scores) + safe[self.player_index]) < maxscore) # Haven't won yet
and(sum(scores) < 20)) # Not at 20 this round
class Desparat(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20 or someone is within 20 of winning'
return (((sum(scores) + safe[self.player_index]) < maxscore) # Haven't won yet
and( (sum(scores) < 20) # Not at 20 this round
or max(safe) >= (maxscore - 20))) # Someone's close
def game__str__(self):
'Pretty printer for Game class'
return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])"
% (self.players, self.maxscore,
',\n '.join(repr(round) for round in self.rounds)))
Game.__str__ = game__str__
def winningorder(players, safescores):
'Return (players in winning order, their scores)'
return tuple(zip(*sorted(zip(players, safescores),
key=lambda x: x[1], reverse=True)))
def playpig(game):
'''
Plays the game of pig returning the players in winning order
and their scores whilst updating argument game with the details of play.
'''
players, maxscore, rounds = game
playercount = len(players)
safescore = [0] * playercount # Safe scores for each player
player = 0 # Who plays this round
scores=[] # Individual scores this round
while max(safescore) < maxscore:
startscore = safescore[player]
rolling = players[player](safescore, scores, game)
if rolling:
rolled = randint(1, 6)
scores.append(rolled)
if rolled == 1:
# Bust!
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
scores, player = [], (player + 1) % playercount
else:
# Stick
safescore[player] += sum(scores)
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
if safescore[player] >= maxscore:
break
scores, player = [], (player + 1) % playercount
# return players in winning order and all scores
return winningorder(players, safescore)
if __name__ == '__main__':
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=20,
rounds=[])
print('ONE GAME')
print('Winning order: %r; Respective scores: %r\n' % playpig(game))
print(game)
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=maxscore,
rounds=[])
algos = (RollTo20, RandPlay, Desparat)
print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES'
% (', '.join(p.__name__ for p in algos), maxgames,))
winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)
for i in range(playercount)),
rounds=[]))[0])
for i in range(maxgames))
print(' Players(position) winning on left; occurrences on right:\n %s'
% ',\n '.join(str(w) for w in winners.most_common())) |
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
| #ALGOL_68 | ALGOL 68 | # reverses the characters in str from start pos to end pos #
PROC in place reverse = ( REF STRING str, INT start pos, INT end pos )VOID:
BEGIN
INT fpos := start pos, epos := end pos;
WHILE fpos < epos
DO
CHAR c := str[ fpos ];
str[ fpos ] := str[ epos ];
str[ epos ] := c;
fpos +:= 1;
epos -:= 1
OD
END; # in place reverse #
STRING original phrase := "rosetta code phrase reversal";
STRING whole reversed := original phrase;
in place reverse( whole reversed, LWB whole reversed, UPB whole reversed );
# reverse the individual words #
STRING words reversed := original phrase;
INT start pos := LWB words reversed;
WHILE
# skip leading spaces #
WHILE IF start pos <= UPB words reversed
THEN words reversed[ start pos ] = " "
ELSE FALSE
FI
DO start pos +:= 1
OD;
start pos <= UPB words reversed
DO
# have another word, find it #
INT end pos := start pos;
WHILE IF end pos <= UPB words reversed
THEN words reversed[ end pos ] /= " "
ELSE FALSE
FI
DO end pos +:= 1
OD;
in place reverse( words reversed, start pos, end pos - 1 );
start pos := end pos + 1
OD;
# reversing the reversed words in the same order as the original will #
# reverse the order of the words #
STRING order reversed := words reversed;
in place reverse( order reversed, LWB order reversed, UPB order reversed );
print( ( original phrase, ": whole reversed -> ", whole reversed, newline
, original phrase, ": words reversed -> ", words reversed, newline
, original phrase, ": order reversed -> ", order reversed, newline
)
) |
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
| #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
abst@ype
pip_type = int
abst@ype
suit_type = int
//
abst@ype
card_type = int
//
(* ****** ****** *)
typedef pip = pip_type
typedef suit = suit_type
(* ****** ****** *)
typedef card = card_type
(* ****** ****** *)
//
extern
fun
pip_make: natLt(13) -> pip
extern
fun
pip_get_name: pip -> string
extern
fun
pip_get_value: pip -> intBtwe(1, 13)
//
extern
fun
suit_make: natLt(4) -> suit
extern
fun
suit_get_name: suit -> string
extern
fun
suit_get_value: suit -> intBtwe(1, 4)
//
overload .name with pip_get_name
overload .name with suit_get_name
overload .value with pip_get_value
overload .value with suit_get_value
//
(* ****** ****** *)
//
(*
| Two | Three | Four | Five
| Six | Seven | Eight | Nine
| Ten | Jack | Queen | King | Ace
*)
//
(*
| Spade | Heart | Diamond | Club
*)
//
(* ****** ****** *)
local
assume
pip_type = natLt(13)
in (* in-of-local *)
implement
pip_make(x) = x
implement
pip_get_value(x) = x + 1
end // end of [local]
(* ****** ****** *)
local
assume
suit_type = natLt(4)
in (* in-of-local *)
implement
suit_make(x) = x
implement
suit_get_value(x) = x + 1
end // end of [local]
(* ****** ****** *)
implement
pip_get_name
(x) =
(
case+
x.value()
of // case+
| 1 => "Ace"
| 2 => "Two"
| 3 => "Three"
| 4 => "Four"
| 5 => "Five"
| 6 => "Six"
| 7 => "Seven"
| 8 => "Eight"
| 9 => "Nine"
| 10 => "Ten"
| 11 => "Jack"
| 12 => "Queen"
| 13 => "King"
)
(* ****** ****** *)
//
implement
suit_get_name
(x) =
(
case+
x.value()
of // case+
| 1 => "S" | 2 => "H" | 3 => "D" | 4 => "C"
) (* end of [suit_get_name] *)
//
(* ****** ****** *)
//
extern
fun
card_get_pip: card -> pip
extern
fun
card_get_suit: card -> suit
//
extern
fun
card_make: natLt(52) -> card
extern
fun
card_make_suit_pip: (suit, pip) -> card
//
(* ****** ****** *)
extern
fun
fprint_pip : fprint_type(pip)
extern
fun
fprint_suit : fprint_type(suit)
extern
fun
fprint_card : fprint_type(card)
(* ****** ****** *)
overload .pip with card_get_pip
overload .suit with card_get_suit
(* ****** ****** *)
implement
fprint_val<card> = fprint_card
(* ****** ****** *)
overload fprint with fprint_pip
overload fprint with fprint_suit
overload fprint with fprint_card
(* ****** ****** *)
local
assume
card_type = natLt(52)
in (* in-of-local *)
//
implement
card_get_pip
(x) = pip_make(nmod(x, 13))
implement
card_get_suit
(x) = suit_make(ndiv(x, 13))
//
implement
card_make(xy) = xy
//
implement
card_make_suit_pip(x, y) =
(x.value()-1) * 13 + (y.value()-1)
//
end // end of [local]
(* ****** ****** *)
//
implement
fprint_pip(out, x) =
fprint!(out, x.name())
implement
fprint_suit(out, x) =
fprint!(out, x.name())
//
implement
fprint_card(out, c) =
fprint!(out, c.suit(), "(", c.pip(), ")")
//
(* ****** ****** *)
//
absvtype
deck_vtype(n:int) = ptr
//
vtypedef deck(n:int) = deck_vtype(n)
//
(* ****** ****** *)
//
extern
fun
deck_get_size
{n:nat}(!deck(n)): int(n)
//
extern
fun
deck_is_empty
{n:nat}(!deck(n)): bool(n==0)
//
overload iseqz with deck_is_empty
//
(* ****** ****** *)
//
extern
fun
deck_free{n:int}(deck(n)): void
//
overload .free with deck_free
//
(* ****** ****** *)
//
extern
fun
deck_make_full((*void*)): deck(52)
//
(* ****** ****** *)
//
extern
fun
fprint_deck
{n:nat}(FILEref, !deck(n)): void
//
overload fprint with fprint_deck
//
(* ****** ****** *)
//
extern
fun
deck_shuffle
{n:nat}(!deck(n) >> _): void
//
overload .shuffle with deck_shuffle
//
(* ****** ****** *)
//
extern
fun
deck_takeout_top
{n:pos}(!deck(n) >> deck(n-1)): card
//
(* ****** ****** *)
local
//
datavtype
deck(int) =
| {n:nat}
Deck(n) of
(
int(n)
, list_vt(card, n)
) // end of [Deck]
//
assume
deck_vtype(n:int) = deck(n)
//
in (* in-of-local *)
implement
deck_get_size
(deck) =
(
let val+Deck(n, _) = deck in n end
)
implement
deck_is_empty
(deck) =
(
let val+Deck(n, _) = deck in n = 0 end
)
(* ****** ****** *)
//
implement
deck_free(deck) =
(
let val+~Deck(n, xs) = deck in free(xs) end
) (* end of [deck_free] *)
//
(* ****** ****** *)
implement
deck_make_full
((*void*)) = let
//
val xys =
list_make_intrange(0, 52)
//
val cards =
list_vt_mapfree_fun<natLt(52)><card>(xys, lam xy => card_make(xy))
//
in
Deck(52, cards)
end // end of [deck_make_full]
(* ****** ****** *)
implement
fprint_deck
(out, deck) = let
//
val+Deck(n, xs) = deck
//
in
//
fprint_list_vt(out, xs)
//
end // end of [fprint_deck]
(* ****** ****** *)
implement
deck_shuffle
(deck) =
fold@(deck) where
{
//
val+@Deck(n, xs) = deck
//
implement
list_vt_permute$randint<>
(n) = randint(n)
//
val ((*void*)) =
(xs := list_vt_permute(xs))
//
} (* end of [deck_shuffle] *)
(* ****** ****** *)
implement
deck_takeout_top
(deck) = let
//
val+@Deck(n, xs) = deck
//
val+
~list_vt_cons(x0, xs_tl) = xs
//
val ((*void*)) = n := n - 1
val ((*void*)) = (xs := xs_tl)
//
in
fold@(deck); x0(*top*)
end // end of [deck_takeout_top]
end // end of [local]
(* ****** ****** *)
implement
main0((*void*)) =
{
//
val () =
println!
(
"Hello from [Playing_cards]!"
) (* println! *)
//
val out = stdout_ref
//
val theDeck =
deck_make_full((*void*))
//
val ((*void*)) =
fprintln!(out, "theDeck = ", theDeck)
//
val ((*void*)) =
theDeck.shuffle((*void*))
//
val ((*void*)) =
fprintln!(out, "theDeck = ", theDeck)
//
val ((*void*)) =
loop_deal(theDeck) where
{
//
fun
loop_deal{n:nat}
(
deck: !deck(n) >> deck(0)
) : void =
(
if (
iseqz(deck)
) then ((*void*))
else
let
val card =
deck_takeout_top(deck)
in
fprintln!(out, card); loop_deal(deck)
end // end of [let]
// end of [else]
)
//
} (* end of [val] *)
//
val ((*freed*)) = theDeck.free()
//
} (* end of [main0] *)
(* ****** ****** *)
|
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
| #Clojure | Clojure | (def max 100)
(defn roll-dice []
(let [roll (inc (rand-int 6))]
(println "Rolled:" roll) roll))
(defn switch [player]
(if (= player :player1) :player2 :player1))
(defn find-winner [game]
(cond
(>= (:player1 game) max) :player1
(>= (:player2 game) max) :player2
:else nil))
(defn bust []
(println "Busted!") 0)
(defn hold [points]
(println "Sticking with" points) points)
(defn play-round [game player temp-points]
(println (format "%s: (%s, %s). Want to Roll? (y/n) " (name player) (player game) temp-points))
(let [input (clojure.string/upper-case (read-line))]
(if (.equals input "Y")
(let [roll (roll-dice)]
(if (= 1 roll)
(bust)
(play-round game player (+ roll temp-points))))
(hold temp-points))))
(defn play-game [game player]
(let [winner (find-winner game)]
(if (nil? winner)
(let [points (play-round game player 0)]
(recur (assoc game player (+ points (player game))) (switch player)))
(println (name winner) "wins!"))))
(defn -main [& args]
(println "Pig the Dice Game.")
(play-game {:player1 0, :player2 0} :player1)) |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #Wren | Wren | import "/dynamic" for Enum
import "/str" for Str, Char
import "/trait" for Stepped
import "/ioutil" for Input
var PlayfairOption = Enum.create("PlayfairOption", ["NO_Q", "I_EQUALS_J"])
class Playfair {
construct new(keyword, pfo) {
_pfo = pfo
// build_table
_table = List.filled(5, null)
for (i in 0..4) _table[i] = List.filled(5, "\0") // 5 * 5 char list
var used = List.filled(26, false)
if (_pfo == PlayfairOption.NO_Q) {
used[16] = true // Q used
} else {
used[9] = true // J used
}
var alphabet = Str.upper(keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var i = 0
var j = 0
for (k in 0...alphabet.count) {
var c = alphabet[k]
if (Char.isAsciiUpper(c)) {
var d = c.bytes[0] - 65
if (!used[d]) {
_table[i][j] = c
used[d] = true
j = j + 1
if (j == 5) {
i = i + 1
if (i == 5) break // table has been filled
j = 0
}
}
}
}
}
getCleanText_(plainText) {
var plainText2 = Str.upper(plainText) // ensure everything is upper case
// get rid of any non-letters and insert X between duplicate letters
var cleanText = ""
var prevChar = "\0" // safe to assume null character won't be present in plainText
for (i in 0...plainText2.count) {
var nextChar = plainText2[i]
// It appears that Q should be omitted altogether if NO_Q option is specified - we assume so anyway
if (Char.isAsciiUpper(nextChar) && (nextChar != "Q" || _pfo != PlayfairOption.NO_Q)) {
// If I_EQUALS_J option specified, replace J with I
if (nextChar == "J" && _pfo == PlayfairOption.I_EQUALS_J) nextChar = "I"
if (nextChar != prevChar) {
cleanText = cleanText + nextChar
} else {
cleanText = cleanText + "X" + nextChar
}
prevChar = nextChar
}
}
var len = cleanText.count
if (len % 2 == 1) { // dangling letter at end so add another letter to complete digram
if (cleanText[-1] != "X") {
cleanText = cleanText + "X"
} else {
cleanText = cleanText + "Z"
}
}
return cleanText
}
findChar_(c) {
for (i in 0..4) {
for (j in 0..4) if (_table[i][j] == c) return [i, j]
}
return [-1, -1]
}
encode(plainText) {
var cleanText = getCleanText_(plainText)
var cipherText = ""
var length = cleanText.count
for (i in Stepped.new(0...length, 2)) {
var pair = findChar_(cleanText[i])
var row1 = pair[0]
var col1 = pair[1]
pair = findChar_(cleanText[i + 1])
var row2 = pair[0]
var col2 = pair[1]
cipherText = cipherText +
((row1 == row2) ? _table[row1][(col1 + 1) % 5] +_table[row2][(col2 + 1) % 5] :
(col1 == col2) ? _table[(row1 + 1) % 5][col1] +_table[(row2 + 1) % 5][col2] :
_table[row1][col2] +_table[row2][col1])
if (i < length - 1) cipherText = cipherText + " "
}
return cipherText
}
decode(cipherText) {
var decodedText = ""
var length = cipherText.count
for (i in Stepped.new(0...length, 3)) { // cipherText will include spaces so we need to skip them
var pair = findChar_(cipherText[i])
var row1 = pair[0]
var col1 = pair[1]
pair = findChar_(cipherText[i + 1])
var row2 = pair[0]
var col2 = pair[1]
decodedText = decodedText +
((row1 == row2) ? _table[row1][(col1 > 0) ? col1-1 : 4] +_table[row2][(col2 > 0) ? col2-1 : 4] :
(col1 == col2) ? _table[(row1 > 0) ? row1-1 : 4][col1] +_table[(row2 > 0) ? row2-1 : 4][col2] :
_table[row1][col2] +_table[row2][col1])
if (i < length - 1) decodedText = decodedText + " "
}
return decodedText
}
printTable() {
System.print("The_table to be used is :\n")
for (i in 0..4) {
for (j in 0..4) System.write(_table[i][j] + " ")
System.print()
}
}
}
var keyword = Input.text("Enter Playfair keyword : ", 1)
var ignoreQ = Str.lower(Input.option("Ignore Q when building_table y/n : ", "yYnN"))
var pfo = (ignoreQ == "y") ? PlayfairOption.NO_Q : PlayfairOption.I_EQUALS_J
var playfair = Playfair.new(keyword, pfo)
playfair.printTable()
var plainText = Input.text("\nEnter plain text : ")
var encodedText = playfair.encode(plainText)
System.print("\nEncoded text is : %(encodedText)")
var decodedText = playfair.decode(encodedText)
System.print("Decoded text is : %(decodedText)") |
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.
| #360_Assembly | 360 Assembly | * Pernicious numbers 04/05/2016
PERNIC CSECT
USING PERNIC,R13 base register and savearea pointer
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
STM STM R14,R12,12(R13) save registers
ST R13,4(R15) link backward SA
ST R15,8(R13) link forward SA
LR R13,R15 establish addressability
SR R7,R7 n=0
MVC PG,=CL80' ' clear buffer
LA R10,PG pgi
LA R6,1 i=1
LOOPI1 C R7,=F'25' do i=1 while(n<25)
BNL ELOOPI1
LR R1,R6 i
BAL R14,POPCOUNT
LR R1,R0 popcount(i)
BAL R14,ISPRIME
C R0,=F'1' if isprime(popcount(i))=1
BNE NOTPRIM1
XDECO R6,XDEC edit i
MVC 0(3,R10),XDEC+9 output i format I3
LA R10,3(R10) pgi=pgi+3
LA R7,1(R7) n=n+1
NOTPRIM1 LA R6,1(R6) i=i+1
B LOOPI1
ELOOPI1 XPRNT PG,80 print buffer
MVC PG,=CL80' ' clear buffer
LA R10,PG pgi
L R6,=F'888888877' i=888888877
LOOPI2 C R6,=F'888888888' do i to 888888888
BH ELOOPI2
LR R1,R6 i
BAL R14,POPCOUNT
LR R1,R0 popcount(i)
BAL R14,ISPRIME
C R0,=F'1' if isprime(popcount(i))=1
BNE NOTPRIM2
XDECO R6,XDEC edit i
MVC 0(10,R10),XDEC+2 output i format I10
LA R10,10(R10) pgi=pgi+10
NOTPRIM2 LA R6,1(R6) i=i+1
B LOOPI2
ELOOPI2 XPRNT PG,80 print buffer
L R13,4(0,R13) restore savearea pointer
LM R14,R12,12(R13) restore registers
XR R15,R15 return code = 0
BR R14 -------------- end main
POPCOUNT CNOP 0,4 -------------- popcount(xx) [R8,R11]
ST R14,POPCOUSA save return address
ST R1,XX store argument
SR R11,R11 rr=0
SR R8,R8 ii=0
LOOPII C R8,=F'31' do ii=0 to 31
BH ELOOPII
L R1,XX xx
LR R2,R8 ii
BAL R14,BTEST
C R0,=F'1' if btest(xx,ii)=1
BNE NOTBTEST
LA R11,1(R11) rr=rr+1
NOTBTEST LA R8,1(R8) ii=ii+1
B LOOPII
ELOOPII LR R0,R11 return(rr)
L R14,POPCOUSA
BR R14 -------------- end popcount
ISPRIME CNOP 0,4 -------------- isprime(number) [R9]
ST R14,ISPRIMSA save return address
ST R1,NUMBER store argument
C R1,=F'2' if number=2
BNE ELSE1
MVC ISPRIMEX,=F'1' isprimex=1
B ELOOPJJ
ELSE1 L R1,NUMBER
C R1,=F'2' if number<2
BL EVEN
L R4,NUMBER
SRDA R4,32
D R4,=F'2' mod(number,2)
C R4,=F'0' if mod(number,2)=0
BNE ELSE2
EVEN MVC ISPRIMEX,=F'0' isprimex=0
B ELOOPJJ
ELSE2 MVC ISPRIMEX,=F'1' isprimex=1
LA R9,3 jj=3
LOOPJJ LR R5,R9 jj
MR R4,R9 jj*jj
C R5,NUMBER do jj=3 by 1 while jj*jj<=number
BH ELOOPJJ
L R4,NUMBER
SRDA R4,32
DR R4,R9 mod(number,jj)
LTR R4,R4 if mod(number,jj)=0
BNZ ITERJJ
MVC ISPRIMEX,=F'0' isprimex=0
L R0,ISPRIMEX return(isprimex)
B ISPRIMRT
ITERJJ LA R9,1(R9) jj=jj+1
B LOOPJJ
ELOOPJJ L R0,ISPRIMEX return(isprimex)
ISPRIMRT L R14,ISPRIMSA
BR R14 -------------- end isprime
BTEST CNOP 0,4 -------------- btest(word,n) [R0:R3]
LA R0,1 ok=1; return(1) if word(n)='1'b
LR R3,R2 i=n
LOOPB LTR R3,R3 if i=0
BZ ELOOPB
SRL R1,1 Shift Right Logical
BCTR R3,0 i=i-1
B LOOPB
ELOOPB STC R1,BTESTX x=word
TM BTESTX,B'00000001' if bit(word,n)='1'b
BO BTESTRET
LA R0,0 ok=0; return(0) if word(n)='0'b
BTESTRET BR R14 -------------- end btest
XX DS F paramter of popcount
NUMBER DS F paramter of isprime
ISPRIMEX DS F return value of isprime
BTESTX DS X byte to see in btest
POPCOUSA DS A return address of popcount
ISPRIMSA DS A return address of isprime
PG DS CL80 buffer
XDEC DS CL12 edit zone
YREGS
END PERNIC |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
/* Fill the integer array <vec> (of size <n>) with the
* permutation at rank <rank>.
*/
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
/* Return the rank of the current permutation of array <vec>
* (of size <n>).
*/
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf("%3d: ", r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf("[ ");
else printf(", ");
printf("%d", tv[i]);
}
printf(" ] = %d\n", get_rank(4, tv));
}
}
|
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
| #Delphi | Delphi |
program Pierpont_primes;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math,
System.StrUtils,
System.Generics.Collections,
System.Generics.Defaults,
Velthuis.BigIntegers,
Velthuis.BigIntegers.Primes;
function Pierpont(ulim, vlim: Integer; first: boolean): TArray<BigInteger>;
begin
var p: BigInteger := 0;
var p2: BigInteger := 1;
var p3: BigInteger := 1;
for var v := 0 to vlim - 1 do
begin
for var u := 0 to ulim - 1 do
begin
p := p2 * p3;
if first then
p := p + 1
else
p := p - 1;
if IsProbablePrime(p, 10) then
begin
SetLength(result, Length(result) + 1);
result[High(result)] := BigInteger(p);
end;
p2 := p2 * 2;
end;
p3 := p3 * 3;
p2 := 1;
end;
TArray.sort<BigInteger>(Result, TComparer<BigInteger>.Construct(
function(const Left, Right: BigInteger): Integer
begin
Result := BigInteger.Compare(Left, Right);
end));
end;
begin
writeln('First 50 Pierpont primes of the first kind:');
var pp := Pierpont(120, 80, True);
for var i := 0 to 49 do
begin
write(pp[i].ToString: 8, ' ');
if ((i - 9) mod 10) = 0 then
writeln;
end;
writeln('First 50 Pierpont primes of the second kind:');
var pp2 := Pierpont(120, 80, False);
for var i := 0 to 49 do
begin
write(pp2[i].ToString: 8, ' ');
if ((i - 9) mod 10) = 0 then
writeln;
end;
Writeln('250th Pierpont prime of the first kind:', pp[249].ToString);
Writeln('250th Pierpont prime of the second kind:', pp2[249].ToString);
readln;
end. |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BaCon | BaCon | ' Pick random element
OPTION BASE 1
DECLARE words$[6]
FOR i = 1 TO 6 : READ words$[i] : NEXT
DATA "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"
element = RANDOM(6) + 1
PRINT "Chose ", element, ": ", words$[element] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Bash | Bash | # borrowed from github.com/search?q=bashnative
rand() {
printf $(( $1 * RANDOM / 32767 ))
}
rand_element () {
local -a th=("$@")
unset th[0]
printf $'%s\n' "${th[$(($(rand "${#th[*]}")+1))]}"
}
echo "You feel like a $(rand_element pig donkey unicorn eagle) today" |
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
| #Scala | Scala | def isPrime(n: Int) =
n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0)) |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Racket | Racket | #lang racket
(define (pig-the-dice #:print? [print? #t] . players)
(define prn (if print? (λ xs (apply printf xs) (flush-output)) void))
(define names (for/list ([p players] [n (in-naturals 1)]) n))
(define points (for/list ([p players]) (box 0)))
(with-handlers ([(negate exn?) identity])
(for ([nm (in-cycle names)] [tp (in-cycle points)] [pl (in-cycle players)])
(prn (string-join (for/list ([n names] [p points])
(format "Player ~a, ~a points" n (unbox p)))
"; " #:before-first "Status: " #:after-last ".\n"))
(let turn ([p 0] [n 0])
(prn "Player ~a, round #~a, [R]oll or [P]ass? " nm (+ 1 n))
(define roll? (pl (unbox tp) p n))
(unless (eq? pl human) (prn "~a\n" (if roll? 'R 'P)))
(if (not roll?) (set-box! tp (+ (unbox tp) p))
(let ([r (+ 1 (random 6))])
(prn " Dice roll: ~s => " r)
(if (= r 1) (prn "turn lost\n")
(let ([p (+ p r)]) (prn "~a points\n" p) (turn p (+ 1 n)))))))
(prn "--------------------\n")
(when (<= 100 (unbox tp)) (prn "Player ~a wins!\n" nm) (raise nm)))))
(define (human total-points turn-points round#)
(case (string->symbol (car (regexp-match #px"[A-Za-z]?" (read-line))))
[(R r) #t] [(P p) #f] [else (human total-points turn-points round#)]))
;; Always do N rolls
(define ((n-rounds n) total-points turn-points round#) (< round# n))
;; Roll until a given number of points
(define ((n-points n) total-points turn-points round#) (< turn-points n))
;; Random decision
(define ((n-random n) total-points turn-points round#) (zero? (random n)))
(define (n-runs n . players)
(define v (make-vector (length players) 0))
(for ([i n])
(define p (sub1 (apply pig-the-dice #:print? #f players)))
(vector-set! v p (add1 (vector-ref v p))))
(for ([wins v] [i (in-naturals 1)])
(printf "Player ~a: ~a%\n" i (round (/ wins n 1/100)))))
;; Things to try
;; (n-runs 1000 (n-random 2) (n-random 3) (n-random 4))
;; (n-runs 1000 (n-rounds 5) (n-points 24))
;; (n-runs 1000 (n-rounds 5) (n-random 2)) |
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
| #AppleScript | AppleScript | -- REVERSED PHRASES, COMPONENT WORDS, AND WORD ORDER ---------------------
-- reverseString, reverseEachWord, reverseWordOrder :: String -> String
on stringReverse(s)
|reverse|(s)
end stringReverse
on reverseEachWord(s)
wordLevel(curry(my map)'s |λ|(my |reverse|))'s |λ|(s)
end reverseEachWord
on reverseWordOrder(s)
wordLevel(my |reverse|)'s |λ|(s)
end reverseWordOrder
-- wordLevel :: ([String] -> [String]) -> String -> String
on wordLevel(f)
script
on |λ|(x)
unwords(mReturn(f)'s |λ|(|words|(x)))
end |λ|
end script
end wordLevel
-- TEST ----------------------------------------------------------------------
on run
unlines(|<*>|({stringReverse, reverseEachWord, reverseWordOrder}, ¬
{"rosetta code phrase reversal"}))
-->
-- "lasrever esarhp edoc attesor
-- attesor edoc esarhp lasrever
-- reversal phrase code rosetta"
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on |<*>|(fs, xs)
set {nf, nx} to {length of fs, length of xs}
set acc to {}
repeat with i from 1 to nf
tell mReturn(item i of fs)
repeat with j from 1 to nx
set end of acc to |λ|(contents of (item j of xs))
end repeat
end tell
end repeat
return acc
end |<*>|
-- curry :: (Script|Handler) -> Script
on curry(f)
script
on |λ|(a)
script
on |λ|(b)
|λ|(a, b) of mReturn(f)
end |λ|
end script
end |λ|
end script
end curry
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- reverse :: [a] -> [a]
on |reverse|(xs)
if class of xs is text then
(reverse of characters of xs) as text
else
reverse of xs
end if
end |reverse|
-- words :: String -> [String]
on |words|(s)
words of s
end |words|
-- unlines :: [String] -> String
on unlines(lstLines)
intercalate(linefeed, lstLines)
end unlines
-- unwords :: [String] -> String
on unwords(lstWords)
intercalate(space, lstWords)
end unwords |
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
| #AutoHotkey | AutoHotkey | suits := ["♠", "♦", "♥", "♣"]
values := [2,3,4,5,6,7,8,9,10,"J","Q","K","A"]
Gui, font, s14
Gui, add, button, w190 gNewDeck, New Deck
Gui, add, button, x+10 wp gShuffle, Shuffle
Gui, add, button, x+10 wp gDeal, Deal
Gui, add, text, xs w600 , Current Deck:
Gui, add, Edit, xs wp r4 vDeck
Gui, add, text, xs , Hands:
Gui, add, Edit, x+10 w60 vHands gHands
Gui, add, UpDown,, 1
Edits := 0
Hands:
Gui, Submit, NoHide
loop, % Edits
GuiControl,Hide, Hand%A_Index%
loop, % Hands
GuiControl,Show, % "Hand" A_Index
loop, % Hands - Edits
{
Edits++
Gui, add, ListBox, % "x" (Edits=1?"s":"+10") " w60 r13 vHand" Edits
}
Gui, show, AutoSize
return
;-----------------------------------------------
GuiClose:
ExitApp
return
;-----------------------------------------------
NewDeck:
cards := [], deck := Dealt:= ""
loop, % Hands
GuiControl,, Hand%A_Index%, |
for each, suit in suits
for each, value in values
cards.Insert(value suit)
for each, card in cards
deck .= card (mod(A_Index, 13) ? " " : "`n")
GuiControl,, Deck, % deck
GuiControl,, Dealt
GuiControl, Enable, Button2
GuiControl, Enable, Hands
return
;-----------------------------------------------
shuffle:
gosub, NewDeck
shuffled := [], deck := ""
loop, 52 {
Random, rnd, 1, % cards.MaxIndex()
shuffled[A_Index] := cards.RemoveAt(rnd)
}
for each, card in shuffled
{
deck .= card (mod(A_Index, 13) ? " " : "`n")
cards.Insert(card)
}
GuiControl,, Deck, % deck
return
;-----------------------------------------------
Deal:
Gui, Submit, NoHide
if ( Hands > cards.MaxIndex())
return
deck := ""
loop, % Hands
GuiControl,, Hand%A_Index%, % cards.RemoveAt(1)
GuiControl, Disable, Button2
GuiControl, Disable, Hands
GuiControl,, Dealt, % Dealt
for each, card in cards
deck .= card (mod(A_Index, 13) ? " " : "`n")
GuiControl,, Deck, % deck
return
;----------------------------------------------- |
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
| #11l | 11l | V ndigits = 0
V q = BigInt(1)
V r = BigInt(0)
V t = q
V k = q
V n = BigInt(3)
V l = n
V first = 1B
L ndigits < 1'000
I 4 * q + r - t < n * t
print(n, end' ‘’)
ndigits++
I ndigits % 70 == 0
print()
I first
first = 0B
print(‘.’, end' ‘’)
V nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) I/ t) - 10 * n
q *= 10
r = nr
E
V nr = (2 * q + r) * l
V nn = (q * (7 * k + 2) + r * l) I/ (t * l)
q *= k
t *= l
l += 2
k++
n = nn
r = nr |
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
| #CLU | CLU | % This program uses the RNG included in PCLU's "misc.lib".
pig = cluster is play
rep = null
own pi: stream := stream$primary_input()
own po: stream := stream$primary_output()
own scores: array[int] := array[int]$[0,0]
% Seed the RNG with the current time
init_rng = proc ()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
end init_rng
% Roll die
roll = proc () returns (int)
return(random$next(6) + 1)
end roll
% Read keypresses until one of the keys in 's' is pressed
accept = proc (s: string) returns (char)
own beep: string := string$ac2s(array[char]$[char$i2c(7), char$i2c(8)])
while true do
c: char := stream$getc(pi)
if string$indexc(c,s) ~= 0 then
stream$putl(po, "")
return(c)
end
stream$puts(po, beep)
end
end accept
% Print the current scores
print_scores = proc ()
stream$puts(po, "\nCurrent scores: ")
for p: int in array[int]$indexes(scores) do
stream$puts(po, "Player " || int$unparse(p)
|| " = " || int$unparse(scores[p]) || "\t")
end
stream$putl(po, "")
end print_scores
% Player P's turn
turn = proc (p: int)
stream$putl(po, "\nPlayer " || int$unparse(p) || "'s turn.")
t: int := 0
while true do
r: int := roll()
stream$puts(po, "Score: " || int$unparse(scores[p]))
stream$puts(po, " Turn: " || int$unparse(t))
stream$puts(po, " Roll: " || int$unparse(r))
if r=1 then
% Rolled a 1, turn is over, no points.
stream$putl(po, " - Too bad!")
break
end
% Add this roll to the score for this turn
t := t + r
stream$puts(po, "\tR)oll again, or H)old? ")
if accept("rh") = 'h' then
% The player stops, and receives the points for this turn.
scores[p] := scores[p] + t
break
end
end
stream$putl(po, "Player " || int$unparse(p) || "'s turn ends.")
end turn
% Play the game
play = proc ()
stream$putl(po, "Game of Pig\n---- -- ----")
init_rng()
scores[1] := 0 % Both players start out with 0 points
scores[2] := 0
% Players take turns until one of them has a score >= 100
p: int := 1
while scores[1] < 100 & scores[2] < 100 do
print_scores()
turn(p) p := 3-p
end
print_scores()
for i: int in array[int]$indexes(scores) do
if scores[i] >= 100 then
stream$putl(po, "Player " || int$unparse(i) || " wins!")
break
end
end
end play
end pig
start_up = proc()
pig$play()
end start_up |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #zkl | zkl | fcn genKeyTable(key,deadChr){ // deadChr=="Q" or "J"
deadChr=deadChr.toUpper();
key=key.toUpper().unique() - " " - deadChr;
return(key + (["A".."Z"].pump(String) - deadChr - key), deadChr);
} |
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.
| #Ada | Ada | with Ada.Text_IO, Population_Count; use Population_Count;
procedure Pernicious is
Prime: array(0 .. 64) of Boolean;
-- we are using 64-bit numbers, so the population count is between 0 and 64
X: Num; use type Num;
Cnt: Positive;
begin
-- initialize array Prime; Prime(I) must be true if and only if I is a prime
Prime := (0 => False, 1 => False, others => True);
for I in 2 .. 8 loop
if Prime(I) then
Cnt := I + I;
while Cnt <= 64 loop
Prime(Cnt) := False;
Cnt := Cnt + I;
end loop;
end if;
end loop;
-- print first 25 pernicious numbers
X := 1;
for I in 1 .. 25 loop
while not Prime(Pop_Count(X)) loop
X := X + 1;
end loop;
Ada.Text_IO.Put(Num'Image(X));
X := X + 1;
end loop;
Ada.Text_IO.New_Line;
-- print pernicious numbers between 888_888_877 and 888_888_888 (inclusive)
for Y in Num(888_888_877) .. 888_888_888 loop
if Prime(Pop_Count(Y)) then
Ada.Text_IO.Put(Num'Image(Y));
end if;
end loop;
Ada.Text_IO.New_Line;
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
| #D | D | import std.stdio, std.algorithm, std.range;
alias TRank = ulong;
TRank factorial(in uint n) pure nothrow {
TRank result = 1;
foreach (immutable i; 2 .. n + 1)
result *= i;
return result;
}
/// Fill the integer array <vec> with the permutation at rank <rank>.
void computePermutation(size_t N)(ref uint[N] vec, TRank rank)
pure nothrow if (N > 0 && N < 22) {
N.iota.copy(vec[]);
foreach_reverse (immutable n; 1 .. N + 1) {
immutable size_t r = rank % n;
rank /= n;
swap(vec[r], vec[n - 1]);
}
}
/// Return the rank of the current permutation.
TRank computeRank(size_t N)(in ref uint[N] vec) pure nothrow
if (N > 0 && N < 22) {
uint[N] vec2, inv = void;
TRank mrRank1(in uint n) nothrow {
if (n < 2)
return 0;
immutable s = vec2[n - 1];
swap(vec2[n - 1], vec2[inv[n - 1]]);
swap(inv[s], inv[n - 1]);
return s + n * mrRank1(n - 1);
}
vec2[] = vec[];
foreach (immutable i; 0 .. N)
inv[vec[i]] = i;
return mrRank1(N);
}
void main() {
import std.random;
uint[4] items1 = void;
immutable rMax1 = items1.length.factorial;
for (TRank rank = 0; rank < rMax1; rank++) {
items1.computePermutation(rank);
writefln("%3d: %s = %d", rank, items1, items1.computeRank);
}
writeln;
uint[21] items2 = void;
immutable rMax2 = items2.length.factorial;
foreach (immutable _; 0 .. 5) {
immutable rank = uniform(0, rMax2);
items2.computePermutation(rank);
writefln("%20d: %s = %d", rank, items2, items2.computeRank);
}
} |
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
| #F.23 | F# |
// Pierpont primes . Nigel Galloway: March 19th., 2021
let fN g=let mutable g=g in ((fun()->g),fun()->g<-g+g;())
let fG y=let rec fG n g=seq{match g|>List.minBy(fun(n,_)->n()) with (f,s) when f()=n->yield f()+y; s(); yield! fG(n*3)(fN(n*3)::g)
|(f,s) ->yield f()+y; s(); yield! fG n g}
seq{yield! fG 1 [fN 1]}|>Seq.filter isPrime
let pierpontT1,pierpontT2=fG 1,fG -1
pierpontT1|>Seq.take 50|>Seq.iter(printf "%d "); printfn ""
pierpontT2|>Seq.take 50|>Seq.iter(printf "%d "); printfn ""
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BASIC | BASIC | 'setup
DIM foo(10) AS LONG
DIM n AS LONG, x AS LONG
FOR n = LBOUND(foo) TO UBOUND(foo)
foo(n) = INT(RND*99999)
NEXT
RANDOMIZE TIMER
'random selection
x = INT(RND * ((UBOUND(foo) - LBOUND(foo)) + 1))
'output
PRINT x, foo(x) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
::Initializing the pseudo-array...
set "pseudo=Alpha Beta Gamma Delta Epsilon"
set cnt=0 & for %%P in (!pseudo!) do (
set /a cnt+=1
set "pseudo[!cnt!]=%%P"
)
::Do the random thing...
set /a rndInt=%random% %% cnt +1
::Print the element corresponding to rndint...
echo.!pseudo[%rndInt%]!
pause
exit /b |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
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
| #Scheme | Scheme | (define (prime? number)
(define (*prime? divisor)
(or (> (* divisor divisor) number)
(and (> (modulo number divisor) 0)
(*prime? (+ divisor 1)))))
(and (> number 1)
(*prime? 2))) |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Raku | Raku | player 0 uses the default strategy, always roll if it can.
player 1 will roll up to 5 times then lock in whatever it earned.
player 2 will try to get at least 20 points per turn.
player 3 randomly picks whether to roll again or not biased so that there is a 90% chance that it will.
player 4 randomly chooses to roll again but gets more consrvative as its score get closer to the goal.
|
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
| #Arturo | Arturo | phr: "rosetta code phrase reversal"
print ["(0)" phr]
print ["(1)" reverse phr]
print ["(2)" join.with:" " map split.words phr => reverse]
print ["(3)" join.with:" " reverse split.words phr] |
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
| #AutoHotkey | AutoHotkey | var =
(
Rosetta Code Phrase Reversal
)
array := strsplit(var, " ")
loop, % array.maxindex()
string .= array[array.maxindex() - A_index + 1] . " "
loop, % array.maxindex()
{
m := array[A_index]
array2 := strsplit(m, "")
Loop, % array2.maxindex()
string2 .= array2[array2.maxindex() - A_index + 1]
string2 .= " "
}
array := strsplit(string, " " )
loop, % array.maxindex()
{
m := array[A_index]
array3 := strsplit(m, "")
Loop, % array3.maxindex()
string3 .= array3[array3.maxindex() - A_index + 1]
string3 .= " "
}
MsgBox % var . "`n" . string3 . "`n" . String . "`n" . string2
ExitApp
esc::ExitApp |
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
| #AutoIt | AutoIt |
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <Array.au3>
; ## GLOBALS ##
Global $SUIT = ["D", "H", "S", "C"]
Global $FACE = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
Global $DECK[52]
; ## CREATES A NEW DECK
Func NewDeck()
For $i = 0 To 3
For $x = 0 To 12
_ArrayPush($DECK, $FACE[$x] & $SUIT[$i])
Next
Next
EndFunc ;==>NewDeck
; ## SHUFFLE DECK
Func Shuffle()
_ArrayShuffle($DECK)
EndFunc ;==>Shuffle
; ## DEAL A CARD
Func Deal()
Return _ArrayPop($DECK)
EndFunc ;==>Deal
; ## PRINT DECK
Func Print()
ConsoleWrite(_ArrayToString($DECK) & @CRLF)
EndFunc ;==>Print
#Region ;#### USAGE ####
NewDeck()
Print()
Shuffle()
Print()
ConsoleWrite("DEALT: " & Deal() & @CRLF)
Print()
#EndRegion ;#### USAGE ####
|
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
| #360_Assembly | 360 Assembly | * Spigot algorithm do the digits of PI 02/07/2016
PISPIG CSECT
USING PISPIG,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
SR R0,R0 0
ST R0,MORE more=0
LA R6,1 i=1
LOOPI1 C R6,=A(NBUF) do i=1 to hbound(buf)
BH ELOOPI1 "
SR R9,R9 karray=0
L R7,=A(NVECT) j=hbound(vect)
LR R1,R7 j
SLA R1,2 .
LA R10,VECT-4(R1) r10=@vect(j)
LOOPJ EQU * do j=hbound(vect) to 1 by -1
L R5,=F'100000' 100000
M R4,0(R10) *vect(j)
LR R2,R5 r2=100000*vect(j)
LR R5,R9 karray
MR R4,R7 karray*j
AR R2,R5 r2+karray*j
LR R11,R2 n=100000*vect(j)+karray*j
LR R3,R7 j
SLA R3,1 2*j
BCTR R3,0 2*j-1)
LR R4,R11 n
SRDA R4,32 .
DR R4,R3 n/(2*j-1)
LR R9,R5 karray=n/(2*j-1)
LR R5,R9 karray
MR R4,R3 karray*(2*j-1)
LR R1,R11 n
SR R1,R5 n-karray*(2*j-1)
ST R1,0(R10) vect(j)=n-karray*(2*j-1)
SH R10,=H'4' r10=@vect(j)
BCT R7,LOOPJ end do j
LR R4,R9 karray
SRDA R4,32 .
D R4,=F'100000' karray/100000
LR R11,R5 k=karray/100000
L R2,MORE more
AR R2,R11 +k
LR R1,R6 i
SLA R1,2 .
ST R2,BUF-4(R1) buf(i)=more+k
LR R5,R11 k
M R4,=F'100000' *100000
LR R1,R9 karray
SR R1,R5 -k*100000
ST R1,MORE more=karray-k*100000
LA R6,1(R6) i=i+1
B LOOPI1 end do i
ELOOPI1 L R1,BUF buf(1)
CVD R1,PACKED convert buf(1) to packed decimal
OI PACKED+7,X'0F' prepare unpack
UNPK PG(1),PACKED packed decimal to zoned printable
MVI PG+1,C'.' output '.'
XPRNT PG,80 print buffer
MVC PG,=CL80' ' clear buffer
LA R3,PG pgi=0
LA R6,2 i=2
LOOPI2 C R6,=A(NBUF) do i=2 to hbound(buf)
BH ELOOPI2 "
MVC 0(1,R3),=C' ' output ' '
LA R3,1(R3) pgi=pgi+1
LR R1,R6 i
SLA R1,2 .
L R2,BUF-4(R1) buf(i)
CVD R2,PACKED convert v to packed decimal
OI PACKED+7,X'0F' prepare unpack
UNPK XDEC,PACKED packed decimal to zoned printable
MVC 0(5,R3),XDEC+7 output buf(i) with 5 decimals
LA R3,5(R3) pgi=pgi+5
LR R4,R6 i
BCTR R4,0 i-1
SRDA R4,32 .
D R4,=F'10' (i-1)/10
LTR R4,R4 if (i-1)//10=0
BNZ NOSKIP then
XPRNT PG,80 print buffer
LA R3,PG pgi=0
MVC PG,=CL80' ' clear buffer
NOSKIP LA R6,1(R6) i=i+1
B LOOPI2 end do i
ELOOPI2 L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
LTORG
MORE DS F more
PACKED DS 0D,PL8 packed decimal
PG DC CL80' ' buffer
XDEC DS CL12 temp
BUF DC (NBUF)F'0' buf(nbuf)
VECT DC (NVECT)F'2' vect(nvect) init 2
YREGS
NBUF EQU 201 number of 5 decimals
NVECT EQU 3350 nvect=ceil(nbuf*50/3)
END PISPIG |
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
| #Common_Lisp | Common Lisp | (defconstant +max-score+ 100)
(defconstant +n-of-players+ 2)
(let ((scores (make-list +n-of-players+ :initial-element 0))
(current-player 0)
(round-score 0))
(loop
(format t "Player ~d: (~d, ~d). Rolling? (Y)"
current-player
(nth current-player scores)
round-score)
(if (member (read-line) '("y" "yes" "") :test #'string=)
(let ((roll (1+ (random 6))))
(format t "~tRolled ~d~%" roll)
(if (= roll 1)
(progn
(format t
"~tBust! you lose ~d but still keep your previous ~d~%"
round-score (nth current-player scores))
(setf round-score 0)
(setf current-player
(mod (1+ current-player) +n-of-players+)))
(incf round-score roll)))
(progn
(incf (nth current-player scores) round-score)
(setf round-score 0)
(when (>= (apply #'max scores) 100)
(return))
(format t "~tSticking with ~d~%" (nth current-player scores))
(setf current-player (mod (1+ current-player) +n-of-players+)))))
(format t "~%Player ~d wins with a score of ~d~%" current-player
(nth current-player scores))) |
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.
| #ALGOL_68 | ALGOL 68 | # calculate various pernicious numbers #
# returns the population (number of bits on) of the non-negative integer n #
PROC population = ( INT n )INT:
BEGIN
INT number := n;
INT result := 0;
WHILE number > 0 DO
IF ODD number THEN result +:= 1 FI;
number OVERAB 2
OD;
result
END # population # ;
# as we are dealing with 32 bit numbers, the maximum possible population is 32 #
# so we only need a table of whether the integers 0 : 32 are prime or not #
# we use the sieve of Eratosthenes... #
INT max number = 32;
[ 0 : max number ]BOOL is prime;
is prime[ 0 ] := FALSE;
is prime[ 1 ] := FALSE;
FOR i FROM 2 TO max number DO is prime[ i ] := TRUE OD;
FOR i FROM 2 TO ENTIER sqrt( max number ) DO
IF is prime[ i ] THEN FOR p FROM i * i BY i TO max number DO is prime[ p ] := FALSE OD FI
OD;
# returns TRUE if n is pernicious, FALSE otherwise #
PROC is pernicious = ( INT n )BOOL: is prime[ population( n ) ];
# find the first 25 pernicious numbers, 0 and 1 are not pernicious #
INT pernicious count := 0;
FOR i FROM 2 WHILE pernicious count < 25 DO
IF is pernicious( i ) THEN
# found a pernicious number #
print( ( whole( i, 0 ), " " ) );
pernicious count +:= 1
FI
OD;
print( ( newline ) );
# find the pernicious numbers between 888 888 877 and 888 888 888 #
FOR i FROM 888 888 877 TO 888 888 888 DO
IF is pernicious( i ) THEN
print( ( whole( i, 0 ), " " ) )
FI
OD;
print( ( newline ) )
|
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
| #FreeBASIC | FreeBASIC | ' version 31-03-2017
' compile with: fbc -s console
' Myrvold and Ruskey
' only for up to 20 elements, 21! > 2^64 -1
Function Factorial(n As Integer) As ULongInt
Dim As ULongInt tmp = 1
For i As ULong = 2 To n
tmp *= i
Next
Return tmp
End Function
Sub unrank1(n As ULong, r As ULongInt , pi() As UByte)
If n > 0 Then
Swap pi(n -1), pi(r Mod n)
unrank1(n -1, (r \ n), pi())
End If
End Sub
Function rank1(n As ULongInt, pi() As UByte, pi_inv() As UByte) As ULongInt
If n = 1 Then Return 0
Dim As UByte s = pi(n -1)
Swap pi(n -1), pi(pi_inv(n -1))
Swap pi_inv(s), pi_inv(n -1)
Return (s + n * rank1(n -1, pi(), pi_inv()))
End Function
Sub unrank2(n As ULong, r As ULongInt, pi() As ubyte)
If n > 0 Then
Dim As ULongInt fac = Factorial(n - 1)
Dim As ULongint s = r \ fac
Swap pi(n -1), pi(s)
unrank2(n -1, r - s * fac, pi())
End If
End Sub
Function rank2(n As ULong, pi() As UByte, pi_inv() As UByte) As ULongInt
If n = 1 Then Return 0
Dim As UByte s = pi(n -1)
Swap pi(n -1), pi(pi_inv(n -1))
Swap pi_inv(s), pi_inv(n -1)
Return (s * Factorial(n -1) + rank2(n -1, pi(), pi_inv()))
End Function
' ------=< MAIN >=------
Dim As ULongInt i, i1, j, n, n1
Dim As UByte pi(), pi_inv()
Dim As String frmt1, frmt2
Randomize timer
n = 3 : n1 = Factorial(n)
ReDim pi(n -1), pi_inv(n - 1)
frmt1 = " ###"
frmt2 = "##"
Print "Rank: unrank1 rank1"
For i = 0 To n1 -1
For j = 0 To n -1
pi(j) = j
Next
Print Using frmt1 & ": --> "; i;
unrank1(n, i, pi())
For j = 0 To n -1
Print Using frmt2; pi(j);
pi_inv(pi(j))= j
Next
Print Using " -->" & frmt1; rank1(n, pi(), pi_inv())
Next
n = 12 : n1 = Factorial(n)
ReDim pi(n -1), pi_inv(n - 1)
frmt1 = "###########"
frmt2 = "###"
Print : Print "4 random samples of permutations from 12 objects"
Print " Rank: unrank1 rank1"
For i = 1 To 4
i1 = Int(Rnd * n1)
For j = 0 To n -1 : pi(j) = j : Next
Print Using frmt1 & ": --> "; i1; : unrank1(n, i1, pi())
For j = 0 To n -1 : Print Using frmt2; pi(j);
pi_inv(pi(j))= j : Next
Print Using " -->" & frmt1; rank1(n, pi(), pi_inv())
Next
Print : Print String(69,"-") : Print
Print "Rank: unrank2 rank2"
n = 3 : n1 = Factorial(n)
ReDim pi(n -1), pi_inv(n - 1)
frmt1 = " ###"
frmt2 = "##"
For i = 0 To n1 -1
For j = 0 To n -1
pi(j) = j
Next
Print Using frmt1 & ": --> "; i;
unrank2(n, i, pi())
For j = 0 To n -1
Print Using frmt2; pi(j);
pi_inv(pi(j))= j
Next
Print Using " -->" & frmt1; rank2(n, pi(), pi_inv())
Next
n = 12 : n1 = Factorial(n)
ReDim pi(n -1), pi_inv(n - 1)
frmt1 = "###########"
frmt2 = "###"
Print : Print "4 random samples of permutations from 12 objects"
Print " Rank: unrank2 rank2"
For i = 1 To 4
i1 = Int(Rnd * n1)
For j = 0 To n -1 : pi(j) = j : Next
Print Using frmt1 & ": --> "; i1; : unrank2(n, i1, pi())
For j = 0 To n -1 : Print Using frmt2; pi(j);
pi_inv(pi(j))= j : Next
Print Using " -->" & frmt1; rank2(n, pi(), pi_inv())
Next
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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
| #Factor | Factor | USING: fry grouping io kernel locals make math math.functions
math.primes prettyprint sequences sorting ;
: pierpont ( ulim vlim quot -- seq )
'[
_ <iota> _ <iota> [
[ 2 ] [ 3 ] bi* [ swap ^ ] 2bi@ * 1 @
dup prime? [ , ] [ drop ] if
] cartesian-each
] { } make natural-sort ; inline
: .fifty ( seq -- ) 50 head 10 group simple-table. nl ;
[let
[ + ] [ - ] [ [ 120 80 ] dip pierpont ] bi@
:> ( first second )
"First 50 Pierpont primes of the first kind:" print
first .fifty
"First 50 Pierpont primes of the second kind:" print
second .fifty
"250th Pierpont prime of the first kind: " write
249 first nth . nl
"250th Pierpont prime of the second kind: " write
249 second nth .
] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BBC_BASIC | BBC BASIC | DIM list$(5)
list$() = "The", "five", "boxing", "wizards", "jump", "quickly"
chosen% = RND(6)
PRINT "Item " ; chosen% " was chosen which is '" list$(chosen%-1) "'" |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BQN | BQN | PR ← {𝕩⊑˜•rand.Range ≠𝕩}
PR1 ← •rand.Range∘≠⊸⊑ |
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
| #Seed7 | Seed7 | const func boolean: isPrime (in integer: number) is func
result
var boolean: prime is FALSE;
local
var integer: upTo is 0;
var integer: testNum is 3;
begin
if number = 2 then
prime := TRUE;
elsif odd(number) and number > 2 then
upTo := sqrt(number);
while number rem testNum <> 0 and testNum <= upTo do
testNum +:= 2;
end while;
prime := testNum > upTo;
end if;
end func; |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #REXX | REXX | /*REXX program plays "pig the dice game" (any number of CBLFs and/or silicons or HALs).*/
sw= linesize() - 1 /*get the width of the terminal screen,*/
parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments from the CL*/
/*names with blanks should use an _ */
if _\=='' then call err 'too many arguments were specified: ' _
@nhp = 'number of human players' ; hp = scrutinize( hp, @nhp , 0, 0, 0)
@ncp = 'number of computer players'; cp = scrutinize( cp, @ncp , 0, 0, 2)
@sn2w = 'score needed to win' ; win= scrutinize(win, @sn2w, 1, 1e6, 60)
@nsid = 'number of sides in die' ; die= scrutinize(die, @nsid, 2, 999, 6)
if hp==0 & cp==0 then cp= 2 /*if both counts are zero, two HALs. */
if hp==1 & cp==0 then cp= 1 /*if one human, then use one HAL. */
name.= /*nullify all names (to a blank). */
L= 0 /*maximum length of a player name. */
do i=1 for hp+cp /*get the player's names, ... maybe. */
if i>hp then @= 'HAL_'i"_the_computer" /*use this for default name. */
else @= 'player_'i /* " " " " " */
name.i = translate( word( strip( word( names, i) ) @, 1), , '_')
L= max(L, length( name.i) ) /*use L for nice name formatting. */
end /*i*/ /*underscores are changed ──► blanks. */
hpn=hp; if hpn==0 then hpn= 'no' /*use normal English for the display. */
cpn=cp; if cpn==0 then cpn= 'no' /* " " " " " " */
say 'Pig (the dice game) is being played with:' /*the introduction to pig-the-dice-game*/
if cpn\==0 then say right(cpn, 9) 'computer player's(cp)
if hpn\==0 then say right(hpn, 9) 'human player's(hp)
!.=
say 'and the' @sn2w "is: " win ' (or greater).'
dieNames= 'ace deuce trey square nickle boxcar' /*some slangy vernacular die─face names*/
!w=0 /*note: snake eyes is for two aces. */
do i=1 for die /*assign the vernacular die─face names.*/
!.i= ' ['word(dieNames,i)"]" /*pick a word from die─face name lists.*/
!w= max(!w, length(!.i) ) /*!w ──► maximum length die─face name. */
end /*i*/
s.= 0 /*set all player's scores to zero. */
!w= !w + length(die) + 3 /*pad the die number and die names. */
@= copies('─', 9) /*eyecatcher (for the prompting text). */
@jra= 'just rolled a ' /*a nice literal to have laying 'round.*/
@ati= 'and the inning' /*" " " " " " " */
/*═══════════════════════════════════════════════════let's play some pig.*/
do game=1; in.= 0; call score /*set each inning's score to 0; display*/
do j=1 for hp+cp; say /*let each player roll their dice. */
say copies('─', sw) /*display a fence for da ole eyeballs. */
it= name.j
say it', your total score (so far) in this pig game is: ' s.j"."
do until stopped /*keep prompting/rolling 'til stopped. */
r= random(1, die) /*get a random die face (number). */
!= left(space(r !.r','), !w) /*for color, use a die─face name. */
in.j= in.j + r /*add die─face number to the inning. */
if r==1 then do; say it @jra ! || @ati "is a bust."; leave; end
say it @jra ! || @ati "total is: " in.j
stopped= what2do(j) /*determine or ask to stop rolling. */
if j>hp & stopped then say ' and' name.j "elected to stop rolling."
end /*until stopped*/
if r\==1 then s.j= s.j + in.j /*if not a bust, then add to the inning*/
if s.j>=win then leave game /*we have a winner, so the game ends. */
end /*j*/ /*that's the end of the players. */
end /*game*/
call score; say; say; say; say; say center(''name.j "won! ", sw, '═')
say; say; exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
score: say; say copies('█', sw) /*display a fence for da ole eyeballs. */
do k=1 for hp+cp /*display the scores (as a recap). */
say 'The score for ' left(name.k, L) " is " right(s.k, length(win) ).
end /*k*/
say copies('█', sw); return /*display a fence for da ole eyeballs. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
scrutinize: parse arg ?,what,min,max /*? is the number, ... or maybe not. */
if ?=='' | ?==',' then return arg(5)
if \datatype(?, 'N') then call err what "isn't numeric: " ?; ?=?/1
if \datatype(?, 'W') then call err what "isn't an integer: " ?
if ?==0 & min>0 then call err what "can't be zero."
if ?<min then call err what "can't be less than" min': ' ?
if ?==0 & max>0 then call err what "can't be zero."
if ?>max & max\==0 then call err what "can't be greater than" max': ' ?
return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
what2do: parse arg who /*"who" is a human or a computer.*/
if j>hp & s.j+in.j>=win then return 1 /*an easy choice for HAL. */
if j>hp & in.j>=win%4 then return 1 /*a simple strategy for HAL. */
if j>hp then return 0 /*HAL says, keep truckin'! */
say @ name.who', what do you want to do? (a QUIT will stop the game),'
say @ 'press ENTER to roll again, or anything else to STOP rolling.'
pull action; action=space(action) /*remove any superfluous blanks. */
if \abbrev('QUIT', action, 1) then return action\==''
say; say; say center(' quitting. ', sw, '─'); say; say; exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say; say center(' error! ', max(40, linesize() % 2), "*"); say
do j=1 for arg(); say arg(j); say; end; say; exit 13 |
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
| #AWK | AWK | # Usage: awk -f phrase_revers.awk
function rev(s, del, n,i,a,r) {
n = split(s, a, del)
r = a[1]
for(i=2; i <= n; i++) {r = a[i] del r }
return r
}
BEGIN {
p0 = "Rosetta Code Phrase Reversal"
fmt = "%-20s: %s\n"
printf( fmt, "input", p0 )
printf( fmt, "string reversed", rev(p0, "") )
wr = rev(p0, " ")
printf( fmt, "word-order reversed", wr )
printf( fmt, "each word reversed", rev(wr) )
} |
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
| #BaCon | BaCon | phrase$ = "rosetta code phrase reversal"
PRINT REVERSE$(phrase$)
PRINT REV$(REVERSE$(phrase$))
PRINT REV$(phrase$) |
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
| #BASIC | BASIC | DECLARE SUB setInitialValues (deck() AS STRING * 2)
DECLARE SUB shuffle (deck() AS STRING * 2)
DECLARE SUB showDeck (deck() AS STRING * 2)
DECLARE FUNCTION deal$ (deck() AS STRING * 2)
DATA "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "TS", "JS", "QS", "KS"
DATA "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "TH", "JH", "QH", "KH"
DATA "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC"
DATA "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD"
RANDOMIZE TIMER
REDIM cards(51) AS STRING * 2
REDIM cards2(51) AS STRING * 2
setInitialValues cards()
setInitialValues cards2()
shuffle cards()
PRINT "Dealt: "; deal$(cards())
PRINT "Dealt: "; deal$(cards())
PRINT "Dealt: "; deal$(cards())
PRINT "Dealt: "; deal$(cards())
showDeck cards()
showDeck cards2()
FUNCTION deal$ (deck() AS STRING * 2)
'technically dealing from the BOTTOM of the deck... whatever
DIM c AS STRING * 2
c = deck(UBOUND(deck))
REDIM PRESERVE deck(LBOUND(deck) TO UBOUND(deck) - 1) AS STRING * 2
deal$ = c
END FUNCTION
SUB setInitialValues (deck() AS STRING * 2)
DIM L0 AS INTEGER
RESTORE
FOR L0 = 0 TO 51
READ deck(L0)
NEXT
END SUB
SUB showDeck (deck() AS STRING * 2)
FOR L% = LBOUND(deck) TO UBOUND(deck)
PRINT deck(L%); " ";
NEXT
PRINT
END SUB
SUB shuffle (deck() AS STRING * 2)
DIM w AS INTEGER
DIM shuffled(51) AS STRING * 2
DIM L0 AS INTEGER
FOR L0 = 51 TO 0 STEP -1
w = INT(RND * (L0 + 1))
shuffled(L0) = deck(w)
IF w <> L0 THEN deck(w) = deck(L0)
NEXT
FOR L0 = 0 TO 51
deck(L0) = shuffled(L0)
NEXT
END SUB |
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
| #Ada | Ada | with Ada.Command_Line;
with Ada.Text_IO;
with GNU_Multiple_Precision.Big_Integers;
with GNU_Multiple_Precision.Big_Rationals;
use GNU_Multiple_Precision;
procedure Pi_Digits is
type Int is mod 2 ** 64;
package Int_To_Big is new Big_Integers.Modular_Conversions (Int);
-- constants
Zero : constant Big_Integer := Int_To_Big.To_Big_Integer (0);
One : constant Big_Integer := Int_To_Big.To_Big_Integer (1);
Two : constant Big_Integer := Int_To_Big.To_Big_Integer (2);
Three : constant Big_Integer := Int_To_Big.To_Big_Integer (3);
Four : constant Big_Integer := Int_To_Big.To_Big_Integer (4);
Ten : constant Big_Integer := Int_To_Big.To_Big_Integer (10);
-- type LFT = (Integer, Integer, Integer, Integer
type LFT is record
Q, R, S, T : Big_Integer;
end record;
-- extr :: LFT -> Integer -> Rational
function Extr (T : LFT; X : Big_Integer) return Big_Rational is
use Big_Integers;
Result : Big_Rational;
begin
-- extr (q,r,s,t) x = ((fromInteger q) * x + (fromInteger r)) /
-- ((fromInteger s) * x + (fromInteger t))
Big_Rationals.Set_Numerator (Item => Result,
New_Value => T.Q * X + T.R,
Canonicalize => False);
Big_Rationals.Set_Denominator (Item => Result,
New_Value => T.S * X + T.T);
return Result;
end Extr;
-- unit :: LFT
function Unit return LFT is
begin
-- unit = (1,0,0,1)
return LFT'(Q => One, R => Zero, S => Zero, T => One);
end Unit;
-- comp :: LFT -> LFT -> LFT
function Comp (T1, T2 : LFT) return LFT is
use Big_Integers;
begin
-- comp (q,r,s,t) (u,v,w,x) = (q*u+r*w,q*v+r*x,s*u+t*w,s*v+t*x)
return LFT'(Q => T1.Q * T2.Q + T1.R * T2.S,
R => T1.Q * T2.R + T1.R * T2.T,
S => T1.S * T2.Q + T1.T * T2.S,
T => T1.S * T2.R + T1.T * T2.T);
end Comp;
-- lfts = [(k, 4*k+2, 0, 2*k+1) | k<-[1..]
K : Big_Integer := Zero;
function LFTS return LFT is
use Big_Integers;
begin
K := K + One;
return LFT'(Q => K,
R => Four * K + Two,
S => Zero,
T => Two * K + One);
end LFTS;
-- next z = floor (extr z 3)
function Next (T : LFT) return Big_Integer is
begin
return Big_Rationals.To_Big_Integer (Extr (T, Three));
end Next;
-- safe z n = (n == floor (extr z 4)
function Safe (T : LFT; N : Big_Integer) return Boolean is
begin
return N = Big_Rationals.To_Big_Integer (Extr (T, Four));
end Safe;
-- prod z n = comp (10, -10*n, 0, 1)
function Prod (T : LFT; N : Big_Integer) return LFT is
use Big_Integers;
begin
return Comp (LFT'(Q => Ten, R => -Ten * N, S => Zero, T => One), T);
end Prod;
procedure Print_Pi (Digit_Count : Positive) is
Z : LFT := Unit;
Y : Big_Integer;
Count : Natural := 0;
begin
loop
Y := Next (Z);
if Safe (Z, Y) then
Count := Count + 1;
Ada.Text_IO.Put (Big_Integers.Image (Y));
exit when Count >= Digit_Count;
Z := Prod (Z, Y);
else
Z := Comp (Z, LFTS);
end if;
end loop;
end Print_Pi;
N : Positive := 250;
begin
if Ada.Command_Line.Argument_Count = 1 then
N := Positive'Value (Ada.Command_Line.Argument (1));
end if;
Print_Pi (N);
end Pi_Digits; |
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
| #D | D | void main() {
import std.stdio, std.string, std.algorithm, std.random;
enum maxScore = 100;
enum playerCount = 2;
immutable confirmations = ["yes", "y", ""];
int[playerCount] safeScore;
int player, score;
while (true) {
writef(" Player %d: (%d, %d). Rolling? (y/n) ", player,
safeScore[player], score);
if (safeScore[player] + score < maxScore &&
confirmations.canFind(readln.strip.toLower)) {
immutable rolled = uniform(1, 7);
writefln(" Rolled %d", rolled);
if (rolled == 1) {
writefln(" Bust! You lose %d but keep %d\n",
score, safeScore[player]);
} else {
score += rolled;
continue;
}
} else {
safeScore[player] += score;
if (safeScore[player] >= maxScore)
break;
writefln(" Sticking with %d\n", safeScore[player]);
}
score = 0;
player = (player + 1) % playerCount;
}
writefln("\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.
| #ALGOL_W | ALGOL W | begin % find some pernicious numbers: numbers with a prime population count %
% returns the population count of n %
integer procedure populationCount( integer value n ) ;
begin
integer v, count;
count := 0;
v := abs n;
while v > 0 do begin
if odd( v ) then count := count + 1;
v := v div 2
end while_v_gt_0 ;
count
end populationCount ;
% sets p( 1 :: n ) to a sieve of primes up to n %
procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
begin
p( 1 ) := false; p( 2 ) := true;
for i := 3 step 2 until n do p( i ) := true;
for i := 4 step 2 until n do p( i ) := false;
for i := 3 step 2 until truncate( sqrt( n ) ) do begin
integer ii; ii := i + i;
if p( i ) then for pr := i * i step ii until n do p( pr ) := false
end for_i ;
end Eratosthenes ;
% returns true if p is pernicious, false otherwise, s must be a sieve %
% of primes upto 32 %
logical procedure isPernicious ( integer value p; logical array s ( * ) ) ; p > 0 and s( populationCount( p ) );
% find the pernicious numbers %
begin
% as we are dealing with 32 bit numbers, the maximum possible %
% population is 32 %
logical array isPrime ( 1 :: 32 );
integer p, pCount;
Eratosthenes( isPrime, 32 );
% show the first 25 pernicious numbers %
pCount := 0;
p := 2; % 0 and 1 aren't pernicious, so start at 2 %
while pCount < 25 do begin
if isPernicious( p, isPrime ) then begin
% have a pernicious number %
pCount := pCount + 1;
writeon( i_w := 1, s_w := 0, " ", p )
end if_pernicious_p ;
p := P + 1
end for_p ;
write();
% find the pernicious numbers between 888 888 877 and 888 888 888 %
for p := 888888877 until 888888888 do begin
if isPernicious( p, isPrime ) then writeon( i_w := 1, s_w := 0, " ", p )
end for_p ;
write();
end
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
| #Go | Go | package main
import (
"fmt"
"math/rand"
)
// returns permutation q of n items, using Myrvold-Ruskey rank.
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
// returns identity permutation of n items.
func ident(n int) []int {
p := make([]int, n)
for i := range p {
p[i] = i
}
return p
}
// returns Myrvold-Ruskey rank of permutation p
func MRRank(p []int) (r int) {
p = append([]int{}, p...)
inv := inverse(p)
for i := len(p) - 1; i > 0; i-- {
s := p[i]
p[inv[i]] = s
inv[s] = inv[i]
}
for i := 1; i < len(p); i++ {
r = r*(i+1) + p[i]
}
return
}
// returns inverse of a permutation.
func inverse(p []int) []int {
r := make([]int, len(p))
for i, x := range p {
r[x] = i
}
return r
}
// returns n!
func fact(n int) (f int) {
for f = n; n > 2; {
n--
f *= n
}
return
}
func main() {
n := 3
fmt.Println("permutations of", n, "items")
f := fact(n)
for i := 0; i < f; i++ {
p := MRPerm(i, n)
fmt.Println(i, p, MRRank(p))
}
n = 12
fmt.Println("permutations of", n, "items")
f = fact(n)
m := map[int]bool{}
for len(m) < 4 {
r := rand.Intn(f)
if m[r] {
continue
}
m[r] = true
fmt.Println(r, MRPerm(r, n))
}
} |
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
| #FreeBASIC | FreeBASIC | #define NPP 50
Function isPrime(Byval n As Ulongint) As Boolean
If n < 2 Then Return false
If n = 2 Then Return true
If n Mod 2 = 0 Then Return false
For i As Uinteger = 3 To Int(Sqr(n))+1 Step 2
If n Mod i = 0 Then Return false
Next i
Return true
End Function
Function is_23(Byval n As Uinteger) As Boolean
While n Mod 2 = 0
n /= 2
Wend
While n Mod 3 = 0
n /= 3
Wend
Return Iif(n=1, true, false)
End Function
Function isPierpont(n As Uinteger) As Uinteger
If Not isPrime(n) Then Return 0 'not prime
Dim As Uinteger p1 = is_23(n+1), p2 = is_23(n-1)
If p1 And p2 Then Return 3 'pierpont prime of both kinds
If p1 Then Return 1 'pierpont prime of the 1st kind
If p2 Then Return 2 'pierpont prime of the 2nd kind
Return 0 'prime, but not pierpont
End Function
Dim As Uinteger pier(1 To 2, 1 To NPP), np(1 To 2) = {0, 0}
Dim As Uinteger x = 1, j
While np(1) <= NPP Or np(2) <= NPP
x += 1
j = isPierpont(x)
If j > 0 Then
If j Mod 2 = 1 Then
np(1) += 1
If np(1) <= NPP Then pier(1, np(1)) = x
End If
If j > 1 Then
np(2) += 1
If np(2) <= NPP Then pier(2, np(2)) = x
End If
End If
Wend
Print "First 50 Pierpoint primes of the first kind:"
For j = 1 To NPP
Print Using " ########"; pier(2, j);
If j Mod 10 = 0 Then Print
Next j
Print !"\nFirst 50 Pierpoint primes of the secod kind:"
For j = 1 To NPP
Print Using " ########"; pier(1, j);
If j Mod 10 = 0 Then Print
Next j
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Burlesque | Burlesque |
blsq ) "ABCDEFG"123456 0 6rn-]!!
'G
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
int i;
time_t t;
srand((unsigned)time(&t));
for(i=0;i<30;i++){
printf("%c\n", array[rand()%10]);
}
return 0;
}
|
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
| #Sidef | Sidef | func is_prime(a) {
given (a) {
when (2) { true }
case (a <= 1 || a.is_even) { false }
default { 3 .. a.isqrt -> any { .divides(a) } -> not }
}
} |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Ruby | Ruby |
def player1(sum,sm)
for i in 1..100
puts "player1 rolled"
a=gets.chomp().to_i
if (a>1 && a<7)
sum+=a
if sum>=100
puts "player1 wins"
break
end
else
goto player2(sum,sm)
end
i+=1
end
end
def player2(sum,sm)
for j in 1..100
puts "player2 rolled"
b=gets.chomp().to_i
if(b>1 && b<7)
sm+=b
if sm>=100
puts "player2 wins"
break
end
else
player1(sum,sm)
end
j+=1
end
end
i=0
j=0
sum=0
sm=0
player1(sum,sm)
return |
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
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%=== The Main Thing... ===%
set "inp=Rosetta Code phrase reversal"
call :reverse_string "!inp!" rev1
call :reverse_order "!inp!" rev2
call :reverse_words "!inp!" rev3
cls
echo.Original: !inp!
echo.Reversed: !rev1!
echo.Reversed Order: !rev2!
echo.Reversed Words: !rev3!
pause>nul
exit /b 0
%=== /The Main Thing... ===%
%=== Reverse the Order Function ===%
:reverse_order
set var1=%2
set %var1%=&set word=&set str1=%1
:process1
for /f "tokens=1,*" %%A in (%str1%) do (set str1=%%B&set word=%%A)
set %var1%=!word! !%var1%!&set str1="!str1!"
if not !str1!=="" goto process1
goto :EOF
%=== /Reverse the Order Function ===%
%=== Reverse the Whole String Function ===%
:reverse_string
set var2=%2
set %var2%=&set cnt=0&set str2=%~1
:process2
set char=!str2:~%cnt%,1!&set %var2%=!char!!%var2%!
if not "!char!"=="" set /a cnt+=1&goto process2
goto :EOF
%=== /Reverse the Whole String Function ===%
%=== Reverse each Words Function ===%
:reverse_words
set var3=%2
set %var3%=&set word=&set str3=%1
:process3
for /f "tokens=1,*" %%A in (%str3%) do (set str3=%%B&set word=%%A)
call :reverse_string "%word%" revs
set %var3%=!%var3%! !revs!&set str3="!str3!"
if not !str3!=="" goto process3
set %var3%=!%var3%:~1,1000000!
goto :EOF
%=== /Reverse each Words Function ===% |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card 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
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
call:newdeck deck
echo new deck:
echo.
call:showcards deck
echo.
echo shuffling:
echo.
call:shuffle deck
call:showcards deck
echo.
echo dealing 5 cards to 4 players
call:deal deck 5 hand1 hand2 hand3 hand4
echo.
echo player 1 & call:showcards hand1
echo.
echo player 2 & call:showcards hand2
echo.
echo player 3 & call:showcards hand3
echo.
echo player 4 & call:showcards hand4
echo.
call:count %deck% cnt
echo %cnt% cards remaining in the deck
echo.
call:showcards deck
echo.
exit /b
:getcard deck hand :: deals 1 card to a player
set "loc1=!%~1!"
set "%~2=!%~2!!loc1:~0,3!"
set "%~1=!loc1:~3!"
exit /b
:deal deck n player1 player2...up to 7
set "loc=!%~1!"
set "cards=%~2"
set players=%3 %4 %5 %6 %7 %8 %9
for /L %%j in (1,1,!cards!) do (
for %%k in (!players!) do call:getcard loc %%k)
set "%~1=!loc!"
exit /b
:newdeck [deck] ::creates a deck of cards
:: in the parentheses below there are ascii chars 3,4,5 and 6 representing the suits
for %%i in ( ♠ ♦ ♥ ♣ ) do (
for %%j in (20 31 42 53 64 75 86 97 T8 J9 QA KB AC) do set loc=!loc!%%i%%j
)
set "%~1=!loc!"
exit /b
:showcards [deck] :: prints a deck or a hand
set "loc=!%~1!"
for /L %%j in (0,39,117) do (
set s=
for /L %%i in (0,3,36) do (
set /a n=%%i+%%j
call set s=%%s%% %%loc:~!n!,2%%
)
if "!s: =!" neq "" echo(!s!
set /a n+=1
if "%loc:~!n!,!%" equ "" goto endloop
)
:endloop
exit /b
:count deck count
set "loc1=%1"
set /a cnt1=0
for %%i in (96 48 24 12 6 3 ) do if "!loc1:~%%i,1!" neq "" set /a cnt1+=%%i & set loc1=!loc1:~%%i!
set /a cnt1=cnt1/3+1
set "%~2=!cnt1!"
exit /b
:shuffle (deck) :: shuffles a deck
set "loc=!%~1!"
call:count %loc%, cnt
set /a cnt-=1
for /L %%i in (%cnt%,-1,0) do (
SET /A "from=%%i,to=(!RANDOM!*(%%i-1)/32768)"
call:swap loc from to
)
set "%~1=!loc!"
exit /b
:swap deck from to :: swaps two cards
set "arr=!%~1!"
set /a "from=!%~2!*3,to=!%~3!*3"
set temp1=!arr:~%from%,3!
set temp2=!arr:~%to%,3!
set arr=!arr:%temp1%=@@@!
set arr=!arr:%temp2%=%temp1%!
set arr=!arr:@@@=%temp2%!
set "%~1=!arr!"
exit /b |
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
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
INT base := 10;
MODE YIELDINT = PROC(INT)VOID;
PROC gen pi digits = (INT decimal places, YIELDINT yield)VOID:
BEGIN
INT nine = base - 1;
INT nines := 0, predigit := 0; # First predigit is a 0 #
[decimal places*10 OVER 3]#LONG# INT digits; # We need 3 times the digits to calculate #
FOR place FROM LWB digits TO UPB digits DO digits[place] := 2 OD; # Start with 2s #
FOR place TO decimal places + 1 DO
INT digit := 0;
FOR i FROM UPB digits BY -1 TO LWB digits DO # Work backwards #
INT x := #SHORTEN#(base*digits[i] + #LENG# digit*i);
digits[i] := x MOD (2*i-1);
digit := x OVER (2*i-1)
OD;
digits[LWB digits] := digit MOD base; digit OVERAB base;
nines :=
IF digit = nine THEN
nines + 1
ELSE
IF digit = base THEN
yield(predigit+1); predigit := 0 ;
FOR repeats TO nines DO yield(0) OD # zeros #
ELSE
IF place NE 1 THEN yield(predigit) FI; predigit := digit;
FOR repeats TO nines DO yield(nine) OD
FI;
0
FI
OD;
yield(predigit)
END;
main:(
INT feynman point = 762; # feynman point + 4 is a good test case #
# the 33rd decimal place is a shorter tricky test case #
INT test decimal places = UPB "3.1415926.......................502"-2;
INT width = ENTIER log(base*(1+small real*10));
# iterate throught the digits as they are being found #
# FOR INT digit IN # gen pi digits(test decimal places#) DO ( #,
## (INT digit)VOID: (
printf(($n(width)d$,digit))
)
# OD #);
print(new line)
) |
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
| #Delphi | Delphi | program Pig_the_dice_game;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Console;
var
playerScores: TArray<Integer> = [0, 0];
turn: Integer = 0;
currentScore: Integer = 0;
player: Integer;
begin
Randomize;
turn := Random(length(playerScores));
writeln('Player ', turn, ' start:');
while True do
begin
Console.Clear;
for var i := 0 to High(playerScores) do
begin
Console.ForegroundColor := TConsoleColor(i mod 15 + 1);
Writeln(format('Player %2d has: %3d points', [i, playerScores[i]]));
end;
Writeln(#10);
player := turn mod length(playerScores);
Console.ForegroundColor := TConsoleColor(player mod 15 + 1);
writeln(format('Player %d [%d, %d], (H)old, (R)oll or (Q)uit: ', [player,
playerScores[player], currentScore]));
var answer := Console.ReadKey.KeyChar;
case UpCase(answer) of
'H':
begin
playerScores[player] := playerScores[player] + currentScore;
writeln(format(' Player %d now has a score of %d.'#10, [player,
playerScores[player]]));
if playerScores[player] >= 100 then
begin
writeln(' Player ', player, ' wins!!!');
readln;
halt;
end;
currentScore := 0;
inc(turn);
end;
'R':
begin
var roll := Random(6) + 1;
if roll = 1 then
begin
writeln(' Rolled a 1. Bust!'#10);
currentScore := 0;
inc(turn);
writeln('Press any key to pass turn');
Console.ReadKey;
end
else
begin
writeln(' Rolled a ', roll, '.');
inc(currentScore, roll);
end;
end;
'Q':
halt;
else
writeln(' Please enter one of the given inputs.');
end;
end;
writeln(format('Player %d wins!!!', [(turn - 1) mod Length(playerScores)]));
Readln;
end. |
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.
| #AppleScript | AppleScript | on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
on isPernicious(n)
-- 8 bits at a time is statistically slightly more efficient than 1 bit at a time.
set popCount to (n mod 4 + 1) div 2 + (n mod 16 + 4) div 8
set n to n div 16
repeat until (n = 0)
set popCount to popCount + (n mod 4 + 1) div 2 + (n mod 16 + 4) div 8
set n to n div 16
end repeat
return isPrime(popCount)
end isPernicious
-- Task code:
on intToText(n)
set output to ""
repeat until (n < 100000000)
set output to text 2 thru 9 of ((100000000 + (n mod 100000000 as integer)) as text) & output
set n to n div 100000000
end repeat
set output to (n as integer as text) & output
return output
end intToText
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set output to lst as text
set AppleScript's text item delimiters to astid
return output
end join
on task()
set l1 to {}
set n to 0
set counter to 0
repeat until (counter = 25)
if (isPernicious(n)) then
set end of l1 to n
set counter to counter + 1
end if
set n to n + 1
end repeat
set l2 to {}
-- One solution to 8,888,877 and up being too large to be AppleScript repeat indices.
repeat with i from 88888877 to 88888888
set n to 8.0E+8 + i
if (isPernicious(n)) then set end of l2 to intToText(n)
end repeat
return join(l1, " ") & (linefeed & join(l2, " "))
end task
task() |
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
| #Haskell | Haskell | fact :: Int -> Int
fact n = product [1 .. n]
-- Always assume elements are unique.
rankPerm [] _ = []
rankPerm list n = c : rankPerm (a ++ b) r
where
(q, r) = n `divMod` fact (length list - 1)
(a, c:b) = splitAt q list
permRank [] = 0
permRank (x:xs) = length (filter (< x) xs) * fact (length xs) + permRank xs
main :: IO ()
main = mapM_ f [0 .. 23]
where
f n = print (n, p, permRank p)
where
p = rankPerm [0 .. 3] 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
| #J | J | A. 2 0 1 NB. return rank of permutation
4
4 A. i.3 NB. return permutation of rank 4
2 0 1
0 1 2 3 4 5 A. i. 3 NB. generate all 6 permutations for 3 items
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
A. 0 1 2 3 4 5 A. i. 3 NB. ranks of each permuation
0 1 2 3 4 5
]ranks=: 4 ? !12 NB. 4 random numbers sampled from integers 0 to 12!
315645285 249293994 432230943 23060830
ranks A. i.12 NB. 4 random samples of 12 items
7 10 11 8 4 0 2 3 9 5 6 1
6 2 8 11 10 0 5 9 7 1 3 4
10 9 1 2 0 3 8 6 7 5 11 4
0 7 4 6 11 5 10 3 9 8 1 2
(4 ?@$ !144x) A. i.144 NB. 4 random samples of 144 items
117 36 129 85 128 95 27 14 15 119 45 60 21 98 135 106 18 64 132 97 79 84 35 139 101 75 59 13 141 99 86 40 10 140 23 92 125 6 68 41 69 20 56 12 127 65 142 116 71 54 1 5 121 8 78 73 48 30 80 131 111 57 66 100 138 77 37 124 136...
111 65 136 58 92 46 4 83 20 54 21 10 72 110 56 28 13 18 73 133 105 117 63 126 114 43 5 80 45 88 86 108 11 29 0 129 71 141 59 53 113 137 2 102 95 15 35 74 107 61 134 36 32 19 106 100 55 69 76 142 64 49 9 30 47 123 12 97 42...
64 76 139 122 37 127 57 143 32 108 46 17 126 9 51 59 1 74 23 89 42 124 132 19 93 137 70 86 14 112 83 91 63 39 73 18 90 120 53 103 140 87 43 55 131 40 142 102 107 111 80 65 61 34 66 75 88 92 13 138 50 117 97 20 44 7 56 94 41...
139 87 98 118 125 65 35 112 10 43 85 66 58 131 36 30 50 11 136 130 71 100 79 142 40 69 101 84 143 33 95 26 18 94 13 68 8 0 47 70 129 48 107 64 93 16 83 39 29 81 6 105 78 92 104 60 15 55 4 14 7 91 86 12 31 46 20 133 53... |
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
| #Go | Go | package main
import (
"fmt"
big "github.com/ncw/gmp"
"sort"
)
var (
one = new(big.Int).SetUint64(1)
two = new(big.Int).SetUint64(2)
three = new(big.Int).SetUint64(3)
)
func pierpont(ulim, vlim int, first bool) []*big.Int {
p := new(big.Int)
p2 := new(big.Int).Set(one)
p3 := new(big.Int).Set(one)
var pp []*big.Int
for v := 0; v < vlim; v++ {
for u := 0; u < ulim; u++ {
p.Mul(p2, p3)
if first {
p.Add(p, one)
} else {
p.Sub(p, one)
}
if p.ProbablyPrime(10) {
q := new(big.Int)
q.Set(p)
pp = append(pp, q)
}
p2.Mul(p2, two)
}
p3.Mul(p3, three)
p2.Set(one)
}
sort.Slice(pp, func(i, j int) bool {
return pp[i].Cmp(pp[j]) < 0
})
return pp
}
func main() {
fmt.Println("First 50 Pierpont primes of the first kind:")
pp := pierpont(120, 80, true)
for i := 0; i < 50; i++ {
fmt.Printf("%8d ", pp[i])
if (i-9)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 50 Pierpont primes of the second kind:")
pp2 := pierpont(120, 80, false)
for i := 0; i < 50; i++ {
fmt.Printf("%8d ", pp2[i])
if (i-9)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\n250th Pierpont prime of the first kind:", pp[249])
fmt.Println("\n250th Pierpont prime of the second kind:", pp2[249])
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #C.23 | C# | using System;
using System.Collections.Generic;
class RandomElementPicker {
static void Main() {
var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
var rng = new Random();
var randomElement = list[rng.Next(list.Count)];
Console.WriteLine("I picked element {0}", randomElement);
}
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #C.2B.2B | C++ | #include <iostream>
#include <random>
#include <vector>
int main( ) {
std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
std::random_device seed ;
// generator
std::mt19937 engine( seed( ) ) ;
// number distribution
std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
std::cout << "random element picked : " << numbers[ choose( engine ) ]
<< " !\n" ;
return 0 ;
} |
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
| #Smalltalk | Smalltalk | | isPrime |
isPrime := [:n |
n even ifTrue: [ ^n=2 ]
ifFalse: [
3 to: n sqrt do: [:i |
(n \\ i = 0) ifTrue: [ ^false ]
].
^true
]
] |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Sidef | Sidef | var (games=100) = ARGV.map{.to_i}...
define DIE = 1..6;
define GOAL = 100;
class Player(score=0, ante=0, rolls=0, strategy={false}) {
method turn {
rolls = 0;
ante = 0;
loop {
rolls++;
given (var roll = DIE.rand) {
when (1) {
ante = 0;
break;
}
case (roll > 1) {
ante += roll;
}
}
((score + ante >= GOAL) || strategy) && break;
}
score += ante;
}
}
var players = [];
# default, go-for-broke, always roll again
players[0] = Player.new;
# try to roll 5 times but no more per turn
players[1] = Player.new( strategy: { players[1].rolls >= 5 } );
# try to accumulate at least 20 points per turn
players[2] = Player.new( strategy: { players[2].ante > 20 } );
# random but 90% chance of rolling again
players[3] = Player.new( strategy: { 1.rand < 0.1 } );
# random but more conservative as approaches goal
players[4] = Player.new( strategy: { 1.rand < ((GOAL - players[4].score) * 0.6 / GOAL) } );
var wins = [0]*players.len;
games.times {
var player = -1;
loop {
player++;
var p = players[player % players.len];
p.turn;
p.score >= GOAL && break;
}
wins[player % players.len]++;
players.map{.score}.join("\t").say;
players.each { |p| p.score = 0 };
}
say "\nSCORES: for #{games} games";
say wins.join("\t"); |
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
| #Bracmat | Bracmat | ( "rosetta code phrase reversal":?text
& rev$!text:?output1
& get$(!text,MEM):?words
& :?output2:?output3
& whl
' ( !words:%?word %?words
& !output2 rev$!word " ":?output2
& " " !word !output3:?output3
)
& str$(!output2 rev$!words):?output2
& str$(!words !output3):?output3
& out
$ ( str
$ ("0:\"" !text "\"\n1:\"" !output1 "\"\n2:\"" !output2 "\"\n3:\"" !output3 \"\n)
)
); |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, 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
| #C | C |
#include <stdio.h>
#include <string.h>
/* The functions used are destructive, so after each call the string needs
* to be copied over again. One could easily allocate new strings as
* required, but this way allows the caller to manage memory themselves */
char* reverse_section(char *s, size_t length)
{
if (length == 0) return s;
size_t i; char temp;
for (i = 0; i < length / 2 + 1; ++i)
temp = s[i], s[i] = s[length - i], s[length - i] = temp;
return s;
}
char* reverse_words_in_order(char *s, char delim)
{
if (!strlen(s)) return s;
size_t i, j;
for (i = 0; i < strlen(s) - 1; ++i) {
for (j = 0; s[i + j] != 0 && s[i + j] != delim; ++j)
;
reverse_section(s + i, j - 1);
s += j;
}
return s;
}
char* reverse_string(char *s)
{
return strlen(s) ? reverse_section(s, strlen(s) - 1) : s;
}
char* reverse_order_of_words(char *s, char delim)
{
reverse_string(s);
reverse_words_in_order(s, delim);
return s;
}
int main(void)
{
char str[] = "rosetta code phrase reversal";
size_t lenstr = sizeof(str) / sizeof(str[0]);
char scopy[lenstr];
char delim = ' ';
/* Original String */
printf("Original: \"%s\"\n", str);
/* Reversed string */
strncpy(scopy, str, lenstr);
reverse_string(scopy);
printf("Reversed: \"%s\"\n", scopy);
/* Reversed words in string */
strncpy(scopy, str, lenstr);
reverse_words_in_order(scopy, delim);
printf("Reversed words: \"%s\"\n", scopy);
/* Reversed order of words in string */
strncpy(scopy, str, lenstr);
reverse_order_of_words(scopy, delim);
printf("Reversed order: \"%s\"\n", scopy);
return 0;
}
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card 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
| #BBC_BASIC | BBC BASIC | DIM Deck{ncards%, card&(51)}, Suit$(3), Rank$(12)
Suit$() = "Clubs", "Diamonds", "Hearts", "Spades"
Rank$() = "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", \
\ "Eight", "Nine", "Ten", "Jack", "Queen", "King"
PRINT "Creating a new deck..."
PROCnewdeck(deck1{})
PRINT "Shuffling the deck..."
PROCshuffle(deck1{})
PRINT "The first few cards are:"
FOR card% = 1 TO 8
PRINT FNcardname(deck1.card&(card%))
NEXT
PRINT "Dealing three cards from the deck:"
FOR card% = 1 TO 3
PRINT FNcardname(FNdeal(deck1{}))
NEXT
PRINT "Number of cards remaining in the deck = " ; deck1.ncards%
END
REM Make a new deck:
DEF PROCnewdeck(RETURN deck{})
LOCAL N%
DIM deck{} = Deck{}
FOR N% = 0 TO 51
deck.card&(N%) = N%
deck.ncards% += 1
NEXT
ENDPROC
REM Shuffle a deck:
DEF PROCshuffle(deck{})
LOCAL N%
FOR N% = 52 TO 2 STEP -1
SWAP deck.card&(N%-1), deck.card&(RND(N%)-1)
NEXT
ENDPROC
REM Deal from the 'bottom' of the deck:
DEF FNdeal(deck{})
IF deck.ncards% = 0 THEN ERROR 100, "Deck is empty"
deck.ncards% -= 1
= deck.card&(deck.ncards%)
REM Return the name of a card:
DEF FNcardname(card&)
= Rank$(card& >> 2) + " of " + Suit$(card& AND 3) |
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
| #Arturo | Arturo | q: 1
r: 0
t: 1
k: 1
n: 3
l: 3
d: 0
dotWritten: false
while [true][
if? (n*t) > (4*q)+r-t [
d: d+1
prints n
unless dotWritten [
prints "."
dotWritten: true
d: d+1
]
if 0 = d%80 -> prints "\n"
nr: 10*(r - n*t)
n: ((10*(r + 3*q)) / t) - 10*n
q: q*10
r: nr
]
else [
nr: (r + 2*q) * l
nn: ((q*(2 + 7*k)) + r*l) / (t*l)
q: q*k
t: t*l
l: l+2
k: k+1
n: nn
r: nr
]
] |
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
| #Eiffel | Eiffel |
class
PLAYER
create
set_name
feature
set_name(n:STRING)
do
name := n.twin
set_points(0)
end
strategy(cur_points:INTEGER)
local
current_points, thrown:INTEGER
do
io.put_string ("You currently have " +points.out+". %NDo you want to save your points? Press y or n.%N")
io.read_line
if io.last_string.same_string ("y") then
set_points(cur_points)
else
io.put_string ("Then throw again.%N")
thrown:=throw_dice
if thrown= 1 then
io.put_string("You loose your points%N")
else
strategy(cur_points+thrown)
end
end
end
set_points (value:INTEGER)
require
value_not_neg: value >= 0
do
points := points + value
end
random: V_RANDOM
-- Random sequence.
once
create Result
end
throw_dice: INTEGER
do
random.forth
Result := random.bounded_item (1, 6)
end
name: STRING
points: INTEGER
end
|
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.
| #Arturo | Arturo | pernicious?: function [n][
prime? size filter split as.binary n 'x -> x="0"
]
i: 1
found: 0
while [found<25][
if pernicious? i [
prints i
prints " "
found: found + 1
]
i: i + 1
]
print ""
print select 888888877..888888888 => pernicious? |
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
| #Java | Java | import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i));
// Create 5 random samples
System.out.println("n = " + n);
for (int i = 0; i < 5; i++)
{
BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);
rank = rank.mod(factorial);
int[] permutation = getPermutation(n, rank);
System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
}
}
} |
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
| #Haskell | Haskell | import Control.Monad (guard)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime)
import Text.Printf (printf)
data PierPointKind = First | Second
merge :: Ord a => [a] -> [a] -> [a]
merge [] b = b
merge a@(x:xs) b@(y:ys) | x < y = x : merge xs b
| otherwise = y : merge a ys
nSmooth :: Integer -> [Integer]
nSmooth p = 1 : foldr u [] factors
where
factors = takeWhile (<=p) primes
primes = map unPrime [nextPrime 1..]
u n s = r
where
r = merge s (map (n*) (1:r))
pierpoints :: PierPointKind -> [Integer]
pierpoints k = do
n <- nSmooth 3
let x = case k of First -> succ n
Second -> pred n
guard (isPrime x) >> [x]
main :: IO ()
main = do
printf "\nFirst 50 Pierpont primes of the first kind:\n"
mapM_ (\row -> mapM_ (printf "%12s" . commas) row >> printf "\n") (rows $ pierpoints First)
printf "\nFirst 50 Pierpont primes of the second kind:\n"
mapM_ (\row -> mapM_ (printf "%12s" . commas) row >> printf "\n") (rows $ pierpoints Second)
printf "\n250th Pierpont prime of the first kind: %s\n" (commas $ pierpoints First !! 249)
printf "\n250th Pierpont prime of the second kind: %s\n\n" (commas $ pierpoints Second !! 249)
where
rows = chunksOf 10 . take 50
commas = reverse . intercalate "," . chunksOf 3 . reverse . show |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
shared void run() {
value random = DefaultRandom();
value element = random.nextElement([1, 2, 3, 4, 5, 6]);
print(element);
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Clojure | Clojure | (rand-nth coll) |
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
| #SNOBOL4 | SNOBOL4 | define('isprime(n)i,max') :(isprime_end)
isprime isprime = n
le(n,1) :s(freturn)
eq(n,2) :s(return)
eq(remdr(n,2),0) :s(freturn)
max = sqrt(n); i = 1
isp1 i = le(i + 2,max) i + 2 :f(return)
eq(remdr(n,i),0) :s(freturn)f(isp1)
isprime_end |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Tcl | Tcl | package require TclOO
oo::class create Player {
variable me
constructor {name} {
set me $name
}
method name {} {
return $me
}
method wantToRoll {safeScore roundScore} {}
method rolled {who what} {
if {$who ne [self]} {
#puts "[$who name] rolled a $what"
}
}
method turnend {who score} {
if {$who ne [self]} {
#puts "End of turn for [$who name] on $score"
}
}
method winner {who score} {
if {$who ne [self]} {
#puts "[$who name] is a winner, on $score"
}
}
}
oo::class create HumanPlayer {
variable me
superclass Player
method wantToRoll {safeScore roundScore} {
while 1 {
puts -nonewline "$me (on $safeScore+$roundScore) do you want to roll? (Y/n)"
flush stdout
if {[gets stdin line] < 0} {
# EOF detected
puts ""
exit
}
if {$line eq "" || $line eq "y" || $line eq "Y"} {
return 1
}
if {$line eq "n" || $line eq "N"} {
return 0
}
}
}
method stuck {score} {
puts "$me sticks with score $score"
}
method busted {score} {
puts "Busted! ($me still on score $score)"
}
method won {score} {
puts "$me has won! (Score: $score)"
}
}
proc rollDie {} {
expr {1+int(rand() * 6)}
}
proc rotateList {var} {
upvar 1 $var l
set l [list {*}[lrange $l 1 end] [lindex $l 0]]
}
proc broadcast {players message score} {
set p0 [lindex $players 0]
foreach p $players {
$p $message $p0 $score
}
}
proc pig {args} {
set players $args
set scores [lrepeat [llength $args] 0]
while 1 {
set player [lindex $players 0]
set safe [lindex $scores 0]
set s 0
while 1 {
if {$safe + $s >= 100} {
incr safe $s
$player won $safe
broadcast $players winner $safe
return $player
}
if {![$player wantToRoll $safe $s]} {
lset scores 0 [incr safe $s]
$player stuck $safe
break
}
set roll [rollDie]
broadcast $players rolled $roll
if {$roll == 1} {
$player busted $safe
break
}
incr s $roll
}
broadcast $players turnend $safe
rotateList players
rotateList scores
}
} |
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
| #C.23 | C# | using System;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//Reverse() is an extension method on IEnumerable<char>.
//The constructor takes a char[], so we have to call ToArray()
Func<string, string> reverse = s => new string(s.Reverse().ToArray());
string phrase = "rosetta code phrase reversal";
//Reverse the string
Console.WriteLine(reverse(phrase));
//Reverse each individual word in the string, maintaining original string order.
Console.WriteLine(string.Join(" ", phrase.Split(' ').Select(word => reverse(word))));
//Reverse the order of each word of the phrase, maintaining the order of characters in each word.
Console.WriteLine(string.Join(" ", phrase.Split(' ').Reverse()));
}
}
} |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
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
| #11l | 11l | F derangements(n)
[[Int]] r
V perm = Array(0 .< n)
L
I all(enumerate(perm).map((indx, p) -> indx != p))
r [+]= perm
I !perm.next_permutation()
L.break
R r
F subfact(n) -> Int64
R I n < 2 {1 - n} E (subfact(n - 1) + subfact(n - 2)) * (n - 1)
V n = 4
print(‘Derangements of ’Array(0 .< n))
L(d) derangements(n)
print(‘ ’d)
print("\nTable of n vs counted vs calculated derangements")
L(n) 10
print(‘#2 #<6 #.’.format(n, derangements(n).len, subfact(n)))
n = 20
print("\n!#. = #.".format(n, subfact(n))) |
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
| #11l | 11l | F s_permutations(seq)
V items = [[Int]()]
L(j) seq
[[Int]] new_items
L(item) items
I L.index % 2
new_items [+]= (0..item.len).map(i -> @item[0 .< i] [+] [@j] [+] @item[i..])
E
new_items [+]= (item.len..0).step(-1).map(i -> @item[0 .< i] [+] [@j] [+] @item[i..])
items = new_items
R enumerate(items).map((i, item) -> (item, I i % 2 {-1} E 1))
L(n) (3, 4)
print(‘Permutations and sign of #. items’.format(n))
L(perm, sgn) s_permutations(Array(0 .< n))
print(‘Perm: #. Sign: #2’.format(perm, sgn))
print() |
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.
| #11l | 11l | V data = [85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
F pick(at, remain, accu, treat)
I remain == 0
R I accu > treat {1} E 0
R pick(at - 1, remain - 1, accu + :data[at - 1], treat) +
(I at > remain {pick(at - 1, remain, accu, treat)} E 0)
V treat = 0
V total = 1.0
L(i) 0..8
treat += data[i]
L(i) (19..11).step(-1)
total *= i
L(i) (9..1).step(-1)
total /= i
V gt = pick(19, 9, 0, treat)
V le = Int(total - gt)
print(‘<= : #.6% #.’.format(100 * le / total, le))
print(‘ > : #.6% #.’.format(100 * gt / total, gt)) |
http://rosettacode.org/wiki/Peripheral_drift_illusion | Peripheral drift illusion | Task
Generate and display a Peripheral Drift Illusion
The image appears to be moving even though it is perfectly static.
Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host.
References
Codepen demo.
| #Action.21 | Action! | PROC DrawTile(INT x BYTE y,flip,c1,c2)
BYTE i
Color=1
FOR i=y+2 TO y+11
DO
Plot(x+1,i) DrawTo(x+5,i)
OD
Color=c1
IF flip THEN
Plot(x,y+12) DrawTo(x,y) DrawTo(x+6,y)
ELSE
Plot(x,y) DrawTo(x+6,y) DrawTo(x+6,y+12)
FI
Plot(x+1,y+1) DrawTo(x+5,y+1)
Color=c2
IF flip THEN
Plot(x,y+13) DrawTo(x+6,y+13) DrawTo(x+6,y+1)
ELSE
Plot(x,y+1) DrawTo(x,y+13) DrawTo(x+6,y+13)
FI
Plot(x+1,y+12) DrawTo(x+5,y+12)
RETURN
PROC Draw()
INT x,y,n
BYTE flip,c1,c2
FOR y=0 TO 8
DO
FOR x=0 TO 15
DO
n=(x-y)&15
IF (n RSH 2)&1 THEN
flip=1
ELSE
flip=0
FI
IF (n RSH 3)&1 THEN
c1=3 c2=2
ELSE
c1=2 c2=3
FI
DrawTile(x*10,y*20+6,flip,c1,c2)
OD
OD
RETURN
PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed
BYTE PALNTSC=$D014 ;To check if PAL or NTSC system is used
Graphics(15+16)
IF PALNTSC=15 THEN
SetColor(4,14,10) ;yellow for NTSC
SetColor(0,8,4) ;blue for NTSC
ELSE
SetColor(4,13,10) ;yellow for PAL
SetColor(0,7,4) ;blue for PAL
FI
SetColor(1,0,0)
SetColor(2,0,14)
Draw()
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Peripheral_drift_illusion | Peripheral drift illusion | Task
Generate and display a Peripheral Drift Illusion
The image appears to be moving even though it is perfectly static.
Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host.
References
Codepen demo.
| #Julia | Julia | using Gtk, Colors, Cairo
function CodepenApp()
# left-top, top-right, right-bottom, bottom-left
LT, TR, RB, BL = 1, 2, 3, 4
edges = [
[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],
[TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT],
[RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT],
[RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR],
[BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR],
[BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB],
[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],
[TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT]]
W, B = colorant"white", colorant"darkgray"
colors = [
[W, B, B, W],
[W, W, B, B],
[B, W, W, B],
[B, B, W, W]]
win = GtkWindow("Peripheral drift illusion", 230, 230) |> (can = GtkCanvas())
@guarded draw(can) do widget
ctx = Gtk.getgc(can)
function line(x1, y1, x2, y2, colr)
set_source(ctx, colr)
move_to(ctx, x1, y1)
line_to(ctx, x2, y2)
stroke(ctx)
end
set_source(ctx, colorant"yellow")
rectangle(ctx, 0, 0, 250, 250)
fill(ctx)
set_line_width(ctx, 2)
for x in 1:12
px = 18 + x * 14
for y in 1:12
py = 18 + y * 14
set_source(ctx, colorant"skyblue")
rectangle(ctx, px, py, 10, 10)
fill(ctx)
carray = colors[edges[y][x]]
line(px, py, px + 9, py, carray[1])
line(px + 9, py, px + 9, py + 9, carray[2])
line(px + 9, py + 9, px, py + 9, carray[3])
line(px, py + 9, px, py, carray[4])
end
end
end
showall(win)
draw(can)
condition = Condition()
endit(w) = notify(condition)
signal_connect(endit, win, :destroy)
showall(win)
wait(condition)
end
CodepenApp()
|
http://rosettacode.org/wiki/Peripheral_drift_illusion | Peripheral drift illusion | Task
Generate and display a Peripheral Drift Illusion
The image appears to be moving even though it is perfectly static.
Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host.
References
Codepen demo.
| #Nim | Nim | import gintro/[glib, gobject, gtk, gio, cairo]
const
Width = 600
Height = 460
type
Color = array[3, float]
Edge {.pure.} = enum LT, TR, RB, BL
const
Edges = [[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],
[TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT],
[RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT],
[RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR],
[BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR],
[BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB],
[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],
[TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT]]
Black: Color = [0.0, 0.0, 0.0]
Blue: Color = [0.2, 0.3, 1.0]
White: Color = [1.0, 1.0, 1.0]
Yellow: Color = [0.8, 0.8, 0.0]
Colors: array[Edge, array[4, Color]] = [[White, Black, Black, White],
[White, White, Black, Black],
[Black, White, White, Black],
[Black, Black, White, White]]
#---------------------------------------------------------------------------------------------------
proc draw(area: DrawingArea; context: Context) =
## Draw the pattern in the area.
func line(x1, y1, x2, y2: float; color: Color) =
context.setSource(color)
context.moveTo(x1, y1)
context.lineTo(x2, y2)
context.stroke
context.setSource(Yellow)
context.rectangle(0, 0, Width, Height)
context.fill()
for x in 0..11:
let px = float(86 + x * 36)
for y in 0..11:
let py = float(16 + y * 36)
context.setSource(Blue)
context.rectangle(px, py, 24, 24)
context.fill()
let carray = Colors[Edges[y][x]]
context.setLineWidth(2)
line(px, py, px + 23, py, carray[0])
line(px + 23, py, px + 23, py + 23, carray[1])
line(px + 23, py + 23, px, py + 23, carray[2])
line(px, py + 23, px, py, carray[3])
#---------------------------------------------------------------------------------------------------
proc onDraw(area: DrawingArea; context: Context; data: pointer): bool =
## Callback to draw/redraw the drawing area contents.
area.draw(context)
result = true
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
let window = app.newApplicationWindow()
window.setSizeRequest(Width, Height)
window.setTitle("Peripheral drift illusion")
# Create the drawing area.
let area = newDrawingArea()
window.add(area)
# Connect the "draw" event to the callback to draw the pattern.
discard area.connect("draw", ondraw, pointer(nil))
window.showAll()
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.Illusion")
discard app.connect("activate", activate)
discard app.run() |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int locale_ok = 0;
wchar_t s_suits[] = L"♠♥♦♣";
/* if your file can't contain unicode, use the next line instead */
//wchar_t s_suits[] = L"\x2660\x2665\x2666\x2663";
const char *s_suits_ascii[] = { "S", "H", "D", "C" };
const char *s_nums[] = { "WHAT",
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K",
"OVERFLOW"
};
typedef struct { int suit, number, _s; } card_t, *card;
typedef struct { int n; card_t cards[52]; } deck_t, *deck;
void show_card(card c)
{
if (locale_ok)
printf(" %lc%s", s_suits[c->suit], s_nums[c->number]);
else
printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]);
}
deck new_deck()
{
int i, j, k;
deck d = malloc(sizeof(deck_t));
d->n = 52;
for (i = k = 0; i < 4; i++)
for (j = 1; j <= 13; j++, k++) {
d->cards[k].suit = i;
d->cards[k].number = j;
}
return d;
}
void show_deck(deck d)
{
int i;
printf("%d cards:", d->n);
for (i = 0; i < d->n; i++)
show_card(d->cards + i);
printf("\n");
}
int cmp_card(const void *a, const void *b)
{
int x = ((card)a)->_s, y = ((card)b)->_s;
return x < y ? -1 : x > y;
}
card deal_card(deck d)
{
if (!d->n) return 0;
return d->cards + --d->n;
}
void shuffle_deck(deck d)
{
int i;
for (i = 0; i < d->n; i++)
d->cards[i]._s = rand();
qsort(d->cards, d->n, sizeof(card_t), cmp_card);
}
int main()
{
int i, j;
deck d = new_deck();
locale_ok = (0 != setlocale(LC_CTYPE, ""));
printf("New deck, "); show_deck(d);
printf("\nShuffle and deal to three players:\n");
shuffle_deck(d);
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++)
show_card(deal_card(d));
printf("\n");
}
printf("Left in deck "); show_deck(d);
/* freeing the data struct requires just free(), but it depends on the
* situation: there might be cards dealt out somewhere, which is not
* in the scope of this task.
*/
//free(d);
return 0;
} |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
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
| #AutoHotkey | AutoHotkey | #NoEnv
#SingleInstance, Force
SetBatchLines, -1
#Include mpl.ahk
dot:=".", i:=0
, MP_SET(q, "1")
, MP_SET(r, "0")
, MP_SET(t, "1")
, MP_SET(k, "1")
, MP_SET(n, "3")
, MP_SET(l, "3")
, MP_SET(ONE, "1")
, MP_SET(TWO, "2")
, MP_SET(THREE, "3")
, MP_SET(FOUR, "4")
, MP_SET(SEVEN, "7")
, MP_SET(TEN, "10")
Loop
{
MP_MUL(q4, q, FOUR)
, MP_ADD(q4r, q4, r)
, MP_SUB(q4rt, q4r, t)
, MP_MUL(tn, t, n)
If (MP_CMP(q4rt,tn) = -1)
{
s := MP_DEC(n) . dot
OutputDebug %s%
dot := ""
, i++
, MP_MUL(tn, t, n)
, MP_SUB(rtn, r, tn)
, MP_MUL(nr, rtn, TEN)
, MP_MUL(q3, q, THREE)
, MP_ADD(q3r, q3, r)
, MP_DIV(q3rt, remainder, q3r, t)
, MP_SUB(q3rtn, q3rt, n)
, MP_MUL(n, q3rtn, TEN)
, MP_MUL(tmp, q, TEN)
, MP_CPY(q, tmp)
, MP_CPY(r, nr)
}
Else
{
MP_MUL(q2, q, TWO)
, MP_ADD(q2r, q2, r)
, MP_MUL(nr, q2r, l)
, MP_MUL(k7, k, SEVEN)
, MP_ADD(k72, k7, TWO)
, MP_MUL(qk, q, k72)
, MP_MUL(rl, r, l)
, MP_ADD(qkrl, qk, rl)
, MP_MUL(tl, t, l)
, MP_DIV(nn, remainder, qkrl, tl)
, MP_MUL(tmp, q, k)
, MP_CPY(q, tmp)
, MP_MUL(tmp, t, l)
, MP_CPY(t, tmp)
, MP_ADD(tmp, l, TWO)
, MP_CPY(l, tmp)
, MP_ADD(tmp, k, ONE)
, MP_CPY(k, tmp)
, MP_CPY(n, nn)
, MP_CPY(r, nr)
}
} |
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
| #Erlang | Erlang |
-module( pig_dice ).
-export( [game/1, goal/0, hold/2, player_name/1, players_totals/1, quit/2, roll/2, score/1, task/0] ).
-record( player, {name, score=0, total=0} ).
game( [_Player | _T]=Players ) ->
My_pid = erlang:self(),
erlang:spawn_link( fun() -> random:seed(os:timestamp()), game_loop( [#player{name=X} || X <- Players], 100, My_pid ) end ).
goal() -> 100.
hold( Player, Game ) -> Game ! {next_player, Player}.
players_totals( Game ) -> ask( Game, players_totals ).
player_name( Game ) -> ask( Game, name ).
quit( Player, Game ) -> Game ! {quit, Player}.
roll( Player, Game ) -> Game ! {roll, Player}.
score( Game ) -> ask( Game, score ).
task() ->
Game = game( ["Player1", "Player2"] ),
Play = erlang:spawn( fun() -> play_loop( Game ) end ),
receive
{pig, Result, Game} ->
erlang:exit( Play, kill ),
task_display( Result ),
Result
end.
ask( Game, Question ) ->
Game ! {Question, erlang:self()},
receive
{Question, Answer, Game} -> Answer
end.
game_loop( [], _Goal, Report_pid ) -> Report_pid ! {pig, game_over_all_quite. erlang:self()};
game_loop( [#player{name=Name}=Player | T]=Players, Goal, Report_pid ) ->
receive
{name, Pid} ->
Pid ! {name, Player#player.name, erlang:self()},
game_loop( Players, Goal, Report_pid );
{next_player, Name} ->
New_players = game_loop_next_player( Player#player.total + Player#player.score, Players, Goal, Report_pid ),
game_loop( New_players, Goal, Report_pid );
{players_totals, Pid} ->
Pid ! {players_totals, [{X#player.name, X#player.total} || X <- Players], erlang:self()},
game_loop( Players, Goal, Report_pid );
{quit, Name} -> game_loop( T, Goal, Report_pid );
{roll, Name} ->
New_players = game_loop_roll( random:uniform(6), Players ),
game_loop( New_players, Goal, Report_pid );
{score, Pid} ->
Pid ! {score, Player#player.score, erlang:self()},
game_loop( Players, Goal, Report_pid )
end.
game_loop_next_player( Total, [Player | T], Goal, Report_pid ) when Total >= Goal ->
Report_pid ! {pig, [{X#player.name, X#player.total} || X <- [Player | T]]. erlang:self()},
[];
game_loop_next_player( Total, [Player | T], _Goal, _Report_pid ) ->
T ++ [Player#player{score=0, total=Total}].
game_loop_roll( 1, [Player | T] ) -> T ++ [Player#player{score=0}];
game_loop_roll( Score, [#player{score=Old_score}=Player | T] ) -> [Player#player{score=Old_score + Score} | T].
play_loop( Game ) ->
Name = player_name( Game ),
io:fwrite( "Currently ~p.~n", [players_totals(Game)] ),
io:fwrite( "Name ~p.~n", [Name] ),
roll( Name, Game ),
Score = score( Game ),
io:fwrite( "Rolled, score this round ~p.~n", [Score] ),
play_loop_next( Score, Name, Game ),
play_loop( Game ).
play_loop_command( {ok, ["y" ++ _T]}, _Name, _Game ) -> ok;
play_loop_command( {ok, ["n" ++ _T]}, Name, Game ) -> hold( Name, Game );
play_loop_command( {ok, ["q" ++ _T]}, Name, Game ) -> quit( Name, Game );
play_loop_command( {ok, _T}, Name, Game ) -> play_loop_command( io:fread("Roll again (y/n/q): ", "~s"), Name, Game ).
play_loop_next( 0, _Name, _Game ) -> io:fwrite( "~nScore 0, next player.~n" );
play_loop_next( _Score, Name, Game ) -> play_loop_command( io:fread("Roll again (y/n/q): ", "~s"), Name, Game ).
task_display( Results ) when is_list(Results) ->
[{Name, Total} | Rest] = lists:reverse( lists:keysort(2, Results) ),
io:fwrite( "Winner is ~p with total of ~p~n", [Name, Total] ),
io:fwrite( "Then follows: " ),
[io:fwrite("~p with ~p~n", [N, T]) || {N, T} <- Rest];
task_display( Result ) -> io:fwrite( "Result: ~p~n", [Result] ).
|
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.
| #AutoHotkey | AutoHotkey | c := 0
while c < 25
if IsPern(A_Index)
Out1 .= A_Index " ", c++
Loop, 12
if IsPern(n := 888888876 + A_Index)
Out2 .= n " "
MsgBox, % Out1 "`n" Out2
IsPern(x) { ;https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
static p := {2:1, 3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1, 41:1, 43:1, 47:1, 53:1, 59:1, 61:1}
x -= (x >> 1) & 0x5555555555555555
, x := (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
, x := (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
return p[(x * 0x0101010101010101) >> 56]
} |
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
| #jq | jq | # Assuming sufficiently-precise integer arithmetic,
# if the input and $j are integers, then the result will be a pair of integers,
# except that if $j is 0, then an error condition is raised.
def divmod($j):
. as $i
| ($i % $j) as $mod
| [($i - $mod) / $j, $mod] ;
# Input may be an object or an array
def swap($i; $j):
.[$i] as $t
| .[$i] = .[$j]
| .[$j] = $t;
def factorial:
. as $n
| reduce range(2; $n) as $i ($n; . * $i);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; |
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
| #Julia | Julia | using Printf
nobjs = 4
a = collect(1:nobjs)
println("All permutations of ", nobjs, " objects:")
for i in 1:factorial(nobjs)
p = nthperm(a, i)
prank = nthperm(p)
print(@sprintf("%5d => ", i))
println(p, " (", prank, ")")
end
nobjs = 12
nsamp = 4
ptaken = Int[]
println()
println(nsamp, " random permutations of ", nobjs, " objects:")
for i in 1:nsamp
p = randperm(nobjs)
prank = nthperm(p)
while prank in ptaken
p = randperm(nobjs)
prank = nthperm(p)
end
push!(ptaken, prank)
println(" ", p, " (", prank, ")")
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
| #J | J | 5 10$(#~ 1 p:])1+/:~,*//2 3x^/i.20
2 3 5 7 13 17 19 37 73 97
109 163 193 257 433 487 577 769 1153 1297
1459 2593 2917 3457 3889 10369 12289 17497 18433 39367
52489 65537 139969 147457 209953 331777 472393 629857 746497 786433
839809 995329 1179649 1492993 1769473 1990657 2654209 5038849 5308417 8503057
5 10$(#~ 1 p:])_1+/:~,*//2 3x^/i.20
2 3 5 7 11 17 23 31 47 53
71 107 127 191 383 431 647 863 971 1151
2591 4373 6143 6911 8191 8747 13121 15551 23327 27647
62207 73727 131071 139967 165887 294911 314927 442367 472391 497663
524287 786431 995327 1062881 2519423 10616831 17915903 25509167 30233087 57395627 |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #CLU | CLU | random_element = proc [T: type] (a: array[T]) returns (T)
return(a[array[T]$low(a) + random$next(array[T]$size(a))])
end random_element
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
arr: array[string] := array[string]$["foo", "bar", "baz", "qux"]
for i: int in int$from_to(1,5) do
stream$putl(po, random_element[string](arr))
end
end start_up |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. random-element.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 nums-area VALUE "123456789".
03 nums PIC 9 OCCURS 9 TIMES.
01 random-idx PIC 9 COMP.
PROCEDURE DIVISION.
COMPUTE random-idx = FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:7)) * 9 + 1
DISPLAY nums (random-idx)
.
END PROGRAM random-element. |
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
| #SQL | SQL | declare @number int
set @number = 514229 -- number to check
;with cte(number) as
(
select 2
union all
select number+1
from cte
where number+1 < @number
)
select
cast(@number as varchar(100)) +
case
when exists
(
select *
from
(
select number, @number % number modNumber
from cte
) tmp
where tmp.modNumber = 0
)
then ' is composite'
else
' is prime'
end primalityTest
option (maxrecursion 0) |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
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 one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Wren | Wren | import "random" for Random
import "os" for Process
var args = Process.arguments
var games = (args.count == 0) ? 100 : Num.fromString(args[0])
var Rand = Random.new()
var Die = 1..6
var Goal = 100
class Player {
construct new(strategy) {
_score = 0
_ante = 0
_rolls = 0
_strategy = strategy
}
score { _score }
rolls { _rolls }
ante { _ante }
score=(s) { _score = s }
turn() {
_rolls = 0
_ante = 0
while (true) {
_rolls = _rolls + 1
var roll = Rand.int(Die.from, Die.to + 1)
if (roll == 1) {
_ante = 0
break
}
_ante = _ante + roll
if (_score + _ante >= Goal || _strategy.call()) break
}
_score = _score + _ante
}
}
var numPlayers = 5
var players = List.filled(numPlayers, null)
// default, go-for-broke, always roll again
players[0] = Player.new { false }
// try to roll 5 times but no more per turn
players[1] = Player.new { players[1].rolls >= 5 }
// try to accumulate at least 20 points per turn
players[2] = Player.new { players[2].ante > 20 }
// random but 90% chance of rolling again
players[3] = Player.new { Rand.float() < 0.1 }
// random but more conservative as approaches goal
players[4] = Player.new { Rand.float() < (Goal - players[4].score) * 0.6 / Goal }
var wins = List.filled(numPlayers, 0)
for (i in 0...games) {
var player = -1
while (true) {
player = player + 1
var p = players[player % numPlayers]
p.turn()
if (p.score >= Goal) break
}
wins[player % numPlayers] = wins[player % numPlayers] + 1
System.print(players.map { |p| p.score }.join("\t"))
players.each { |p| p.score = 0 }
}
System.print("\nSCORES: for %(games) games")
System.print(wins.join("\t")) |
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
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
#include <sstream>
int main() {
std::string s = "rosetta code phrase reversal";
std::cout << "Input : " << s << '\n'
<< "Input reversed : " << std::string(s.rbegin(), s.rend()) << '\n' ;
std::istringstream is(s);
std::vector<std::string> words(std::istream_iterator<std::string>(is), {});
std::cout << "Each word reversed : " ;
for(auto w : words)
std::cout << std::string(w.rbegin(), w.rend()) << ' ';
std::cout << '\n'
<< "Original word order reversed : " ;
reverse_copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, " "));
std::cout << '\n' ;
} |
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
| #360_Assembly | 360 Assembly | * Permutations/Derangements 01/04/2017
DERANGE CSECT
USING DERANGE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
XPRNT PG1,L'PG1 print title
LA R1,4 4
LA R2,1 1 : combinations print
BAL R14,DERGEN call dergen
STH R0,COUNT count=dergen(4,1)
XPRNT PG2,L'PG2 print table headings
XPRNT PG3,L'PG3 print hyphens
SR R4,R4
STH R4,II ii=0
DO WHILE=(CH,R4,LE,=H'9') do ii=0 to 9
MVC PG,=CL80' ' clear buffer
XDECO R4,PG edit ii
LR R1,R4 ii
LA R2,0 0 : no combination print
BAL R14,DERGEN dergen(ii,0)
XDECO R0,PG+12 edit
LH R1,II ii
BAL R14,SUBFACT subfact(ii)
XDECO R0,PG+24 edit
XPRNT PG,L'PG print
LH R4,II ii
LA R4,1(R4) i+1
STH R4,II i=i+1
ENDDO , enddo i
LA R0,12 12
STH R0,II ii=12
MVC PG,=CL16'!xx=' init buffer
XDECO R0,XDEC edit ii
MVC PG+1(2),XDEC+10 output
LH R1,II ii
BAL R14,SUBFACT subfact(ii)
XDECO R0,PG+4 edit subfact(ii)
XPRNT PG,16 print
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
*------- ---- -------------------------------------------
DERGEN EQU * dergen(n,fprt)
ST R14,SAVEDG
ST R1,N n
ST R2,FPRT fprt
IF LTR,R1,Z,R1 THEN if n=0 then
LA R0,1 1
B RETDG return(1)
ENDIF , endif
MVC C,=F'0' c=0
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to 2
LR R1,R6 i
SLA R1,1
STH R6,A-2(R1) a(i)=i
STH R6,AO-2(R1) ao(i)=i
LA R6,1(R6) i++
ENDDO , enddo i
L R1,N n
BAL R14,FACT
ST R0,FACTNM1 fact(n)-1
SR R6,R6 i=0
DO WHILE=(C,R6,LE,FACTNM1) do i=0 to fact(n)-1
L R1,N n
BAL R14,NEXTPER call nextper(n)
MVI D,X'01' d=true
LA R7,1
DO WHILE=(C,R7,LE,N) do j=1 to n
LR R1,R7 j
SLA R1,1
LH R2,A-2(R1) a(j)
LH R3,AO-2(R1) ao(j)
IF CR,R2,EQ,R3 THEN if a(j)=ao(j) then
MVI D,X'00' d=false
ENDIF , endif
LA R7,1(R7) j++
ENDDO , enddo j
IF CLI,D,EQ,X'01' THEN if d then
L R2,C c
LA R2,1(R2) c+1
ST R2,C c=c+1
IF CLI,FPRT+3,EQ,X'01' THEN if fprt=1 then
MVC PG,=CL80' ' clear buffer
LA R10,PG pgi=0
LA R7,1 j=1
DO WHILE=(C,R7,LE,N) do j=1 to n
LR R1,R7 j
SLA R1,1
LH R2,A-2(R1) a(j)
XDECO R2,XDEC edit
MVC 0(1,R10),XDEC+11 output
LA R10,2(R10) pgi=pgi+2
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print
ENDIF , endif
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
L R0,C c
B RETDG return(c)
RETDG L R14,SAVEDG
BR R14
SAVEDG DS A
*------- ---- -------------------------------------------
NEXTPER EQU * nextper(nk)
ST R14,SAVENP
ST R1,NK nk
BCTR R1,0 nk-1
ST R1,NELEM nelem=nk-1
IF C,R1,LT,=F'1' THEN if nelem<1 then
LA R0,0 return(0)
B RETNP
ENDIF , endif
L R8,NELEM nelem
BCTR R8,0 pos=nelem-1
LOOPW1 EQU * while a(pos+1)>=a(pos+2)
LR R1,R8 pos
SLA R1,1
LH R2,A(R1) a(pos+1)
CH R2,A+2(R1) if a(pos+1)<a(pos+2)
BL ELOOPW1 then exit while
BCTR R8,0 pos=pos-1
IF LTR,R8,M,R8 THEN if pos<0 then
LA R1,0 0
L R2,NELEM nelem
BAL R14,PERMREV call permrev(0,nelem)
LA R0,0 return(0)
B RETNP
ENDIF , endif
B LOOPW1 endwhile
ELOOPW1 L R9,NELEM last=nelem
LOOPW2 EQU * do while a(last+1)<=a(pos+1)
LR R1,R9 last
SLA R1,1
LH R2,A(R1) a(last+1)
LR R1,R8 pos
SLA R1,1
CH R2,A(R1) if a(last+1)>a(pos+1)
BH ELOOPW2 then exit while
BCTR R9,0 last=last-1
B LOOPW2 endwhile
ELOOPW2 LR R1,R8 pos
SLA R1,1 *2
LA R2,A(R1) @a(pos+1)
LR R1,R9 last
SLA R1,1
LA R3,A(R1) @a(last+1)
LH R0,0(R2) w=a(pos+1)
MVC 0(2,R2),0(R3) a(pos+1)=a(last+1)
STH R0,0(R3) a(last+1)=w
LA R1,1(R8) pos+1
L R2,NELEM nelem
BAL R14,PERMREV call permrev(pos+1,nelem)
RETNP L R14,SAVENP
BR R14
SAVENP DS A
*------- ---- -------------------------------------------
PERMREV EQU * permrev(firstix,lastix)
LR R4,R1 xfirst
LR R5,R2 xlast
DO WHILE=(CR,R4,LT,R5) do while(xfirst<xlast)
LR R1,R4 xfirst
SLA R1,1 *2
LA R2,A(R1) @a(xfirst+1)
LR R1,R5 xlast
SLA R1,1 *2
LA R3,A(R1) @a(xlast+1)
LH R0,0(R2) w=a(xfirst+1)
MVC 0(2,R2),0(R3) a(xfirst+1)=a(xlast+1)
STH R0,0(R3) a(xlast+1)=w
LA R4,1(R4) xfirst=xfirst+1
BCTR R5,0 xlast=xlast-1
ENDDO , enddo
BR R14
*------- ---- ----------------------------------------
FACT EQU * fact(n)
IF C,R1,LE,=F'1' THEN if n<=1 then
LA R0,1 return(1)
ELSE , else
LA R5,1 f=1
LA R2,1 i=1
DO WHILE=(CR,R2,LE,R1) do i=1 to n
MR R4,R2 f*i
LA R2,1(R2) i++
ENDDO , enddo
LR R0,R5 return(f)
ENDIF , endif
BR R14
*------- ---- -------------------------------------------
SUBFACT EQU * subfact(n)
ST R1,NY n
IF LTR,R1,Z,R1 THEN if n=0 then
LA R0,1 return(1)
ELSE , else
LA R4,1 1
ST R4,TT tt(0)=1
ST R4,IY i=1
DO WHILE=(C,R4,LE,NY) do i=1 to n
L R4,IY i
SRDA R4,32
D R4,=F'2' i/2
IF LTR,R4,Z,R4 THEN if i//2=0 then
LA R0,1 nn=1
ELSE , else
L R0,=F'-1' nn=-1
ENDIF , endif
L R1,IY i
SLA R1,2
L R3,TT-4(R1) tt(i-1)
M R2,IY *i
AR R3,R0 +nn
L R1,IY i
SLA R1,2
ST R3,TT(R1) tt(i)=i*tt(i-1)+nn
L R4,IY i
LA R4,1(R4) i++
ST R4,IY i
ENDDO , enddo
L R1,NY n
SLA R1,2
L R0,TT(R1) return(tt(n))
ENDIF , endif
BR R14
* ---- -------------------------------------------
A DS 12H A work
AO DS 12H A origin
II DS H
COUNT DS H
N DS F
FPRT DS F flag for printing
C DS F
D DS X boolean : a(i) different ao(i)
FACTNM1 DS F fact(n)-1
NK DS F n in nextper
NELEM DS F n elements in nextper
NY DS F n in subfact
IY DS F i in subfact
TT DS 13F tt(0:12)
PG1 DC CL44'derangements for the numbers : 1 2 3 4 are :'
PG2 DC CL38' table of n counted calculated :'
PG3 DC CL36' ----------- ----------- -----------'
XDEC DS CL12 temp for xdeco
PG DC CL80' ' buffer
YREGS
END DERANGE |
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.