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 (lod...
#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) / ...
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 ...
#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]}}}...
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 pi...
#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...
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 pi...
#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.   ...
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 ...
#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 dur...
#C.2B.2B
C++
  #include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int PLAYERS = 4, MAX_POINT...
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 (lod...
#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 (/ ...
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 ...
#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...
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 pi...
#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..$...
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 ...
#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 dur...
#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 :acc...
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 (lod...
#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 => {hs...
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 ...
#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 al...
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 pi...
#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 (p...
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 pi...
#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 (p...
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 ...
#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 dur...
#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...
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 (lod...
#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) ...
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 (lod...
#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++) ...
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 ...
#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 ...
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 pi...
#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...
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 ...
#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 dur...
#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 ...
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 (lod...
#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_...
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 ...
#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; ...
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 pi...
#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))   #Cre...
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 ...
#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 dur...
#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 g...
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 (lod...
#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)) (defi...
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 (lod...
#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(sq...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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 = ...
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 ...
#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...
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 pi...
#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)...
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 pi...
#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((...
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 ...
#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 dur...
#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 (lod...
#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(...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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 PigTheDiceGa...
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 ...
#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.""" d...
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 pi...
#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,...
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 pi...
#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) ...
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 ...
#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 ...
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 dur...
#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 (lod...
#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| buf...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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, Opp...
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 ...
#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...
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] ;retriev...
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 pi...
#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 pi...
#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 $...
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 ...
#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 dur...
#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....
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 (lod...
#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()...
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 (lod...
#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)...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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 GuiC...
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 ...
#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 ...
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 pi...
#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"), // whi...
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 ...
#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 dur...
#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 >...
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 (lod...
#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)) ...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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 = toupp...
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 ...
#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 == ...
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#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; #...
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 ...
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 pi...
#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 bec...
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 pi...
#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, `M...
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 ...
#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 ...
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 dur...
#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 ...
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 (lod...
#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 = ...
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#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 (xarg...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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 ...
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 ...
#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' -...
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#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...
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 a...
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#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).f...
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 dur...
#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 man...
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 (lod...
#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...
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#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...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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++){ ...
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 ...
#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...
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#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...
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 ...
#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 <...
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 dur...
#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-...
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#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 mu...
#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 ...
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#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...
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 ...
#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 Err...
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#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_...
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 ...
#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)) ...
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 dur...
#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 pla...
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#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...
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#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...
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#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 ...