task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and th... | #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int PLAYERS = 2, MAX_POINT... |
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 ... | #Vlang | Vlang | import os
import strings
type PlayfairOption = int
const (
no_q = 0
i_equals_j = 1
)
struct Playfair {
mut:
keyword string
pfo PlayfairOption
table [5][5]u8
}
fn (mut p Playfair) init() {
// Build table.
mut used := [26]bool{} // all elements false
if p.pfo == no_q {
... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #11l | 11l | F popcount(n)
R bin(n).count(‘1’)
F is_prime(n)
I n < 2
R 0B
L(i) 2 .. Int(sqrt(n))
I n % i == 0
R 0B
R 1B
V i = 0
V cnt = 0
L
I is_prime(popcount(i))
print(i, end' ‘ ’)
cnt++
I cnt == 25
L.break
i++
print()
L(i) 888888877..888888888
I is_prime(... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R (:seed >> 16) / Float(FF'FF)
F mrUnrank1(&vec, rank, n)
I n < 1 {R}
V (q, r) = divmod(rank, n)
swap(&vec[r], &vec[n - 1])
mrUnrank1(&vec, q, n - 1)
F mrRank1(&vec, &inv, n)
I n < 2 {R 0}
V s = vec[n - 1]
swap(&vec[n - 1]... |
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... | #D | D | import std.algorithm;
import std.bigint;
import std.random;
import std.stdio;
immutable PRIMES = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #AutoHotkey | AutoHotkey | list := ["abc", "def", "gh", "ijklmnop", "hello", "world"]
Random, randint, 1, % list.MaxIndex()
MsgBox % List[randint] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #AWK | AWK | # syntax: GAWK -f PICK_RANDOM_ELEMENT.AWK
BEGIN {
n = split("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",day_of_week,",")
srand()
x = int(n*rand()) + 1
printf("%s\n",day_of_week[x])
exit(0)
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #SAS | SAS | data primes;
do n=1 to 1000;
link primep;
if primep then output;
end;
stop;
primep:
if n < 4 then do;
primep=n=2 or n=3;
return;
end;
primep=0;
if mod(n,2)=0 then return;
do k=3 to sqrt(n) by 2;
if mod(n,k)=0 then return;
end;
primep=1;
return;
keep n;
run; |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play dur... | #Python | Python | #!/usr/bin/python3
'''
See: http://en.wikipedia.org/wiki/Pig_(dice)
This program scores, throws the dice, and plays for an N player game of Pig.
'''
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
max... |
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... | #ALGOL_68 | ALGOL 68 | # reverses the characters in str from start pos to end pos #
PROC in place reverse = ( REF STRING str, INT start pos, INT end pos )VOID:
BEGIN
INT fpos := start pos, epos := end pos;
WHILE fpos < epos
DO
CHAR c := str[ fpos ];
str[ fpos ] := str... |
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... | #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
abst@ype
pip_type = int
abst@ype
suit_type = int
//
abst@ype
card_type = int
//
(* ****** ****** *)
typedef pip = pip_type
typedef suit = suit_type
(* ****** ****** *)
typede... |
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... | #Clojure | Clojure | (def max 100)
(defn roll-dice []
(let [roll (inc (rand-int 6))]
(println "Rolled:" roll) roll))
(defn switch [player]
(if (= player :player1) :player2 :player1))
(defn find-winner [game]
(cond
(>= (:player1 game) max) :player1
(>= (:player2 game) max) :player2
:else nil))
(defn bust []
(... |
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 ... | #Wren | Wren | import "/dynamic" for Enum
import "/str" for Str, Char
import "/trait" for Stepped
import "/ioutil" for Input
var PlayfairOption = Enum.create("PlayfairOption", ["NO_Q", "I_EQUALS_J"])
class Playfair {
construct new(keyword, pfo) {
_pfo = pfo
// build_table
_table = List.filled(5, null)
... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #360_Assembly | 360 Assembly | * Pernicious numbers 04/05/2016
PERNIC CSECT
USING PERNIC,R13 base register and savearea pointer
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
STM STM R14,R12,12(R13) save registers
ST R13,4(R15) link backward SA
ST R15,8(R13) ... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #C | C | #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv)... |
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... | #Delphi | Delphi |
program Pierpont_primes;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math,
System.StrUtils,
System.Generics.Collections,
System.Generics.Defaults,
Velthuis.BigIntegers,
Velthuis.BigIntegers.Primes;
function Pierpont(ulim, vlim: Integer; first: boolean): TArray<BigInteger>;
begin
var p: BigIn... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BaCon | BaCon | ' Pick random element
OPTION BASE 1
DECLARE words$[6]
FOR i = 1 TO 6 : READ words$[i] : NEXT
DATA "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"
element = RANDOM(6) + 1
PRINT "Chose ", element, ": ", words$[element] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Bash | Bash | # borrowed from github.com/search?q=bashnative
rand() {
printf $(( $1 * RANDOM / 32767 ))
}
rand_element () {
local -a th=("$@")
unset th[0]
printf $'%s\n' "${th[$(($(rand "${#th[*]}")+1))]}"
}
echo "You feel like a $(rand_element pig donkey unicorn eagle) today" |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Scala | Scala | def isPrime(n: Int) =
n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0)) |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play dur... | #Racket | Racket | #lang racket
(define (pig-the-dice #:print? [print? #t] . players)
(define prn (if print? (λ xs (apply printf xs) (flush-output)) void))
(define names (for/list ([p players] [n (in-naturals 1)]) n))
(define points (for/list ([p players]) (box 0)))
(with-handlers ([(negate exn?) identity])
(for ([nm (in-cy... |
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... | #AppleScript | AppleScript | -- REVERSED PHRASES, COMPONENT WORDS, AND WORD ORDER ---------------------
-- reverseString, reverseEachWord, reverseWordOrder :: String -> String
on stringReverse(s)
|reverse|(s)
end stringReverse
on reverseEachWord(s)
wordLevel(curry(my map)'s |λ|(my |reverse|))'s |λ|(s)
end reverseEachWord
on reverseWo... |
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... | #AutoHotkey | AutoHotkey | suits := ["♠", "♦", "♥", "♣"]
values := [2,3,4,5,6,7,8,9,10,"J","Q","K","A"]
Gui, font, s14
Gui, add, button, w190 gNewDeck, New Deck
Gui, add, button, x+10 wp gShuffle, Shuffle
Gui, add, button, x+10 wp gDeal, Deal
Gui, add, text, xs w600 , Current Deck:
Gui, add, Edit, xs wp r4 vDeck
Gui, add, text, xs , Hands:
Gui, ... |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...... | #11l | 11l | V ndigits = 0
V q = BigInt(1)
V r = BigInt(0)
V t = q
V k = q
V n = BigInt(3)
V l = n
V first = 1B
L ndigits < 1'000
I 4 * q + r - t < n * t
print(n, end' ‘’)
ndigits++
I ndigits % 70 == 0
print()
I first
first = 0B
print(‘.’, end' ‘’)
V nr = 10 * (r - n * t... |
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... | #CLU | CLU | % This program uses the RNG included in PCLU's "misc.lib".
pig = cluster is play
rep = null
own pi: stream := stream$primary_input()
own po: stream := stream$primary_output()
own scores: array[int] := array[int]$[0,0]
% Seed the RNG with the current time
init_rng = proc ()
d: date ... |
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 ... | #zkl | zkl | fcn genKeyTable(key,deadChr){ // deadChr=="Q" or "J"
deadChr=deadChr.toUpper();
key=key.toUpper().unique() - " " - deadChr;
return(key + (["A".."Z"].pump(String) - deadChr - key), deadChr);
} |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #Ada | Ada | with Ada.Text_IO, Population_Count; use Population_Count;
procedure Pernicious is
Prime: array(0 .. 64) of Boolean;
-- we are using 64-bit numbers, so the population count is between 0 and 64
X: Num; use type Num;
Cnt: Positive;
begin
-- initialize array Prime; Prime(I) must be true if and only if... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #D | D | import std.stdio, std.algorithm, std.range;
alias TRank = ulong;
TRank factorial(in uint n) pure nothrow {
TRank result = 1;
foreach (immutable i; 2 .. n + 1)
result *= i;
return result;
}
/// Fill the integer array <vec> with the permutation at rank <rank>.
void computePermutation(size_t N)(r... |
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... | #F.23 | F# |
// Pierpont primes . Nigel Galloway: March 19th., 2021
let fN g=let mutable g=g in ((fun()->g),fun()->g<-g+g;())
let fG y=let rec fG n g=seq{match g|>List.minBy(fun(n,_)->n()) with (f,s) when f()=n->yield f()+y; s(); yield! fG(n*3)(fN(n*3)::g)
|(f,s) ... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BASIC | BASIC | 'setup
DIM foo(10) AS LONG
DIM n AS LONG, x AS LONG
FOR n = LBOUND(foo) TO UBOUND(foo)
foo(n) = INT(RND*99999)
NEXT
RANDOMIZE TIMER
'random selection
x = INT(RND * ((UBOUND(foo) - LBOUND(foo)) + 1))
'output
PRINT x, foo(x) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
::Initializing the pseudo-array...
set "pseudo=Alpha Beta Gamma Delta Epsilon"
set cnt=0 & for %%P in (!pseudo!) do (
set /a cnt+=1
set "pseudo[!cnt!]=%%P"
)
::Do the random thing...
set /a rndInt=%random% %% cnt +1
::Print the element corresponding to rndint...
echo.!ps... |
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
... | #Scheme | Scheme | (define (prime? number)
(define (*prime? divisor)
(or (> (* divisor divisor) number)
(and (> (modulo number divisor) 0)
(*prime? (+ divisor 1)))))
(and (> number 1)
(*prime? 2))) |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play dur... | #Raku | Raku | player 0 uses the default strategy, always roll if it can.
player 1 will roll up to 5 times then lock in whatever it earned.
player 2 will try to get at least 20 points per turn.
player 3 randomly picks whether to roll again or not biased so that there is a 90% chance that it will.
player 4 randomly chooses to ro... |
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... | #Arturo | Arturo | phr: "rosetta code phrase reversal"
print ["(0)" phr]
print ["(1)" reverse phr]
print ["(2)" join.with:" " map split.words phr => reverse]
print ["(3)" join.with:" " reverse split.words phr] |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaini... | #AutoHotkey | AutoHotkey | var =
(
Rosetta Code Phrase Reversal
)
array := strsplit(var, " ")
loop, % array.maxindex()
string .= array[array.maxindex() - A_index + 1] . " "
loop, % array.maxindex()
{
m := array[A_index]
array2 := strsplit(m, "")
Loop, % array2.maxindex()
string2 .= array2[array2.maxindex() - A_index + 1]
string2 .= ... |
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... | #AutoIt | AutoIt |
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <Array.au3>
; ## GLOBALS ##
Global $SUIT = ["D", "H", "S", "C"]
Global $FACE = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
Global $DECK[52]
; ## CRE... |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...... | #360_Assembly | 360 Assembly | * Spigot algorithm do the digits of PI 02/07/2016
PISPIG CSECT
USING PISPIG,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13)... |
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... | #Common_Lisp | Common Lisp | (defconstant +max-score+ 100)
(defconstant +n-of-players+ 2)
(let ((scores (make-list +n-of-players+ :initial-element 0))
(current-player 0)
(round-score 0))
(loop
(format t "Player ~d: (~d, ~d). Rolling? (Y)"
current-player
(nth current-player scores)
round-s... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #ALGOL_68 | ALGOL 68 | # calculate various pernicious numbers #
# returns the population (number of bits on) of the non-negative integer n #
PROC population = ( INT n )INT:
BEGIN
INT number := n;
INT result := 0;
WHILE number > 0 DO
IF ODD number THEN result +:= 1 F... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #FreeBASIC | FreeBASIC | ' version 31-03-2017
' compile with: fbc -s console
' Myrvold and Ruskey
' only for up to 20 elements, 21! > 2^64 -1
Function Factorial(n As Integer) As ULongInt
Dim As ULongInt tmp = 1
For i As ULong = 2 To n
tmp *= i
Next
Return tmp
End Function
Sub unrank1(n As ULong, r As ULongIn... |
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... | #Factor | Factor | USING: fry grouping io kernel locals make math math.functions
math.primes prettyprint sequences sorting ;
: pierpont ( ulim vlim quot -- seq )
'[
_ <iota> _ <iota> [
[ 2 ] [ 3 ] bi* [ swap ^ ] 2bi@ * 1 @
dup prime? [ , ] [ drop ] if
] cartesian-each
] { } make natural-s... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BBC_BASIC | BBC BASIC | DIM list$(5)
list$() = "The", "five", "boxing", "wizards", "jump", "quickly"
chosen% = RND(6)
PRINT "Item " ; chosen% " was chosen which is '" list$(chosen%-1) "'" |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #BQN | BQN | PR ← {𝕩⊑˜•rand.Range ≠𝕩}
PR1 ← •rand.Range∘≠⊸⊑ |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Seed7 | Seed7 | const func boolean: isPrime (in integer: number) is func
result
var boolean: prime is FALSE;
local
var integer: upTo is 0;
var integer: testNum is 3;
begin
if number = 2 then
prime := TRUE;
elsif odd(number) and number > 2 then
upTo := sqrt(number);
while number rem testNum <... |
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... | #REXX | REXX | /*REXX program plays "pig the dice game" (any number of CBLFs and/or silicons or HALs).*/
sw= linesize() - 1 /*get the width of the terminal screen,*/
parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments from the CL*/
... |
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... | #AWK | AWK | # Usage: awk -f phrase_revers.awk
function rev(s, del, n,i,a,r) {
n = split(s, a, del)
r = a[1]
for(i=2; i <= n; i++) {r = a[i] del r }
return r
}
BEGIN {
p0 = "Rosetta Code Phrase Reversal"
fmt = "%-20s: %s\n"
printf( fmt, "input", p0 )
printf( fmt, "string reversed", r... |
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... | #BaCon | BaCon | phrase$ = "rosetta code phrase reversal"
PRINT REVERSE$(phrase$)
PRINT REV$(REVERSE$(phrase$))
PRINT REV$(phrase$) |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card mu... | #BASIC | BASIC | DECLARE SUB setInitialValues (deck() AS STRING * 2)
DECLARE SUB shuffle (deck() AS STRING * 2)
DECLARE SUB showDeck (deck() AS STRING * 2)
DECLARE FUNCTION deal$ (deck() AS STRING * 2)
DATA "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "TS", "JS", "QS", "KS"
DATA "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H"... |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...... | #Ada | Ada | with Ada.Command_Line;
with Ada.Text_IO;
with GNU_Multiple_Precision.Big_Integers;
with GNU_Multiple_Precision.Big_Rationals;
use GNU_Multiple_Precision;
procedure Pi_Digits is
type Int is mod 2 ** 64;
package Int_To_Big is new Big_Integers.Modular_Conversions (Int);
-- constants
Zero : constant Big_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 th... | #D | D | void main() {
import std.stdio, std.string, std.algorithm, std.random;
enum maxScore = 100;
enum playerCount = 2;
immutable confirmations = ["yes", "y", ""];
int[playerCount] safeScore;
int player, score;
while (true) {
writef(" Player %d: (%d, %d). Rolling? (y/n) ", player,
... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #ALGOL_W | ALGOL W | begin % find some pernicious numbers: numbers with a prime population count %
% returns the population count of n %
integer procedure populationCount( integer value n ) ;
begin
integer v, count;
count := 0;
v := abs n;
while v > 0 do b... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Go | Go | package main
import (
"fmt"
"math/rand"
)
// returns permutation q of n items, using Myrvold-Ruskey rank.
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
// returns identity permutation o... |
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... | #FreeBASIC | FreeBASIC | #define NPP 50
Function isPrime(Byval n As Ulongint) As Boolean
If n < 2 Then Return false
If n = 2 Then Return true
If n Mod 2 = 0 Then Return false
For i As Uinteger = 3 To Int(Sqr(n))+1 Step 2
If n Mod i = 0 Then Return false
Next i
Return true
End Function
Function is_23(Byval n ... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Burlesque | Burlesque |
blsq ) "ABCDEFG"123456 0 6rn-]!!
'G
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
int i;
time_t t;
srand((unsigned)time(&t));
for(i=0;i<30;i++){
printf("%c\n", array[rand()%10]);
}
return 0;
}
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Sidef | Sidef | func is_prime(a) {
given (a) {
when (2) { true }
case (a <= 1 || a.is_even) { false }
default { 3 .. a.isqrt -> any { .divides(a) } -> not }
}
} |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play dur... | #Ruby | Ruby |
def player1(sum,sm)
for i in 1..100
puts "player1 rolled"
a=gets.chomp().to_i
if (a>1 && a<7)
sum+=a
if sum>=100
puts "player1 wins"
break
end
else
goto player2(sum,sm)
end
i+=1
end
end
def player2(sum,sm)
for j in 1..100
puts "player2 rolled"
b=gets.chomp().to_i
if(b>1 && b<7)
sm+=b
if sm>=100
puts "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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%=== The Main Thing... ===%
set "inp=Rosetta Code phrase reversal"
call :reverse_string "!inp!" rev1
call :reverse_order "!inp!" rev2
call :reverse_words "!inp!" rev3
cls
echo.Original: !inp!
echo.Reversed: !rev1!
echo.Reversed Order: !rev2!
echo.Reversed Words: !r... |
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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
call:newdeck deck
echo new deck:
echo.
call:showcards deck
echo.
echo shuffling:
echo.
call:shuffle deck
call:showcards deck
echo.
echo dealing 5 cards to 4 players
call:deal deck 5 hand1 hand2 hand3 hand4
echo.
echo player 1 & call:showcards hand1
echo.
echo player 2 & ... |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
INT base := 10;
MODE YIELDINT = PROC(INT)VOID;
PROC gen pi digits = (INT decimal places, YIELDINT yield)VOID:
BEGIN
INT nine = base - 1;
INT nines := 0, predigit := 0; # First predigit is a 0 #
[decimal places*10 OVER 3]#LONG# INT digits; # We need 3 times the digits to calcul... |
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... | #Delphi | Delphi | program Pig_the_dice_game;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Console;
var
playerScores: TArray<Integer> = [0, 0];
turn: Integer = 0;
currentScore: Integer = 0;
player: Integer;
begin
Randomize;
turn := Random(length(playerScores));
writeln('Player ', turn, ' start:');
while... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #AppleScript | AppleScript | on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
on isPernicious(n)
-- 8 bits at a time is... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Haskell | Haskell | fact :: Int -> Int
fact n = product [1 .. n]
-- Always assume elements are unique.
rankPerm [] _ = []
rankPerm list n = c : rankPerm (a ++ b) r
where
(q, r) = n `divMod` fact (length list - 1)
(a, c:b) = splitAt q list
permRank [] = 0
permRank (x:xs) = length (filter (< x) xs) * fact (length xs) + permR... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #J | J | A. 2 0 1 NB. return rank of permutation
4
4 A. i.3 NB. return permutation of rank 4
2 0 1
0 1 2 3 4 5 A. i. 3 NB. generate all 6 permutations for 3 items
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
A. 0 1 2 3 4 5 A. i. 3 NB. ranks of each permuation
0 1 2 3 4 5
]ranks=: 4 ?... |
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... | #Go | Go | package main
import (
"fmt"
big "github.com/ncw/gmp"
"sort"
)
var (
one = new(big.Int).SetUint64(1)
two = new(big.Int).SetUint64(2)
three = new(big.Int).SetUint64(3)
)
func pierpont(ulim, vlim int, first bool) []*big.Int {
p := new(big.Int)
p2 := new(big.Int).Set(one)
p3 :=... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #C.23 | C# | using System;
using System.Collections.Generic;
class RandomElementPicker {
static void Main() {
var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
var rng = new Random();
var randomElement = list[rng.Next(list.Count)];
Console.WriteLine("I picked element {0}", randomElement);
}
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #C.2B.2B | C++ | #include <iostream>
#include <random>
#include <vector>
int main( ) {
std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
std::random_device seed ;
// generator
std::mt19937 engine( seed( ) ) ;
// number distribution
std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1... |
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
... | #Smalltalk | Smalltalk | | isPrime |
isPrime := [:n |
n even ifTrue: [ ^n=2 ]
ifFalse: [
3 to: n sqrt do: [:i |
(n \\ i = 0) ifTrue: [ ^false ]
].
^true
]
] |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play dur... | #Sidef | Sidef | var (games=100) = ARGV.map{.to_i}...
define DIE = 1..6;
define GOAL = 100;
class Player(score=0, ante=0, rolls=0, strategy={false}) {
method turn {
rolls = 0;
ante = 0;
loop {
rolls++;
given (var roll = DIE.rand) {
when (1) {
a... |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaini... | #Bracmat | Bracmat | ( "rosetta code phrase reversal":?text
& rev$!text:?output1
& get$(!text,MEM):?words
& :?output2:?output3
& whl
' ( !words:%?word %?words
& !output2 rev$!word " ":?output2
& " " !word !output3:?output3
)
& str$(!output2 rev$!words):?output2
& str$(!words !output3):?output3
& out
$ ( str
$ ("0:\"... |
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... | #C | C |
#include <stdio.h>
#include <string.h>
/* The functions used are destructive, so after each call the string needs
* to be copied over again. One could easily allocate new strings as
* required, but this way allows the caller to manage memory themselves */
char* reverse_section(char *s, size_t length)
{
if (... |
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... | #BBC_BASIC | BBC BASIC | DIM Deck{ncards%, card&(51)}, Suit$(3), Rank$(12)
Suit$() = "Clubs", "Diamonds", "Hearts", "Spades"
Rank$() = "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", \
\ "Eight", "Nine", "Ten", "Jack", "Queen", "King"
PRINT "Creating a new deck..."
PROCnewdeck(deck1{})
... |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...... | #Arturo | Arturo | q: 1
r: 0
t: 1
k: 1
n: 3
l: 3
d: 0
dotWritten: false
while [true][
if? (n*t) > (4*q)+r-t [
d: d+1
prints n
unless dotWritten [
prints "."
dotWritten: true
d: d+1
]
if 0 = d%80 -> prints "\n"
nr: 10*(r - n*t)
n: ((10*(r... |
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... | #Eiffel | Eiffel |
class
PLAYER
create
set_name
feature
set_name(n:STRING)
do
name := n.twin
set_points(0)
end
strategy(cur_points:INTEGER)
local
current_points, thrown:INTEGER
do
io.put_string ("You currently have " +points.out+". %NDo you want to save your points? Press y or n.%N")
io.read_line
if io.l... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #Arturo | Arturo | pernicious?: function [n][
prime? size filter split as.binary n 'x -> x="0"
]
i: 1
found: 0
while [found<25][
if pernicious? i [
prints i
prints " "
found: found + 1
]
i: i + 1
]
print ""
print select 888888877..888888888 => pernicious? |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Java | Java | import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.va... |
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... | #Haskell | Haskell | import Control.Monad (guard)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime)
import Text.Printf (printf)
data PierPointKind = First | Second
merge :: Ord a => [a] -> [a] -> [a]
merge [] b =... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
shared void run() {
value random = DefaultRandom();
value element = random.nextElement([1, 2, 3, 4, 5, 6]);
print(element);
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Clojure | Clojure | (rand-nth coll) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #SNOBOL4 | SNOBOL4 | define('isprime(n)i,max') :(isprime_end)
isprime isprime = n
le(n,1) :s(freturn)
eq(n,2) :s(return)
eq(remdr(n,2),0) :s(freturn)
max = sqrt(n); i = 1
isp1 i = le(i + 2,max) i + 2 :f(return)
eq(remdr(n,i),0) :s(freturn)f(isp1)
isprime_end |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play dur... | #Tcl | Tcl | package require TclOO
oo::class create Player {
variable me
constructor {name} {
set me $name
}
method name {} {
return $me
}
method wantToRoll {safeScore roundScore} {}
method rolled {who what} {
if {$who ne [self]} {
#puts "[$who name] rolled a $what"
}
}
method turn... |
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... | #C.23 | C# | using System;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//Reverse() is an extension method on IEnumerable<char>.
//The constructor takes a char[], so we have to call ToArray()
Func<string, string> rever... |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
The... | #11l | 11l | F derangements(n)
[[Int]] r
V perm = Array(0 .< n)
L
I all(enumerate(perm).map((indx, p) -> indx != p))
r [+]= perm
I !perm.next_permutation()
L.break
R r
F subfact(n) -> Int64
R I n < 2 {1 - n} E (subfact(n - 1) + subfact(n - 2)) * (n - 1)
V n = 4
print(‘Derangements of... |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs ... | #11l | 11l | F s_permutations(seq)
V items = [[Int]()]
L(j) seq
[[Int]] new_items
L(item) items
I L.index % 2
new_items [+]= (0..item.len).map(i -> @item[0 .< i] [+] [@j] [+] @item[i..])
E
new_items [+]= (item.len..0).step(-1).map(i -> @item[0 .< i] [+] [@j] [+] @item[i..]... |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment... | #11l | 11l | V data = [85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
F pick(at, remain, accu, treat)
I remain == 0
R I accu > treat {1} E 0
R pick(at - 1, remain - 1, accu + :data[at - 1], treat) +
(I at > remain {pick(at - 1, remain, accu, treat)} E 0)
V treat = 0
V total =... |
http://rosettacode.org/wiki/Peripheral_drift_illusion | Peripheral drift illusion | Task
Generate and display a Peripheral Drift Illusion
The image appears to be moving even though it is perfectly static.
Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host.
References
Codepen demo.
| #Action.21 | Action! | PROC DrawTile(INT x BYTE y,flip,c1,c2)
BYTE i
Color=1
FOR i=y+2 TO y+11
DO
Plot(x+1,i) DrawTo(x+5,i)
OD
Color=c1
IF flip THEN
Plot(x,y+12) DrawTo(x,y) DrawTo(x+6,y)
ELSE
Plot(x,y) DrawTo(x+6,y) DrawTo(x+6,y+12)
FI
Plot(x+1,y+1) DrawTo(x+5,y+1)
Color=c2
IF flip THEN
Plot(x,y+13)... |
http://rosettacode.org/wiki/Peripheral_drift_illusion | Peripheral drift illusion | Task
Generate and display a Peripheral Drift Illusion
The image appears to be moving even though it is perfectly static.
Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host.
References
Codepen demo.
| #Julia | Julia | using Gtk, Colors, Cairo
function CodepenApp()
# left-top, top-right, right-bottom, bottom-left
LT, TR, RB, BL = 1, 2, 3, 4
edges = [
[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL]... |
http://rosettacode.org/wiki/Peripheral_drift_illusion | Peripheral drift illusion | Task
Generate and display a Peripheral Drift Illusion
The image appears to be moving even though it is perfectly static.
Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host.
References
Codepen demo.
| #Nim | Nim | import gintro/[glib, gobject, gtk, gio, cairo]
const
Width = 600
Height = 460
type
Color = array[3, float]
Edge {.pure.} = enum LT, TR, RB, BL
const
Edges = [[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, R... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int locale_ok = 0;
wchar_t s_suits[] = L"♠♥♦♣";
/* if your file can't contain unicode, use the next line instead */
//wchar_t s_suits[] = L"\x2660\x2665\x2666\x2663";
const char *s_suits_ascii[] = { "S", "H", "D", "C" };
const char *s_nums[] = { "WHAT",
... |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...... | #AutoHotkey | AutoHotkey | #NoEnv
#SingleInstance, Force
SetBatchLines, -1
#Include mpl.ahk
dot:=".", i:=0
, MP_SET(q, "1")
, MP_SET(r, "0")
, MP_SET(t, "1")
, MP_SET(k, "1")
, MP_SET(n, "3")
, MP_SET(l, "3")
, MP_SET(ONE, "1")
, MP_SET(TWO, "2")
, MP_SET(THREE, "3")
, MP_SET(FOUR, "4")
, MP_SET(SEVEN, "7")
, MP_SET(TEN, "10")
Loop
{
MP_MUL(q... |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and th... | #Erlang | Erlang |
-module( pig_dice ).
-export( [game/1, goal/0, hold/2, player_name/1, players_totals/1, quit/2, roll/2, score/1, task/0] ).
-record( player, {name, score=0, total=0} ).
game( [_Player | _T]=Players ) ->
My_pid = erlang:self(),
erlang:spawn_link( fun() -> random:seed(os:timestamp()), game_loop( [#player{... |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #AutoHotkey | AutoHotkey | c := 0
while c < 25
if IsPern(A_Index)
Out1 .= A_Index " ", c++
Loop, 12
if IsPern(n := 888888876 + A_Index)
Out2 .= n " "
MsgBox, % Out1 "`n" Out2
IsPern(x) { ;https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
static p := {2:1, 3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1,... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #jq | jq | # Assuming sufficiently-precise integer arithmetic,
# if the input and $j are integers, then the result will be a pair of integers,
# except that if $j is 0, then an error condition is raised.
def divmod($j):
. as $i
| ($i % $j) as $mod
| [($i - $mod) / $j, $mod] ;
# Input may be an object or an array
def swap(... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Julia | Julia | using Printf
nobjs = 4
a = collect(1:nobjs)
println("All permutations of ", nobjs, " objects:")
for i in 1:factorial(nobjs)
p = nthperm(a, i)
prank = nthperm(p)
print(@sprintf("%5d => ", i))
println(p, " (", prank, ")")
end
nobjs = 12
nsamp = 4
ptaken = Int[]
println()
println(nsamp, " random permut... |
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... | #J | J | 5 10$(#~ 1 p:])1+/:~,*//2 3x^/i.20
2 3 5 7 13 17 19 37 73 97
109 163 193 257 433 487 577 769 1153 1297
1459 2593 2917 3457 3889 10369 12289 17497 18433 39367
52489 65537 139969 147457 209953 331777 4... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #CLU | CLU | random_element = proc [T: type] (a: array[T]) returns (T)
return(a[array[T]$low(a) + random$next(array[T]$size(a))])
end random_element
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
arr: array[string] := array[string]$... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. random-element.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 nums-area VALUE "123456789".
03 nums PIC 9 OCCURS 9 TIMES.
01 random-idx PIC 9 COMP.
PROCEDURE DIVISION.
COM... |
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
... | #SQL | SQL | declare @number int
set @number = 514229 -- number to check
;with cte(number) as
(
select 2
union all
select number+1
from cte
where number+1 < @number
)
select
cast(@number as varchar(100)) +
case
when exists
(
select *
from
(
select number, @number % number ... |
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... | #Wren | Wren | import "random" for Random
import "os" for Process
var args = Process.arguments
var games = (args.count == 0) ? 100 : Num.fromString(args[0])
var Rand = Random.new()
var Die = 1..6
var Goal = 100
class Player {
construct new(strategy) {
_score = 0
_ante = 0
_rolls = 0
_strate... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
#include <sstream>
int main() {
std::string s = "rosetta code phrase reversal";
std::cout << "Input : " << s << '\n'
<< "Input reversed : " << std::string(s.rbegin(), s.rend()) << '\n' ;
std::istring... |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
The... | #360_Assembly | 360 Assembly | * Permutations/Derangements 01/04/2017
DERANGE CSECT
USING DERANGE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.