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/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Nim | Nim | import math
import imageman
const
Width = 400
Height = 400
var img = initImage[ColorRGBF](Width, Height)
for x in 0..<Width:
for y in 0..<Height:
let fx = float32(x)
let fy = float32(y)
var hue = sin(fx / 16) + sin(fy / 8) + sin((fx + fy) / 16) + sin(sqrt((fx^2 + fy^2)) / 8)
hue = (hue + 4) / 8 # Between 0 and 1.
let rgb = to(ColorHSL([hue * 360, 1, 0.5]), ColorRGBF)
img[x, y] = rgb
img.savePNG("plasma.png") |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[MakeTranslationTable, PlayfairCipher, PlayfairDecipher]
MakeTranslationTable[tt_List] := Module[{poss, in, out},
poss = Tuples[Tuples[Range[5], 2], 2];
Table[
If[p[[1, 1]] == p[[2, 1]],
(* same row *)
{in, out} = {p, {{p[[1, 1]], Mod[p[[1, 2]] + 1, 5, 1]}, {p[[2, 1]], Mod[p[[2, 2]] + 1, 5, 1]}}};
,
If[p[[1, 2]] == p[[2, 2]],
(* same column *)
{in, out} = {p, {{Mod[p[[1, 1]] + 1, 5, 1], p[[1, 2]]}, {Mod[p[[2, 1]] + 1, 5, 1], p[[2, 2]]}}};
,
(*rectangle*)
{in, out} = {p, {{p[[1, 1]], p[[2, 2]]}, {p[[2, 1]], p[[1, 2]]}}};
]
];
StringJoin[Extract[tt, in]] -> StringJoin[Extract[tt, out]]
,
{p, poss}
]
]
PlayfairCipher[txt_String, key_String, iisj_ : True] :=
Module[{text, tt},
text = RemoveDiacritics[ToUpperCase[txt]];
tt = RemoveDiacritics[ToUpperCase[key]] <> CharacterRange["A", "Z"];
text //= StringReplace[Except[Alternatives @@ CharacterRange["A", "Z"]] -> ""];
tt //= StringReplace[Except[Alternatives @@ CharacterRange["A", "Z"]] -> ""];
If[iisj,
tt //= StringReplace["J" -> "I"];
text //= StringReplace["J" -> "I"];
,
tt //= StringReplace["Q" -> ""];
text //= StringReplace["Q" -> ""];
];
tt //= Characters /* DeleteDuplicates;
text = FixedPoint[StringReplace[#, x_ ~~ x_ :> x ~~ "X" ~~ x, 1] &, text];
If[OddQ[StringLength[text]], text = text <> "X"];
If[Length[tt] == 25,
tt = Partition[tt, 5];
tt = MakeTranslationTable[tt];
text = StringPartition[text, 2];
StringRiffle[text /. tt, " "]
,
Print["Something went wrong!"]
]
]
PlayfairDecipher[txt_String, key_String, iisj_ : True] :=
Module[{text, tt},
text = RemoveDiacritics[ToUpperCase[txt]];
tt = RemoveDiacritics[ToUpperCase[key]] <> CharacterRange["A", "Z"];
text //= StringReplace[Except[Alternatives @@ CharacterRange["A", "Z"]] -> ""];
tt //= StringReplace[Except[Alternatives @@ CharacterRange["A", "Z"]] -> ""];
If[iisj,
tt //= StringReplace["J" -> "I"];
text //= StringReplace["J" -> "I"];
,
tt //= StringReplace["Q" -> ""];
text //= StringReplace["Q" -> ""];
];
tt //= Characters /* DeleteDuplicates;
If[OddQ[StringLength[text]], text = text <> "X"];
If[Length[tt] == 25,
tt = Partition[tt, 5];
tt = MakeTranslationTable[tt];
text = StringPartition[text, 2];
StringRiffle[text /. (Reverse /@ tt), " "]
,
Print["Something went wrong!"]
]
]
PlayfairCipher["Hide the gold in...the TREESTUMP!!!", "Playfair example"]
PlayfairDecipher[%, "Playfair example"] |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | color[y_] := {White, Black}[[Mod[y, 2] + 1]];
Graphics[Join[{Thickness[1/408]},
Flatten[{color[#], Line[{{# - 1/2, 408}, {# - 1/2, 307}}]} & /@
Range[408]], {Thickness[1/204]},
Flatten[{color[#], Line[{{2 # - 1, 306}, {2 # - 1, 205}}]} & /@
Range[204]], {Thickness[1/136]},
Flatten[{color[#], Line[{{3 # - 3/2, 204}, {3 # - 3/2, 103}}]} & /@
Range[136]], {Thickness[1/102]},
Flatten[{color[#], Line[{{4 # - 2, 102}, {4 # - 2, 1}}]} & /@
Range[102]]], ImageSize -> {408, 408}] |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Nim | Nim | import gintro/[glib, gobject, gtk, gio, cairo]
const
Width = 420
Height = 420
const Colors = [[255.0, 255.0, 255.0], [0.0, 0.0, 0.0]]
#---------------------------------------------------------------------------------------------------
proc draw(area: DrawingArea; context: Context) =
## Draw the bars.
const lineHeight = Height div 4
var y = 0.0
for lineWidth in [1.0, 2.0, 3.0, 4.0]:
context.setLineWidth(lineWidth)
var x = 0.0
var colorIndex = 0
while x < Width:
context.setSource(Colors[colorIndex])
context.moveTo(x, y)
context.lineTo(x, y + lineHeight)
context.stroke()
colorIndex = 1 - colorIndex
x += lineWidth
y += lineHeight
#---------------------------------------------------------------------------------------------------
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("Color pinstripe")
# Create the drawing area.
let area = newDrawingArea()
window.add(area)
# Connect the "draw" event to the callback to draw the bars.
discard area.connect("draw", ondraw, pointer(nil))
window.showAll()
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.Pinstripe")
discard app.connect("activate", activate)
discard app.run() |
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
| #Qi | Qi | (define prime?-0
K N -> true where (> (* K K) N)
K N -> false where (= 0 (MOD N K))
K N -> (prime?-0 (+ K 2) N))
(define prime?
1 -> false
2 -> true
N -> false where (= 0 (MOD N 2))
N -> (prime?-0 3 N)) |
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.
| #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int PLAYERS = 4, MAX_POINTS = 100;
//--------------------------------------------------------------------------------------------------
enum Moves { ROLL, HOLD };
//--------------------------------------------------------------------------------------------------
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
//--------------------------------------------------------------------------------------------------
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
//--------------------------------------------------------------------------------------------------
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
//--------------------------------------------------------------------------------------------------
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
//--------------------------------------------------------------------------------------------------
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
//--------------------------------------------------------------------------------------------------
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Ol | Ol |
; creating the "plasma" image buffer
(import (scheme inexact))
(define plasma
(fold append #null
(map (lambda (y)
(map (lambda (x)
(let ((value (/
(+ (sin (/ y 4))
(sin (/ (+ x y) 8))
(sin (/ (sqrt (+ (* x x) (* y y))) 8))
4) 8)))
value))
(iota 256)))
(iota 256))))
|
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
| #Nim | Nim | import pegs, strutils
type
Position = tuple[x, y: int]
Playfair = object
positions: array['A'..'Z', Position]
table: array[5, array[5, char]]
const None: Position = (-1, -1) # Default value for positions.
proc initPlayfair(key: string; jti: bool): Playfair =
for item in result.positions.mitems: item = None
var alphabet = key & "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphabet = if jti: alphabet.replace('J', 'I')
else: alphabet.replace("Q", "")
var k = 0
for ch in alphabet:
if result.positions[ch] == None:
result.table[k div 5][k mod 5] = ch
result.positions[ch] = (k mod 5, k div 5)
inc k
proc codec(playfair: Playfair; text: string; direction: int): string =
result.setLen(text.len)
for i in countup(0, text.high, 2):
var
(col1, row1) = playfair.positions[text[i]]
(col2, row2) = playfair.positions[text[i + 1]]
if row1 == row2:
col1 = (col1 + direction) mod 5
col2 = (col2 + direction) mod 5
elif col1 == col2:
row1 = (row1 + direction) mod 5
row2 = (row2 + direction) mod 5
else:
swap col1, col2
result[i] = playfair.table[row1][col1]
result[i + 1] = playfair.table[row2][col2]
proc encode(playfair: Playfair; text: string): string =
var
text = text
i = 0
while i < text.len:
if i == text.high:
if (text.len and 1) != 0:
text.add 'X'
elif text[i] == text[i + 1]:
text.insert("X", i + 1)
inc i, 2
result = playfair.codec(text, 1)
proc decode(playfair: Playfair; text: string): string =
result = playfair.codec(text, 4)
proc prompt(msg: string): string =
stdout.write msg
try:
result = stdin.readLine()
except EOFError:
echo ""
quit getCurrentExceptionMsg(), QuitFailure
when isMainModule:
var key: string
while key.len <= 6:
key = prompt("Enter an encryption key (min letters 6): ").toUpperAscii().replace(peg"[^A-Z]")
var text: string
while text.len == 0:
text = prompt("Enter the message: ").toUpperAscii().replace(peg"[^A-Z]")
var answer: string
while answer notin ["y", "n"]:
answer = prompt("Replace J with I? y/n: ").toLowerAscii()
let jti = (answer == "y")
let playfair = initPlayfair(key, jti)
let enc = playfair.encode(text)
let dec = playfair.decode(enc)
echo "Encoded message: ", enc
echo "Decoded message: ", dec |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Perl | Perl | use Imager;
my($xsize,$ysize) = (640,400);
$img = Imager->new(xsize => $xsize, ysize => $ysize);
my $eps = 10**-14;
my $height = int $ysize / 4;
for my $width (1..4) {
$stripes = int((1-$eps) + $xsize / $width / 2);
@row = ((0) x $width, (1) x $width) x $stripes;
for $x (0..$#row) {
for $y (0..$height) {
my $offset = $height*($width-1);
$img->setpixel(x => $x, y => $y+$offset, color => $row[$x] ? 'black' : 'white')
}
}
}
$img->write(file => 'pinstripes-bw.png'); |
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
| #Quackery | Quackery | [ dup 4 < iff [ 1 > ] done
dup 1 & not iff [ drop false ] done
true swap dup sqrt
0 = iff [ 2drop not ] done
1 >> times
[ dup i^ 1 << 3 + mod 0 = if
[ dip not conclude ] ]
drop ] is isprime ( n --> b )
|
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.
| #Common_Lisp | Common Lisp | (defclass player ()
((score :initform 0 :accessor score)
(name :initarg :name :accessor name)))
(defun make-player (name)
(make-instance 'player :name name))
(defmethod has-won ((player player))
(>= (score player) 100))
(defclass score-based (player)
((score-base :initarg :score-base :initform 25 :accessor score-base)))
(defun make-score-based (name &optional (base 25))
(make-instance 'score-based :score-base base :name name))
(defmethod roll-again ((player score-based) other turn-score)
(declare (ignorable other))
(< turn-score (score-base player)))
(defclass neller (player) ())
(defun make-neller (name) (make-instance 'neller :name name))
(defmethod roll-again ((player neller) other turn-score)
(let ((other-score (score other)) (my-score (score player)))
(or
(> other-score 71)
(> my-score 71)
(< turn-score (+ 21 (/ (- other-score my-score) 8))))))
(defun query-turn (player other roll added-score)
(format t "~A: Rolled a ~A - Turn: ~A Current Score: ~A Keep rolling (Y, N or Q)?"
(name player)
roll
added-score
(+ added-score (score player)))
(let ((ret (roll-again player other added-score)))
(if ret (format t "Y~%") (format t "N~%"))
ret))
(defun do-turns (player other)
(do ((new-score 0)
(take-turn t))
((not take-turn) (setf (score player) (+ (score player) new-score)))
(let ((roll (+ 1 (random 6))))
(cond
((>= (+ (score player) roll new-score) 100)
(format t "~A rolls a ~A and WINS!~%" (name player) roll)
(setf new-score (+ new-score roll))
(setf take-turn nil))
((eql 1 roll)
(format t "Ooh! Sorry - ~A rolled a 1 and busted!~%" (name player))
(setf new-score 0)
(setf take-turn nil))
(t
(setf new-score (+ new-score roll))
(setf take-turn (query-turn player other roll new-score)))))))
(defun play-pig-winner (p1 p2)
(do* ((otherplayer p2 curplayer)
(curplayer p1 (if (eql curplayer p1) p2 p1)))
((has-won otherplayer) otherplayer)
(do-turns curplayer otherplayer)))
(defun play-pig-player (player1 player2)
(catch 'quit (format t "Hooray! ~A won the game!" |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Perl | Perl | use Imager;
sub plasma {
my ($w, $h) = @_;
my $img = Imager->new(xsize => $w, ysize => $h);
for my $x (0 .. $w-1) {
for my $y (0 .. $h-1) {
my $hue = 4 + sin($x/19) + sin($y/9) + sin(($x+$y)/25) + sin(sqrt($x**2 + $y**2)/8);
$img->setpixel(x => $x, y => $y, color => {hsv => [360 * $hue / 8, 1, 1]});
}
}
return $img;
}
my $img = plasma(400, 400);
$img->write(file => 'plasma-perl.png'); |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
-- input arguments:
-- encipher/decipher IQ-switch key text
-- encipher/decipher -
-- a character E, D (default E; . is an alias for E)
-- IQ-switch -
-- a character I, Q (default I for I==J, Q for exclude Q; . is an alias for I)
-- key -
-- the cipher key - default plugh_xyzzy (really just PLUGHXYZ)
-- text -
-- the text to encipher/decipher
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method cipher(d_, km, digraphs) public static
if d_.upper() = 'D' then d_ = -1 -- encode or decode adjustment
else d_ = +1
cipherText = ''
loop dw = 1 to digraphs.words()
-- process the digraphs one at a time
digraph = digraphs.word(dw)
cl = ''
cr = ''
-- get each letter from the digraph
parse digraph dl +1 dr
loop r_ = 1 to km[0] while (cl cr).words() < 4
-- locate the row/col of each letter in the cipher matrix
clx = km[r_].wordpos(dl)
crx = km[r_].wordpos(dr)
if clx > 0 then cl = r_ clx
if crx > 0 then cr = r_ crx
end r_
-- process the digraph's rows, columns or rectangles
select
when cl.word(1) = cr.word(1) then do
-- a row
rx = cl.word(1)
clx = cl.word(2) + d_
crx = cr.word(2) + d_
if clx > 5 then clx = 1 -- wrap
if crx > 5 then crx = 1
if clx < 1 then clx = 5
if crx < 1 then crx = 5
cy = km[rx].word(clx) || km[rx].word(crx)
cipherText = cipherText cy
end
when cl.word(2) = cr.word(2) then do
-- a column
cx = cl.word(2)
rlx = cl.word(1) + d_
rrx = cr.word(1) + d_
if rlx > 5 then rlx = 1 -- wrap
if rrx > 5 then rrx = 1
if rlx < 1 then rlx = 5
if rrx < 1 then rrx = 5
cy = km[rlx].word(cx) || km[rrx].word(cx)
cipherText = cipherText cy
end
otherwise do
-- a rectangle
r1 = cl.word(1)
r2 = cr.word(1)
cy = km[r1].word(cr.word(2)) || km[r2].word(cl.word(2))
cipherText = cipherText cy
end
end
end dw
return cipherText.strip()
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method encipher(km, digraphs) public static
return cipher('E', km, digraphs)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method decipher(km, digraphs) public static
return cipher('D', km, digraphs)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getDigraphs(text, IorQ, ED) private static
a2z = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if ED.upper() \= 'D' then eks = 'X'
else eks = ''
tp = text.upper().translate('', a2z)
text = text.upper().translate(' '.copies(tp.length()), tp).space(0)
rtext = ''
ll = ''
loop while text \= ''
parse text lc +1 text
if ll \= lc then rtext = rtext || lc
else rtext = rtext || eks || lc
ll = lc
end
-- I == J or remove Q fixup
if IorQ \= 'Q' then
parse 'J I' IorQ sc .
else
sc = ''
rtext = rtext.changestr(IorQ, sc)
if rtext.length() // 2 \= 0 then rtext = rtext || eks
digraphs = ''
loop while rtext \= ''
parse rtext digraph +2 rtext
digraphs = digraphs digraph
end
return digraphs.space()
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getKey(key, IorQ) private static
a2z = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
kp = (key || a2z).upper()
kr = ''
loop while kp \= ''
parse kp xx +1 kp
if \xx.datatype('u') then iterate
kr = kr xx
kp = kp.changestr(xx, '')
end
if IorQ = 'I' | IorQ = 'J' | IorQ = '' then
kr = kr.changestr('J', '')
else
kr = kr.changestr('Q', '')
return kr.space()
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getKeyMatrix(kr) private static
km = ''
loop r_ = 1 while kr \= ''
parse kr kp +10 kr
km[0] = r_
km[r_] = kp
end r_
return km
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg ciph IorQ key text
if ciph = '' | ciph = '.' then ciph = 'E'
if IorQ = '' | IorQ = '.' then IorQ = 'I'
if key = '' | key = '.' then key = 'plugh_xyzzy'
if text = '' | text = '.' then text = 'NetRexx; not just a programing language for kings & queens!'
kr = getKey(key.space(0), IorQ)
km = getKeyMatrix(kr)
digraphs = getDigraphs(text, IorQ, ciph)
-- fixup for a Q in the text when Q is excluded (substitute K for Q)
if IorQ.upper = 'Q' then digraphs = digraphs.changestr('Q', 'K')
if ciph = 'E' then say text
say digraphs
if ciph.upper() = 'E' then
say encipher(km, digraphs)
else
say decipher(km, digraphs)
return
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Phix | Phix | (let Pbm # Create PBM of 384 x 288 pixels
(make
(for N 4
(let
(C 0
L (make
(do (/ 384 N)
(do N (link C))
(setq C (x| 1 C)) ) ) )
(do 72 (link L)) ) ) )
(out '(display) # Pipe to ImageMagick
(prinl "P1")
(prinl (length (car Pbm)) " " (length Pbm))
(mapc prinl Pbm) ) ) |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #PicoLisp | PicoLisp | (let Pbm # Create PBM of 384 x 288 pixels
(make
(for N 4
(let
(C 0
L (make
(do (/ 384 N)
(do N (link C))
(setq C (x| 1 C)) ) ) )
(do 72 (link L)) ) ) )
(out '(display) # Pipe to ImageMagick
(prinl "P1")
(prinl (length (car Pbm)) " " (length Pbm))
(mapc prinl Pbm) ) ) |
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
| #R | R | is.prime <- function(n) n == 2 || n > 2 && n %% 2 == 1 && (n < 9 || all(n %% seq(3, floor(sqrt(n)), 2) > 0))
which(sapply(1:100, is.prime))
# [1] 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 |
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.
| #D | D | import std.stdio, std.random;
enum nPlayers = 4, maxPoints = 100;
enum Moves { roll, hold }
abstract class Player {
public:
final void addCurrScore() pure nothrow {
current_score += round_score;
}
final int getCurrScore() const pure nothrow {
return current_score;
}
final int getRoundScore() const pure nothrow {
return round_score;
}
final void addRoundScore(in int rs) pure nothrow {
round_score += rs;
}
final void zeroRoundScore() pure nothrow {
round_score = 0;
}
Moves getMove();
protected int current_score, round_score;
}
final class PlayerRand: Player {
override Moves getMove() {
if (round_score + current_score >= maxPoints)
return Moves.hold;
if (uniform(0, 2) == 0)
return Moves.roll;
if (round_score > 0)
return Moves.hold;
return Moves.roll;
}
}
final class PlayerQ2Win: Player {
override Moves getMove() {
if (round_score + current_score >= maxPoints)
return Moves.hold;
int q = maxPoints - current_score;
if (q < 6)
return Moves.roll;
q /= 4;
if (round_score < q)
return Moves.roll;
return Moves.hold;
}
}
final class PlayerAL20: Player {
override Moves getMove() {
if (round_score + current_score >= maxPoints)
return Moves.hold;
if (round_score < 20)
return Moves.roll;
return Moves.hold;
}
}
final class PlayerAL20T: Player {
override Moves getMove() {
if (round_score + current_score >= maxPoints)
return Moves.hold;
immutable d = (100 * round_score) / 20;
if (round_score < 20 && d < uniform(0, 100))
return Moves.roll;
return Moves.hold;
}
}
void main() {
auto players = [new PlayerRand, new PlayerQ2Win,
new PlayerAL20, new PlayerAL20T];
void nextTurn(ref uint p) nothrow {
players[p].zeroRoundScore;
p = (p + 1) % nPlayers;
}
uint p = 0;
bool endGame = false;
while (!endGame) {
final switch (players[p].getMove) {
case Moves.roll:
immutable die = uniform(1, 7);
if (die == 1) {
writeln("Player ", p + 1, " rolled ", die,
" - current score: ",
players[p].getCurrScore, "\n");
nextTurn(p);
continue;
}
players[p].addRoundScore(die);
writeln("Player ", p + 1, " rolled ", die,
" - round score: ",
players[p].getRoundScore);
break;
case Moves.hold:
players[p].addCurrScore;
writeln("Player ", p + 1,
" holds - current score: ",
players[p].getCurrScore, "\n");
if (players[p].getCurrScore >= maxPoints)
endGame = true;
else
nextTurn(p);
}
}
writeln;
writeln("Player I (Rand): ", players[0].getCurrScore);
writeln("Player II (Q2Win): ", players[1].getCurrScore);
writeln("Player III (AL20): ", players[2].getCurrScore);
writeln("Player IV (AL20T): ", players[3].getCurrScore, "\n\n");
} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Phix | Phix | -- demo\rosetta\plasma.exw
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
sequence plasma
integer pw = 0, ph = 0
procedure createPlasma(integer w, h)
plasma = repeat(repeat(0,w),h)
for y=1 to h do
for x=1 to w do
atom v = sin(x/16)
v += sin(y/8)
v += sin((x+y)/16)
v += sin(sqrt(x*x + y*y)/8)
v += 4 -- shift range from -4 .. 4 to 0 .. 8
v /= 8 -- bring range down to 0 .. 1
plasma[y][x] = v
end for
end for
pw = w
ph = h
end procedure
atom hueShift = 0
procedure drawPlasma(integer w, h)
hueShift = remainder(hueShift + 0.02,1)
sequence rgb3 = repeat(repeat(0,w*h),3)
integer cx = 1
for y=1 to h do
for x=1 to w do
atom hue = hueShift + remainder(plasma[y][x],1)
integer i = floor(hue * 6)
atom t = 255,
f = (hue * 6 - i)*t,
q = t - f,
r, g, b
switch mod(i,6) do
case 0: r = t; g = f; b = 0
case 1: r = q; g = t; b = 0
case 2: r = 0; g = t; b = f
case 3: r = 0; g = q; b = t
case 4: r = f; g = 0; b = t
case 5: r = t; g = 0; b = q
end switch
rgb3[1][cx] = r
rgb3[2][cx] = g
rgb3[3][cx] = b
cx += 1
end for
end for
cdCanvasPutImageRectRGB(cddbuffer, w, h, rgb3, 0, 0, 0, 0, 0, 0, 0, 0)
end procedure
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
atom {w,h} = IupGetIntInt(canvas, "DRAWSIZE")
if pw!=w or ph!=h then
createPlasma(w,h)
end if
cdCanvasActivate(cddbuffer)
drawPlasma(w,h)
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function timer_cb(Ihandle /*ih*/)
IupUpdate(canvas)
return IUP_IGNORE
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_GRAY)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "450x300")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", "Plasma")
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
Ihandle timer = IupTimer(Icallback("timer_cb"), 50)
IupMainLoop()
IupClose()
end procedure
main() |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Processing | Processing | /**
Plasmas with Palette Looping
https://lodev.org/cgtutor/plasma.html#Plasmas_with_Palette_Looping_
*/
int pal[] = new int[128];
int[] buffer;
float r = 42, g = 84, b = 126;
boolean rd, gd, bd;
void setup() {
size(600, 600);
frameRate(25);
buffer = new int[width*height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
buffer[x+y*width] = int(((128+(128*sin(x/32.0)))
+(128+(128*cos(y/32.0)))
+(128+(128*sin(sqrt((x*x+y*y))/32.0))))/4);
}
}
}
void draw() {
if (r > 128) rd = true;
if (!rd) r++;
else r--;
if (r < 0) rd = false;
if (g > 128) gd = true;
if (!gd) g++;
else g--;
if (r < 0) gd = false;
if (b > 128) bd = true;
if (!bd) b++;
else b--;
if (b < 0){ bd = false;}
float s_1, s_2;
for (int i = 0; i < 128; i++) {
s_1 = sin(i*PI/25);
s_2 = sin(i*PI/50+PI/4);
pal[i] = color(r+s_1*128, g+s_2*128, b+s_1*128);
}
loadPixels();
for (int i = 0; i < buffer.length; i++) {
pixels[i] = pal[(buffer[i]+frameCount)&127];
}
updatePixels();
} |
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
| #ooRexx | ooRexx | /*---------------------------------------------------------------------
* REXX program implements a PLAYFAIR cipher (encryption & decryption).
* 11.11.2013 Walter Pachl revamped, for ooRexx, the REXX program
* the logic of which was devised by Gerard Schildberger
* Invoke as rexx pf O abcd efgh ( phrase to be processed
* Defaults: 'Playfair example.'
* J
* 'Hide the gold in the tree stump'
* Major changes: avoid language elements not allowed in ooRexx
* show use of a.[expr1,expr2]
* allow key to be more than one word
* add restriction of using X or Q in text
* 12.11.2013 change order of arguments
* and comment the use of a.[expr1,expr2]
* Program should run on all Rexxes that have changestr-bif
*--------------------------------------------------------------------*/
Parse Upper Version v
oorexx=pos('OOREXX',v)>0
Parse Arg omit oldk '(' text
If omit='' Then omit='J'
If oldk='' Then oldk='Playfair example.'
If text='' Then text='Hide the gold in the tree stump!!'
newkey=scrub(oldk,1)
newtext=scrub(text)
If newtext=='' Then Call err 'TEXT is empty or has no letters'
If length(omit)\==1 Then Call err 'OMIT letter must be only one letter'
If\datatype(omit,'M') Then Call err 'OMIT letter must be a Latin alphabet letter.'
omit=translate(omit)
cant='must not contain the "OMIT" character: ' omit
If pos(omit,newtext)\==0 Then Call err 'TEXT' cant
If pos(omit,newkey)\==0 Then Call err 'cipher key' cant
abc='abcdefghijklmnopqrstuvwxyz'
abcu=translate(abc) /* uppercase alphabet */
abcx=space(translate(abcu,,omit),0) /*elide OMIT char from alphabet */
xx='X' /* char used for double characters*/
If omit==xx Then
xx='Q'
If pos(xx,newtext)>0 Then
Call err 'Sorry,' xx 'is not allowed in text'
If length(newkey)<3 Then
Call err 'cipher key is too short, must be at least 3 different letters'
abcx=space(translate(abcx,,newkey),0) /*remove any cipher characters */
grid=newkey||abcx /* only first 25 chars are used*/
Say 'old cipher key: ' strip(oldk)
padl=14+2
pad=left('',padl)
Say 'new cipher key: ' newkey
padx=left('',padl,"-")'Playfair'
Say ' omit char: ' omit /* [?] lowercase of double char. */
Say ' double char: ' xx
lxx=translate(xx,abc,abcu)
Say ' original text: ' strip(text)/* [?] doubled version of Lxx. */
Call show 'cleansed',newtext
lxxlxx=lxx||lxx
n=0 /* number of grid characters used.*/
Do row=1 For 5 /* build array of individual cells*/
Do col=1 For 5
n=n+1
a.row.col=substr(grid,n,1)
If row==1 Then
a.0.col=a.1.col
If col==5 Then Do
a.row.6=a.row.1
a.row.0=a.row.5
End
If row==5 Then Do
a.6.col=a.1.col
a.0.col=a.5.col
End
End
End
etext=playfair(newtext,1)
Call show 'encrypted',etext
ptext=playfair(etext,-1)
Call show 'plain',ptext
qtext=changestr(xx||xx,ptext,lxx) /*change doubled doublechar-?sing*/
qtext=changestr(lxx||xx,qtext,lxxlxx) /*change Xx --? lowercase dblChar*/
qtext=space(translate(qtext,,xx),0) /*remove char used for "doubles."*/
qtext=translate(qtext) /*reinstate the use of upperchars*/
Call show 'decoded',qtext
Say ' original text: ' newtext /* ·· and show the original text.*/
Say ''
Exit
playfair:
/*---------------------------------------------------------------------
* encode (e=1) or decode (e=-1) the given text (t) using the grid
*--------------------------------------------------------------------*/
Arg t,e
d=''
If e=1 Then Do
Do k=1 By 1 Until c=''
c=substr(t,k,1)
If substr(t,k+1,1)==c Then
t=left(t,k)||lxx||substr(t,k+1)
End
End
t=translate(t)
Do j=1 By 2 To length(t)
c2=strip(substr(t,j,2))
If length(c2)==1 Then
c2=c2||xx /* append X or Q char, rule 1*/
Call LR
Select
/*- This could/should be used on ooRexx -------------------------
When rowl==rowr Then c2=a.[rowl,coll+e]a.[rowr,colr+e] /*rule 2*/
When coll==colr Then c2=a.[rowl+e,coll]a.[rowr+e,colr] /*rule 3*/
*--------------------------------------------------------------*/
When rowl==rowr Then c2=aa(rowl,coll+e)aa(rowr,colr+e) /*rule 2*/
When coll==colr Then c2=aa(rowl+e,coll)aa(rowr+e,colr) /*rule 3*/
Otherwise c2=a.rowl.colr||a.rowr.coll /*rule 4*/
End
d=d||c2
End
Return d
aa:
/*---------------------------------------------------------------------
* ooRexx allows to use a.[rowl,coll+e]
* this function can be removed when ooRexx syntax is used to access a.
*--------------------------------------------------------------------*/
Parse Arg xrow,xcol
Return a.xrow.xcol
err:
/*---------------------------------------------------------------------
* Exit with an error message
*--------------------------------------------------------------------*/
Say
Say '***error!***' arg(1)
Say
Exit 13
lr:
/*---------------------------------------------------------------------
* get grid positions of the 2 characters
*--------------------------------------------------------------------*/
Parse Value rowcol(left(c2,1)) with rowl coll
Parse Value rowcol(right(c2,1)) with rowr colr
Return
rowcol: procedure Expose grid
/*---------------------------------------------------------------------
* compute row and column of the given character in the 5x5 grid
*--------------------------------------------------------------------*/
Parse Arg c
p=pos(c,grid)
col=(p-1)//5+1
row=(4+p)%5
Return row col
show:
/*---------------------------------------------------------------------
* Show heading and text
*--------------------------------------------------------------------*/
Arg,y
Say
Say right(arg(1) 'text: ',padl) digram(arg(2))
result=space(arg(2),0)
If arg(1)='decoded' Then Do
result=strip(result,'T',xx)
End
Say pad result
Return
scrub: Procedure
/*---------------------------------------------------------------------
* Remove all non-letters from the given string, uppercase letters
* and, if unique=1 remove duplicates
* 'aB + c1Bb' -> 'ABCBB' or 'ABC', respectively
*--------------------------------------------------------------------*/
Arg xxx,unique /* ARG caps all args */
d=''
used.=0
Do While xxx<>''
Parse Var xxx c +1 xxx
If datatype(c,'U') Then
If (unique=1 & pos(c,d)=0) |,
unique<>1 Then
d=d||c
End
Return d
digram: Procedure
/*---------------------------------------------------------------------
* Return the given string as character pairs separated by blanks
* 'ABCDEF' -> 'AB CD EF'
* 'ABCDE' -> 'AB CD E'
*--------------------------------------------------------------------*/
Parse Arg x
d=''
Do j=1 By 2 To length(x)
d=d||substr(x,j,2)' '
End
Return strip(d) |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #PureBasic | PureBasic | #White = $FFFFFF ;color
;Create a Pinstripe image
Procedure PinstripeDisplay(width, height)
Protected x, imgID, psHeight = height / 4, psWidth = 1, psTop, horzBand
imgID = CreateImage(#PB_Any, width, height)
If imgID
StartDrawing(ImageOutput(imgID))
Repeat
x = 0
Repeat
Box(x, psTop, psWidth, psHeight, #White)
x + 2 * psWidth
Until x >= width
psWidth + 1
horzBand + 1
psTop = horzBand * height / 4 ;move to the top of next horizontal band of image
Until psTop >= height
StopDrawing()
EndIf
ProcedureReturn imgID
EndProcedure
;Open a window and display the pinstripe
If OpenWindow(0, 0, 0, 1, 1,"PureBasic Pinstripe", #PB_Window_Maximize | #PB_Window_SystemMenu)
PicID = PinstripeDisplay(WindowWidth(0), WindowHeight(0))
ImageGadget(0, 0, 0, WindowWidth(0), WindowHeight(0), ImageID(PicID))
While WaitWindowEvent() <> #PB_Event_CloseWindow
Wend
EndIf |
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
| #Racket | Racket | #lang racket
(define (prime? number)
(cond ((not (positive? number)) #f)
((= 1 number) #f)
((even? number) (= 2 number))
(else (for/and ((i (in-range 3 (ceiling (sqrt number)))))
(not (zero? (remainder number i))))))) |
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.
| #Erlang | Erlang |
-module( pig_dice_player ).
-export( [task/0] ).
task() ->
Goal = pig_dice:goal(),
Players_holds = [{"Player"++ erlang:integer_to_list(X), X} || X <- [5, 10, 15, 20]],
Fun = fun ({Player, Total}, Dict) when Total >= Goal -> dict:update_counter( Player, 1, Dict );
(_Player_total, Dict) -> Dict
end,
Dict = lists:foldl( Fun, dict:new(), task_play(Players_holds, Goal, []) ),
display( dict:to_list(Dict) ).
display( Results ) ->
[{Name, Total} | Rest] = lists:reverse( lists:keysort(2, Results) ),
io:fwrite( "Winner is ~p with total of ~p wins~n", [Name, Total] ),
io:fwrite( "Then follows: " ),
[io:fwrite("~p with ~p~n", [N, T]) || {N, T} <- Rest].
is_goal_reached( Score, Player, Goal, Player, Game ) ->
Score + proplists:get_value(Player, pig_dice:players_totals(Game)) >= Goal;
is_goal_reached( _Score, _Other_player, _Goal, _Player, _Game ) -> false.
loop( Hold, Hold, Goal, Player, Game ) ->
pig_dice:hold( Player, Game ),
loop( 1, Hold, Goal, Player, Game );
loop( N, Hold, Goal, Player, Game ) ->
loop_await_my_turn( pig_dice:player_name(Game), Player, Game ),
pig_dice:roll( Player, Game ),
Is_goal_reached = is_goal_reached( pig_dice:score(Game), pig_dice:player_name(Game), Goal, Player, Game ),
loop_done( Is_goal_reached, N, Hold, Goal, Player, Game ).
loop_await_my_turn( Player, Player, _Game ) -> ok;
loop_await_my_turn( _Other, Player, Game ) -> loop_await_my_turn( pig_dice:player_name(Game), Player, Game ).
loop_done( true, _N, _Hold, _Goal, Player, Game ) -> pig_dice:hold( Player, Game );
loop_done( false, N, Hold, Goal, Player, Game ) -> loop( N + 1, Hold, Goal, Player, Game ).
rotate( [H | T] ) -> T ++ [H].
task_play( Players_holds, _Goal, Acc ) when erlang:length(Players_holds) =:= erlang:length(Acc) -> lists:flatten( Acc );
task_play( Players_holds, Goal, Acc ) ->
Results = [task_play_n(Players_holds, Goal) || _X <- lists:seq(1, 100)],
task_play( rotate(Players_holds), Goal, [Results | Acc] ).
task_play_n( Players_holds, Goal ) ->
Game = pig_dice:game( [X || {X, _Y} <- Players_holds] ),
Pids = [erlang:spawn(fun() -> loop(1, Y, Goal, X, Game) end) || {X, Y} <- Players_holds],
receive
{pig, Result, Game} ->
[erlang:exit(X, kill) || X <- [Game | Pids]],
Result
end.
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Python | Python | import math
import colorsys
from PIL import Image
def plasma (w, h):
out = Image.new("RGB", (w, h))
pix = out.load()
for x in range (w):
for y in range(h):
hue = 4.0 + math.sin(x / 19.0) + math.sin(y / 9.0) \
+ math.sin((x + y) / 25.0) + math.sin(math.sqrt(x**2.0 + y**2.0) / 8.0)
hsv = colorsys.hsv_to_rgb(hue/8.0, 1, 1)
pix[x, y] = tuple([int(round(c * 255.0)) for c in hsv])
return out
if __name__=="__main__":
im = plasma(400, 400)
im.show() |
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
| #Perl | Perl | use Math::Cartesian::Product;
# Pregenerate all forward and reverse translations
sub playfair {
our($key,$from) = @_;
$from //= 'J';
our $to = $from eq 'J' ? 'I' : '';
my(%ENC,%DEC,%seen,@m);
sub canon {
my($str) = @_;
$str =~ s/[^[:alpha:]]//g;
$str =~ s/$from/$to/gi;
uc $str;
}
my @uniq = grep { ! $seen{$_}++ } split '', canon($key . join '', 'A'..'Z');
while (@uniq) { push @m, [splice @uniq, 0, 5] }
# Map pairs in same row.
for my $r (@m) {
for my $x (cartesian {@_} [0..4], [0..4]) {
my($i,$j) = @$x;
next if $i == $j;
$ENC{ @$r[$i] . @$r[$j] } = @$r[($i+1)%5] . @$r[($j+1)%5];
}
}
# Map pairs in same column.
for my $c (0..4) {
my @c = map { @$_[$c] } @m;
for my $x (cartesian {@_} [0..4], [0..4]) {
my($i,$j) = @$x;
next if $i == $j;
$ENC{ $c[$i] . $c[$j] } = $c[($i+1)%5] . $c[($j+1)%5];
}
}
# Map pairs with cross-connections.
for my $x (cartesian {@_} [0..4], [0..4], [0..4], [0..4]) {
my($i1,$j1,$i2,$j2) = @$x;
next if $i1 == $i2 or $j1 == $j2;
$ENC{ $m[$i1][$j1] . $m[$i2][$j2] } = $m[$i1][$j2] . $m[$i2][$j1];
}
# Generate reverse translations.
while (my ($k, $v) = each %ENC) { $DEC{$v} = $k }
# Return code-refs for encoding/decoding routines
return
sub { my($red) = @_; # encode
my $str = canon($red);
my @list;
while ($str =~ /(.)(?(?=\1)|(.?))/g) {
push @list, substr($str,$-[0], $-[2] ? 2 : 1);
}
join ' ', map { length($_)==1 ? $ENC{$_.'X'} : $ENC{$_} } @list;
},
sub { my($black) = @_; # decode
join ' ', map { $DEC{$_} } canon($black) =~ /../g;
}
}
my($encode,$decode) = playfair('Playfair example');
my $orig = "Hide the gold in...the TREESTUMP!!!";
my $black = &$encode($orig);
my $red = &$decode($black);
print " orig:\t$orig\n";
print "black:\t$black\n";
print " red:\t$red\n"; |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Python | Python |
#Python task for Pinstripe/Display
#Tested for Python2.7 by Benjamin Curutchet
#Import PIL libraries
from PIL import Image
from PIL import ImageColor
from PIL import ImageDraw
#Create the picture (size parameter 1660x1005 like the example)
x_size = 1650
y_size = 1000
im = Image.new('RGB',(x_size, y_size))
#Create a full black picture
draw = ImageDraw.Draw(im)
#RGB code for the White Color
White = (255,255,255)
#First loop in order to create four distinct lines
y_delimiter_list = []
for y_delimiter in range(1,y_size,y_size/4):
y_delimiter_list.append(y_delimiter)
#Four different loops in order to draw columns in white depending on the
#number of the line
for x in range(1,x_size,2):
for y in range(1,y_delimiter_list[1],1):
draw.point((x,y),White)
for x in range(1,x_size-1,4):
for y in range(y_delimiter_list[1],y_delimiter_list[2],1):
draw.point((x,y),White)
draw.point((x+1,y),White)
for x in range(1,x_size-2,6):
for y in range(y_delimiter_list[2],y_delimiter_list[3],1):
draw.point((x,y),White)
draw.point((x+1,y),White)
draw.point((x+2,y),White)
for x in range(1,x_size-3,8):
for y in range(y_delimiter_list[3],y_size,1):
draw.point((x,y),White)
draw.point((x+1,y),White)
draw.point((x+2,y),White)
draw.point((x+3,y),White)
#Save the picture under a name as a jpg file.
print "Your picture is saved"
im.save('PictureResult.jpg')
|
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
| #Raku | Raku | sub prime (Int $i --> Bool) {
$i > 1 and so $i %% none 2..$i.sqrt;
} |
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.
| #Go | Go | package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const (
// Status messages
gameOver = iota
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
// Players
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
// Max score
maxScore = 100
// Strategies
scoreChaseStrat = iota
rollCountStrat
)
// Returns "s" if n != 1
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
// Creates an intializes a new PigGameData structure, returns a *PigGameData
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
// Create a status message for a given message ID
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
// Print a status message, if pg.Verbose is true
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
// Play a given strategy
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
// Get the score for a given player
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
// Check if the game is over
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
// Returns the Player ID if there is a winner, or -1
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
// Get the ID of the other player
func (pg *PigGameData) otherPlayer() PlayerID {
// 0 becomes 1, 1 becomes 0
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
// Run the simulation
func main() {
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
// Start a new game
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
// Play until game over
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Racket | Racket | #lang racket
;; from lisp (cos I could just lift the code)
(require images/flomap
2htdp/universe
racket/flonum)
;; copied from pythagoras-triangle#racket
(define (real-remainder x q) (- x (* (floor (/ x q)) q)))
(define (HSV->RGB H S V)
(define C (* V S)) ; chroma
(define H′ (/ H 60))
(define X (* C (- 1 (abs (- (real-remainder H′ 2) 1)))))
(define-values (R1 G1 B1)
(cond
[(< H′ 1) (values C X 0.)]
[(< H′ 2) (values X C 0.)]
[(< H′ 3) (values 0. C X)]
[(< H′ 4) (values 0. X C)]
[(< H′ 5) (values X 0. C)]
[(< H′ 6) (values C 0. X)]
[else (values 0. 0. 0.)]))
(define m (- V C))
(values (+ R1 m) (+ G1 m) (+ B1 m)))
(define ((colour-component-by-pos ϕ) k x y)
(let ((rv
(/ (+ (+ 1/2 (* 1/2 (sin (+ ϕ (/ x 16.0)))))
(+ 1/2 (* 1/2 (sin (+ ϕ (/ y 8.0)))))
(+ 1/2 (* 1/2 (sin (+ ϕ (/ (+ x y) 16.0)))))
(+ 1/2 (* 1/2 (sin (+ ϕ (/ (sqrt (+ (sqr x) (sqr y))) 8.0))))))
4.0)))
rv))
(define ((plasma-flomap (ϕ 0)) w h)
(build-flomap 1 w h (colour-component-by-pos ϕ)))
(define ((plasma-image (ϕ 0)) w h)
(flomap->bitmap ((plasma-flomap ϕ) w h)))
(define ((colour-plasma plsm) t)
(let ((w (flomap-width plsm))
(h (flomap-height plsm)))
(flomap->bitmap
(build-flomap* 3 w h
(λ (x y)
(define-values (r g b)
(HSV->RGB (real-remainder
(+ (* t 5.)
(* 360 (flomap-ref plsm 0 x y)))
360.) 1. 1.))
(flvector r g b))))))
;((plasma-image) 200 200)
;((plasma-image (/ pi 32)) 200 200)
(define plsm ((plasma-flomap) 300 300))
(animate (λ (t)
((colour-plasma plsm) t))) |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Raku | Raku | use Image::PNG::Portable;
my ($w, $h) = 400, 400;
my $out = Image::PNG::Portable.new: :width($w), :height($h);
plasma($out);
$out.write: 'Plasma-perl6.png';
sub plasma ($png) {
(^$w).race.map: -> $x {
for ^$h -> $y {
my $hue = 4 + sin($x / 19) + sin($y / 9) + sin(($x + $y) / 25) + sin(sqrt($x² + $y²) / 8);
$png.set: $x, $y, |hsv2rgb($hue/8, 1, 1);
}
}
}
sub hsv2rgb ( $h, $s, $v ){
my $c = $v * $s;
my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );
my $m = $v - $c;
(do given $h {
when 0..^1/6 { $c, $x, 0 }
when 1/6..^1/3 { $x, $c, 0 }
when 1/3..^1/2 { 0, $c, $x }
when 1/2..^2/3 { 0, $x, $c }
when 2/3..^5/6 { $x, 0, $c }
when 5/6..1 { $c, 0, $x }
} ).map: ((*+$m) * 255).Int
} |
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
| #11l | 11l | V playercount = 2
V maxscore = 100
V safescore = [0] * playercount
V player = 0
V score = 0
L max(safescore) < maxscore
V rolling = input(‘Player #.: (#., #.) Rolling? (Y) ’.format(
player, safescore[player], score)).trim(‘ ’).lowercase() C Set([‘yes’, ‘y’, ‘’])
I rolling
V rolled = random:(1 .. 6)
print(‘ Rolled #.’.format(rolled))
I rolled == 1
print(‘ Bust! you lose #. but still keep your previous #.’.format(score, safescore[player]))
(score, player) = (0, (player + 1) % playercount)
E
score += rolled
E
safescore[player] += score
I safescore[player] >= maxscore
L.break
print(‘ Sticking with #.’.format(safescore[player]))
(score, player) = (0, (player + 1) % playercount)
print("\nPlayer #. wins with a score of #.".format(player, safescore[player])) |
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
| #Phix | Phix | with javascript_semantics
constant keyword = "Playfair example",
option = 'Q' -- ignore Q
-- option = 'J' -- replace J with I
sequence table,
findchar
procedure build_table()
table = repeat(repeat(' ',5),5)
findchar = repeat(0,26)
findchar[option-'A'+1] = {0,0}
-- (note any (J/Q) in keyword are simply ignored)
string alphabet = upper(keyword) & tagset('Z','A')
integer i=1, j=1
for k=1 to length(alphabet) do
integer c = alphabet[k]
if c>='A' and c<='Z' then
integer d = c-'A'+1
if findchar[d]=0 then
table[i][j] = c
findchar[d] = {i,j}
j += 1
if j=6 then
i += 1
if i=6 then exit end if -- table filled
j = 1
end if
end if
end if
end for
end procedure
build_table()
function clean_text(string plaintext)
--
-- get rid of any non-letters and insert X between duplicate letters
--
plaintext = upper(plaintext)
string cleantext = ""
integer prevChar = -1
for i=1 to length(plaintext) do
integer nextChar = plaintext[i]
if nextChar>='A' and nextChar<='Z'
and (nextChar!='Q' or option!='Q') then
if nextChar='J' and option='J' then nextChar = 'I' end if
if nextChar=prevChar then
cleantext &= 'X'
end if
cleantext &= nextChar
prevChar = nextChar
end if
end for
if odd(length(cleantext)) then
-- dangling letter at end so add another letter to complete digraph
cleantext &= iff(cleantext[$]='X'?'Z':'X')
end if
return cleantext
end function
function remove_x(string text)
for i=2 to length(text)-1 do
if text[i]='X'
and ((text[i-1]=' ' and text[i-2]=text[i+1]) or
(text[i+1]=' ' and text[i-1]=text[i+2])) then
text[i] = '_'
end if
end for
return text
end function
function playfair(string text, integer step, sequence d)
--
-- text may be the plaintext or the encoded version
-- step is 2 for plaintext, 3 for encoded(/skip spaces)
-- d is {2,3,4,5,1} instead of mod(+1,5), or
-- {5,1,2,3,4} -- -1
--
string res = ""
for i=1 to length(text) by step do
integer {row1, col1} = findchar[text[i]-'A'+1],
{row2, col2} = findchar[text[i+1]-'A'+1]
if i>1 then res &= " " end if
if row1=row2 then
{col1,col2} = {d[col1],d[col2]}
elsif col1=col2 then
{row1,row2} = {d[row1],d[row2]}
else
{col1,col2} = {col2,col1}
end if
res &= table[row1][col1] & table[row2][col2]
end for
return res
end function
function encode(string plaintext)
return playfair(clean_text(plaintext),2,{2,3,4,5,1})
end function
function decode(string ciphertext)
-- ciphertext includes spaces we need to skip, hence by 3
return remove_x(playfair(ciphertext,3,{5,1,2,3,4}))
end function
printf(1,"Playfair keyword : %s\n",{keyword})
printf(1,"Option: J=I or no Q (J/Q) : %s\n",option)
printf(1,"The table to be used is :\n\n%s\n\n",{join(table,"\n")})
string plaintext = "Hide the gold...in the TREESTUMP!!!!",
encoded = encode(plaintext),
decoded = decode(encoded)
printf(1,"The plain text : %s\n\n",{plaintext})
printf(1,"Encoded text is : %s\n",{encoded})
printf(1,"Decoded text is : %s\n",{decoded})
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Racket | Racket |
#lang racket/gui
(define-values [W H] (get-display-size #t))
(define parts 4)
(define (paint-pinstripe canvas dc)
(send dc set-pen "black" 0 'solid)
(send dc set-brush "black" 'solid)
(define H* (round (/ H parts)))
(for ([row parts])
(define Y (* row H*))
(for ([X (in-range 0 W (* (add1 row) 2))])
(send dc draw-rectangle X Y (add1 row) H*))))
(define full-frame%
(class frame%
(define/override (on-subwindow-char r e)
(when (eq? 'escape (send e get-key-code))
(send this show #f)))
(super-new
[label "Pinstripe"] [width W] [height H]
[style '(no-caption no-resize-border hide-menu-bar no-system-menu)])
(define c (new canvas% [parent this] [paint-callback paint-pinstripe]))
(send this show #t)))
(void (new full-frame%))
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Raku | Raku | my ($x,$y) = 1280,720;
my @colors = 0, 1;
spurt "pinstripes.pgm", qq:to/EOH/ orelse .die;
P5
# pinstripes.pgm
$x $y
1
EOH
my $img = open "pinstripes.pgm", :a, :bin orelse .die;
my $vzones = $y div 4;
for 1..4 -> $w {
my $stripes = ceiling $x / $w / +@colors;
my $line = Buf.new: (flat((@colors Xxx $w) xx $stripes).Array).splice(0,$x); # DH change 2015-12-20
$img.write: $line for ^$vzones;
}
$img.close; |
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
| #REBOL | REBOL | prime?: func [n] [
case [
n = 2 [ true ]
n <= 1 or (n // 2 = 0) [ false ]
true [
for i 3 round square-root n 2 [
if n // i = 0 [ return 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.
| #Haskell | Haskell | - player1 always rolls until he gets 20 or more
- player2 always rolls four times
- player3 rolls three times until she gets more than 60 points, then she rolls until she gets 20 or more
- player4 rolls 3/4 of the time, 1/4 he holds, but if he gets a score more than 75 he goes for the win
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Ring | Ring |
# Project : Plasma effect
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget()
{
setwindowtitle("Plasma effect")
setgeometry(100,100,500,600)
label1 = new qlabel(win1)
{
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1)
{
setgeometry(150,500,100,30)
settext("Draw")
setclickevent("Draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() { setrgb(0,0,255,255) } ### <<< BLUE
pen = new qpen() { setcolor(color) setwidth(1) }
paint = new qpainter()
{
begin(p1)
setpen(pen)
w = 256
h = 256
time = 0
for x = 0 to w -1
for y = 0 to h -1
time = time + 0.99
value = sin(dist(x + time, y, 128, 128) / 8) +
sin(dist(x, y, 64, 64) / 8) +
sin(dist(x, y + time / 7, 192, 64) / 7) +
sin(dist(x, y, 192, 100) / 8) + 4
c = floor(value * 32)
r = c
g = (c*2)%255
b = 255-c
color2 = new qcolor()
color2.setrgb(r,g,b,255)
pen.setcolor(color2)
setpen(pen)
drawpoint(x,y)
next
next
endpaint()
}
label1 { setpicture(p1) show() }
return
func dist(a, b, c, d)
d = sqrt(((a - c) * (a - c) + (b - d) * (b - d)))
return d
|
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
| #ActionScript | ActionScript |
package {
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class PigTheDiceGame extends Sprite {
/**
* The name of the first player.
*
* @private
*/
private var _name1:String = "Player 1";
/**
* The name of the second player.
*
* @private
*/
private var _name2:String = "Player 2";
/**
* True if the next turn is of the second player, false if it is of the first player.
*
* @private
*/
private var _isPlayer2:Boolean = false;
/**
* The score of the first player.
*
* @private
*/
private var __p1Score:uint;
/**
* The score of the second player.
*
* @private
*/
private var __p2Score:uint;
/**
* The number of points in the current turn.
*
* @private
*/
private var __turnPts:uint;
/**
* The text field displaying the score of the first player.
*
* @private
*/
private var _p1ScoreText:TextField;
/**
* The text field displaying the score of the second player.
*
* @private
*/
private var _p2ScoreText:TextField;
/**
* The button which must be clicked for a player to roll the dice.
*
* @private
*/
private var _rollButton:Sprite;
/**
* The button which must be clicked for a player to hold.
*
* @private
*/
private var _holdButton:Sprite;
/**
* The text field displaying the name of the current player.
*/
private var _currentPlayerText:TextField;
/**
* The text field displaying the number of points in the current turn.
*
* @private
*/
private var _ptsThisTurnText:TextField;
/**
* The dice.
*
* @private
*/
private var _dice:Shape;
/**
* The number of points required to win the game.
*
* @private
*/
private var _maxScore:uint = 100;
/**
* The text field displaying additional information about the game.
*
* @private
*/
private var _statusText:TextField;
/**
* Creates a new PigTheDiceGame instance.
*/
public function PigTheDiceGame() {
if ( stage ) _init();
else addEventListener(Event.ADDED_TO_STAGE, _init);
}
/**
* Function which constructs the dice game when the object is added to the stage.
*
* @private
*/
private function _init(e:Event = null):void {
// Border and background
graphics.beginFill(0xFFFFDD);
graphics.lineStyle(2, 0xFFCC00);
graphics.drawRect(0, 0, 450, 280)
x = 20;
y = 20;
// Text fields and labels
var currentPlayerText:TextField = _createTextField(_name1 + "'s turn", 20, 0, 10, 0xDD0000, TextFieldAutoSize.CENTER, width);
var p1ScoreLabel:TextField = _createTextField(_name1 + "'s score:", 15, 20, currentPlayerText.y + currentPlayerText.height + 20, 0x000000, TextFieldAutoSize.LEFT, 120);
var p1ScoreText:TextField = _createTextField("0", 17, 135, p1ScoreLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50);
var p2ScoreLabel:TextField = _createTextField(_name2 + "'s score:", 15, 20, p1ScoreText.y + p1ScoreText.height + 5, 0x000000, TextFieldAutoSize.LEFT, 120);
var p2ScoreText:TextField = _createTextField("0", 17, 135, p2ScoreLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50);
var ptsThisTurnLabel:TextField = _createTextField("Points in this turn:", 15, 20, p2ScoreText.y + p2ScoreText.height + 15, 0x000000, TextFieldAutoSize.LEFT, 120);
var ptsThisTurnText:TextField = _createTextField("0", 17, 135, ptsThisTurnLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50);
// Dice
var dice:Shape = new Shape();
dice.x = 201;
dice.y = ptsThisTurnText.y + ptsThisTurnText.height + 30;
dice.visible = false;
var statusText:TextField = _createTextField("Start Play!", 15, 0, dice.y + 70, 0x0000A0, TextFieldAutoSize.CENTER, 450);
// "Roll" button
var rollButton:Sprite = new Sprite();
var rollButtonText:TextField = _createTextField("Roll dice", 17, 0, 0, 0x000000, TextFieldAutoSize.CENTER, 100);
rollButton.mouseChildren = false;
rollButton.buttonMode = true;
rollButton.graphics.lineStyle(1, 0x444444);
rollButton.graphics.beginFill(0xDDDDDD);
rollButton.graphics.drawRect(0, 0, 100, rollButtonText.height);
rollButton.x = 330;
rollButton.y = 80;
rollButton.addChild(rollButtonText);
// "Hold" button
var holdButton:Sprite = new Sprite();
var holdButtonText:TextField = _createTextField("Hold", 17, 0, 0, 0x000000, TextFieldAutoSize.CENTER, 100);
holdButton.mouseChildren = false;
holdButton.buttonMode = true;
holdButton.graphics.copyFrom(rollButton.graphics);
holdButton.x = 330;
holdButton.y = rollButton.y + rollButton.height + 10;
holdButton.addChild(holdButtonText);
rollButton.addEventListener(MouseEvent.CLICK, _rollButtonClick);
holdButton.addEventListener(MouseEvent.CLICK, _holdButtonClick);
_currentPlayerText = currentPlayerText;
_p1ScoreText = p1ScoreText;
_p2ScoreText = p2ScoreText;
_ptsThisTurnText = ptsThisTurnText;
_rollButton = rollButton;
_holdButton = holdButton;
_dice = dice;
_statusText = statusText;
addChild(currentPlayerText);
addChild(p1ScoreLabel);
addChild(p1ScoreText);
addChild(p2ScoreLabel);
addChild(p2ScoreText);
addChild(ptsThisTurnLabel);
addChild(ptsThisTurnLabel);
addChild(ptsThisTurnText);
addChild(statusText);
addChild(_dice);
addChild(rollButton);
addChild(holdButton);
}
/**
* Creates a new text field.
*
* @param text The text to be displayed in the text field.
* @param size The font size of the text.
* @param x The x-coordinate of the text field.
* @param y The y-coordinate of the text field.
* @param colour The text colour.
* @param autoSize The text alignment mode.
* @param width The width of the text field.
* @return A TextField object.
* @private
*/
private function _createTextField(text:String, size:Number, x:Number, y:Number, colour:uint, autoSize:String, width:Number):TextField {
var t:TextField = new TextField();
t.defaultTextFormat = new TextFormat(null, size, colour);
t.autoSize = autoSize;
t.x = x;
t.y = y;
t.width = width;
t.text = text;
t.height = t.textHeight + 5;
return t;
}
/**
* Rolls the dice.
*
* @return The result of the roll (1-6)
* @private
*/
private function _rollDice():uint {
// Since Math.random() returns a number between 0 and 1, multiplying it by 6 and then rounding down
// gives a number between 0 and 5, so add 1 to it.
var roll:uint = uint(Math.random() * 6) + 1;
_dice.visible = true;
var diceGraphics:Graphics = _dice.graphics;
// Draw the dice.
diceGraphics.clear();
diceGraphics.lineStyle(2, 0x555555);
diceGraphics.beginFill(0xFFFFFF);
diceGraphics.drawRect(0, 0, 48, 48);
diceGraphics.beginFill(0x000000);
diceGraphics.lineStyle(0);
switch ( roll ) {
case 1:
diceGraphics.drawCircle(24, 24, 3);
break;
case 2:
diceGraphics.drawCircle(16, 16, 3);
diceGraphics.drawCircle(32, 32, 3);
break;
case 3:
diceGraphics.drawCircle(12, 12, 3);
diceGraphics.drawCircle(24, 24, 3);
diceGraphics.drawCircle(36, 36, 3);
break;
case 4:
diceGraphics.drawCircle(16, 16, 3);
diceGraphics.drawCircle(16, 32, 3);
diceGraphics.drawCircle(32, 16, 3);
diceGraphics.drawCircle(32, 32, 3);
break;
case 5:
diceGraphics.drawCircle(12, 12, 3);
diceGraphics.drawCircle(24, 24, 3);
diceGraphics.drawCircle(36, 36, 3);
diceGraphics.drawCircle(36, 12, 3);
diceGraphics.drawCircle(12, 36, 3);
break;
case 6:
diceGraphics.drawCircle(16, 12, 3);
diceGraphics.drawCircle(16, 24, 3);
diceGraphics.drawCircle(16, 36, 3);
diceGraphics.drawCircle(32, 12, 3);
diceGraphics.drawCircle(32, 24, 3);
diceGraphics.drawCircle(32, 36, 3);
break;
}
return roll;
}
/**
* The score of the first player.
*
* @private
*/
private function get _p1Score():uint {
return __p1Score;
}
/**
* @private
*/
private function set _p1Score(value:uint):void {
__p1Score = value;
_p1ScoreText.text = String(value);
if ( value >= _maxScore ) {
_currentPlayerText.text = "Game over!";
_statusText.text = _name1 + " wins!";
removeChild(_rollButton);
removeChild(_holdButton);
}
}
/**
* The score of the second player.
*
* @private
*/
private function get _p2Score():uint {
return __p2Score;
}
/**
* @private
*/
private function set _p2Score(value:uint):void {
__p2Score = value;
_p2ScoreText.text = String(value);
if ( value >= _maxScore ) {
_currentPlayerText.text = "Game over!";
_statusText.text = _name2 + " wins!";
removeChild(_rollButton);
removeChild(_holdButton);
}
}
/**
* The number of points in the current turn.
*
* @private
*/
private function get _turnPts():uint {
return __turnPts;
}
/**
* @private
*/
private function set _turnPts(value:uint):void {
__turnPts = value;
_ptsThisTurnText.text = String(value);
if ( _isPlayer2 && __p2Score + value >= _maxScore ) {
_ptsThisTurnText.text = "0";
_p2Score += value;
}
else if ( ! _isPlayer2 && __p1Score + value >= _maxScore ) {
_ptsThisTurnText.text = "0";
_p1Score += value;
}
}
/**
* Function called when the "Roll dice" button is clicked.
*
* @private
*/
private function _rollButtonClick(e:MouseEvent):void {
var roll:uint = _rollDice();
if ( roll == 1 ) {
if ( _isPlayer2 ) {
_currentPlayerText.text = _name1 + "'s turn";
_statusText.text = _name2 + " rolls 1 and loses " + __turnPts + " points. " + _name1 + "'s turn now.";
}
else {
_currentPlayerText.text = _name2 + "'s turn";
_statusText.text = _name1 + " rolls 1 and loses " + __turnPts + " points. " + _name2 + "'s turn now.";
}
_isPlayer2 = ! _isPlayer2;
_turnPts = 0;
}
else {
_turnPts += roll;
_statusText.text = "";
}
}
/**
* Function called when the "Hold" button is clicked.
*
* @private
*/
private function _holdButtonClick(e:MouseEvent):void {
if ( _isPlayer2 ) {
_currentPlayerText.text = _name1 + "'s turn";
_statusText.text = _name2 + " holds and wins " + __turnPts + " points. " + _name1 + "'s turn now.";
_p2Score += __turnPts;
}
else {
_currentPlayerText.text = _name2 + "'s turn";
_statusText.text = _name1 + " holds and wins " + __turnPts + " points. " + _name2 + "'s turn now.";
_p1Score += __turnPts;
}
_dice.visible = false;
_turnPts = 0;
_isPlayer2 = ! _isPlayer2;
}
}
}
|
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
| #Python | Python | from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
"""Instantiate a specific encoder/decoder."""
def playfair(key, from_ = 'J', to = None):
if to is None:
to = 'I' if from_ == 'J' else ''
def canonicalize(s):
return filter(str.isupper, s.upper()).replace(from_, to)
# Build 5x5 matrix.
m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)
# Pregenerate all forward translations.
enc = {}
# Map pairs in same row.
for row in m:
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]
# Map pairs in same column.
for c in zip(*m):
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]
# Map pairs with cross-connections.
for i1, j1, i2, j2 in product(xrange(5), repeat=4):
if i1 != i2 and j1 != j2:
enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]
# Generate reverse translations.
dec = dict((v, k) for k, v in enc.iteritems())
def sub_enc(txt):
lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt))
return " ".join(enc[a + (b if b else 'X')] for a, b in lst)
def sub_dec(encoded):
return " ".join(dec[p] for p in partition(canonicalize(encoded), 2))
return sub_enc, sub_dec
(encode, decode) = playfair("Playfair example")
orig = "Hide the gold in...the TREESTUMP!!!"
print "Original:", orig
enc = encode(orig)
print "Encoded:", enc
print "Decoded:", decode(enc) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #11l | 11l | print(random:choice([‘foo’, ‘bar’, ‘baz’])) |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Ring | Ring |
# Project : Pinstripe/Display
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Pinstripe/Display")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
xscreen = 100
yscreen = 100
color = new qcolor()
color.setrgb(0,0,0,255)
mybrush = new qbrush() {setstyle(1) setcolor(color)}
setbrush(mybrush)
for x = 0 to xscreen*4-4 step 4
drawrect(x,yscreen*3/2,2,yscreen/2)
next
for x = 0 to xscreen*4-8 step 8
drawrect(x,yscreen*2/2,4,yscreen/2)
next
for x = 0 to xscreen*4-12 step 12
drawrect(x,yscreen*1/2,6,yscreen/2)
next
for x = 0 to xscreen*4-16 step 16
drawrect(x,yscreen*0/2,8,yscreen/2)
next
endpaint()
}
label1 { setpicture(p1) show() }
return
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Scala | Scala | import java.awt._
import javax.swing._
object PinstripeDisplay extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Pinstripe") {
class Pinstripe_Display extends JPanel {
override def paintComponent(g: Graphics): Unit = {
val bands = 4
super.paintComponent(g)
for (b <- 1 to bands) {
var colIndex = 0
for (x <- 0 until getWidth by b) {
g.setColor(if (colIndex % 2 == 0) Color.white
else Color.black)
g.fillRect(x, (b - 1) * (getHeight / bands), x + b, b * (getHeight / bands))
colIndex += 1
}
}
}
setPreferredSize(new Dimension(900, 600))
}
add(new Pinstripe_Display, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setVisible(true)
})
} |
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
| #REXX | REXX | /*REXX program tests for primality by using (kinda smartish) trial division. */
parse arg n .; if n=='' then n=10000 /*let the user choose the upper limit. */
tell=(n>0); n=abs(n) /*display the primes only if N > 0. */
p=0 /*a count of the primes found (so far).*/
do j=-57 to n /*start in the cellar and work up. */
if \isPrime(j) then iterate /*if not prime, then keep looking. */
p=p+1 /*bump the jelly bean counter. */
if tell then say right(j,20) 'is prime.' /*maybe display prime to the terminal. */
end /*j*/
say
say "There are " p " primes up to " n ' (inclusive).'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure; parse arg x /*get the number to be tested. */
if wordpos(x, '2 3 5 7')\==0 then return 1 /*is number a teacher's pet? */
if x<2 | x//2==0 | x//3==0 then return 0 /*weed out the riff-raff. */
do k=5 by 6 until k*k>x /*skips odd multiples of 3. */
if x//k==0 | x//(k+2)==0 then return 0 /*a pair of divides. ___ */
end /*k*/ /*divide up through the √ x */
/*Note: // is ÷ remainder.*/
return 1 /*done dividing, it's prime. */ |
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.
| #J | J | pigval=:4 :0
(+/%#)(-x),}.(1+i.6)<.100-y+x
) |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Ruby | Ruby |
attr_reader :buffer, :palette, :r, :g, :b, :rd, :gd, :bd, :dim
def settings
size(600, 600)
end
def setup
sketch_title 'Plasma Effect'
frame_rate 25
@r = 42
@g = 84
@b = 126
@rd = true
@gd = true
@bd = true
@dim = width * height
@buffer = Array.new(dim)
grid(width, height) do |x, y|
buffer[x + y * width] = (
(
(128 + (128 * sin(x / 32.0))) +
(128 + (128 * cos(y / 32.0))) +
(128 + (128 * sin(Math.hypot(x, y) / 32.0)))
) / 4
).to_i
end
load_pixels
end
def draw
if rd
@r -= 1
@rd = false if r.negative?
else
@r += 1
@rd = true if r > 128
end
if gd
@g -= 1
@gd = false if g.negative?
else
@g += 1
@gd = true if g > 128
end
if bd
@b -= 1
@bd = false if b.negative?
else
@b += 1
@bd = true if b > 128
end
@palette = (0..127).map do |col|
s1 = sin(col * Math::PI / 25)
s2 = sin(col * Math::PI / 50 + Math::PI / 4)
color(r + s1 * 128, g + s2 * 128, b + s1 * 128)
end
dim.times do |idx|
pixels[idx] = palette[(buffer[idx] + frame_count) & 127]
end
update_pixels
end
|
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Ada | Ada | package Pig is
type Dice_Score is range 1 .. 6;
type Player is tagged private;
function Recent(P: Player) return Natural;
function All_Recent(P: Player) return Natural;
function Score(P: Player) return Natural;
type Actor is abstract tagged null record;
function Roll_More(A: Actor; Self, Opponent: Player'Class)
return Boolean is abstract;
procedure Play(First, Second: Actor'Class; First_Wins: out Boolean);
private
type Player is tagged record
Score: Natural := 0;
All_Recent: Natural := 0;
Recent_Roll: Dice_Score := 1;
end record;
end Pig; |
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
| #Raku | Raku | # Instantiate a specific encoder/decoder.
sub playfair( $key,
$from = 'J',
$to = $from eq 'J' ?? 'I' !! ''
) {
sub canon($str) { $str.subst(/<-alpha>/,'', :g).uc.subst(/$from/,$to,:g) }
# Build 5x5 matrix.
my @m = canon($key ~ ('A'..'Z').join).comb.unique.map:
-> $a,$b,$c,$d,$e { [$a,$b,$c,$d,$e] }
# Pregenerate all forward translations.
my %ENC = gather {
# Map pairs in same row.
for @m -> @r {
for ^@r X ^@r -> (\i,\j) {
next if i == j;
take @r[i] ~ @r[j] => @r[(i+1)%5] ~ @r[(j+1)%5];
}
}
# Map pairs in same column.
for ^5 -> $c {
my @c = @m.map: *.[$c];
for ^@c X ^@c -> (\i,\j) {
next if i == j;
take @c[i] ~ @c[j] => @c[(i+1)%5] ~ @c[(j+1)%5];
}
}
# Map pairs with cross-connections.
for ^5 X ^5 X ^5 X ^5 -> (\i1,\j1,\i2,\j2) {
next if i1 == i2 or j1 == j2;
take @m[i1][j1] ~ @m[i2][j2] => @m[i1][j2] ~ @m[i2][j1];
}
}
# Generate reverse translations.
my %DEC = %ENC.invert;
return
anon sub enc($red) {
my @list = canon($red).comb(/(.) (.?) <?{ $1 ne $0 }>/);
~@list.map: { .chars == 1 ?? %ENC{$_~'X'} !! %ENC{$_} }
},
anon sub dec($black) {
my @list = canon($black).comb(/../);
~@list.map: { %DEC{$_} }
}
}
my (&encode,&decode) = playfair 'Playfair example';
my $orig = "Hide the gold in...the TREESTUMP!!!";
say " orig:\t$orig";
my $black = encode $orig;
say "black:\t$black";
my $red = decode $black;
say " red:\t$red"; |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #8086_Assembly | 8086 Assembly | .model small
.stack 1024
.data
TestList byte 00h,05h,10h,15h,20h,25h,30h,35h
.code
start:
mov ax,@data
mov ds,ax
mov ax,@code
mov es,ax
call seedXorshift32 ;seeds the xorshift rng using the computer's date and time
call doXorshift32
mov ax,word ptr [ds:xorshift32_state_lo] ;retrieve the rng output
and al,00000111b ;constrain the rng to values 0-7
mov bx,offset TestList
XLAT ;translate AL according to [DS:BX]
call PrintHex ;display AL to the terminal
mov ax,4C00h
int 21h ;exit program and return to MS-DOS
end start |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Sinclair_ZX81_BASIC | Sinclair ZX81 BASIC | 10 FOR W=1 TO 4
20 FOR I=0 TO 63 STEP 2*W
30 FOR J=1 TO W
40 FOR K=43-11*(W-1) TO 33-11*(W-1) STEP -1
50 PLOT I+J,K
60 NEXT K
70 NEXT J
80 NEXT I
90 NEXT W |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Tcl | Tcl | package require Tcl 8.5
package require Tk 8.5
wm attributes . -fullscreen 1
pack [canvas .c -highlightthick 0] -fill both -expand 1
set colors {black white}
set dy [expr {[winfo screenheight .c]/4}]
set y 0
foreach dx {1 2 3 4} {
for {set x 0} {$x < [winfo screenwidth .c]} {incr x $dx} {
.c create rectangle $x $y [expr {$x+$dx}] [expr {$y+$dy}] \
-fill [lindex $colors 0] -outline {}
set colors [list {*}[lrange $colors 1 end] [lindex $colors 0]]
}
incr y $dy
} |
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
| #Ring | Ring | give n
flag = isPrime(n)
if flag = 1 see n + " is a prime number"
else see n + " is not a prime number" ok
func isPrime num
if (num <= 1) return 0 ok
if (num % 2 = 0 and num != 2) return 0 ok
for i = 3 to floor(num / 2) -1 step 2
if (num % i = 0) return 0 ok
next
return 1 |
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.
| #Java | Java | import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
//Validate the input
while(true) {
//Get the number of players
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
//Gotta be more than 0
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
//Start the game
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
//Set the number of strategies available.
final int STRATEGIES = 5;
//Construct the dice- accepts an int as an arg for number of sides, but defaults to 6.
Dice dice = new Dice();
//Create an array of players and initialize them to defaults.
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
/*****Print strategy options here. Modify Player.java to add strategies. *****/
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
//Get the strategy for each player
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
//Validate the strategy is a real strategy.
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
//Here is where the rules for the game are programmatically defined.
int max = 0;
while(max < 100) {
//Begin the round
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
//Set the points for the turn to 0
player.setTurnPoints(0);
//Determine whether the player chooses to roll or hold.
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
//Increment the player's built in iterator.
player.incIter();
//If the player rolls a 1, their turn is over and they gain 0 points this round.
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
//Check if the player held or not.
else {
System.out.println(" The player has held. ");
break;
}
}
//End the turn and add any accumulated points to the player's pool.
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
//Reset the player's built in iterator.
player.resetIter();
//Update the max score if necessary.
if(max < player.getPoints()) {
max = player.getPoints();
}
//If someone won, stop the game and announce the winner.
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
//Announce the final scores.
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Rust | Rust |
extern crate image;
use image::ColorType;
use std::path::Path;
// Framebuffer dimensions
const WIDTH: usize = 640;
const HEIGHT: usize = 480;
/// Formula for plasma at any particular address
fn plasma_pixel(x: f64, y: f64) -> f64 {
((x / 16.0).sin()
+ (y / 8.0).sin()
+ ((x + y) / 16.0).sin()
+ ((x * x + y * y).sqrt() / 8.0).sin()
+ 4.0)
/ 8.0
}
/// Precalculate plasma field lookup-table for performance
fn create_plasma_lut() -> Vec<f64> {
let mut plasma: Vec<f64> = vec![0.0; WIDTH * HEIGHT];
for y in 0..HEIGHT {
for x in 0..WIDTH {
plasma[(y * WIDTH) + x] = plasma_pixel(x as f64, y as f64);
}
}
plasma
}
/// Convert from HSV float(1.0,1.0,1.0) to RGB u8 tuple (255,255,255).
/// From https://crates.io/crates/palette 0.5.0 rgb.rs, simplified for example
fn hsv_to_rgb(hue: f64, saturation: f64, value: f64) -> (u8, u8, u8) {
let c = value * saturation;
let h = hue * 6.0;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let m = value - c;
let (red, green, blue) = match (h % 6.0).floor() as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
// Convert back to RGB (where components are integers from 0 to 255)
(
((red + m) * 255.0).round() as u8,
((green + m) * 255.0).round() as u8,
((blue + m) * 255.0).round() as u8,
)
}
fn main() {
// The bitmap/framebuffer for our application. 3 u8 elements per output pixel
let mut framebuffer: Vec<u8> = vec![0; WIDTH * HEIGHT * 3];
// Generate a lookup table so we don't do too much math for every pixel.
// Do it in a function so that the local one can be immutable.
let plasma_lookup_table = create_plasma_lut();
// For each (r,g,b) pixel in our output buffer
for (index, rgb) in framebuffer.chunks_mut(3).enumerate() {
// Lookup the precalculated plasma value
let hue_lookup = plasma_lookup_table[index] % 1.0;
let (red, green, blue) = hsv_to_rgb(hue_lookup, 1.0, 1.0);
rgb[0] = red;
rgb[1] = green;
rgb[2] = blue;
}
// Save our plasma image to out.png
let output_path = Path::new("out.png");
match image::save_buffer(
output_path,
framebuffer.as_slice(),
WIDTH as u32,
HEIGHT as u32,
ColorType::RGB(8),
) {
Err(e) => println!("Error writing output image:\n{}", e),
Ok(_) => println!("Output written to:\n{}", output_path.to_str().unwrap()),
}
}
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Scala | Scala | import java.awt._
import java.awt.event.ActionEvent
import java.awt.image.BufferedImage
import javax.swing._
import scala.math.{sin, sqrt}
object PlasmaEffect extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Plasma Effect") {
class PlasmaEffect extends JPanel {
private val (w, h) = (640, 640)
private var hueShift = 0.0f
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawPlasma(g: Graphics2D) = {
val img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB)
for (y <- 0 until h;
x <- 0 until w) {
def design =
(sin(x / 16f) + sin(y / 8f) + sin((x + y) / 16f) + sin(sqrt(x * x + y * y) / 8f) + 4).toFloat / 8
img.setRGB(x, y, Color.HSBtoRGB(hueShift + design % 1, 1, 1))
}
g.drawImage(img, 0, 0, null)
}
super.paintComponent(gg)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawPlasma(g)
}
// animate about 24 fps and shift hue value with every frame
new Timer(42, (_: ActionEvent) => {
hueShift = (hueShift + 0.02f) % 1
repaint()
}).start()
setBackground(Color.white)
setPreferredSize(new Dimension(h, w))
}
add(new PlasmaEffect, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
})
} |
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
| #AutoHotkey | AutoHotkey | Gui, Font, s12, Verdana
Gui, Add, Text, vPlayer0, Player 0
Gui, Add, Text, vSum0, 000
Gui, Add, Button, Default, Roll
Gui, Add, Text, ys vLastRoll, Roll 0
Gui, Add, Text, vTurnSum, Sum 000
Gui, Add, Button, , Hold
Gui, Add, Text, ys vPlayer1, Player 1
Gui, Add, Text, vSum1, 000
Gui, Add, Button, , Reload
Gui, Show
GuiControl, Disable, Player1
CurrentPlayer := 0
ButtonRoll:
Loop 10
{
Random, LastRoll, 1, 6
GuiControl, , LastRoll, Roll %LastRoll%
Sleep 50
}
If LastRoll != 1
{
TurnSum += LastRoll
GuiControl, , TurnSum, Sum %TurnSum%
Return
}
TurnSum := 0
ButtonHold:
Sum%CurrentPlayer% += TurnSum
TurnSum := 0
GuiControl, , LastRoll, Roll
GuiControl, , TurnSum, Sum %TurnSum%
GuiControl, , Sum%CurrentPlayer%, % Sum%CurrentPlayer%
If Sum%CurrentPlayer% >= 100
{
MsgBox Player %CurrentPlayer% Won!
GuiClose:
ExitApp
}
GuiControl, Disable, Player%CurrentPlayer%
CurrentPlayer := !CurrentPlayer
GuiControl, Enable, Player%CurrentPlayer%
Return
ButtonReload:
Reload |
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
| #REXX | REXX | /*REXX program implements a PLAYFAIR cipher (encryption and decryption). */
@abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU= @abc /*literals for lower and upper ABC's.*/
parse arg omit key '(' text /*TEXT is the phrase to be used. */
oldKey= key /*save the old key. */
if key =='' | key ==',' then do; key= 'Playfair example.'
oldKey= key " ◄───using the default."
end
if omit=='' | omit==',' then omit= 'J' /*the "omitted" character string. */
if text='' then text= 'Hide the gold in the tree stump!!' /*default.*/
upper omit @abcU /*uppercase OMIT characters & alphabet.*/
@cant= 'can''t contain the "OMIT" character: ' omit /*literal used in error text.*/
@uchars= 'unique characters.' /*a literal used below in an error msg.*/
newKey = scrub(key, 1) /*scrub old cipher key ──► newKey */
newText= scrub(text ) /* " " text ──► newText */
if newText=='' then call err 'TEXT is empty or has no letters.'
if length(omit)\==1 then call err 'OMIT letter must be only one letter.'
if \datatype(omit, 'M') then call err 'OMIT letter must be a Latin alphabet letter.'
if pos(omit, newText)\==0 then call err 'TEXT' @cant
if pos(omit, newKey) \==0 then call err 'cipher key' @cant
fill= space( translate(@abcU, , omit), 0) /*elide OMIT characters from alphabet. */
xx= 'X' /*character used for double characters.*/
if omit==xx then xx= 'Q' /* " " " " " */
if length(newKey)<3 then call err 'cipher key is too short, must be ≥ 3' @uchars
fill= space( translate(fill, , newKey), 0) /*remove any cipher characters. */
grid= newKey || fill /*only first 25 characters are used. */
say 'old cipher key: ' strip(oldKey)
say 'new cipher key: ' newKey
say ' omit char: ' omit
say ' double char: ' xx
say ' original text: ' strip(text)
padL= 14 + 2
call show 'cleansed', newText
#= 0 /*number of grid characters used. */
do row =1 for 5 /*build array of individual cells. */
do col=1 for 5; #= # + 1; @.row.col= substr(grid, #, 1)
if row==1 then @.0.col= @.1.col
if col==5 then do; @.row.6= @.row.1; @.row.0= @.row.5; end
if row==5 then do; @.6.col= @.1.col; @.0.col= @.5.col; end
end /*col*/
end /*row*/
pad = left('', padL)
padX= left('', padL, "═")'Playfair'
Lxx = translate(xx, @abc, @abcU) /* [↓] lowercase of double character. */
LxxLxx= Lxx || Lxx /* [↓] doubled version of Lxx. */
eText= .Playfair(newText, 1); call show 'encrypted' , eText
pText= .Playfair(eText ); call show 'plain' , pText
qText= changestr(xx || xx, pText, Lxx) /*change doubled doublechar ──► single.*/
qText= changestr(Lxx || xx, qText, LxxLxx) /*change xx ──► lowercase dblCharacter*/
qText= space( translate( qText, , xx), 0) /*remove character used for "doubles". */
upper qText /*reinstate the use of upper characters*/
if length(qText)\==length(pText) then call show 'possible', qText
say ' original text: ' newText; say /*··· and also show the original text. */
if qtext==newText then say padx 'encryption──► decryption──► encryption worked.'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@@: parse arg Xrow,Xcol; return @.Xrow.Xcol
err: say; say '***error!***' arg(1); say; exit 13
LR: rowL= row(left(__, 1)); colL= _; rowR= row(right(__,1)); colR= _; return length(__)
row: ?= pos(arg(1), grid); _= (?-1) // 5 + 1; return (4+?) % 5
show: arg ,y; say; say right(arg(1) 'text: ',padL) digram(y); say pad space(y, 0); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
.Playfair: arg T,encrypt; i= -1; if encrypt==1 then i= 1; $=
do k=1 while i==1; _= substr(T, k, 1); if _==' ' then leave
if _==substr(T, k+1, 1) then T= left(T, k) || Lxx || substr(T, k + 1)
end /*k*/
upper T
do j=1 by 2 to length(T); __= strip( substr(T, j, 2) )
if LR()==1 then __= __ || xx; call LR /*append X or Q char, rule 1*/
select /*rule*/
when rowL==rowR then __= @@(rowL, colL+i)@@(rowR, colR+i) /*2*/
when colL==colR then __= @@(rowL+i, colL )@@(rowR+i, colR) /*3*/
otherwise __= @@(rowL, colR )@@(rowR, colL) /*4*/
end /*select*/
$= $ || __
end /*j*/
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
digram: procedure; parse arg x,,$; do j=1 by 2 to length(x)
$= $ || substr(x, j, 2)' '
end /*j*/
return strip($)
/*──────────────────────────────────────────────────────────────────────────────────────*/
scrub: procedure; arg xxx,unique; xxx= space(xxx, 0) /*ARG capitalizes all args*/
$=; do j=1 for length(xxx); _= substr(xxx, j, 1)
if unique==1 then if pos(_, $)\==0 then iterate /*is unique?*/
if datatype(_, 'M') then $= $ || _ /*only use Latin letters. */
end /*j*/
return $ |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #ACL2 | ACL2 | :set-state-ok t
(defun pick-random-element (xs state)
(mv-let (idx state)
(random$ (len xs) state)
(mv (nth idx xs) state))) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Action.21 | Action! | PROC Main()
DEFINE PTR="CARD"
PTR ARRAY a(7)
BYTE i,index
a(0)="Monday"
a(1)="Tuesday"
a(2)="Wednesday"
a(3)="Thursday"
a(4)="Friday"
a(5)="Saturday"
a(6)="Sunday"
FOR i=1 TO 20
DO
index=Rand(7)
PrintE(a(index))
OD
RETURN |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
class Game {
static init() {
Window.title = "Pinstripe"
__width = 900
__height = 600
Canvas.resize(__width, __height)
Window.resize(__width, __height)
var colors = [
Color.hex("FFFFFF"), // white
Color.hex("000000") // black
]
pinstripe(colors)
}
static pinstripe(colors) {
var w = __width
var h = (__height/4).floor
for (b in 1..4) {
var x = 0
var ci = 0
while (x < w) {
var y = h * (b - 1)
Canvas.rectfill(x, y, b, h, colors[ci%2])
x = x + b
ci = ci + 1
}
}
}
static update() {}
static draw(dt) {}
} |
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
| #Ruby | Ruby | def prime(a)
if a == 2
true
elsif a <= 1 || a % 2 == 0
false
else
divisors = (3..Math.sqrt(a)).step(2)
divisors.none? { |d| a % d == 0 }
end
end
p (1..50).select{|i| prime(i)} |
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.
| #Julia | Julia | mutable struct Player
score::Int
ante::Int
wins::Int
losses::Int
strategy::Pair{String, Function}
end
randomchoicetostop(player, group) = rand(Bool)
variablerandtostop(player, group) = any(x -> x.score > player.score, group) ? rand() < 0.1 : rand(Bool)
overtwentystop(player, group) = player.ante > 20
over20unlesslosingstop(player, group) = player.ante > 20 && all(x -> x.score < 80, group)
const strategies = ("random choice to stop" => randomchoicetostop, "variable rand to stop" => variablerandtostop,
"roll to 20" => overtwentystop, "roll to 20 then if not losing stop" => over20unlesslosingstop)
const players = [Player(0, 0, 0, 0, s) for s in strategies]
const dice = collect(1:6)
function turn(player, verbose=false)
playernum = findfirst(p -> p == player, players)
scorewin() = for p in players if p == player p.wins += 1 else p.losses += 1 end; p.score = 0 end
player.ante = 0
while (r = rand(dice)) != 1
player.ante += r
verbose && println("Player $playernum rolls a $r.")
if player.score + player.ante >= 100
scorewin()
verbose && println("Player $playernum wins.\n")
return false
elseif player.strategy[2](player, players)
player.score += player.ante
verbose && println("Player $playernum holds and has a new score of $(player.score).")
return true
end
end
verbose && println("Player $playernum rolls a 1, so turn is over.")
true
end
function rungames(N)
for i in 1:N
verbose = (i == 3) ? true : false # do verbose if it's game number 3
curplayer = rand(collect(1:length(players)))
while turn(players[curplayer], verbose)
curplayer = curplayer >= length(players) ? 1 : curplayer + 1
end
end
results = sort([(p.wins/(p.wins + p.losses), p.strategy[1]) for p in players], rev=true)
println(" Strategy % of wins (N = $N)")
println("------------------------------------------------------------")
for pair in results
println(lpad(pair[2], 34), lpad(round(pair[1] * 100, digits=1), 18))
end
end
rungames(1000000)
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Sidef | Sidef | require('Imager')
class Plasma(width=400, height=400) {
has img = nil
method init {
img = %O|Imager|.new(xsize => width, ysize => height)
}
method generate {
for y=(^height), x=(^width) {
var hue = (4 + sin(x/19) + sin(y/9) + sin((x+y)/25) + sin(hypot(x, y)/8))
img.setpixel(x => x, y => y, color => Hash(hsv => [360 * hue / 8, 1, 1]))
}
}
method save_as(filename) {
img.write(file => filename)
}
}
var plasma = Plasma(256, 256)
plasma.generate
plasma.save_as('plasma.png') |
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
| #AWK | AWK |
# syntax: GAWK -f PIG_THE_DICE_GAME.AWK
# converted from LUA
BEGIN {
players = 2
p = 1 # start with first player
srand()
printf("Enter: Hold or Roll?\n\n")
while (1) {
printf("Player %d, your score is %d, with %d temporary points\n",p,scores[p],points)
getline reply
reply = toupper(substr(reply,1,1))
if (reply == "R") {
roll = int(rand() * 6) + 1 # roll die
printf("You rolled a %d\n",roll)
if (roll == 1) {
printf("Too bad. You lost %d temporary points\n\n",points)
points = 0
p = (p % players) + 1
}
else {
points += roll
}
}
else if (reply == "H") {
scores[p] += points
points = 0
if (scores[p] >= 100) {
printf("Player %d wins with a score of %d\n",p,scores[p])
break
}
printf("Player %d, your new score is %d\n\n",p,scores[p])
p = (p % players) + 1
}
else if (reply == "Q") { # abandon game
break
}
}
exit(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
| #Sidef | Sidef | func playfair(key, from = 'J', to = (from == 'J' ? 'I' : '')) {
func canon(str) {
str.gsub(/[^[:alpha:]]/, '').uc.gsub(from, to)
}
var m = canon(key + ('A'..'Z' -> join)).chars.uniq.slices(5)
var :ENC = gather {
m.each { |r|
for i,j in (^r ~X ^r) {
i == j && next
take(Pair("#{r[i]}#{r[j]}", "#{r[(i+1)%5]}#{r[(j+1)%5]}"))
}
}
^5 -> each { |k|
var c = m.map {|a| a[k] }
for i,j in (^c ~X ^c) {
i == j && next
take(Pair("#{c[i]}#{c[j]}", "#{c[(i+1)%5]}#{c[(j+1)%5]}"))
}
}
cartesian([^5, ^5, ^5, ^5], {|i1,j1,i2,j2|
i1 == i2 && next
j1 == j2 && next
take(Pair("#{m[i1][j1]}#{m[i2][j2]}", "#{m[i1][j2]}#{m[i2][j1]}"))
})
}.map { (.key, .value) }...
var DEC = ENC.flip
func enc(red) {
gather {
var str = canon(red)
while (var m = (str =~ /(.)(?(?=\1)|(.?))/g)) {
take("#{m[0]}#{m[1] == '' ? 'X' : m[1]}")
}
}.map { ENC{_} }.join(' ')
}
func dec(black) {
canon(black).split(2).map { DEC{_} }.join(' ')
}
return(enc, dec)
}
var (encode, decode) = playfair('Playfair example')
var orig = "Hide the gold in...the TREESTUMP!!!"
say " orig:\t#{orig}"
var black = encode(orig)
say "black:\t#{black}"
var red = decode(black)
say " red:\t#{red}" |
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
| #ALGOL_68 | ALGOL 68 | BEGIN # find some pierpoint primes of the first kind (2^u3^v + 1) #
# and second kind (2^u3^v - 1) #
# construct a sieve of primes up to 10 000 #
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE 10 000;
# returns the minimum of a and b #
PROC min = ( INT a, b )INT: IF a < b THEN a ELSE b FI;
# returns TRUE if p is prime, FALSE otherwise #
PROC is prime = ( INT p )BOOL:
IF NOT ODD p
THEN p = 2
ELIF p <= UPB prime
THEN prime[ p ] # small enough to use the sieve #
ELSE # use trial division by the sieved primes #
BOOL probably prime := TRUE;
FOR d FROM 3 BY 2 WHILE d * d <= p AND probably prime DO
IF prime[ d ] THEN probably prime := p MOD d /= 0 FI
OD;
probably prime
FI; # is prime #
# sets the elements of pp1 to the first UPB pp1 Pierpoint primes of the #
# first kind and pp2 to the first UPB pp2 Pierpoint primes of the #
# second kind #
PROC find pierpoint = ( REF[]INT pp1, pp2 )VOID:
BEGIN
# saved 3-smooth values #
# - only the currently active part of the seuence is kept #
INT three smooth limit = 33;
[ 1 : three smooth limit * 3 ]INT s3s; FOR i TO UPB s3s DO s3s[ i ] := 0 OD;
INT pp1 pos := LWB pp1 - 1, pp2 pos := LWB pp2 - 1;
INT pp1 max = UPB pp1;
INT pp2 max = UPB pp2;
INT p2, p3, last2, last3;
INT s pos := s3s[ 1 ] := last2 := last3 := p2 := p3 := 1;
FOR n FROM 2 WHILE pp1 pos < pp1 max OR pp2 pos < pp2 max DO
# the next 3-smooth number is the lowest of the next #
# multiples of 2 and 3 #
INT m = min( p2, p3 );
IF pp1 pos < pp1 max THEN
IF INT first = m + 1;
is prime( first )
THEN # have a Pierpoint prime of the first kind #
pp1[ pp1 pos +:= 1 ] := first
FI
FI;
IF pp2 pos < pp2 max THEN
IF INT second = m - 1;
is prime( second )
THEN # have a Pierpoint prime of the second kind #
pp2[ pp2 pos +:= 1 ] := second
FI
FI;
s3s[ s pos +:= 1 ] := m;
IF m = p2 THEN p2 := 2 * s3s[ last2 +:= 1 ] FI;
IF m = p3 THEN p3 := 3 * s3s[ last3 +:= 1 ] FI;
INT last min = IF last2 > last3 THEN last3 ELSE last2 FI;
IF last min > three smooth limit THEN
# shuffle the sequence down, over the now unused bits #
INT new pos := 0;
FOR pos FROM last min TO s pos DO
s3s[ new pos +:= 1 ] := s3s[ pos ]
OD;
INT diff := last min - 1;
last2 -:= diff;
last3 -:= diff;
s pos -:= diff
FI
OD
END; # find pierpoint #
# prints a table of Pierpoint primes of the specified kind #
PROC print pierpoint = ( []INT primes, STRING kind )VOID:
BEGIN
print( ( "The first "
, whole( ( UPB primes + 1 ) - LWB primes, 0 )
, " Pierpoint primes of the "
, kind
, " kind:"
, newline
)
);
INT p count := 0;
FOR i FROM LWB primes TO UPB primes DO
print( ( " ", whole( primes[ i ], -8 ) ) );
IF ( p count +:= 1 ) MOD 10 = 0 THEN print( ( newline ) ) FI
OD;
print( ( newline ) )
END; # print pierpoint #
# find the first 50 Pierpoint primes of the first and second kinds #
INT max pierpoint = 50;
[ 1 : max pierpoint ]INT pfirst;
[ 1 : max pierpoint ]INT psecond;
find pierpoint( pfirst, psecond );
# show the Pierpoint primes #
print pierpoint( pfirst, "First" );
print pierpoint( psecond, "Second" )
END |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Float_Random;
procedure Pick_Random_Element is
package Rnd renames Ada.Numerics.Float_Random;
Gen: Rnd.Generator; -- used globally
type Char_Arr is array (Natural range <>) of Character;
function Pick_Random(A: Char_Arr) return Character is
-- Chooses one of the characters of A (uniformly distributed)
begin
return A(A'First + Natural(Rnd.Random(Gen) * Float(A'Last)));
end Pick_Random;
Vowels : Char_Arr := ('a', 'e', 'i', 'o', 'u');
Consonants: Char_Arr := ('t', 'n', 's', 'h', 'r', 'd', 'l');
Specials : Char_Arr := (',', '.', '?', '!');
begin
Rnd.Reset(Gen);
for J in 1 .. 3 loop
for I in 1 .. 10 loop
Ada.Text_IO.Put(Pick_Random(Consonants));
Ada.Text_IO.Put(Pick_Random(Vowels));
end loop;
Ada.Text_IO.Put(Pick_Random(Specials) & " ");
end loop;
Ada.Text_IO.New_Line;
end Pick_Random_Element; |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #XPL0 | XPL0 | include c:\cxpl\codes; \include 'code' declarations
int X, Y, W, C;
[SetVid($13); \320x200x8 graphics
for Y:= 0 to 200-1 do \for all the scan lines...
[W:= Y/50 + 1; \width of stripe = 1, 2, 3, 4
C:= 0; \set color to black so first pixel becomes white
for X:= 0 to 320-1 do \for all the pixels on a scan line...
[if rem(X/W) = 0 then C:= C xor $0F; \alternate B&W
Point(X, Y, C); \set pixel at X,Y to color C
];
];
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text display
] |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Z80_Assembly | Z80 Assembly | ;;; Display pinstripes on an MSX, using Z80 assembly.
;;; We'll use the monochrome 'text' mode to do it, by changing
;;; a few characters in the VDP font. This program will use
;;; either low resolution mode (240x192) or high resolution
;;; mode (480x192) depending on which is already active.
;;; (In MSX-DOS, `MODE 40` and `MODE 80` switch between them.)
;;;
;;; The characters are 6x8, stored row-wise, and the low two
;;; bits are ignored. This means that one-pixel alternating
;;; pinstripes are created using the following pattern:
onep: equ 0A8h ; 1 0 1 0 1 0 (0 0)
;;; A 2-pixel pattern needs two alternating characters:
twop1: equ 0CCh ; 1 1 0 0 1 1 (0 0)
twop2: equ 030h ; 0 0 1 1 0 0 (0 0)
;;; 3 * 2 = 6, so the 3-pixel pattern fits in one character:
threep: equ 0E0h ; 1 1 1 0 0 0 (0 0)
;;; And we need four characters for the 4-pixel pattern:
fourp1: equ 0F0h ; 1 1 1 1 0 0 (0 0)
fourp2: equ 03Ch ; 0 0 1 1 1 1 (0 0)
fourp3: equ 0Ch ; 0 0 0 0 1 1 (0 0)
fourp4: equ 0C0h ; 1 1 0 0 0 0 (0 0)
;;; -------------------------------------------------------------
bdos: equ 5 ; Use the BDOS routine to wait for a keypress
dirio: equ 6 ; after the drawing is done
;;; MSX ROM calls
calslt: equ 1Ch ; Interslot call
rom: equ 0FCC0h ; Main ROM slot
initxt: equ 6Ch ; Initialize text mode
;;; RAM location
linlen: equ 0F3B0h ; Contains line length, if <=40 we're in low res mode
;;; VDP data
vreg: equ 99h ; Port on which the VDP registers are accessed
vdata: equ 98h ; Port on which the VRAM is accessed
VWRITE: equ 40h ; Bit 6 in VDP address = enable writing
;;; (these are for low-res mode, high-res mode has them doubled)
font: equ 0800h ; Location of start of font data
qrtr: equ 240 ; Amount of bytes that fill a quarter of the screen
;;; -------------------------------------------------------------
org 100h
;;; Redefine characters 0-7 to the eight characters we need
ld hl,font ; Get VDP font location
call reshl ; Correct for hires mode if necessary
call setadr ; Set the VDP to read from that address
ld hl,pats ; Pattern data
ld c,8 ; Write 8 characters
wrpats: ld b,8 ; 8 lines per character
ld a,(hl) ; Load current pattern byte
wrpat: out (vdata),a ; Write it to the VDP,
djnz wrpat ; 8 times.
inc hl ; Next pattern
dec c ; Any patterns left?
jr nz,wrpats ; If so, write next pattern
ld hl,0 ; Set the VDP to write to address 0
call setadr ; which is the beginning of the text screen.
;;; Figure out how big a quarter of the screen is
ld hl,qrtr ; Get value for low resolution,
call reshl ; Correct for high res mode if necessary
push hl ; Store number on the stack
;;; Write the first quarter of the screen: 1-pixel stripes
;;; (character 0).
ld b,0
call qrtrch
;;; Write the second quarter of the screen: 2-pixel stripes
;;; (characters 1 and 2 alternating).
pop hl ; Load size from the stack
push hl
or a ; Clear carry
rr h ; Divide by 2
rr l
q2loop: ld a,1 ; Character 1,
out (vdata),a
inc a ; and character 2.
nop ; Slowdown to make sure the VDP can keep up
nop
out (vdata),a
dec hl
ld a,h ; HL = 0?
or l
jr nz,q2loop ; If not, next 2 bytes
;;; Write the third quarter of the screen: 3-pixel stripes
;;; (character 3)
ld b,3
call qrtrch
;;; Write the fourth quarter of the screen: 4-pixel stripes
;;; (characters 4, 5, 6, and 7 alternating)
pop hl ; Load size from stack
or a ; Divide by 4
rr h
rr l
or a
rr h
rr l
q4loop: ld a,4 ; Character 4
ld b,a ; 4 characters at a time
q4out: out (vdata),a ; Write the character,
inc a ; Next character,
djnz q4out ; 4 times.
dec hl
ld a,h ; Done yet?
or l
jr nz,q4loop ; If not, next 4 bytes
;;; -------------------------------------------------------------
;;; We're done, now wait for a keypress.
clear: ld c,dirio ; First, wait while a key IS pressed
ld e,0FFh ; (so we don't quit immediately if the user
call bdos ; has held the enter key a bit too long)
and a
jr nz,clear
wait: ld c,dirio ; Then, wait while a key is NOT pressed
ld e,0FFh
call bdos
and a
jr z,wait
;;; Afterwards, use a BIOS routine to reinitialize the screen
;;; (this will reload the default font).
ld iy,rom ; BIOS call to initialize text mode
ld ix,initxt
jp calslt
;;; -------------------------------------------------------------
;;; Subroutine: write character in B to a quarter of the screen
qrtrch: pop de ; Return address
pop hl ; Load size from the stack
push hl
push de ; Put return address back
qloop: ld a,b ; Write character in B
out (vdata),a
dec hl ; One fewer byte left
ld a,h ; Done yet?
or l
jr nz,qloop ; If not, next byte
ret
;;; -------------------------------------------------------------
;;; Subroutine: double HL if we are in high resolution mode
reshl: ld a,(linlen) ; Check which mode we're in
cp 41 ; Higher than 40?
ret c ; If not, we're not in hires mode
add hl,hl ; We are in hires mode, so double HL
ret
;;; -------------------------------------------------------------
;;; Subroutine: set the VDP to write to address HL.
setadr: di ; No interrupts while we're messing with VDP
xor a ; High address bits for MSX-2 VDP are all 0
out (vreg),a ; (MSX-1 VDP will just ignore the zeroes)
ld a,14|128 ; Write to register 14
out (vreg),a
ld a,l ; Write the low address byte
out (vreg),a
ld a,h
or VWRITE ; High address bits bits (5..0)
out (vreg),a ; Write high addr bits and write flag
ei ; Reenable interrupts
ret
;;; Patterns to replace the first characters with
pats: db onep,twop1,twop2,threep
db fourp1,fourp2,fourp3,fourp4 |
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
| #Run_BASIC | Run BASIC | ' Test and display primes 1 .. 50
for i = 1 TO 50
if prime(i) <> 0 then print i;" ";
next i
FUNCTION prime(n)
if n < 2 then prime = 0 : goto [exit]
if n = 2 then prime = 1 : goto [exit]
if n mod 2 = 0 then prime = 0 : goto [exit]
prime = 1
for i = 3 to int(n^.5) step 2
if n mod i = 0 then prime = 0 : goto [exit]
next i
[exit]
END FUNCTION |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module GamePig (games, strategy1, strategy2) {
Print "Game of Pig"
win1=0
win2=0
While games {
games--
dice=-1
res$=""
Player1points=0
Player1sum=0
Player2points=0
Player2sum=0
HaveWin=False
score()
\\ for simulation
simulate$=String$("R", 500)
Keyboard simulate$
\\ end simulation
while res$<>"Q" {
Print "Player 1 turn"
PlayerTurn(&Player1points, &player1sum, player2sum, ! strategy1)
if res$="Q" then exit
Player1sum+=Player1points
Score()
Print "Player 2 turn"
PlayerTurn(&Player2points,&player2sum, player1sum, ! strategy2)
if res$="Q" then exit
Player2sum+=Player2points
Score()
}
If HaveWin then {
Score()
If Player1Sum>Player2sum then {
Print "Player 1 Win"
win1++
} Else Print "Player 2 Win" : win2++
}
}
\\ use stack as FIFO
If win1>win2 Then {
Data "Player 1 Win", win1,win2, array(strategy1,0), array(strategy1,1)
} Else {
Data "Player 2 Win", win2,win1, array(strategy2,0), array(strategy2,1)
}
Sub Rolling()
dice=random(1,6)
Print "dice=";dice
End Sub
Sub PlayOrQuit()
Print "R - Roling Q-Quit"
Repeat {
res$=Ucase$(Key$)
} Until Instr("RQ", res$)>0
End Sub
Sub PlayAgain()
Print "R - Roling H - Hold Q-Quit"
Repeat {
res$=Ucase$(Key$)
} Until Instr("RHQ", res$)>0
End Sub
Sub PlayerTurn(&playerpoints, &sum, othersum, Max_Points, Min_difference)
PlayOrQuit()
If res$="Q" then Exit Sub
playerpoints=0
Rolling()
While dice<>1 and res$="R" {
playerpoints+=dice
if dice>1 and playerpoints+sum>100 then {
sum+=playerpoints
HaveWin=True
res$="Q"
} Else {
if playerpoints>=Max_Points Then If 100-othersum>Min_difference Then res$="H" : exit
PlayAgain()
if res$="R" then Rolling()
}
}
if dice=1 then playerpoints=0
End Sub
Sub Score()
Print "Player1 points="; Player1sum
Print "Player2 points="; Player2sum
End Sub
}
Flush
GamePig 20, (8,10), (12, 20)
GamePig 20, (12, 20), (8,10)
Print "Results"
While not Empty {
Read WhoWin$, winA,winb, Max_Points, Min_difference
Print WhoWin$, winA;">";winb, Max_Points, Min_difference
}
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Wren | Wren | import "graphics" for Canvas, Color, ImageData
import "dome" for Window
import "math" for Math
class PlasmaEffect {
construct new(width, height) {
Window.title = "Plasma Effect"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
_bmp = ImageData.create("plasma_effect", _w, _h)
_plasma = createPlasma() // stores the hues for the colors
}
init() {
_frame = 0
_hueShift = 0
Canvas.cls(Color.white)
}
createPlasma() {
var buffer = List.filled(_w, null)
for (x in 0..._w) {
buffer[x] = List.filled(_h, 0)
for (y in 0..._h) {
var value = Math.sin(x / 16)
value = value + Math.sin(y / 8)
value = value + Math.sin((x + y) / 16)
value = value + Math.sin((x * x + y * y).sqrt / 8)
value = value + 4 // shift range from -4 .. 4 to 0 .. 8
value = value / 8 // bring range down to 0 .. 1
if (value < 0 || value > 1) Fiber.abort("Hue value out of bounds")
buffer[x][y] = value
pset(x, y, Color.hsv(value * 360, 1, 1))
}
}
return buffer
}
pset(x, y, col) { _bmp.pset(x, y, col) }
pget(x, y) { _bmp.pget(x, y) }
update() {
_frame = _frame + 1
if (_frame % 3 == 0) { // update every 3 frames or 1/20th second
_hueShift = (_hueShift + 0.02) % 1
}
}
draw(alpha) {
for (x in 0..._w) {
for (y in 0..._h) {
var hue = (_hueShift + _plasma[x][y]) % 1
var col = Color.hsv(hue * 360, 1, 1)
pset(x, y, col)
}
}
_bmp.draw(0, 0)
}
}
var Game = PlasmaEffect.new(640, 640) |
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
| #ACL2 | ACL2 | (defun remove-nth (i xs)
(if (or (zp i) (endp (rest xs)))
(rest xs)
(cons (first xs)
(remove-nth (1- i) (rest xs)))))
(defthm remove-nth-shortens
(implies (consp xs)
(< (len (remove-nth i xs)) (len xs))))
:set-state-ok t
(defun shuffle-r (xs ys state)
(declare (xargs :measure (len xs)))
(if (endp xs)
(mv ys state)
(mv-let (idx state)
(random$ (len xs) state)
(shuffle-r (remove-nth idx xs)
(cons (nth idx xs) ys)
state))))
(defun shuffle (xs state)
(shuffle-r xs nil state))
(defun cross-r (x ys)
(if (endp ys)
nil
(cons (cons x (first ys))
(cross-r x (rest ys)))))
(defun cross (xs ys)
(if (or (endp xs) (endp ys))
nil
(append (cross-r (first xs) ys)
(cross (rest xs) ys))))
(defun make-deck ()
(cross '(ace 2 3 4 5 6 7 8 9 10 jack queen king)
'(hearts diamonds clubs spades)))
(defun print-card (card)
(cw "~x0 of ~x1~%" (car card) (cdr card)))
(defun print-deck (deck)
(if (endp deck)
nil
(progn$ (print-card (first deck))
(print-deck (rest deck)))))
(defun draw-from-deck (deck)
(mv (first deck) (rest deck)))
|
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
| #BASIC256 | BASIC256 |
numjugadores = 2
maxpuntos = 100
Dim almacenpuntos(3)
almacenpuntos[1] = 1
almacenpuntos[2] = 1
Cls: Print "The game of PIG"
Print "===============" + Chr(13) + Chr(10)
Print "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
Print "Si jugador saca 2-6, se agrega al total del turno y su turno continúa."
Print "Si jugador elige 'mantener', su total de puntos se añade a su puntuación, "
Print " y se convierte en el turno del siguiente jugador." + Chr(10)
Print "El primer jugador en anotar 100 o más puntos gana."&Chr(13)&Chr(10)
Do
For jugador = 1 To 2 #numjugadores
puntos = 0
While almacenpuntos[jugador] <= maxpuntos
Print
Print "Jugador "; jugador; ": (";almacenpuntos[jugador];",";puntos;")";
Input " ¿Tirada? (Sn) ", nuevotiro
If Upper(nuevotiro) = "S" Then
tirada = Int(Rand* 5) + 1
Print " Tirada:"; tirada
If tirada = 1 Then
Print Chr(10) + "¡Pierdes tu turno! jugador "; jugador;
Print " pero mantienes tu puntuación anterior de "; almacenpuntos[jugador]
Exit While
End If
puntos = puntos + tirada
Else
almacenpuntos[jugador] = almacenpuntos[jugador] + puntos
Print " Te quedas con: "; almacenpuntos[jugador]
If almacenpuntos[jugador] >= maxpuntos Then
Print Chr(10) + "Gana el Jugador "; jugador; " con "; almacenpuntos[jugador]; " puntos."
End
End If
Exit While
End If
End While
Next jugador
Until false
|
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
| #SQL | SQL |
--Clean up previous run
IF EXISTS (SELECT *
FROM SYS.TYPES
WHERE NAME = 'FairPlayTable')
DROP TYPE FAIRPLAYTABLE
--Set Types
CREATE TYPE FAIRPLAYTABLE AS TABLE (LETTER VARCHAR(1), COLID INT, ROWID INT)
GO
--Configuration Variables
DECLARE @KEYWORD VARCHAR(25) = 'CHARLES' --Keyword for encryption
DECLARE @INPUT VARCHAR(MAX) = 'Testing Seeconqz' --Word to be encrypted
DECLARE @Q INT = 0 -- Q removed?
DECLARE @ENCRYPT INT = 1 --Encrypt?
--Setup Variables
DECLARE @WORDS TABLE
(
WORD_PRE VARCHAR(2),
WORD_POST VARCHAR(2)
)
DECLARE @T_TABLE FAIRPLAYTABLE
DECLARE @NEXTLETTER CHAR(1)
DECLARE @WORD VARCHAR(2),
@COL1 INT,
@COL2 INT,
@ROW1 INT,
@ROW2 INT,
@TMP INT
DECLARE @SQL NVARCHAR(MAX) = '',
@COUNTER INT = 1,
@I INT = 1
DECLARE @COUNTER_2 INT = 1
SET @INPUT = REPLACE(@INPUT, ' ', '')
SET @KEYWORD = UPPER(@KEYWORD)
DECLARE @USEDLETTERS VARCHAR(MAX) = ''
DECLARE @TESTWORDS VARCHAR(2),
@A INT = 0
WHILE @COUNTER_2 <= 5
BEGIN
WHILE @COUNTER <= 5
BEGIN
IF LEN(@KEYWORD) > 0
BEGIN
SET @NEXTLETTER = LEFT(@KEYWORD, 1)
SET @KEYWORD = RIGHT(@KEYWORD, LEN(@KEYWORD) - 1)
IF CHARINDEX(@NEXTLETTER, @USEDLETTERS) = 0
BEGIN
INSERT INTO @T_TABLE
SELECT @NEXTLETTER,
@COUNTER,
@COUNTER_2
SET @COUNTER = @COUNTER + 1
SET @USEDLETTERS = @USEDLETTERS + @NEXTLETTER
END
END
ELSE
BEGIN
WHILE 1 = 1
BEGIN
IF CHARINDEX(CHAR(64 + @I), @USEDLETTERS) = 0
AND NOT ( CHAR(64 + @I) = 'Q'
AND @Q = 1 )
AND NOT ( @Q = 0
AND CHAR(64 + @I) = 'J' )
BEGIN
SET @NEXTLETTER = CHAR(64 + @I)
SET @USEDLETTERS = @USEDLETTERS + CHAR(64 + @I)
SET @I = @I + 1
BREAK
END
SET @I = @I + 1
END
-- SELECT 1 AS [T]
--BREAK
INSERT INTO @T_TABLE
SELECT @NEXTLETTER,
@COUNTER,
@COUNTER_2
SET @COUNTER = @COUNTER + 1
END
END
SET @COUNTER_2 = @COUNTER_2 + 1
SET @COUNTER = 1
END
--Split word into Digraphs
WHILE @A < 1
BEGIN
SET @TESTWORDS = UPPER(LEFT(@INPUT, 2))
IF LEN(@TESTWORDS) = 1
BEGIN
SET @TESTWORDS = @TESTWORDS + 'X'
SET @A = 1
END
ELSE IF RIGHT(@TESTWORDS, 1) = LEFT(@TESTWORDS, 1)
BEGIN
SET @TESTWORDS = RIGHT(@TESTWORDS, 1) + 'X'
SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 1)
END
ELSE
SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 2)
IF LEN(@INPUT) = 0
SET @A = 1
INSERT @WORDS
SELECT @TESTWORDS,
''
END
--Start Encryption
IF @ENCRYPT = 1
BEGIN
--Loop through Digraphs amd encrypt
DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR
SELECT WORD_PRE
FROM @WORDS
FOR UPDATE OF WORD_POST
OPEN WORDS_LOOP
FETCH NEXT FROM WORDS_LOOP INTO @WORD
WHILE @@FETCH_STATUS = 0
BEGIN
--Find letter positions
SET @ROW1 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @ROW2 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
SET @COL1 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @COL2 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
--Move positions according to encryption rules
IF @COL1 = @COL2
BEGIN
SET @ROW1 = @ROW1 + 1
SET @ROW2 = @ROW2 + 1
--select 'row'
END
ELSE IF @ROW1 = @ROW2
BEGIN
SET @COL1 = @COL1 + 1
SET @COL2 = @COL2 + 1
--select 'col'
END
ELSE
BEGIN
SET @TMP = @COL2
SET @COL2 = @COL1
SET @COL1 = @TMP
--select 'reg'
END
IF @ROW1 = 6
SET @ROW1 = 1
IF @ROW2 = 6
SET @ROW2 = 1
IF @COL1 = 6
SET @COL1 = 1
IF @COL2 = 6
SET @COL2 = 1
--Find encrypted letters by positions
UPDATE @WORDS
SET WORD_POST = (SELECT (SELECT LETTER
FROM @T_TABLE
WHERE ROWID = @ROW1
AND COLID = @COL1)
+ (SELECT LETTER
FROM @T_TABLE
WHERE COLID = @COL2
AND ROWID = @ROW2))
WHERE WORD_PRE = @WORD
FETCH NEXT FROM WORDS_LOOP INTO @WORD
END
CLOSE WORDS_LOOP
DEALLOCATE WORDS_LOOP
END
--Start Decryption
ELSE
BEGIN
--Loop through Digraphs amd decrypt
DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR
SELECT WORD_PRE
FROM @WORDS
FOR UPDATE OF WORD_POST
OPEN WORDS_LOOP
FETCH NEXT FROM WORDS_LOOP INTO @WORD
WHILE @@FETCH_STATUS = 0
BEGIN
--Find letter positions
SET @ROW1 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @ROW2 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
SET @COL1 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @COL2 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
--Move positions according to encryption rules
IF @COL1 = @COL2
BEGIN
SET @ROW1 = @ROW1 - 1
SET @ROW2 = @ROW2 - 1
--select 'row'
END
ELSE IF @ROW1 = @ROW2
BEGIN
SET @COL1 = @COL1 - 1
SET @COL2 = @COL2 - 1
--select 'col'
END
ELSE
BEGIN
SET @TMP = @COL2
SET @COL2 = @COL1
SET @COL1 = @TMP
--select 'reg'
END
IF @ROW1 = 0
SET @ROW1 = 5
IF @ROW2 = 0
SET @ROW2 = 5
IF @COL1 = 0
SET @COL1 = 5
IF @COL2 = 0
SET @COL2 = 5
--Find decrypted letters by positions
UPDATE @WORDS
SET WORD_POST = (SELECT (SELECT LETTER
FROM @T_TABLE
WHERE ROWID = @ROW1
AND COLID = @COL1)
+ (SELECT LETTER
FROM @T_TABLE
WHERE COLID = @COL2
AND ROWID = @ROW2))
WHERE WORD_PRE = @WORD
FETCH NEXT FROM WORDS_LOOP INTO @WORD
END
CLOSE WORDS_LOOP
DEALLOCATE WORDS_LOOP
END
--Output
DECLARE WORDS CURSOR LOCAL FAST_FORWARD FOR
SELECT WORD_POST
FROM @WORDS
OPEN WORDS
FETCH NEXT FROM WORDS INTO @WORD
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = @SQL + @WORD + ' '
FETCH NEXT FROM WORDS INTO @WORD
END
CLOSE WORDS
DEALLOCATE WORDS
SELECT @SQL
--Cleanup
IF EXISTS (SELECT *
FROM SYS.TYPES
WHERE NAME = 'FairPlayTable')
DROP TYPE FAIRPLAYTABLE
|
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
| #C | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int 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,
};
#define PRIME_SIZE (sizeof(PRIMES) / sizeof(int))
bool isPrime(const int n) {
int i;
if (n < 2) {
return false;
}
for (i = 0; i < PRIME_SIZE; i++) {
if (n == PRIMES[i]) {
return true;
}
if (n % PRIMES[i] == 0) {
return false;
}
}
if (n < PRIMES[PRIME_SIZE - 1] * PRIMES[PRIME_SIZE - 1]) {
return true;
}
i = PRIMES[PRIME_SIZE - 1]+2;
while (i * i < n) {
if (n % i == 0) {
return false;
}
i += 2;
}
return true;
}
#define N 50
int p[2][50];
void pierpont() {
int64_t s[8 * N];
int count = 0;
int count1 = 1;
int count2 = 0;
int i2 = 0;
int i3 = 0;
int k = 1;
int64_t n2, n3, t;
int64_t *sp = &s[1];
memset(p[0], 0, N * sizeof(int));
memset(p[1], 0, N * sizeof(int));
p[0][0] = 2;
s[0] = 1;
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]) {
*sp++ = t;
k++;
t++;
if (count1 < N && isPrime(t)) {
p[0][count1] = t;
count1++;
}
t -= 2;
if (count2 < N && isPrime(t)) {
p[1][count2] = t;
count2++;
}
count = min(count1, count2);
}
}
}
int main() {
int i;
pierpont();
printf("First 50 Pierpont primes of the first kind:\n");
for (i = 0; i < N; i++) {
printf("%8d ", p[0][i]);
if ((i - 9) % 10 == 0) {
printf("\n");
}
}
printf("\n");
printf("First 50 Pierpont primes of the second kind:\n");
for (i = 0; i < N; i++) {
printf("%8d ", p[1][i]);
if ((i - 9) % 10 == 0) {
printf("\n");
}
}
printf("\n");
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Aime | Aime | list l;
l_append(l, 'a');
l_append(l, 'b');
l_append(l, 'c');
l_append(l, 'd');
l_append(l, 'e');
l_append(l, 'f');
o_byte(l[drand(5)]);
o_byte('\n'); |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #ALGOL_68 | ALGOL 68 | # pick a random element from an array of strings #
OP PICKRANDOM = ( []STRING list )STRING:
BEGIN
INT number of elements = ( UPB list - LWB list ) + 1;
INT random element =
ENTIER ( next random * ( number of elements ) );
list[ LWB list + random element ]
END; # PICKRANDOM #
# can define additional operators for other types of array #
main: (
[]STRING days = ( "Sunday", "Monday", "Tuesday", "Wednesday"
, "Thursday", "Friday", "Saturday"
);
print( ( PICKRANDOM days, newline ) )
) |
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
| #Rust | Rust | fn is_prime(n: u64) -> bool {
match n {
0 | 1 => false,
2 => true,
_even if n % 2 == 0 => false,
_ => {
let sqrt_limit = (n as f64).sqrt() as u64;
(3..=sqrt_limit).step_by(2).find(|i| n % i == 0).is_none()
}
}
}
fn main() {
for i in (1..30).filter(|i| is_prime(*i)) {
println!("{} ", i);
}
} |
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.
| #Nim | Nim | import random, strformat
const MaxPoints = 100
type
Move {.pure.} = enum Roll, Hold
Strategy {.pure.} = enum Rand, Q2Win, AL20, AL20T
# Player description.
Player = ref object
num: Natural
currentScore: Natural
roundScore: Natural
strategy: Strategy
next: Player
# Player list managed as a singly linked ring.
PlayerList = object
count: Natural
head, tail: Player
proc addPlayer(playerList: var PlayerList; strategy: Strategy) =
## Add a player with given strategy.
inc playerList.count
let newPlayer = Player(num: playerList.count, strategy: strategy)
if playerList.head.isNil:
playerList.head = newPlayer
else:
playerList.tail.next = newPlayer
playerList.tail = newPlayer
newPlayer.next = playerList.head
iterator items(playerList: PlayerList): Player =
## Yield the successive players of a player list.
var player = playerList.head
yield player
while player != playerList.tail:
player = player.next
yield player
proc getMove(player: Player): Move =
## Get the move for the given player.
if player.roundScore + player.currentScore >= MaxPoints: return Hold
case player.strategy
of Strategy.Rand:
result = if rand(1) == 0: Roll
elif player.roundScore > 0: Hold
else: Roll
of Strategy.Q2Win:
let q = MaxPoints - player.currentScore
result = if q < 6 or player.roundScore < q div 4: Roll
else: Hold
of Strategy.AL20:
result = if player.roundScore < 20: Roll
else: Hold
of Strategy.AL20T:
let d = 5 * player.roundScore
result = if player.roundScore < 20 and d < rand(99): Roll
else: Hold
randomize()
# Create player list.
var playerList = PlayerList()
for strategy in Strategy.low..Strategy.high:
playerList.addPlayer(strategy)
var endGame = false
var player = playerList.head
while not endGame:
case player.getMove()
of Roll:
let die = rand(1..6)
if die == 1:
echo &"Player {player.num} rolled {die} Current score: {player.currentScore:3}\n"
player.roundScore = 0
player = player.next
continue
inc player.roundScore, die
echo &"Player {player.num} rolled {die} Round score: {player.roundScore:3}"
of Hold:
inc player.currentScore, player.roundScore
echo &"Player {player.num} holds Current score: {player.currentScore:3}\n"
if player.currentScore >= MaxPoints:
endGame = true
else:
player.roundScore = 0
player = player.next
for player in playerList:
let stratStr = &"({player.strategy}):"
echo &"Player {player.num} {stratStr:8} {player.currentScore:3}" |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #XPL0 | XPL0 | func real Dist(X1, Y1, X2, Y2);
int X1, Y1, X2, Y2;
return sqrt( float((X1-X2)*(X1-X2) + (Y1-Y2)*(Y1-Y2)) );
int Time, X, Y, Color;
real Value;
[SetVid($112); \640x480x24
repeat Time:= GetTime/50_000;
for Y:= 0 to 256-1 do
for X:= 0 to 256-1 do
[Value:= Sin(Dist(X+Time, Y, 128, 128) / 8.0) +
Sin(Dist(X, Y, 64, 64) / 8.0) +
Sin(Dist(X, Y+Time/7, 192, 64) / 7.0) +
Sin(Dist(X, Y, 192, 100) / 8.0);
Color:= fix((4.0+Value) * 31.875); \[0..255]
Point(X, Y, Color<<16 + ((Color*2)&$FF)<<8 + (255-Color));
];
until KeyHit;
] |
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
| #Action.21 | Action! | DEFINE PTR="CARD"
DEFINE MAXDECKSIZE="52"
TYPE Deck=[
PTR cards ;BYTE ARRAY
BYTE first,count]
BYTE FUNC IsEmpty(Deck POINTER d)
IF d.count=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC IsFull(Deck POINTER d)
IF d.count=MAXDECKSIZE THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC Index(Deck POINTER d BYTE i)
RETURN ((d.first+i) MOD MAXDECKSIZE)
PROC InitEmpty(Deck POINTER d BYTE ARRAY crds)
d.cards=crds
d.first=0
d.count=0
RETURN
PROC InitFull(Deck POINTER d BYTE ARRAY crds)
BYTE i
d.cards=crds
d.first=0
d.count=MAXDECKSIZE
FOR i=0 TO MAXDECKSIZE-1
DO
crds(i)=i
OD
RETURN
PROC Shuffle(Deck POINTER d)
BYTE i,j,i2,j2,tmp
BYTE ARRAY crds
crds=d.cards
i=d.count-1
WHILE i>0
DO
j=Rand(i)
i2=Index(d,i)
j2=Index(d,j)
tmp=crds(i2)
crds(i2)=crds(j2)
crds(j2)=tmp
i==-1
OD
RETURN
BYTE FUNC Deal(Deck POINTER d)
BYTE ARRAY crds
BYTE c
IF IsEmpty(d) THEN
PrintE("Error: deck is empty!")
Break()
FI
crds=d.cards
c=crds(d.first)
d.count==-1
d.first==+1
IF d.first=MAXDECKSIZE THEN
d.first=0
FI
RETURN (c)
PROC Add(Deck POINTER d BYTE c)
BYTE ARRAY crds
BYTE i
IF IsFull(d) THEN
PrintE("Error: deck is full!")
Break()
FI
crds=d.cards
i=Index(d,d.count)
crds(i)=c
d.count==+1
RETURN
PROC PrintCard(BYTE c)
BYTE s,v
BYTE ARRAY fig=['J 'Q 'K 'A]
BYTE ARRAY suit=[16 96 0 123]
s=c/13 v=c MOD 13
IF v<=8 THEN
PrintB(v+2)
ELSE
Put(fig(v-9))
FI
Put(suit(s))
RETURN
PROC PrintDeck(Deck POINTER d)
BYTE i,i2
BYTE ARRAY crds
crds=d.cards
IF IsEmpty(d) THEN
Print("Empty")
ELSE
FOR i=0 TO d.count-1
DO
i2=Index(d,i)
PrintCard(crds(i2))
IF i<d.count-1 THEN
Put(' )
FI
OD
FI
RETURN
PROC Main()
BYTE LMARGIN=$52,oldLMARGIN,i,c
BYTE ARRAY crds(MAXDECKSIZE),crds1(MAXDECKSIZE),crds2(MAXDECKSIZE)
Deck d,d1,d2
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
PrintE("New deck:")
InitFull(d,crds)
PrintDeck(d) PutE() PutE()
PrintE("Shuffle:")
Shuffle(d)
PrintDeck(d) PutE() PutE()
PrintE("Deal cards:")
InitEmpty(d1,crds1) InitEmpty(d2,crds2)
FOR i=1 TO 5
DO
c=Deal(d) Add(d1,c)
c=Deal(d) Add(d2,c)
OD
Print(" Player 1: ") PrintDeck(d1) PutE()
Print(" Player 2: ") PrintDeck(d2) PutE() PutE()
PrintE("Deck after dealing:")
PrintDeck(d)
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN |
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 | C |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int NUM_PLAYERS = 2;
const int MAX_POINTS = 100;
//General functions
int randrange(int min, int max){
return (rand() % (max - min + 1)) + min;
}
//Game functions
void ResetScores(int *scores){
for(int i = 0; i < NUM_PLAYERS; i++){
scores[i] = 0;
}
}
void Play(int *scores){
int scoredPoints = 0;
int diceResult;
int choice;
for(int i = 0; i < NUM_PLAYERS; i++){
while(1){
printf("Player %d - You have %d total points and %d points this turn \nWhat do you want to do (1)roll or (2)hold: ", i + 1, scores[i], scoredPoints);
scanf("%d", &choice);
if(choice == 1){
diceResult = randrange(1, 6);
printf("\nYou rolled a %d\n", diceResult);
if(diceResult != 1){
scoredPoints += diceResult;
}
else{
printf("You loose all your points from this turn\n\n");
scoredPoints = 0;
break;
}
}
else if(choice == 2){
scores[i] += scoredPoints;
printf("\nYou holded, you have %d points\n\n", scores[i]);
break;
}
}
scoredPoints = 0;
CheckForWin(scores[i], i + 1);
}
}
void CheckForWin(int playerScore, int playerNum){
if(playerScore >= MAX_POINTS){
printf("\n\nCONGRATULATIONS PLAYER %d, YOU WIN\n\n!", playerNum);
exit(EXIT_SUCCESS);
}
}
int main()
{
srand(time(0));
int scores[NUM_PLAYERS];
ResetScores(scores);
while(1){
Play(scores);
}
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
| #Tcl | Tcl | package require TclOO
oo::class create Playfair {
variable grid lookup excluder
constructor {{keyword "PLAYFAIR EXAMPLE"} {exclude "J"}} {
# Tweaking according to exact operation mode
if {$exclude eq "J"} {
set excluder "J I"
} else {
set excluder [list $exclude ""]
}
# Clean up the keyword source
set keys [my Clean [append keyword "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]]
# Generate the encoding grid
set grid [lrepeat 5 [lrepeat 5 ""]]
set idx -1
for {set i 0} {$i < 5} {incr i} {for {set j 0} {$j < 5} {} {
if {![info exist lookup([set c [lindex $keys [incr idx]]])]} {
lset grid $i $j $c
set lookup($c) [list $i $j]
incr j
}
}}
# Sanity check
if {[array size lookup] != 25} {
error "failed to build encoding table correctly"
}
}
# Worker to apply a consistent cleanup/split rule
method Clean {str} {
set str [string map $excluder [string toupper $str]]
split [regsub -all {[^A-Z]} $str ""] ""
}
# These public methods are implemented by a single non-public method
forward encode my Transform 1
forward decode my Transform -1
# The application of the Playfair cypher transform
method Transform {direction message} {
# Split message into true digraphs
foreach c [my Clean $message] {
if {![info exists lookup($c)]} continue
if {![info exists c0]} {
set c0 $c
} else {
if {$c0 ne $c} {
lappend digraphs $c0 $c
unset c0
} else {
lappend digraphs $c0 "X"
set c0 $c
}
}
}
if {[info exists c0]} {
lappend digraphs $c0 "Z"
}
# Encode the digraphs
set result ""
foreach {a b} $digraphs {
lassign $lookup($a) ai aj
lassign $lookup($b) bi bj
if {$ai == $bi} {
set aj [expr {($aj + $direction) % 5}]
set bj [expr {($bj + $direction) % 5}]
} elseif {$aj == $bj} {
set ai [expr {($ai + $direction) % 5}]
set bi [expr {($bi + $direction) % 5}]
} else {
set tmp $aj
set aj $bj
set bj $tmp
}
lappend result [lindex $grid $ai $aj][lindex $grid $bi $bj]
}
# Real use would be: return [join $result ""]
return $result
}
} |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Numerics;
namespace PierpontPrimes {
public static class Helper {
private static readonly Random rand = new Random();
private static readonly List<int> primeList = new List<int>() {
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,
};
public static BigInteger GetRandom(BigInteger min, BigInteger max) {
var bytes = max.ToByteArray();
BigInteger r;
do {
rand.NextBytes(bytes);
bytes[bytes.Length - 1] &= (byte)0x7F; // force sign bit to positive
r = new BigInteger(bytes);
} while (r < min || r >= max);
return r;
}
//Modified from https://rosettacode.org/wiki/Miller-Rabin_primality_test#Python
public static bool IsProbablePrime(this BigInteger n) {
if (n == 0 || n == 1) {
return false;
}
bool Check(BigInteger num) {
foreach (var prime in primeList) {
if (num == prime) {
return true;
}
if (num % prime == 0) {
return false;
}
if (prime * prime > num) {
return true;
}
}
return true;
}
if (Check(n)) {
var large = primeList[primeList.Count - 1];
if (n <= large) {
return true;
}
}
var s = 0;
var d = n - 1;
while (d.IsEven) {
d >>= 1;
s++;
}
bool TrialComposite(BigInteger a) {
if (BigInteger.ModPow(a, d, n) == 1) {
return false;
}
for (int i = 0; i < s; i++) {
var t = BigInteger.Pow(2, i);
if (BigInteger.ModPow(a, t * d, n) == n - 1) {
return false;
}
}
return true;
}
for (int i = 0; i < 8; i++) {
var a = GetRandom(2, n);
if (TrialComposite(a)) {
return false;
}
}
return true;
}
}
class Program {
static List<List<BigInteger>> Pierpont(int n) {
var p = new List<List<BigInteger>> {
new List<BigInteger>(),
new List<BigInteger>()
};
for (int i = 0; i < n; i++) {
p[0].Add(0);
p[1].Add(0);
}
p[0][0] = 2;
var count = 0;
var count1 = 1;
var count2 = 0;
List<BigInteger> s = new List<BigInteger> { 1 };
var i2 = 0;
var i3 = 0;
var k = 1;
BigInteger n2;
BigInteger n3;
BigInteger 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.Add(t);
k++;
t += 1;
if (count1 < n && t.IsProbablePrime()) {
p[0][count1] = t;
count1++;
}
t -= 2;
if (count2 < n && t.IsProbablePrime()) {
p[1][count2] = t;
count2++;
}
count = Math.Min(count1, count2);
}
}
return p;
}
static void Main() {
var p = Pierpont(250);
Console.WriteLine("First 50 Pierpont primes of the first kind:");
for (int i = 0; i < 50; i++) {
Console.Write("{0,8} ", p[0][i]);
if ((i - 9) % 10 == 0) {
Console.WriteLine();
}
}
Console.WriteLine();
Console.WriteLine("First 50 Pierpont primes of the second kind:");
for (int i = 0; i < 50; i++) {
Console.Write("{0,8} ", p[1][i]);
if ((i - 9) % 10 == 0) {
Console.WriteLine();
}
}
Console.WriteLine();
Console.WriteLine("250th Pierpont prime of the first kind: {0}", p[0][249]);
Console.WriteLine("250th Pierpont prime of the second kind: {0}", p[1][249]);
Console.WriteLine();
}
}
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #APL | APL | pickRandom ← (?≢)⊃⊢ |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #App_Inventor | App Inventor | get some item of [1, "two", pi, "4", 5 > 4, 5 + 1, Sunday] |
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
| #S-BASIC | S-BASIC |
$lines
$constant FALSE = 0
$constant TRUE = 0FFFFH
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
rem - return true (-1) if n is prime, otherwise false (0)
function isprime(n = integer) = integer
var i, limit, result = integer
if n = 2 then
result = TRUE
else if (n < 2) or (mod(n,2) = 0) then
result = FALSE
else
begin
limit = int(sqr(n))
i = 3
while (i <= limit) and (mod(n, i) <> 0) do
i = i + 2
result = not (i <= limit)
end
end = result
rem - test by looking for primes in range 1 to 50
var i = integer
for i = 1 to 50
if isprime(i) then print using "#####";i;
next i
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.
| #Perl | Perl | my $GOAL = 100;
package Player;
sub new {
my ($class,$strategy) = @_;
my $self = {
score => 0,
rolls => 0,
ante => 0,
strategy => $strategy || sub { 0 } # as fallback, always roll again
};
return bless($self, $class);
}
sub turn {
my ($P) = @_;
$P->{rolls} = 0;
$P->{ante} = 0;
my $done = 0;
do {
my $v = 1 + int rand 6;
$P->{rolls}++;
if ($v == 1) {
$P->{ante} = 0;
$done = 1;
} else {
$P->{ante} += $v;
}
$done = 1 if $P->{score} + $P->{ante} >= $GOAL or $P->{strategy}();
} until $done;
$P->{score} += $P->{ante};
}
package Main;
# 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( sub { $players[1]->{rolls} >= 5 } );
# try to accumulate at least 20 points per turn
@players[2] = Player->new( sub { $players[2]->{ante} > 20 } );
# random but 90% chance of rolling again
$players[3] = Player->new( sub { rand() < 0.1 } );
# random but more conservative as approaches goal
$players[4] = Player->new( sub { rand() < ( $GOAL - $players[4]->{score} ) * .6 / $GOAL } );
for (1 .. shift || 100) {
my $player = -1;
do {
$player++;
@players[$player % @players]->turn;
} until $players[$player % @players]->{score} >= $GOAL;
$wins[$player % @players]++;
printf "%5d", $players[$_]->{score} for 0..$#players; print "\n";
$players[$_]->{score} = 0 for 0..$#players; # reset scores for next game
}
print ' ----' x @players, "\n";
printf "%5d", $_ for @wins; print "\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
| #11l | 11l | V phrase = ‘rosetta code phrase reversal’
print(reversed(phrase))
print(phrase.split(‘ ’).map(word -> reversed(word)).join(‘ ’))
print(reversed(phrase.split(‘ ’)).join(‘ ’)) |
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
| #Ada | Ada | MODE CARD = STRUCT(STRING pip, suit); # instance attributes #
# class members & attributes #
STRUCT(
PROC(REF CARD, STRING, STRING)VOID init,
FORMAT format,
PROC(REF CARD)STRING repr,
[]STRING suits, pips
) class card = (
# PROC init = # (REF CARD self, STRING pip, suit)VOID:(
pip OF self:=pip;
suit OF self :=suit
),
# format = # $"("g" OF "g")"$,
# PROC repr = # (REF CARD self)STRING: (
HEAP STRING out; putf(BOOK out,(format OF class card,self)); out
),
# suits = # ("Clubs","Hearts","Spades","Diamonds"),
# pips = # ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
);
MODE DECK = STRUCT(REF[]CARD deck); # instance attributes #
# class members & attributes #
STRUCT(
PROC(REF DECK)VOID init, shuffle,
PROC(REF DECK)STRING repr,
PROC(REF DECK)CARD deal
) class deck = (
# PROC init = # (REF DECK self)VOID:(
HEAP[ UPB suits OF class card * UPB pips OF class card ]CARD new;
FOR suit TO UPB suits OF class card DO
FOR pip TO UPB pips OF class card DO
new[(suit-1)*UPB pips OF class card + pip] :=
((pips OF class card)[pip], (suits OF class card)[suit])
OD
OD;
deck OF self := new
),
# PROC shuffle = # (REF DECK self)VOID:
FOR card TO UPB deck OF self DO
CARD this card = (deck OF self)[card];
INT random card = random int(LWB deck OF self,UPB deck OF self);
(deck OF self)[card] := (deck OF self)[random card];
(deck OF self)[random card] := this card
OD,
# PROC repr = # (REF DECK self)STRING: (
FORMAT format = $"("n(UPB deck OF self-1)(f(format OF class card)", ")f(format OF class card)")"$;
HEAP STRING out; putf(BOOK out,(format, deck OF self)); out
),
# PROC deal = # (REF DECK self)CARD: (
(shuffle OF class deck)(self);
(deck OF self)[UPB deck OF self]
)
);
# associate a STRING with a FILE for easy text manipulation #
OP BOOK = (REF STRING string)REF FILE:(
HEAP FILE book;
associate(book, string);
book
);
# Pick a random integer between from [lwb..upb] #
PROC random int = (INT lwb, upb)INT:
ENTIER(random * (upb - lwb + 1) + lwb);
DECK deck;
(init OF class deck)(deck);
(shuffle OF class deck)(deck);
print (((repr OF class deck)(deck), 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
| #C.23 | C# |
using System;
using System.IO;
namespace Pig {
class Roll {
public int TotalScore{get;set;}
public int RollScore{get;set;}
public bool Continue{get;set;}
}
class Player {
public String Name{get;set;}
public int Score {get;set;}
Random rand;
public Player() {
Score = 0;
rand = new Random();
}
public Roll Roll(int LastScore){
Roll roll = new Roll();
roll.RollScore = rand.Next(6) + 1;
if(roll.RollScore == 1){
roll.TotalScore = 0;
roll.Continue = false;
return roll;
}
roll.TotalScore = LastScore + roll.RollScore;
roll.Continue = true;
return roll;
}
public void FinalizeTurn(Roll roll){
Score = Score + roll.TotalScore;
}
}
public class Game {
public static void Main(String[] argv){
String input = null;
Player[] players = new Player[2];
// Game loop
while(true){
Console.Write("Greetings! Would you like to play a game (y/n)?");
while(input == null){
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
players[0] = new Player();
players[1] = new Player();
Console.Write("Player One, what's your name?");
input = Console.ReadLine();
players[0].Name = input;
Console.Write("Player Two, what's your name?");
input = Console.ReadLine();
players[1].Name = input;
Console.WriteLine(players[0].Name + " and " + players[1].Name + ", prepare to do battle!");
} else if (input.ToLowerInvariant() == "n"){
goto Goodbye; /* Not considered harmful */
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
// Play the game
int currentPlayer = 0;
Roll roll = null;
bool runTurn = true;
while(runTurn){
Player p = players[currentPlayer];
roll = p.Roll( (roll !=null) ? roll.TotalScore : 0 );
if(roll.Continue){
if(roll.TotalScore + p.Score > 99){
Console.WriteLine("Congratulations, " + p.Name + "! You rolled a " + roll.RollScore + " for a final score of " + (roll.TotalScore + p.Score) + "!");
runTurn = false;
} else {
Console.Write(p.Name + ": Roll " + roll.RollScore + "/Turn " + roll.TotalScore + "/Total " + (roll.TotalScore + p.Score) + ". Roll again (y/n)?");
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
// Do nothing
} else if (input.ToLowerInvariant() == "n"){
p.FinalizeTurn(roll);
currentPlayer = Math.Abs(currentPlayer - 1);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
Console.WriteLine(players[currentPlayer].Name + ", your turn begins.");
roll = null;
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
} else {
Console.WriteLine(p.Name + @", you rolled a 1 and lost your points for this turn.
Your current score: " + p.Score);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
currentPlayer = Math.Abs(currentPlayer - 1);
}
}
input = null;
}
Goodbye:
Console.WriteLine("Thanks for playing, and remember: the house ALWAYS wins!");
System.Environment.Exit(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
| #VBA | VBA |
Option Explicit
Private Type Adress
Row As Integer
Column As Integer
End Type
Private myTable() As String
Sub Main()
Dim keyw As String, boolQ As Boolean, text As String, test As Long
Dim res As String
keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example")
If keyw = "" Then GoTo ErrorHand
Debug.Print "Enter your keyword : " & keyw
boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes
Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N")
Debug.Print ""
Debug.Print "Table : "
myTable = CreateTable(keyw, boolQ)
On Error GoTo ErrorHand
test = UBound(myTable)
On Error GoTo 0
text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump")
If text = "" Then GoTo ErrorHand
Debug.Print ""
Debug.Print "Text to encode : " & text
Debug.Print "-------------------------------------------------"
res = Encode(text)
Debug.Print "Encoded text is : " & res
res = Decode(res)
Debug.Print "Decoded text is : " & res
text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump")
If text = "" Then GoTo ErrorHand
Debug.Print ""
Debug.Print "Text to encode : " & text
Debug.Print "-------------------------------------------------"
res = Encode(text)
Debug.Print "Encoded text is : " & res
res = Decode(res)
Debug.Print "Decoded text is : " & res
Exit Sub
ErrorHand:
Debug.Print "error"
End Sub
Private Function CreateTable(strKeyword As String, Q As Boolean) As String()
Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer
Dim strT As String, coll As New Collection
Dim s As String
strKeyword = UCase(Replace(strKeyword, " ", ""))
If Q Then
If InStr(strKeyword, "J") > 0 Then
Debug.Print "Your keyword isn't available with your choice : Not Q (==> J) !"
Exit Function
End If
Else
If InStr(strKeyword, "Q") > 0 Then
Debug.Print "Your keyword isn't available with your choice : Q (==> Not J) !"
Exit Function
End If
End If
strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ")
t = Split(StrConv(strKeyword, vbUnicode), Chr(0))
For c = LBound(t) To UBound(t) - 1
strT = Replace(strT, t(c), "")
On Error Resume Next
coll.Add t(c), t(c)
On Error GoTo 0
Next
strKeyword = vbNullString
For c = 1 To coll.Count
strKeyword = strKeyword & coll(c)
Next
t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))
c = 1: r = 1
For cpt = LBound(t) To UBound(t) - 1
temp(r, c) = t(cpt)
s = s & " " & t(cpt)
c = c + 1
If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = ""
Next
CreateTable = temp
End Function
Private Function Encode(s As String) As String
Dim i&, t() As String, cpt&
s = UCase(Replace(s, " ", ""))
'insert "X"
For i = 1 To Len(s) - 1
If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i)
Next
'Do the pairs
For i = 1 To Len(s) Step 2
ReDim Preserve t(cpt)
t(cpt) = Mid(s, i, 2)
cpt = cpt + 1
Next i
If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X"
Debug.Print "[the pairs : " & Join(t, " ") & "]"
'swap the pairs
For i = LBound(t) To UBound(t)
t(i) = SwapPairsEncoding(t(i))
Next
Encode = Join(t, " ")
End Function
Private Function SwapPairsEncoding(s As String) As String
Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean
Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress
d1 = Left(s, 1): d2 = Right(s, 1)
For r = 1 To 5
For c = 1 To 5
If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c
If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c
If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For
Next
If Flag Then Exit For
Next
Select Case True
Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column
'same row, different columns
resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)
resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)
SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)
Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column
'same columns, different rows
resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)
resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)
SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)
Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column
'different rows, different columns
resD1.Row = addD1.Row
resD2.Row = addD2.Row
resD1.Column = addD2.Column
resD2.Column = addD1.Column
SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)
End Select
End Function
Private Function Decode(s As String) As String
Dim t, i&, j&, e&
t = Split(s, " ")
e = UBound(t) - 1
'swap the pairs
For i = LBound(t) To UBound(t)
t(i) = SwapPairsDecoding(CStr(t(i)))
Next
'remove "X"
For i = LBound(t) To e
If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then
t(i) = Left(t(i), 1) & Left(t(i + 1), 1)
For j = i + 1 To UBound(t) - 1
t(j) = Right(t(j), 1) & Left(t(j + 1), 1)
Next j
If Right(t(j), 1) = "X" Then
ReDim Preserve t(j - 1)
Else
t(j) = Right(t(j), 1) & "X"
End If
ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then
For j = i + 1 To UBound(t) - 1
t(j) = Right(t(j), 1) & Left(t(j + 1), 1)
Next j
If Right(t(j), 1) = "X" Then
ReDim Preserve t(j - 1)
Else
t(j) = Right(t(j), 1) & "X"
End If
End If
Next
Decode = Join(t, " ")
End Function
Private Function SwapPairsDecoding(s As String) As String
Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean
Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress
d1 = Left(s, 1): d2 = Right(s, 1)
For r = 1 To 5
For c = 1 To 5
If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c
If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c
If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For
Next
If Flag Then Exit For
Next
Select Case True
Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column
'same row, different columns
resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)
resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)
SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)
Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column
'same columns, different rows
resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)
resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)
SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)
Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column
'different rows, different columns
resD1.Row = addD1.Row
resD2.Row = addD2.Row
resD1.Column = addD2.Column
resD2.Column = addD1.Column
SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)
End Select
End Function |
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
| #C.2B.2B | C++ | #include <cassert>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
using big_int = mpz_class;
bool is_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25);
}
template <typename integer>
class n_smooth_generator {
public:
explicit n_smooth_generator(size_t n);
integer next();
size_t size() const {
return results_.size();
}
private:
std::vector<size_t> primes_;
std::vector<size_t> index_;
std::vector<integer> results_;
std::vector<integer> queue_;
};
template <typename integer>
n_smooth_generator<integer>::n_smooth_generator(size_t n) {
for (size_t p = 2; p <= n; ++p) {
if (is_prime(p)) {
primes_.push_back(p);
queue_.push_back(p);
}
}
index_.assign(primes_.size(), 0);
results_.push_back(1);
}
template <typename integer>
integer n_smooth_generator<integer>::next() {
integer last = results_.back();
for (size_t i = 0, n = primes_.size(); i < n; ++i) {
if (queue_[i] == last)
queue_[i] = results_[++index_[i]] * primes_[i];
}
results_.push_back(*min_element(queue_.begin(), queue_.end()));
return last;
}
void print_vector(const std::vector<big_int>& numbers) {
for (size_t i = 0, n = numbers.size(); i < n; ++i) {
std::cout << std::setw(9) << numbers[i];
if ((i + 1) % 10 == 0)
std::cout << '\n';
}
std::cout << '\n';
}
int main() {
const int max = 250;
std::vector<big_int> first, second;
int count1 = 0;
int count2 = 0;
n_smooth_generator<big_int> smooth_gen(3);
big_int p1, p2;
while (count1 < max || count2 < max) {
big_int n = smooth_gen.next();
if (count1 < max && is_prime(n + 1)) {
p1 = n + 1;
if (first.size() < 50)
first.push_back(p1);
++count1;
}
if (count2 < max && is_prime(n - 1)) {
p2 = n - 1;
if (second.size() < 50)
second.push_back(p2);
++count2;
}
}
std::cout << "First 50 Pierpont primes of the first kind:\n";
print_vector(first);
std::cout << "First 50 Pierpont primes of the second kind:\n";
print_vector(second);
std::cout << "250th Pierpont prime of the first kind: " << p1 << '\n';
std::cout << "250th Pierpont prime of the second kind: " << p2 << '\n';
return 0;
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #AppleScript | AppleScript | get some item of [1, "two", pi, "4", 5 > 4, 5 + 1, Sunday] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Arturo | Arturo | fruit: ["apple" "banana" "pineapple" "apricot" "watermelon"]
print sample fruit |
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
| #S-lang | S-lang | define is_prime(n)
{
if (n == 2) return(1);
if (n <= 1) return(0);
if ((n & 1) == 0) return(0);
variable mx = int(sqrt(n)), i;
_for i (3, mx, 1) {
if ((n mod i) == 0)
return(0);
}
return(1);
}
define ptest()
{
variable lst = {};
_for $1 (1, 64, 1)
if (is_prime($1))
list_append(lst, string($1));
print(strjoin(list_to_array(lst), ", "));
}
ptest(); |
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.
| #Phix | Phix | with javascript_semantics
constant maxScore = 100
function one_game(sequence strategies)
integer numPlayers = length(strategies),
points = 0, -- points accumulated in current turn, 0=swap turn
rolls = 0, -- number of rolls
player = rand(numPlayers) -- start with a random player
sequence scores = repeat(0,numPlayers)
while true do
integer roll = rand(6)
if roll=1 then
points = 0 -- swap turn
else
points += roll
if scores[player]+points>=maxScore then exit end if
rolls += 1
integer play = strategies[player]
if not play(scores,player,points,rolls) then
scores[player] += points
points = 0 -- swap turn
end if
end if
if points=0 then
player = mod(player,numPlayers) + 1
rolls = 0
end if
end while
return player
end function
-- each strategy returns true to roll, false to hold.
function strategy1(sequence /*scores*/, integer /*player*/, points, /*rolls*/)
return points<20 -- roll until 20 or more
end function
function strategy2(sequence /*scores*/, integer /*player*/, /*points*/, rolls)
return rolls<4 -- roll 4 times
end function
function strategy3(sequence scores, integer player, points, /*rolls*/)
-- roll until 20 or score>80
return points<20 or scores[player]+points>80
end function
function strategy4(sequence scores, integer player, points, /*rolls*/)
-- roll until 20 or any player has >71
for i=1 to length(scores) do
if scores[i]>71 then return true end if
end for
return points<20
end function
constant strategies = {strategy1,strategy2,strategy3,strategy4},
numStrategies = length(strategies),
numOpponents = numStrategies-1
-- play each strategy 1000 times against all combinations of other strategies
for s=1 to numStrategies do
integer strategy = strategies[s],
mask = power(2,numOpponents)-1,
wins = 0
sequence opponents = deep_copy(strategies)
opponents[s..s] = {} -- (ie all others only)
for m=1 to mask do -- (all possible bit settings, bar 0, eg/ie 1..7)
sequence game = {strategy}
for g=1 to numOpponents do
if and_bits(m,power(2,g-1)) then
game &= opponents[g]
end if
end for
for n=1 to 1000 do
wins += one_game(game)=1
end for
end for
printf(1,"strategy %d: %d wins\n",{s,wins})
end for
|
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
| #Action.21 | Action! | PROC ReversePart(CHAR ARRAY src,dst BYTE start,len)
BYTE i
FOR i=0 TO len-1
DO
dst(start+len-i-1)=src(start+i)
OD
RETURN
PROC ReverseString(CHAR ARRAY src,dst)
BYTE i
dst(0)=src(0)
ReversePart(src,dst,1,src(0))
RETURN
PROC ReverseInWords(CHAR ARRAY src,dst)
BYTE i,start
dst(0)=src(0)
i=1
WHILE i<=src(0)
DO
IF src(i)=32 THEN
dst(i)=32 i==+1
ELSE
start=i
WHILE i<=src(0) AND src(i)#32
DO i==+1 OD
ReversePart(src,dst,start,i-start)
FI
OD
RETURN
PROC ReverseWords(CHAR ARRAY src,dst)
CHAR ARRAY tmp(100)
ReverseString(src,tmp)
ReverseInWords(tmp,dst)
RETURN
PROC Main()
CHAR ARRAY s="rosetta code phrase reversal",rev(100)
PrintE(s)
ReverseString(s,rev)
PrintE(rev)
ReverseInWords(s,rev)
PrintE(rev)
ReverseWords(s,rev)
PrintE(rev)
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
| #Ada | Ada | <with Ada.Text_IO, Simple_Parse;
procedure Phrase_Reversal is
function Reverse_String (Item : String) return String is
Result : String (Item'Range);
begin
for I in Item'range loop
Result (Result'Last - I + Item'First) := Item (I);
end loop;
return Result;
end Reverse_String;
function Reverse_Words(S: String) return String is
Cursor: Positive := S'First;
Word: String := Simple_Parse.Next_Word(S, Cursor);
begin
if Cursor > S'Last then -- Word holds the last word
return Reverse_String(Word);
else
return Reverse_String(Word) & " " & Reverse_Words(S(Cursor .. S'Last));
end if;
end Reverse_Words;
function Reverse_Order(S: String) return String is
Cursor: Positive := S'First;
Word: String := Simple_Parse.Next_Word(S, Cursor);
begin
if Cursor > S'Last then -- Word holds the last word
return Word;
else
return Reverse_Order(S(Cursor .. S'Last)) & " " & Word;
end if;
end Reverse_Order;
Phrase: String := "rosetta code phrase reversal";
use Ada.Text_IO;
begin
Put_Line("0. The original phrase: """ & Phrase & """");
Put_Line("1. Reverse the entire phrase: """ & Reverse_String(Phrase) & """");
Put_Line("2. Reverse words, same order: """ & Reverse_Words(Phrase) & """");
Put_Line("2. Reverse order, same words: """ & Reverse_Order(Phrase) & """");
end Phrase_Reversal; |
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
| #ALGOL_68 | ALGOL 68 | MODE CARD = STRUCT(STRING pip, suit); # instance attributes #
# class members & attributes #
STRUCT(
PROC(REF CARD, STRING, STRING)VOID init,
FORMAT format,
PROC(REF CARD)STRING repr,
[]STRING suits, pips
) class card = (
# PROC init = # (REF CARD self, STRING pip, suit)VOID:(
pip OF self:=pip;
suit OF self :=suit
),
# format = # $"("g" OF "g")"$,
# PROC repr = # (REF CARD self)STRING: (
HEAP STRING out; putf(BOOK out,(format OF class card,self)); out
),
# suits = # ("Clubs","Hearts","Spades","Diamonds"),
# pips = # ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
);
MODE DECK = STRUCT(REF[]CARD deck); # instance attributes #
# class members & attributes #
STRUCT(
PROC(REF DECK)VOID init, shuffle,
PROC(REF DECK)STRING repr,
PROC(REF DECK)CARD deal
) class deck = (
# PROC init = # (REF DECK self)VOID:(
HEAP[ UPB suits OF class card * UPB pips OF class card ]CARD new;
FOR suit TO UPB suits OF class card DO
FOR pip TO UPB pips OF class card DO
new[(suit-1)*UPB pips OF class card + pip] :=
((pips OF class card)[pip], (suits OF class card)[suit])
OD
OD;
deck OF self := new
),
# PROC shuffle = # (REF DECK self)VOID:
FOR card TO UPB deck OF self DO
CARD this card = (deck OF self)[card];
INT random card = random int(LWB deck OF self,UPB deck OF self);
(deck OF self)[card] := (deck OF self)[random card];
(deck OF self)[random card] := this card
OD,
# PROC repr = # (REF DECK self)STRING: (
FORMAT format = $"("n(UPB deck OF self-1)(f(format OF class card)", ")f(format OF class card)")"$;
HEAP STRING out; putf(BOOK out,(format, deck OF self)); out
),
# PROC deal = # (REF DECK self)CARD: (
(shuffle OF class deck)(self);
(deck OF self)[UPB deck OF self]
)
);
# associate a STRING with a FILE for easy text manipulation #
OP BOOK = (REF STRING string)REF FILE:(
HEAP FILE book;
associate(book, string);
book
);
# Pick a random integer between from [lwb..upb] #
PROC random int = (INT lwb, upb)INT:
ENTIER(random * (upb - lwb + 1) + lwb);
DECK deck;
(init OF class deck)(deck);
(shuffle OF class deck)(deck);
print (((repr OF class deck)(deck), new line)) |
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.