task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #ALGOL_68 | ALGOL 68 | BEGIN # Heap's algorithm for generating permutations - from the pseudo-code on the Wikipedia page #
# generate permutations of a #
PROC generate = ( INT k, REF[]INT a, REF INT swap count )VOID:
IF k = 1 THEN
output permutation( a, swap count )
ELSE
# Generate permutations with kth unaltered #
# Initially k = length a #
generate( k - 1, a, swap count );
# Generate permutations for kth swapped with each k-1 initial #
FOR i FROM 0 TO k - 2 DO
# Swap choice dependent on parity of k (even or odd) #
swap count +:= 1;
INT swap item = IF ODD k THEN 0 ELSE i FI;
INT t = a[ swap item ];
a[ swap item ] := a[ k - 1 ];
a[ k - 1 ] := t;
generate( k - 1, a, swap count )
OD
FI # generate # ;
# generate permutations of a #
PROC permute = ( REF[]INT a )VOID:
BEGIN
INT swap count := 0;
generate( ( UPB a + 1 ) - LWB a, a[ AT 0 ], swap count )
END # permute # ;
# handle a permutation #
PROC output permutation = ( REF[]INT a, INT swap count )VOID:
BEGIN
print( ( "[" ) );
FOR i FROM LWB a TO UPB a DO
print( ( whole( a[ i ], 0 ) ) );
IF i = UPB a THEN print( ( "]" ) ) ELSE print( ( ", " ) ) FI
OD;
print( ( " sign: ", IF ODD swap count THEN "-1" ELSE " 1" FI, newline ) )
END # output permutation # ;
[ 1 : 3 ]INT a := ( 1, 2, 3 );
permute( a )
END |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Ada | Ada | with Ada.Text_IO; with Iterate_Subsets;
procedure Permutation_Test is
type Group_Type is array(Positive range <>) of Positive;
Treat_Group: constant Group_Type := (85, 88, 75, 66, 25, 29, 83, 39, 97);
Ctrl_Group: constant Group_Type := (68, 41, 10, 49, 16, 65, 32, 92, 28, 98);
package Iter is new Iterate_Subsets(Treat_Group'Length, Ctrl_Group'Length);
Full_Group: constant Group_Type(1 .. Iter.All_Elements)
:= Treat_Group & Ctrl_Group;
function Mean(S: Iter.Subset) return Float is
Sum: Natural := 0;
begin
for I in S'Range loop
Sum := Sum + Full_Group(S(I));
end loop;
return Float(Sum)/Float(S'Length);
end Mean;
package FIO is new Ada.Text_IO.Float_IO(Float);
T_Avg: Float := Mean(Iter.First);
S_Avg: Float;
S: Iter.Subset := Iter.First;
Equal: Positive := 1; -- Mean(Iter'First) = Mean(Iter'First)
Higher: Natural := 0;
Lower: Natural := 0;
begin -- Permutation_Test;
-- first, count the subsets with a higher, an equal or a lower mean
loop
Iter.Next(S);
S_Avg := Mean(S);
if S_Avg = T_Avg then
Equal := Equal + 1;
elsif S_Avg >= T_Avg then
Higher := Higher + 1;
else
Lower := Lower + 1;
end if;
exit when Iter.Last(S);
end loop;
-- second, output the results
declare
use Ada.Text_IO;
Sum: Float := Float(Higher + Equal + Lower);
begin
Put("Less or Equal: ");
FIO.Put(100.0*Float(Lower+Equal) / Sum, Fore=>3, Aft=>1, Exp=>0);
Put(Integer'Image(Lower+Equal));
New_Line;
Put("More: ");
FIO.Put(100.0*Float(Higher) / Sum, Fore=>3, Aft=>1, Exp=>0);
Put(Integer'Image(Higher));
New_Line;
end;
end Permutation_Test; |
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.
| #Perl | Perl | use strict;
use warnings;
my $svg = <<'EOD';
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="1200" height="825">
<rect width="100%" height="100%" fill="#d3d004" />
<defs>
<g id="block">
<polygon points="-25,-25,-25,25,25,25" fill="white" />
<polygon points="25,25,25,-25,-25,-25" fill="black" />
<rect x="-20" y="-20" width="40" height="40" fill="#3250ff" />
</g>
</defs>
EOD
for my $X (1..15) {
for my $Y (1..10) {
my $r = int(($X + $Y) / 2) % 4 * 90;
my $x = $X * 75;
my $y = $Y * 75;
my $a = $r > 0 ? "rotate($r,$x,$y) " : '';
$svg .= qq{<use xlink:href="#block" transform="$a translate($x,$y)" />\n}
}
}
$svg .= '</svg>';
open my $fh, '>', 'peripheral-drift.svg';
print $fh $svg;
close $fh; |
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.
| #Phix | Phix | --
-- demo\rosetta\Peripheral_Drift_Illusion.exw
-- ==========================================
--
-- converted from https://codepen.io/josetxu/pen/rNmXjrq
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cdcanvas
constant title = "Peripheral Drift Illusion",
CD_LIGHT_OLIVE = #d3d004,
CD_PALE_BLUE = #3250ff,
dxy = {{45,45},{0,45},{0,0},{45,0},{45,45},{0,45}}
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cdcanvas)
cdCanvasSetBackground(cdcanvas, CD_LIGHT_OLIVE)
cdCanvasClear(cdcanvas)
integer c = 0,
cy = floor(height/2)*2-81
while cy>100 do
integer d = c,
cx = 81
while cx<width-100 do
cdCanvasSetForeground(cdcanvas, CD_WHITE)
cdCanvasBox(cdcanvas, cx, cx+45, cy, cy-45)
cdCanvasSetForeground(cdcanvas, CD_BLACK)
cdCanvasBegin(cdcanvas, CD_FILL)
for i=4 to 6 do
integer {dy,dx} = dxy[i-d]
cdCanvasVertex(cdcanvas, cx+dx, cy-dy)
end for
cdCanvasEnd(cdcanvas)
cdCanvasSetForeground(cdcanvas, CD_PALE_BLUE)
cdCanvasBox(cdcanvas, cx+4, cx+41, cy-4, cy-41)
d = remainder(d+(odd(cx)==odd(cy)),4)
cx += 63
end while
c = remainder(c+4-even(cy),4)
cy -= 63
end while
cdCanvasFlush(cdcanvas)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
IupGLMakeCurrent(canvas)
if platform()=JS then
cdcanvas = cdCreateCanvas(CD_IUP, canvas)
else
cdcanvas = cdCreateCanvas(CD_GL, "10x10 %g", {res})
end if
cdCanvasSetBackground(cdcanvas, CD_PARCHMENT)
return IUP_DEFAULT
end function
function canvas_resize_cb(Ihandle /*canvas*/)
integer {cw, ch} = IupGetIntInt(canvas, "DRAWSIZE")
atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
cdCanvasSetAttribute(cdcanvas, "SIZE", "%dx%d %g", {cw, ch, res})
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupGLCanvas("RASTERSIZE=780x600") -- (sensible restore size)
sequence cb = {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb"),
"RESIZE_CB", Icallback("canvas_resize_cb")}
IupSetCallbacks(canvas, cb)
dlg = IupDialog(canvas,`TITLE="%s",PLACEMENT=MAXIMIZED`,{title})
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
public struct Card
{
public Card(string rank, string suit) : this()
{
Rank = rank;
Suit = suit;
}
public string Rank { get; }
public string Suit { get; }
public override string ToString() => $"{Rank} of {Suit}";
}
public class Deck : IEnumerable<Card>
{
static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
readonly List<Card> cards;
public Deck() {
cards = (from suit in suits
from rank in ranks
select new Card(rank, suit)).ToList();
}
public int Count => cards.Count;
public void Shuffle() {
// using Knuth Shuffle (see at http://rosettacode.org/wiki/Knuth_shuffle)
var random = new Random();
for (int i = 0; i < cards.Count; i++) {
int r = random.Next(i, cards.Count);
var temp = cards[i];
cards[i] = cards[r];
cards[r] = temp;
}
}
public Card Deal() {
int last = cards.Count - 1;
Card card = cards[last];
//Removing from the front will shift the other items back 1 spot,
//so that would be an O(n) operation. Removing from the back is O(1).
cards.RemoveAt(last);
return card;
}
public IEnumerator<Card> GetEnumerator() {
//Reverse enumeration of the list so that they are returned in the order they would be dealt.
//LINQ's Reverse() copies the entire list. Let's avoid that.
for (int i = cards.Count - 1; i >= 0; i--)
yield return cards[i];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
} |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #BASIC | BASIC | 10 REM ADOPTED FROM COMMODORE BASIC
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
40 ND = 1
50 DIM A(LN)
60 N9 = 0
70 PD = 0:REM FIRST PRE-DIGIT IS A 0
80 REM
90 FOR J = 1 TO LN
100 A(J-1) = 2:REM START WITH 2S
110 NEXT J
120 REM
130 FOR J = 1 TO N
140 Q = 0
150 FOR I = LN TO 1 STEP -1:REM WORK BACKWARDS
160 X = 10*A(I-1) + Q*I
170 A(I-1) = X - (2*I-1)*INT(X/(2*I-1)):REM X - INT ( X / Y) * Y
180 Q = INT(X/(2*I - 1))
190 NEXT I
200 A(0) = Q-10*INT(Q/10)
210 Q = INT(Q/10)
220 IF Q=9 THEN N9 = N9 + 1: GOTO 450
240 IF Q<>10 THEN GOTO 350
250 REM Q == 10
260 D = PD+1: GOSUB 500
270 IF N9 <= 0 THEN GOTO 320
280 FOR K = 1 TO N9
290 D = 0: GOSUB 500
300 NEXT K
310 REM END IF
320 PD = 0
330 N9 = 0
335 GOTO 450
340 REM Q <> 10
350 D = PD: GOSUB 500
360 PD = Q
370 IF N9 = 0 THEN GOTO 450
380 FOR K = 1 TO N9
390 D = 9: GOSUB 500
400 NEXT K
410 N9 = 0
450 NEXT J
460 PRINT PD
470 END
480 REM
490 REM OUTPUT DIGITS
500 IF ND=0 THEN PRINT D;: RETURN
510 IF D=0 THEN RETURN
520 PRINT D;".";
530 ND = 0
550 RETURN
|
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #6502_Assembly | 6502 Assembly | Lookup: ;INPUT: X = atomic number of the element of interest.
LDA PeriodicTable_Column,x
STA $20 ;store column number in memory (I chose $20 arbitrarily, you can store it anywhere)
LDA PeriodicTable_Row,x
STA $21 ;store row number in memory
RTS
PeriodicTable_Column:
db $ff,$01,$18,$01,$02,$13,$14,$15,$16,$17,$18,... ;I don't need to write them all out, the concept is self-explanatory enough.
PeriodicTable_Row:
db $ff,$01,$01,$02,$02,$02,$02,$02,$02,$02,$02,... |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #FOCAL | FOCAL | 01.10 T "GAME OF PIG"!
01.20 S S(1)=0;S S(2)=0;S P=1
01.30 T !"PLAYER",%1,P," TURN BEGINS"!
01.40 D 3;I (99-S(P))1.7
01.50 S P=3-P
01.60 G 1.3
01.70 T !"THE WINNER IS PLAYER",%1,P,!
01.80 Q
02.10 S A=10*FRAN();S A=1+FITR(6*(A-FITR(A)))
03.10 S T=0
03.20 T "PLAYER",%1,P," SCORE",%3,S(P)," TURN",%3,T
03.25 D 2;T " ROLL",%1,A," "
03.30 I (A-2)3.55;S T=T+A
03.35 A "- R)OLL OR H)OLD",C
03.40 I (C-0R)3.45,3.2,3.45
03.45 I (C-0H)3.5,3.6,3.5
03.50 T "INVALID INPUT ";G 3.35
03.55 T "- TOO BAD!"!;S T=0
03.60 S S(P)=S(P)+T
03.65 T "PLAYER",%1,P," SCORE",%3,S(P)," TURN FINISHED"! |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #AWK | AWK |
# syntax: GAWK -f PERNICIOUS_NUMBERS.AWK
BEGIN {
pernicious(25)
pernicious(888888877,888888888)
exit(0)
}
function pernicious(x,y, count,n) {
if (y == "") { # print first X pernicious numbers
while (count < x) {
if (is_prime(pop_count(++n)) == 1) {
printf("%d ",n)
count++
}
}
}
else { # print pernicious numbers in X-Y range
for (n=x; n<=y; n++) {
if (is_prime(pop_count(n)) == 1) {
printf("%d ",n)
}
}
}
print("")
}
function dec2bin(n, str) {
while (n) {
if (n%2 == 0) {
str = "0" str
}
else {
str = "1" str
}
n = int(n/2)
}
if (str == "") {
str = "0"
}
return(str)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
function pop_count(n) {
n = dec2bin(n)
return gsub(/1/,"&",n)
}
|
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Kotlin | Kotlin | // version 1.1.2
import java.util.Random
fun IntArray.swap(i: Int, j: Int) {
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
tailrec fun mrUnrank1(rank: Int, n: Int, vec: IntArray) {
if (n < 1) return
val q = rank / n
val r = rank % n
vec.swap(r, n - 1)
mrUnrank1(q, n - 1, vec)
}
fun mrRank1(n: Int, vec: IntArray, inv: IntArray): Int {
if (n < 2) return 0
val s = vec[n - 1]
vec.swap(n - 1, inv[n - 1])
inv.swap(s, n - 1)
return s + n * mrRank1(n - 1, vec, inv)
}
fun getPermutation(rank: Int, n: Int, vec: IntArray) {
for (i in 0 until n) vec[i] = i
mrUnrank1(rank, n, vec)
}
fun getRank(n: Int, vec: IntArray): Int {
val v = IntArray(n)
val inv = IntArray(n)
for (i in 0 until n) {
v[i] = vec[i]
inv[vec[i]] = i
}
return mrRank1(n, v, inv)
}
fun main(args: Array<String>) {
var tv = IntArray(3)
for (r in 0..5) {
getPermutation(r, 3, tv)
System.out.printf("%2d -> %s -> %d\n", r, tv.contentToString(), getRank(3, tv))
}
println()
tv = IntArray(4)
for (r in 0..23) {
getPermutation(r, 4, tv)
System.out.printf("%2d -> %s -> %d\n", r, tv.contentToString(), getRank(4, tv))
}
println()
tv = IntArray(12)
val a = IntArray(4)
val rand = Random()
val fact12 = (2..12).fold(1) { acc, i -> acc * i }
for (i in 0..3) a[i] = rand.nextInt(fact12)
for (r in a) {
getPermutation(r, 12, tv)
System.out.printf("%9d -> %s -> %d\n", r, tv.contentToString(), getRank(12, tv))
}
} |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Java | Java |
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class PierpontPrimes {
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getNumberInstance();
display("First 50 Pierpont primes of the first kind:", pierpontPrimes(50, true));
display("First 50 Pierpont primes of the second kind:", pierpontPrimes(50, false));
System.out.printf("250th Pierpont prime of the first kind: %s%n%n", nf.format(pierpontPrimes(250, true).get(249)));
System.out.printf("250th Pierpont prime of the second kind: %s%n%n", nf.format(pierpontPrimes(250, false).get(249)));
}
private static void display(String message, List<BigInteger> primes) {
NumberFormat nf = NumberFormat.getNumberInstance();
System.out.printf("%s%n", message);
for ( int i = 1 ; i <= primes.size() ; i++ ) {
System.out.printf("%10s ", nf.format(primes.get(i-1)));
if ( i % 10 == 0 ) {
System.out.printf("%n");
}
}
System.out.printf("%n");
}
public static List<BigInteger> pierpontPrimes(int n, boolean first) {
List<BigInteger> primes = new ArrayList<BigInteger>();
if ( first ) {
primes.add(BigInteger.valueOf(2));
n -= 1;
}
BigInteger two = BigInteger.valueOf(2);
BigInteger twoTest = two;
BigInteger three = BigInteger.valueOf(3);
BigInteger threeTest = three;
int twoIndex = 0, threeIndex = 0;
List<BigInteger> twoSmooth = new ArrayList<BigInteger>();
BigInteger one = BigInteger.ONE;
BigInteger mOne = BigInteger.valueOf(-1);
int count = 0;
while ( count < n ) {
BigInteger min = twoTest.min(threeTest);
twoSmooth.add(min);
if ( min.compareTo(twoTest) == 0 ) {
twoTest = two.multiply(twoSmooth.get(twoIndex));
twoIndex++;
}
if ( min.compareTo(threeTest) == 0 ) {
threeTest = three.multiply(twoSmooth.get(threeIndex));
threeIndex++;
}
BigInteger test = min.add(first ? one : mOne);
if ( test.isProbablePrime(10) ) {
primes.add(test);
count++;
}
}
return primes;
}
}
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #CoffeeScript | CoffeeScript | array = [1,2,3]
console.log array[Math.floor(Math.random() * array.length)] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Common_Lisp | Common Lisp | (defvar *list* '(one two three four five))
(print (nth (random (length *list*)) *list*))
(print (nth (random (length *list*)) *list*))
(print (nth (random (length *list*)) *list*)) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Standard_ML | Standard ML | fun is_prime n =
if n = 2 then true
else if n < 2 orelse n mod 2 = 0 then false
else let
fun loop k =
if k * k > n then true
else if n mod k = 0 then false
else loop (k+2)
in loop 3
end |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Clojure | Clojure | (use '[clojure.string :only (join split)])
(def phrase "rosetta code phrase reversal")
(defn str-reverse [s] (apply str (reverse s)))
; Reverse string
(str-reverse phrase)
; Words reversed
(join " " (map str-reverse (split phrase #" ")))
; Word order reversed
(apply str (interpose " " (reverse (split phrase #" "))))
|
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure DePermute is
type U64 is mod 2**64;
type Num is range 0 .. 20;
type NumList is array (Natural range <>) of Num;
type PtNumList is access all NumList;
package IO is new Ada.Text_IO.Integer_IO (Num);
package UIO is new Ada.Text_IO.Modular_IO (U64);
function deranged (depth : Natural; list : PtNumList;
show : Boolean) return U64 is
tmp : Num; count : U64 := 0;
begin
if depth = list'Length then
if show then
for i in list'Range loop IO.Put (list (i), 2); end loop;
New_Line;
end if; return 1;
end if;
for i in reverse depth .. list'Last loop
if Num (i + 1) /= list (depth) then
tmp := list (i); list (i) := list (depth); list (depth) := tmp;
count := count + deranged (depth + 1, list, show);
tmp := list (i); list (i) := list (depth); list (depth) := tmp;
end if;
end loop;
return count;
end deranged;
function gen_n (len : Natural; show : Boolean) return U64 is
list : PtNumList;
begin
list := new NumList (0 .. len - 1);
for i in list'Range loop list (i) := Num (i + 1); end loop;
return deranged (0, list, show);
end gen_n;
function sub_fact (n : Natural) return U64 is begin
if n < 2 then return U64 (1 - n);
else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1);
end if;
end sub_fact;
count : U64;
begin
Put_Line ("Deranged 4:");
count := gen_n (4, True);
Put_Line ("List vs. calc:");
for i in Natural range 0 .. 9 loop
IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7);
UIO.Put (sub_fact (i), 7); New_Line;
end loop;
Put_Line ("!20 = " & U64'Image (sub_fact (20)));
end DePermute; |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Arturo | Arturo | permutations: function [arr][
d: 1
c: array.of: size arr 0
xs: new arr
sign: 1
ret: new @[@[xs, sign]]
while [true][
while [d > 1][
d: d-1
c\[d]: 0
]
while [c\[d] >= d][
d: d+1
if d >= size arr -> return ret
]
i: (1 = and d 1)? -> c\[d] -> 0
tmp: xs\[i]
xs\[i]: xs\[d]
xs\[d]: tmp
sign: neg sign
'ret ++ @[new @[xs, sign]]
c\[d]: c\[d] + 1
]
return ret
]
loop permutations 0..2 'row ->
print [row\0 "-> sign:" row\1]
print ""
loop permutations 0..3 'row ->
print [row\0 "-> sign:" row\1] |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #AWK | AWK |
# syntax: GAWK -f PERMUTATION_TEST.AWK
# converted from C
BEGIN {
# "treatment..................control......................"
n = split("85,88,75,66,25,29,83,39,97,68,41,10,49,16,65,32,92,28,98",data,",")
for (i=1; i<=n; i++) { # make AWK array look like a C array
data[i-1] = data[i]
}
delete data[n]
total = 1
for (i=0; i<9; i++) { treat += data[i] }
for (i=19; i>10; i--) { total *= i }
for (i=9; i>0; i--) { total /= i }
gt = pick(19,9,0,treat)
le = total - gt
printf("<= : %9.6f%% %6d\n",100*le/total,le)
printf(" > : %9.6f%% %6d\n",100*gt/total,gt)
exit(0)
}
function pick(at,remain,accu,treat) {
if (!remain) {
return (accu > treat) ? 1 : 0
}
return pick(at-1,remain-1,accu+data[at-1],treat) + ( (at > remain) ? pick(at-1,remain,accu,treat) : 0 )
}
|
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.
| #Raku | Raku | use SVG;
my @blocks = (1..15 X 1..10).map: -> ($X, $Y) {
my $x = $X * 75;
my $y = $Y * 75;
my $a = (my $r = ($X + $Y) div 2 % 4 * 90) > 0 ?? "rotate($r,$x,$y) " !! '';
:use['xlink:href'=>'#block', 'transform'=>"{$a}translate($x,$y)"]
}
'peripheral-drift-raku.svg'.IO.spurt: SVG.serialize(
svg => [
:1200width, :825height,
:rect[:width<100%>, :height<100%>, :fill<#d3d004>],
:defs[
:g[
:id<block>,
:polygon[:points<-25,-25,-25,25,25,25>, :fill<white>],
:polygon[:points<25,25,25,-25,-25,-25>, :fill<black>],
:rect[:x<-20>, :y<-20>, :width<40>, :height<40>, :fill<#3250ff>]
]
],
|@blocks,
]
) |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #C.2B.2B | C++ | #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
enum { unique_count = pip_count * suite_count };
card(suite_type s, pip_type p): value(s + suite_count * p) {}
explicit card(unsigned char v = 0): value(v) {}
pip_type pip() { return pip_type(value / suite_count); }
suite_type suite() { return suite_type(value % suite_count); }
private:
unsigned char value;
};
const char* const pip_names[] =
{ "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"jack", "queen", "king", "ace" };
std::ostream& operator<<(std::ostream& os, card::pip_type pip)
{
return os << pip_names[pip];
}
const char* const suite_names[] =
{ "hearts", "spades", "diamonds", "clubs" };
std::ostream& operator<<(std::ostream& os, card::suite_type suite)
{
return os << suite_names[suite];
}
std::ostream& operator<<(std::ostream& os, card c)
{
return os << c.pip() << " of " << c.suite();
}
class deck
{
public:
deck()
{
for (int i = 0; i < card::unique_count; ++i) {
cards.push_back(card(i));
}
}
void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }
card deal() { card c = cards.front(); cards.pop_front(); return c; }
typedef std::deque<card>::const_iterator const_iterator;
const_iterator begin() const { return cards.cbegin(); }
const_iterator end() const { return cards.cend(); }
private:
std::deque<card> cards;
};
inline std::ostream& operator<<(std::ostream& os, const deck& d)
{
std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n"));
return os;
}
} |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #BBC_BASIC | BBC BASIC | WIDTH 80
M% = (HIMEM-END-1000) / 4
DIM B%(M%)
FOR I% = 0 TO M% : B%(I%) = 20 : NEXT
E% = 0
L% = 2
FOR C% = M% TO 14 STEP -7
D% = 0
A% = C%*2-1
FOR P% = C% TO 1 STEP -1
D% = D%*P% + B%(P%)*&64
B%(P%) = D% MOD A%
D% DIV= A%
A% -= 2
NEXT
CASE TRUE OF
WHEN D% = 99: E% = E% * 100 + D% : L% += 2
WHEN C% = M%: PRINT ;(D% DIV 100) / 10; : E% = D% MOD 100
OTHERWISE:
PRINT RIGHT$(STRING$(L%,"0") + STR$(E% + D% DIV 100),L%);
E% = D% MOD 100 : L% = 2
ENDCASE
NEXT |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #68000_Assembly | 68000 Assembly | Lookup:
;input: D0.W = the atomic number of interest.
LEA PeriodicTable,A0
ADD.W D0,D0 ;we're indexing a table of words, so double the index.
MOVE.W (A0,D0),D0 ;D0.W contains row number in the high byte and column number in the low byte.
RTS
PeriodicTable:
DC.W $FFFF ;padding since arrays start at zero in assembly.
DC.W $0101 ;HYDROGEN
DC.W $0118 ;HELIUM
DC.W $0201 ;LITHIUM
DC.W $0202 ;BERYLLIUM
DC.W $0213 ;BORON
DC.W $0214 ;CARBON
DC.W $0215 ;NITROGEN
DC.W $0216 ;OXYGEN
DC.W $0217 ;FLUORINE
DC.W $0218 ;NEON
;etc. |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Forth | Forth | include lib/choose.4th
include lib/yesorno.4th
: turn ( n1 -- n2)
." Player " . ." is up" cr \ which player is up
0 begin \ nothing so far
s" Rolling" yes/no? \ stand or roll?
while \ now roll the dice
6 choose 1+ dup ." Rolling " . dup 1 =
if drop drop 0 else + ." (" dup 0 .r ." )" then cr dup 0=
until \ until player stands or 1 is rolled
;
: pigthedice ( --)
2 0 1 over \ setup players
begin over turn + dup ." Total score: " . cr cr dup 100 < while 2swap repeat
." Player " swap . ." won with " . ." points." cr
." Player " swap . ." lost with " . ." points." cr
; \ show the results
pigthedice |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Befunge | Befunge | 55*00p1>:"ZOA>/"***7-*>\:2>/\v
>8**`!#^_$@\<(^v^)>/#2^#\<2 2
^+**"X^yYo":+1<_:.48*,00v|: <%
v".D}Tx"$,+55_^#!p00:-1g<v |<
> * + : * * + ^^ ! % 2 $ <^ <^ |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | fromrank[list_, 0] := list;
fromrank[list_, n_] :=
Prepend[fromrank[DeleteCases[list, #],
Mod[n, (Length@list - 1)!]], #] &@
RankedMin[list, Quotient[n, (Length@list - 1)!] + 1];
rank[{}] = 0;
rank[{x_, y___}] := Count[{y}, _?(# < x &)] Length@{y}! + rank[{y}];
Print /@ Table[{n, fromrank[{0, 1, 2, 3}, n],
rank@fromrank[{0, 1, 2, 3}, n]}, {n, 0, 23}];
Do[Print@fromrank[Range[0, 12 - 1], RandomInteger[12!]], {4}];
Do[Print@fromrank[Range[0, 144 - 1], RandomInteger[144!]], {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 called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #jq | jq | def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
else {i:23}
| until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
| .i * .i > $n
end;
# pretty-printing
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def table($ncols; $colwidth):
nwise($ncols) | map(lpad($colwidth)) | join(" "); |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Crystal | Crystal |
puts [1, 2, 3, 4, 5].sample(1)
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #D | D | import std.stdio, std.random;
void main() {
const items = ["foo", "bar", "baz"];
items[uniform(0, $)].writeln;
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Swift | Swift | import Foundation
extension Int {
func isPrime() -> Bool {
switch self {
case let x where x < 2:
return false
case 2:
return true
default:
return
self % 2 != 0 &&
!stride(from: 3, through: Int(sqrt(Double(self))), by: 2).contains {self % $0 == 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, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #COBOL | COBOL |
program-id. phra-rev.
data division.
working-storage section.
1 phrase pic x(28) value "rosetta code phrase reversal".
1 wk-str pic x(16).
1 binary.
2 phrase-len pic 9(4).
2 pos pic 9(4).
2 cnt pic 9(4).
procedure division.
compute phrase-len = function length (phrase)
display phrase
display function reverse (phrase)
perform display-words
move function reverse (phrase) to phrase
perform display-words
stop run
.
display-words.
move 1 to pos
perform until pos > phrase-len
unstring phrase delimited space
into wk-str count in cnt
with pointer pos
end-unstring
display function reverse (wk-str (1:cnt))
with no advancing
if pos < phrase-len
display space with no advancing
end-if
end-perform
display space
.
end program phra-rev.
|
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Arturo | Arturo | isClean?: function [s,o][
loop.with:'i s 'a [
if a = o\[i] -> return false
]
return true
]
derangements: function [n][
original: 1..n
select permutate original 'x ->
isClean? x original
]
subfactorial: function [n].memoize[
(n =< 1)? -> 1 - n
-> (n-1) * (add subfactorial n-1 subfactorial n-2)
]
print "Derangements of 1 2 3 4:"
loop derangements 4 'x [
print x
]
print "\nNumber of derangements:"
print [pad "n" 5 pad "counted" 15 pad "calculated" 15]
print repeat "-" 39
loop 0..9 'z [
counted: size derangements z
calculated: subfactorial z
print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15]
]
print ~"\n!20 = |subfactorial 20|" |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #AutoHotkey | AutoHotkey | Permutations_By_Swapping(str, list:=""){
ch := SubStr(str, 1, 1) ; get left-most charachter of str
for i, line in StrSplit(list, "`n") ; for each line in list
loop % StrLen(line) + 1 ; loop each possible position
Newlist .= RegExReplace(line, mod(i,2) ? "(?=.{" A_Index-1 "}$)" : "^.{" A_Index-1 "}\K", ch) "`n"
list := Newlist ? Trim(Newlist, "`n") : ch ; recreate list
if !str := SubStr(str, 2) ; remove charachter from left hand side
return list ; done if str is empty
return Permutations_By_Swapping(str, list) ; else recurse
} |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #BBC_BASIC | BBC BASIC | ntreated% = 9
nplacebo% = 10
DIM results%(ntreated% + nplacebo% - 1)
results%() = 85, 88, 75, 66, 25, 29, 83, 39, 97, \ REM treated group
\ 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 : REM placebo group
greater% = 0
FOR comb% = 0 TO 2^(ntreated%+nplacebo%)-1
IF FNnbits(comb%) = ntreated% THEN
tsum% = 0 : psum% = 0
FOR b% = 0 TO ntreated%+nplacebo%-1
IF comb% AND 2^b% THEN
tsum% += results%(b%)
ELSE
psum% += results%(b%)
ENDIF
NEXT
meandiff = tsum%/ntreated% - psum%/nplacebo%
IF comb% = 2^ntreated% - 1 THEN
actual = meandiff
ELSE
greater% -= meandiff > actual
groups% += 1
ENDIF
ENDIF
NEXT
percent = 100 * greater%/groups%
PRINT "Percentage groupings <= actual experiment: "; 100 - percent
PRINT "Percentage groupings > actual experiment: "; percent
END
DEF FNnbits(N%)
N% -= N% >>> 1 AND &55555555
N% = (N% AND &33333333) + (N% >>> 2 AND &33333333)
N% = (N% + (N% >>> 4)) AND &0F0F0F0F
N% += N% >>> 8 : N% += N% >>> 16
= N% AND &7F |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #C | C | #include <stdio.h>
int data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int pick(int at, int remain, int accu, int treat)
{
if (!remain) return (accu > treat) ? 1 : 0;
return pick(at - 1, remain - 1, accu + data[at - 1], treat) +
( at > remain ? pick(at - 1, remain, accu, treat) : 0 );
}
int main()
{
int treat = 0, i;
int le, gt;
double total = 1;
for (i = 0; i < 9; i++) treat += data[i];
for (i = 19; i > 10; i--) total *= i;
for (i = 9; i > 0; i--) total /= i;
gt = pick(19, 9, 0, treat);
le = total - gt;
printf("<= : %f%% %d\n > : %f%% %d\n",
100 * le / total, le, 100 * gt / total, gt);
return 0;
} |
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.
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color
// signifies the white edges on the blue squares
var LT = 0
var TR = 1
var RB = 2
var BL = 3
var Edges = [
[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],
[TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT],
[RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT],
[RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR],
[BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR],
[BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB],
[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],
[LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],
[TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],
[TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT]
]
var Light_olive = Color.hex("#d3d004")
var Pale_blue = Color.hex("#3250ff")
var W = Color.white
var B = Color.black
var Colors = [
[W, B, B, W],
[W, W, B, B],
[B, W, W, B],
[B, B, W, W]
]
class PeripheralDrift {
construct new() {
Window.resize(1000, 1000)
Canvas.resize(1000, 1000)
Window.title = "Peripheral drift illusion"
}
init() {
Canvas.cls(Light_olive)
for (x in 0..11) {
var px = 90 + x * 70
for (y in 0..11) {
var py = 90 + y * 70
Canvas.rectfill(px, py, 50, 50, Pale_blue)
drawEdge(px, py, Edges[y][x])
}
}
}
drawEdge(px, py, edge) {
var c = Colors[edge]
Canvas.line(px, py, px + 46, py, c[0], 4)
Canvas.line(px + 46, py, px + 46, py + 46, c[1], 4)
Canvas.line(px, py + 46, px + 46, py + 46, c[2], 4)
Canvas.line(px, py + 46, px, py, c[3], 4)
}
update() {}
draw(alpha) {}
}
var Game = PeripheralDrift.new() |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Ceylon | Ceylon | import com.vasileff.ceylon.random.api { ... }
"""Run the example code for Rosetta Code ["Playing cards" task] (http://rosettacode.org/wiki/Playing_cards)."""
shared void run() {
variable value deck = Deck();
print("New deck (``deck.size`` cards): ``deck``
");
deck = deck.shuffle();
print("Shuffeled deck (``deck.size`` cards): ``deck``
");
print("Deal three hands: ");
for (i in 1..3) {
value [hand, _deck] = deck.deal();
print("- Dealt ``hand.size`` cards to hand ``i`` : ``join(hand)``");
deck = _deck;
}
print("
Deck (``deck.size`` cards) after dealing three hands: ``deck``");
}
abstract class Suit() of clubs | hearts | spades | diamonds {}
object clubs extends Suit() { string = "♣"; }
object hearts extends Suit() { string = "♥"; }
object spades extends Suit() { string = "♠"; }
object diamonds extends Suit() { string = "♦"; }
abstract class Pip() of two | three | four | five | six | seven | eight | nine | ten | jack | queen | king | ace {}
object two extends Pip() { string = "2"; }
object three extends Pip() { string = "3"; }
object four extends Pip() { string = "4"; }
object five extends Pip() { string = "5"; }
object six extends Pip() { string = "6"; }
object seven extends Pip() { string = "7"; }
object eight extends Pip() { string = "8"; }
object nine extends Pip() { string = "9"; }
object ten extends Pip() { string = "10"; }
object jack extends Pip() { string = "J"; }
object queen extends Pip() { string = "Q"; }
object king extends Pip() { string = "K"; }
object ace extends Pip() { string = "A"; }
class Card(shared Pip pip, shared Suit suit) {
string = "``pip`` of ``suit``";
}
String join(Card[] cards) => ", ".join { *cards };
class Deck (cards = [ for (suit in `Suit`.caseValues) for (pip in `Pip`.caseValues) Card(pip, suit) ]) {
shared Card[] cards;
shared Deck shuffle(Random rnd = platformRandom())
=> if (nonempty cards)
then Deck( [*randomize(cards, rnd)] )
else this;
shared Integer size => cards.size;
shared Boolean empty => cards.empty;
string => if (size > 13)
then "\n " + "\n ". join { *cards.partition(13).map((cards) => join(cards)) }
else join(cards);
shared [Card[], Deck] deal(Integer handSize = 5) {
if (handSize >= cards.size) {
return [cards, Deck([])];
}
else {
return [
cards.initial(handSize),
Deck(cards.skip(handSize).sequence())
];
}
}
} |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #bc | bc | #!/usr/bin/bc -l
scaleinc= 20
define zeropad ( n ) {
auto m
for ( m= scaleinc - 1; m > 0; --m ) {
if ( n < 10^m ) {
print "0"
}
}
return ( n )
}
wantscale= scaleinc - 2
scale= wantscale + 2
oldpi= 4*a(1)
scale= wantscale
oldpi= oldpi / 1
oldpi
while( 1 ) {
wantscale= wantscale + scaleinc
scale= wantscale + 2
pi= 4*a(1)
scale= 0
digits= ((pi - oldpi) * 10^wantscale) / 1
zeropad( digits )
scale= wantscale
oldpi= pi / 1
} |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #ALGOL_68 | ALGOL 68 | BEGIN # display the period and group number of an element, #
# given its atomic number #
INT max atomic number = 118; # highest known element #
# the positions are stored as: #
# ( group number * group multiplier ) + period #
INT group multiplier = 100;
[ 1 : max atomic number ]INT position;
# construct the positions of the elements in the table #
BEGIN
STRING periodic table = "- ="
+ "-- -----="
+ "-- -----="
+ "-----------------="
+ "-----------------="
+ "--8--------------="
+ "--9--------------="
;
INT period := 1;
INT group := 1;
INT element := 1;
FOR t FROM LWB periodic table TO UPB periodic table DO
CHAR p = periodic table[ t ];
IF p = "8" OR p = "9" THEN
# lantanoids or actinoids #
INT series period = IF p = "8" THEN 8 ELSE 9 FI;
INT series group := 4;
FOR e TO 15 DO
position[ element ] := ( group multiplier * series group ) + series period;
element +:= 1;
series group +:= 1
OD
ELIF p /= " " THEN
# there is a single element here #
position[ element ] := ( group multiplier * group ) + period;
element +:= 1;
IF p = "=" THEN
# final element of the period #
period +:= 1;
group := 0
FI
FI;
group +:= 1
OD
END;
# display the period and group numbers of test elements #
[]INT test = ( 1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113 );
FOR t FROM LWB test TO UPB test DO
INT e = test[ t ];
IF e < LWB position OR e > UPB position THEN
print( ( "Invalid element: ", whole( e, 0 ), newline ) )
ELSE
INT period = position[ e ] MOD group multiplier;
INT group = position[ e ] OVER group multiplier;
print( ( "Element ", whole( e, -3 )
, " -> ", whole( period, 0 ), ", ", whole( group, -2 )
, newline
)
)
FI
OD
END |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #FreeBASIC | FreeBASIC |
Const numjugadores = 2
Const maxpuntos = 100
Dim As Byte almacenpuntos(numjugadores), jugador, puntos, tirada
Dim As String nuevotiro
Cls: Color 15: Print "The game of PIG"
Print String(15, "=") + Chr(13) + Chr(10): Color 7
Print "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
Print "Si jugador saca 2-6, se agrega al total del turno y su turno continúa."
Print "Si jugador elige 'mantener', su total de puntos se añade a su puntuación, "
Print " y se convierte en el turno del siguiente jugador." + Chr(10)
Print "El primer jugador en anotar 100 o más puntos gana." + Chr(13) + Chr(10): Color 7
Do
For jugador = 1 To numjugadores
puntos = 0
While almacenpuntos(jugador) <= maxpuntos
Color 15: Print
Print Using "Jugador #: (&_, &)"; jugador;almacenpuntos(jugador);puntos;: Color 11
Input " ¿Tirada? (Sn) ", nuevotiro
If Ucase(nuevotiro) = "S" Then
tirada = Int(Rnd* 5) + 1
Print " Tirada:"; tirada
If tirada = 1 Then
Color 11: Print Chr(10) + "¡Pierdes tu turno! jugador"; jugador;
Print " pero mantienes tu puntuación anterior de "; almacenpuntos(jugador): Color 7
Exit While
End If
puntos = puntos + tirada
Else
almacenpuntos(jugador) = almacenpuntos(jugador) + puntos
Print " Te quedas con:"; almacenpuntos(jugador)
If almacenpuntos(jugador) >= maxpuntos Then
Color 14: Print Chr(10) + "Gana el jugador"; jugador; " con"; almacenpuntos(jugador); " puntos."
Sleep: End
End If
Exit While
End If
Wend
Next jugador
Loop
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #C | C | #include <stdio.h>
typedef unsigned uint;
uint is_pern(uint n)
{
uint c = 2693408940u; // int with all prime-th bits set
while (n) c >>= 1, n &= (n - 1); // take out lowerest set bit one by one
return c & 1;
}
int main(void)
{
uint i, c;
for (i = c = 0; c < 25; i++)
if (is_pern(i))
printf("%u ", i), ++c;
putchar('\n');
for (i = 888888877u; i <= 888888888u; i++)
if (is_pern(i))
printf("%u ", i);
putchar('\n');
return 0;
} |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Nim | Nim | func mrUnrank1(vec: var openArray[int]; rank, n: int) =
if n < 1: return
let q = rank div n
let r = rank mod n
swap vec[r], vec[n - 1]
vec.mrUnrank1(q, n - 1)
func mrRank1(vec, inv: var openArray[int]; n: int): int =
if n < 2: return 0
let s = vec[n - 1]
swap vec[n - 1], vec[inv[n - 1]]
swap inv[s], inv[n - 1]
result = s + n * vec.mrRank1(inv, n - 1)
func getPermutation(vec: var openArray[int]; rank: int) =
for i in 0..vec.high: vec[i] = i
vec.mrUnrank1(rank, vec.len)
func getRank(vec: openArray[int]): int =
var v, inv = newSeq[int](vec.len)
for i, val in vec:
v[i] = val
inv[val] = i
result = v.mrRank1(inv, vec.len)
when isMainModule:
import math, random, sequtils, strformat
randomize()
var tv3: array[3, int]
for r in 0..5:
tv3.getPermutation(r)
echo &"{r:>2} → {tv3} → {tv3.getRank()}"
echo ""
var tv4: array[4, int]
for r in 0..23:
tv4.getPermutation(r)
echo &"{r:>2} → {tv4} → {tv4.getRank()}"
echo ""
var tv12: array[12, int]
for r in newSeqWith(4, rand(fac(12))):
tv12.getPermutation(r)
echo &"{r:>9} → {tv12} → {tv12.getRank()}" |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #PARI.2FGP | PARI/GP | vector(3!,i,permtonum(numtoperm(3,i-1)))==vector(3!,i,i-1)
vector(4,i,numtoperm(12,random(12!)))
for(i=1,1e6,numtoperm(144,random(144!))) |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Julia | Julia | using Primes
function pierponts(N, firstkind = true)
ret, incdec = BigInt[], firstkind ? 1 : -1
for k2 in 0:10000, k3 in 0:k2, switch in false:true
i, j = switch ? (k3, k2) : (k2, k3)
n = BigInt(2)^i * BigInt(3)^j + incdec
if isprime(n) && !(n in ret)
push!(ret, n)
if length(ret) == N * 2
return sort(ret)[1:N]
end
end
end
throw("Failed to find $(N * 2) primes")
end
println("The first 50 Pierpont primes (first kind) are: ", pierponts(50))
println("\nThe first 50 Pierpont primes (second kind) are: ", pierponts(50, false))
println("\nThe 250th Pierpont prime (first kind) is: ", pierponts(250)[250])
println("\nThe 250th Pierpont prime (second kind) is: ", pierponts(250, false)[250])
println("\nThe 1000th Pierpont prime (first kind) is: ", pierponts(1000)[1000])
println("\nThe 1000th Pierpont prime (second kind) is: ", pierponts(1000, false)[1000])
println("\nThe 2000th Pierpont prime (first kind) is: ", pierponts(2000)[2000])
println("\nThe 2000th Pierpont prime (second kind) is: ", pierponts(2000, false)[2000])
|
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Kotlin | Kotlin | import java.math.BigInteger
import kotlin.math.min
val one: BigInteger = BigInteger.ONE
val two: BigInteger = BigInteger.valueOf(2)
val three: BigInteger = BigInteger.valueOf(3)
fun pierpont(n: Int): List<List<BigInteger>> {
val p = List(2) { MutableList(n) { BigInteger.ZERO } }
p[0][0] = two
var count = 0
var count1 = 1
var count2 = 0
val s = mutableListOf<BigInteger>()
s.add(one)
var i2 = 0
var i3 = 0
var k = 1
var n2: BigInteger
var n3: BigInteger
var t: BigInteger
while (count < n) {
n2 = s[i2] * two
n3 = s[i3] * three
if (n2 < n3) {
t = n2
i2++
} else {
t = n3
i3++
}
if (t > s[k - 1]) {
s.add(t)
k++
t += one
if (count1 < n && t.isProbablePrime(10)) {
p[0][count1] = t
count1++
}
t -= two
if (count2 < n && t.isProbablePrime(10)) {
p[1][count2] = t
count2++
}
count = min(count1, count2)
}
}
return p
}
fun main() {
val p = pierpont(2000)
println("First 50 Pierpont primes of the first kind:")
for (i in 0 until 50) {
print("%8d ".format(p[0][i]))
if ((i - 9) % 10 == 0) {
println()
}
}
println("\nFirst 50 Pierpont primes of the second kind:")
for (i in 0 until 50) {
print("%8d ".format(p[1][i]))
if ((i - 9) % 10 == 0) {
println()
}
}
println("\n250th Pierpont prime of the first kind: ${p[0][249]}")
println("\n250th Pierpont prime of the first kind: ${p[1][249]}")
println("\n1000th Pierpont prime of the first kind: ${p[0][999]}")
println("\n1000th Pierpont prime of the first kind: ${p[1][999]}")
println("\n2000th Pierpont prime of the first kind: ${p[0][1999]}")
println("\n2000th Pierpont prime of the first kind: ${p[1][1999]}")
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Delphi | Delphi | !print choose [ "one" "two" "chicken" ] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | !print choose [ "one" "two" "chicken" ] |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Tcl | Tcl | proc is_prime n {
if {$n <= 1} {return false}
if {$n == 2} {return true}
if {$n % 2 == 0} {return false}
for {set i 3} {$i <= sqrt($n)} {incr i 2} {
if {$n % $i == 0} {return false}
}
return true
} |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Common_Lisp | Common Lisp |
(defun split-string (str)
"Split a string into space separated words including spaces"
(do* ((lst nil)
(i (position-if #'alphanumericp str) (position-if #'alphanumericp str :start j))
(j (when i (position #\Space str :start i)) (when i (position #\Space str :start i))) )
((null j) (nreverse (push (subseq str i nil) lst)))
(push (subseq str i j) lst)
(push " " lst) ))
(defun task (str)
(print (reverse str))
(let ((lst (split-string str)))
(print (apply #'concatenate 'string (mapcar #'reverse lst)))
(print (apply #'concatenate 'string (reverse lst))) )
nil )
|
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AutoHotkey | AutoHotkey | #NoEnv
SetBatchLines -1
Process, Priority,, high
output := "Derangements for 1, 2, 3, 4:`n"
obj := [1, 2, 3, 4], objS := obj.Clone()
Loop ; permute 4
{
obj := perm_NextObj(Obj)
If !obj
break
For k, v in obj
if ( objS[k] = v )
continue 2
output .= ObjDisp(obj) "`n"
}
output .= "`nTable of n, counted, calculated derangements:`n"
Loop 10 ; Count !n
{
obj := []
count := 0
output .= A_Tab . (i := A_Index-1) . A_Tab
Loop % i
obj[A_Index] := A_Index
objS := obj.Clone()
Loop
{
obj := perm_NextObj(Obj)
If !obj
break
For k, v in obj
if ( objS[k] = v )
continue 2
count++
}
output .= count . A_Tab . cd(i) . "`n"
}
output .= "`nApproximation of !20: " . cd(20)
MsgBox % Clipboard := output
perm_NextObj(obj){ ; next lexicographic permutation
p := 0, objM := ObjMaxIndex(obj)
Loop % objM
{
If A_Index=1
continue
t := obj[objM+1-A_Index]
n := obj[objM+2-A_Index]
If ( t < n )
{
p := objM+1-A_Index, pC := obj[p]
break
}
}
If !p
return false
Loop
{
t := obj[objM+1-A_Index]
If ( t > pC )
{
n := objM+1-A_Index, nC := obj[n]
break
}
}
obj[n] := pC, obj[p] := nC
return ObjReverse(obj, objM-p)
}
ObjReverse(Obj, tail){
o := ObjClone(Obj), ObjM := ObjMaxIndex(O)
Loop % tail
o[ObjM-A_Index+1] := Obj[ObjM+A_Index-tail]
return o
}
ObjDisp(obj){
For k, v in obj
s .= v ", "
return SubStr(s, 1, strLen(s)-2)
}
cd(n){ ; Count Derangements
static e := 2.71828182845904523536028747135
return n ? floor(ft(n)/e + 1/2) : 1
}
ft(n){ ; FacTorial
a := 1
Loop % n
a *= A_Index
return a
} |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #BASIC | BASIC | call perms(3)
print
call perms(4)
end
subroutine perms(n)
dim p((n+1)*4)
for i = 1 to n
p[i] = -i
next i
s = 1
do
print "Perm: [ ";
for i = 1 to n
print abs(p[i]); " ";
next i
print "] Sign: "; s
k = 0
for i = 2 to n
if p[i] < 0 and (abs(p[i]) > abs(p[i-1])) and (abs(p[i]) > abs(p[k])) then k = i
next i
for i = 1 to n-1
if p[i] > 0 and (abs(p[i]) > abs(p[i+1])) and (abs(p[i]) > abs(p[k])) then k = i
next i
if k then
for i = 1 to n #reverse elements > k
if abs(p[i]) > abs(p[k]) then p[i] = -p[i]
next i
if p[k] < 0 then i = k-1 else i = k+1
temp = p[k]
p[k] = p[i]
p[i] = temp
s = -s
end if
until k = 0
end subroutine |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #BBC_BASIC | BBC BASIC | PROCperms(3)
PRINT
PROCperms(4)
END
DEF PROCperms(n%)
LOCAL p%(), i%, k%, s%
DIM p%(n%)
FOR i% = 1 TO n%
p%(i%) = -i%
NEXT
s% = 1
REPEAT
PRINT "Perm: [ ";
FOR i% = 1 TO n%
PRINT ;ABSp%(i%) " ";
NEXT
PRINT "] Sign: ";s%
k% = 0
FOR i% = 2 TO n%
IF p%(i%)<0 IF ABSp%(i%)>ABSp%(i%-1) IF ABSp%(i%)>ABSp%(k%) k% = i%
NEXT
FOR i% = 1 TO n%-1
IF p%(i%)>0 IF ABSp%(i%)>ABSp%(i%+1) IF ABSp%(i%)>ABSp%(k%) k% = i%
NEXT
IF k% THEN
FOR i% = 1 TO n%
IF ABSp%(i%)>ABSp%(k%) p%(i%) *= -1
NEXT
i% = k%+SGNp%(k%)
SWAP p%(k%),p%(i%)
s% = -s%
ENDIF
UNTIL k% = 0
ENDPROC |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace PermutationTest {
class Program {
static readonly List<int> DATA = new List<int>{
85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98
};
static int Pick(int at, int remain, int accu, int treat) {
if (remain == 0) {
return (accu > treat) ? 1 : 0;
}
return Pick(at - 1, remain - 1, accu + DATA[at - 1], treat)
+ ((at > remain) ? Pick(at - 1, remain, accu, treat) : 0);
}
static void Main() {
int treat = 0;
double total = 1.0;
for (int i = 0; i <= 8; i++) {
treat += DATA[i];
}
for (int i = 19; i >= 11; i--) {
total *= i;
}
for (int i = 9; i >= 1; --i) {
total /= i;
}
int gt = Pick(19, 9, 0, treat);
int le = (int) (total - gt);
Console.WriteLine("<= {0}% {1}", 100.0 * le / total, le);
Console.WriteLine(" > {0}% {1}", 100.0 * gt / total, gt);
}
}
} |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #C.2B.2B | C++ | #include<iostream>
#include<vector>
#include<numeric>
#include<functional>
class
{
public:
int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}
private:
int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }
int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}
}combinations;
int main()
{
static constexpr int treatment = 9;
const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);
std::function<int (int, int, int)> pick;
pick = [&](int n, int from, int accumulated)
{
if(n == 0)
return accumulated > treated ? 1 : 0;
else
return pick(n - 1, from - 1, accumulated + data[from - 1]) +
(from > n ? pick(n, from - 1, accumulated) : 0);
};
int total = combinations(data.size(), treatment);
int greater = pick(treatment, data.size(), 0);
int lesser = total - greater;
std::cout << "<= : " << 100.0 * lesser / total << "% " << lesser << std::endl
<< " > : " << 100.0 * greater / total << "% " << greater << std::endl;
} |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #11l | 11l | F φ(n)
R sum((1..n).filter(k -> gcd(@n, k) == 1).map(k -> 1))
F perfect_totient(cnt)
[Int] r
L(n0) 1..
V parts = 0
V n = n0
L n != 1
n = φ(n)
parts += n
I parts == n0
r [+]= n0
I r.len == cnt
R r
print(perfect_totient(20)) |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Clojure | Clojure | (def suits [:club :diamond :heart :spade])
(def pips [:ace 2 3 4 5 6 7 8 9 10 :jack :queen :king])
(defn deck [] (for [s suits p pips] [s p]))
(def shuffle clojure.core/shuffle)
(def deal first)
(defn output [deck]
(doseq [[suit pip] deck]
(println (format "%s of %ss"
(if (keyword? pip) (name pip) pip)
(name suit))))) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Bracmat | Bracmat | ( pi
= f,q r t k n l,first
. !arg:((=?f),?q,?r,?t,?k,?n,?l)
& yes:?first
& whl
' ( 4*!q+!r+-1*!t+-1*!n*!t:<0
& f$!n
& ( !first:yes
& f$"."
& no:?first
|
)
& "compute and update variables for next cycle"
& 10*(!r+-1*!n*!t):?nr
& div$(10*(3*!q+!r).!t)+-10*!n:?n
& !q*10:?q
& !nr:?r
| "compute and update variables for next cycle"
& (2*!q+!r)*!l:?nr
& div$(!q*(7*!k+2)+!r*!l.!t*!l):?nn
& !q*!k:?q
& !t*!l:?t
& !l+2:?l
& !k+1:?k
& !nn:?n
& !nr:?r
)
)
& pi$((=.put$!arg),1,0,1,1,3,3) |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #Applesoft_BASIC | Applesoft BASIC | 0 GR:HOME:COLOR=11:FORR=1TO7:FORC=1TO2:GOSUB7:NEXTC,R:COLOR=7:FORR=4TO7:FORC=3+(R>5)TO12:GOSUB7:NEXTC,R:COLOR=13:FORR=2TO7:FORC=13TO18:GOSUB7:NEXTC,R
1 forr=2to7:forc=13to18:GOSUB7:NEXTC,R:COLOR=14:R=8:FORC=4TO18:GOSUB7:NEXTC:COLOR=12:R=9:FORC=4TO18:GOSUB7:NEXTC:R=9:FORC=4TO18:GOSUB7:NEXTC:Z=2:R=7:C=3:GOSUB7:COLOR=14:R=6:C=3:GOSUB7:COLOR=15
2 S=14:W=18:FORI=1TO7:READN(I),I(I):NEXT:DATA2,0,10,0,18,0,36,0,54,0,86,57,118,89,1,1,1,2,1,18,29,4,11,42,5,6,57,8,4,58,8,5,72,6,4,89,9,4,59,8,6,71,8,18,90,9,5,103,9,18
3 FORT=1TO8:READA,Y,X:GOSUB4:PRINTRIGHT$(" "+STR$(A),3)"->"R" "LEFT$(STR$(C)+" ",3);:GOSUB7:NEXTT:VTAB23:END
4 N=0:FORR=1TO7:P=N:N=N(R):IFA>NTHEN:NEXTR
5 E=N-P:K=A-P:IFI(R)AND(I(R)<=AANDA<=I(R)+S)THENR=R+2:C=K+1:RETURN
6 E=W-E:L=1+(N>2):C=K+E*(K>L):RETURN
7 K=C+(R=1ANDC=2)*16:VLINR*4+Z,R*4+2ATK*2+1:RETURN |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Go | Go | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano()) //Set seed to current time
playerScores := [...]int{0, 0}
turn := 0
currentScore := 0
for {
player := turn % len(playerScores)
fmt.Printf("Player %v [%v, %v], (H)old, (R)oll or (Q)uit: ", player,
playerScores[player], currentScore)
var answer string
fmt.Scanf("%v", &answer)
switch strings.ToLower(answer) {
case "h": //Hold
playerScores[player] += currentScore
fmt.Printf(" Player %v now has a score of %v.\n\n", player, playerScores[player])
if playerScores[player] >= 100 {
fmt.Printf(" Player %v wins!!!\n", player)
return
}
currentScore = 0
turn += 1
case "r": //Roll
roll := rand.Intn(6) + 1
if roll == 1 {
fmt.Printf(" Rolled a 1. Bust!\n\n")
currentScore = 0
turn += 1
} else {
fmt.Printf(" Rolled a %v.\n", roll)
currentScore += roll
}
case "q": //Quit
return
default: //Incorrent input
fmt.Print(" Please enter one of the given inputs.\n")
}
}
fmt.Printf("Player %v wins!!!\n", (turn-1)%len(playerScores))
} |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #C.23 | C# | using System;
using System.Linq;
namespace PerniciousNumbers
{
class Program
{
public static int PopulationCount(long n)
{
int cnt = 0;
do
{
if ((n & 1) != 0)
{
cnt++;
}
} while ((n >>= 1) > 0);
return cnt;
}
public static bool isPrime(int x)
{
if (x <= 2 || (x & 1) == 0)
{
return x == 2;
}
var limit = Math.Sqrt(x);
for (int i = 3; i <= limit; i += 2)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
private static IEnumerable<int> Pernicious(int start, int count, int take)
{
return Enumerable.Range(start, count).Where(n => isPrime(PopulationCount(n))).Take(take);
}
static void Main(string[] args)
{
foreach (var n in Pernicious(0, int.MaxValue, 25))
{
Console.Write("{0} ", n);
}
Console.WriteLine();
foreach (var n in Pernicious(888888877, 11, 11))
{
Console.Write("{0} ", n);
}
Console.ReadKey();
}
}
} |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Perl | Perl | use ntheory qw/:all/;
my $n = 3;
print " Iterate Lexicographic rank/unrank of $n objects\n";
for my $k (0 .. factorial($n)-1) {
my @perm = numtoperm($n, $k);
my $rank = permtonum(\@perm);
die unless $rank == $k;
printf "%2d --> [@perm] --> %2d\n", $k, $rank;
}
print "\n";
print " Four 12-object random permutations using ranks\n";
print join(" ", numtoperm(12,urandomm(factorial(12)))), "\n" for 1..4;
print "\n";
print " Four 12-object random permutations using randperm\n";
print join(" ", randperm(12)),"\n" for 1..4;
print "\n";
print " Four 4-object random permutations of 100k objects using randperm\n";
print join(" ", randperm(100000,4)),"\n" for 1..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 called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Lua | Lua | local function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local f, limit = 5, math.sqrt(n)
for f = 5, limit, 6 do
if n % f == 0 then return false end
if n % (f+2) == 0 then return false end
end
return true
end
local function s3iter()
local s, i2, i3 = {1}, 1, 1
return function()
local n2, n3, val = 2*s[i2], 3*s[i3], s[#s]
s[#s+1] = math.min(n2, n3)
i2, i3 = i2 + (n2<=n3 and 1 or 0), i3 + (n2>=n3 and 1 or 0)
return val
end
end
local function pierpont(n)
local list1, list2, s3next = {}, {}, s3iter()
while #list1 < n or #list2 < n do
local s3 = s3next()
if #list1 < n then
if isprime(s3+1) then list1[#list1+1] = s3+1 end
end
if #list2 < n then
if isprime(s3-1) then list2[#list2+1] = s3-1 end
end
end
return list1, list2
end
local N = 50
local p1, p2 = pierpont(N)
print("First 50 Pierpont primes of the first kind:")
for i, p in ipairs(p1) do
io.write(string.format("%8d%s", p, (i%10==0 and "\n" or " ")))
end
print()
print("First 50 Pierpont primes of the second kind:")
for i, p in ipairs(p2) do
io.write(string.format("%8d%s", p, (i%10==0 and "\n" or " ")))
end |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #EasyLang | EasyLang | ar$[] = [ "spring" "summer" "autumn" "winter" ]
print ar$[random len ar$[]] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #EchoLisp | EchoLisp |
(define (pick-random list)
(list-ref list (random (length list))))
(pick-random (iota 1000)) → 667
(pick-random (iota 1000)) → 179
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #TI-83_BASIC | TI-83 BASIC | Prompt A
If A=2:Then
Disp "PRIME"
Stop
End
If (fPart(A/2)=0 and A>0) or A<2:Then
Disp "NOT PRIME"
Stop
End
1→P
For(B,3,int(√(A)))
If FPart(A/B)=0:Then
0→P
√(A)→B
End
B+1→B
End
If P=1:Then
Disp "PRIME"
Else
Disp "NOT PRIME"
End
|
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #D | D | void main() @safe {
import std.stdio, std.range, std.algorithm;
immutable phrase = "rosetta code phrase reversal";
phrase.retro.writeln; // Reversed string.
phrase.splitter.map!retro.joiner(" ").writeln; // Words reversed.
phrase.split.retro.joiner(" ").writeln; // Word order reversed.
} |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BBC_BASIC | BBC BASIC | PRINT"Derangements for the numbers 0,1,2,3 are:"
Count% = FN_Derangement_Generate(4,TRUE)
PRINT'"Table of n, counted derangements, calculated derangements :"
FOR I% = 0 TO 9
PRINT I%, FN_Derangement_Generate(I%,FALSE), FN_SubFactorial(I%)
NEXT
PRINT'"There is no long int in BBC BASIC!"
PRINT"!20 = ";FN_SubFactorial(20)
END
DEF FN_Derangement_Generate(N%, fPrintOut)
LOCAL A%(), O%(), C%, D%, I%, J%
IF N% = 0 THEN = 1
DIM A%(N%-1), O%(N%-1)
FOR I% = 0 TO N%-1 : A%(I%) = I% : NEXT
O%() = A%()
FOR I% = 0 TO FN_Factorial(DIM(A%(),1)+1)-1
PROC_NextPermutation(A%())
D% = TRUE
FOR J%=0 TO N%-1
IF A%(J%) = O%(J%) THEN D% = FALSE
NEXT
IF D% THEN
C% += 1
IF fPrintOut THEN
FOR K% = 0 TO N%-1
PRINT ;A%(K%);" ";
NEXT
PRINT
ENDIF
ENDIF
NEXT
= C%
DEF PROC_NextPermutation(A%())
LOCAL first, last, elementcount, pos
elementcount = DIM(A%(),1)
IF elementcount < 1 THEN ENDPROC
pos = elementcount-1
WHILE A%(pos) >= A%(pos+1)
pos -= 1
IF pos < 0 THEN
PROC_Permutation_Reverse(A%(), 0, elementcount)
ENDPROC
ENDIF
ENDWHILE
last = elementcount
WHILE A%(last) <= A%(pos)
last -= 1
ENDWHILE
SWAP A%(pos), A%(last)
PROC_Permutation_Reverse(A%(), pos+1, elementcount)
ENDPROC
DEF PROC_Permutation_Reverse(A%(), firstindex, lastindex)
LOCAL first, last
first = firstindex
last = lastindex
WHILE first < last
SWAP A%(first), A%(last)
first += 1
last -= 1
ENDWHILE
ENDPROC
DEF FN_Factorial(N) : IF (N = 1) OR (N = 0) THEN =1 ELSE = N * FN_Factorial(N-1)
DEF FN_SubFactorial(N) : IF N=0 THEN =1 ELSE =N*FN_SubFactorial(N-1)+-1^N
REM Or you could use:
REM DEF FN_SubFactorial(N) : IF N<1 THEN =1 ELSE =(N-1)*(FN_SubFactorial(N-1)+FN_SubFactorial(N-2)) |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #C | C |
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int flag = 1;
void heapPermute(int n, int arr[],int arrLen){
int temp;
int i;
if(n==1){
printf("\n[");
for(i=0;i<arrLen;i++)
printf("%d,",arr[i]);
printf("\b] Sign : %d",flag);
flag*=-1;
}
else{
for(i=0;i<n-1;i++){
heapPermute(n-1,arr,arrLen);
if(n%2==0){
temp = arr[i];
arr[i] = arr[n-1];
arr[n-1] = temp;
}
else{
temp = arr[0];
arr[0] = arr[n-1];
arr[n-1] = temp;
}
}
heapPermute(n-1,arr,arrLen);
}
}
int main(int argC,char* argV[0])
{
int *arr, i=0, count = 1;
char* token;
if(argC==1)
printf("Usage : %s <comma separated list of integers>",argV[0]);
else{
while(argV[1][i]!=00){
if(argV[1][i++]==',')
count++;
}
arr = (int*)malloc(count*sizeof(int));
i = 0;
token = strtok(argV[1],",");
while(token!=NULL){
arr[i++] = atoi(token);
token = strtok(NULL,",");
}
heapPermute(i,arr,count);
}
return 0;
}
|
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Common_Lisp | Common Lisp | (defun perm-test (s1 s2)
(let ((more 0) (leq 0)
(all-data (append s1 s2))
(thresh (apply #'+ s1)))
(labels
((recur (data sum need avail)
(cond ((zerop need) (if (>= sum thresh)
(incf more)
(incf leq)))
((>= avail need)
(recur (cdr data) sum need (1- avail))
(recur (cdr data) (+ sum (car data)) (1- need) (1- avail))))))
(recur all-data 0 (length s1) (length all-data))
(cons more leq))))
(let* ((a (perm-test '(68 41 10 49 16 65 32 92 28 98)
'(85 88 75 66 25 29 83 39 97)))
(x (car a))
(y (cdr a))
(s (+ x y)))
(format t "<=: ~a ~6f%~% >: ~a ~6f%~%"
x (* 100e0 (/ x s))
y (* 100e0 (/ y s)))) |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program totientPerfect64.s */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ MAXI, 20
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessNumber: .asciz " @ "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
mov x4,#2 // start number
mov x6,#0 // line counter
mov x7,#0 // result counter
1:
mov x0,x4
mov x5,#0 // totient sum
2:
bl totient // compute totient
add x5,x5,x0 // add totient
cmp x0,#1
beq 3f
b 2b
3:
cmp x5,x4 // compare number and totient sum
bne 4f
mov x0,x4 // display result if equals
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrszMessNumber
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
add x7,x7,#1
add x6,x6,#1 // increment indice line display
cmp x6,#5 // if = 5 new line
bne 4f
mov x6,#0
ldr x0,qAdrszCarriageReturn
bl affichageMess
4:
add x4,x4,#1 // increment number
cmp x7,#MAXI // maxi ?
blt 1b // and loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszMessNumber: .quad szMessNumber
/******************************************************************/
/* compute totient of number */
/******************************************************************/
/* x0 contains number */
totient:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x4,x0 // totient
mov x5,x0 // save number
mov x1,#0 // for first divisor
1: // begin loop
mul x3,x1,x1 // compute square
cmp x3,x5 // compare number
bgt 4f // end
add x1,x1,#2 // next divisor
udiv x2,x5,x1
msub x3,x1,x2,x5 // compute remainder
cmp x3,#0 // remainder null ?
bne 3f
2: // begin loop 2
udiv x2,x5,x1
msub x3,x1,x2,x5 // compute remainder
cmp x3,#0
csel x5,x2,x5,eq // new value = quotient
beq 2b
udiv x2,x4,x1 // divide totient
sub x4,x4,x2 // compute new totient
3:
cmp x1,#2 // first divisor ?
mov x0,1
csel x1,x0,x1,eq // divisor = 1
b 1b // and loop
4:
cmp x5,#1 // final value > 1
ble 5f
mov x0,x4 // totient
mov x1,x5 // divide by value
udiv x2,x4,x5 // totient divide by value
sub x4,x4,x2 // compute new totient
5:
mov x0,x4
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #ALGOL_68 | ALGOL 68 | BEGIN # find the first 20 perfect totient numbers #
# returns the number of integers k where 1 <= k <= n that are mutually prime to n #
PROC totient = ( INT n )INT: # algorithm from the second Go sample #
IF n < 3 THEN 1
ELIF n = 3 THEN 2
ELSE
INT result := n;
INT v := n;
INT i := 2;
WHILE i * i <= v DO
IF v MOD i = 0 THEN
WHILE v MOD i = 0 DO v OVERAB i OD;
result -:= result OVER i
FI;
IF i = 2 THEN
i := 1
FI;
i +:= 2
OD;
IF v > 1 THEN result -:= result OVER v FI;
result
FI # totient # ;
# find the first 20 perfect totient numbers #
INT p count := 0;
FOR i FROM 2 WHILE p count < 20 DO
INT t := totient( i );
INT sum := t;
WHILE t /= 1 DO
t := totient( t );
sum +:= t
OD;
IF sum = i THEN
# have a perfect totient #
p count +:= 1;
print( ( " ", whole( i, 0 ) ) )
FI
OD;
print( ( newline ) )
END |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #CLU | CLU | % Represents one playing card.
card = cluster is make, parse, unparse, equal, all_cards
rep = struct[pip: int, suit: char]
own suits: string := "CHSD";
own pips: sequence[string] := sequence[string]$
["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
find_pip = proc (pip: string) returns (int) signals (bad_format)
for i: int in int$from_to(1, sequence[string]$size(pips)) do
if pips[i] = pip then return(i) end
end
signal bad_format
end find_pip
make = proc (pip: int, suit: char) returns (cvt) signals (bad_format)
if string$indexc(suit, suits) = 0
cor ~(pip >= 1 cand pip <= 13)
then signal bad_format
end
return(rep${pip: pip, suit: suit})
end make
parse = proc (s: string) returns (cvt) signals (bad_format)
size: int := string$size(s)
if size<2 cor size>3 then signal bad_format end
pip: string := string$substr(s, 1, size-1)
suit: char := string$rest(s, size-1)[1]
return(down(make(find_pip(pip), suit))) resignal bad_format
end parse
unparse = proc (c: cvt) returns (string)
return( pips[c.pip] || string$c2s(c.suit) )
end unparse
equal = proc (a, b: cvt) returns (bool)
return( a.pip = b.pip cand a.suit = b.suit )
end equal
% Yield all cards in the canonical order
all_cards = iter () yields (cvt)
for suit: char in string$chars(suits) do
for pip: int in int$from_to(1,sequence[string]$size(pips)) do
yield(down(make(pip, suit)))
end
end
end all_cards
end card
% Represents a deck
deck = cluster is new, shuffle, cards, deal, unparse
rep = array[card]
new = proc () returns (cvt)
d: rep := rep$new()
for c: card in card$all_cards() do rep$addh(d, c) end
return(d)
end new
shuffle = proc (d: cvt)
lo: int := rep$low(d)
hi: int := rep$high(d)
for i: int in int$from_to_by(hi, lo+1, -1) do
j: int := lo + random$next(i-lo)
c: card := d[i]
d[i] := d[j]
d[j] := c
end
end shuffle
cards = iter (d: cvt) yields (card)
for c: card in rep$elements(d) do yield(c) end
end cards
deal = proc (d: cvt) returns (card) signals (empty)
if rep$empty(d) then signal empty end
return(rep$reml(d))
end deal
unparse = proc (d: cvt) returns (string)
ss: stream := stream$create_output()
n: int := 0
for c: card in cards(up(d)) do
if n~=0 cand n//13=0 then stream$putc(ss, '\n')
elseif n~=0 then stream$putc(ss, ' ')
end
stream$puts(ss, card$unparse(c))
n := n+1
end
return(stream$get_contents(ss))
end unparse
end deck
start_up = proc ()
po: stream := stream$primary_output()
% seed the RNG
d_: date := now()
random$seed(d_.second + 60*(d_.minute + 60*d_.hour))
% make a new deck
d: deck := deck$new()
stream$putl(po, "New deck: ")
stream$putl(po, deck$unparse(d))
% shuffle the deck
deck$shuffle(d)
stream$putl(po, "\nShuffled deck: ")
stream$putl(po, deck$unparse(d))
% deal some cards
stream$puts(po, "\nDealing 10 cards:")
for i: int in int$from_to(1, 10) do
stream$puts(po, " " || card$unparse(deck$deal(d)))
end
% show remaining deck
stream$putl(po, "\n\nRemaining cards in deck:")
stream$putl(po, deck$unparse(d))
end start_up |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
/* write out digits up to the last one not preceding a 0 or 9*/
got -= 2; /* -2: length estimate may be longer than actual */
while (s[got] == '0' || s[got] == '9') got--;
printf("%.*s", (int)(got - done), s + done);
free(s);
done = got;
/* double the desired digits; slows down at least cubically */
accu *= 2;
}
return 0;
} |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #BASIC | BASIC | SUB MostarPos (N)
DIM a(7)
RESTORE a:
FOR x = 0 TO 7: READ a(x): NEXT x
DIM b(7)
RESTORE b:
FOR x = 0 TO 7: READ b(x): NEXT x
I = 7
WHILE a(I) > N
I = I - 1
WEND
M = N + b(I)
R = (M \ 18) + 1
C = (M MOD 18) + 1
PRINT USING "Atomic number ### -> #_, ##"; N; R; C
END SUB
DIM Element(0 TO 12)
RESTORE elements
elements:
DATA 1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113
FOR x = 0 TO 12: READ Element(x): NEXT x
FOR I = 0 TO UBOUND(Element)
MostarPos (Element(I))
NEXT I
a:
DATA 1, 2, 5, 13, 57, 72, 89, 104
b:
DATA -1, 15, 25, 35, 72, 21, 58, 7 |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Groovy | Groovy |
class PigDice {
final static int maxScore = 100;
final static yesses = ["yes", "y", "", "Y", "YES"]
static main(args) {
def playersCount = 2
Scanner sc = new Scanner(System.in)
Map scores = [:]
def current = 0
def player = 0
def gameOver = false
def firstThrow = true
Random rnd = new Random()
// Initialise the players' scores
(0..(playersCount-1)).each{ it->
scores[it] = 0
}
// Game starts
while (!gameOver) {
def nextPlayer = false
String ln
// Automatic rolls for the first dice roll
if (firstThrow){
println "player ${player+1} Auto Rolling... "
ln = 'y'
firstThrow = false
} else {
println "player ${player+1} Rolling? Yes(y) or No(n) "
ln = sc.nextLine()
}
if (ln in yesses){
// if yes then roll the dice
int rolled = rnd.nextInt(6) + 1
print "The Roll was $rolled --- "
if (rolled == 1) {
println " Bust! Player ${player+1} loses $current but keep ${scores[player]}"
current = 0
nextPlayer = true
firstThrow = true
} else {
// dice rolls 2 to 6
current = current + rolled
if ((current + scores[player]) > maxScore){
gameOver = true
}else{
// as a session score gets larger the message returned changes
switch (current){
case 6..15:
print "Good. "
break
case 15..29:
print "lucky! "
break
case 29..39:
print "Great! "
break
default:
print "Amazing "
}
println "Player ${player+1} now has $current this session (possible score of ${current + scores[player]})"
}
}
} else{
// if no then bank the session score
nextPlayer = true
firstThrow = true
scores[player] = scores[player] + current
current = 0
println "chicken! player ${player+1} now has ${scores[player]} and $gameOver"
println "Current scores :"
for (i in scores){
println "player ${i.key + 1}| ${i.value} "
}
println "------------------------------"
}
println ""
if (nextPlayer) {
player = (player+1)%playersCount
println "** Next player is ${player+1}"
}
}
// Game ends
println "Player ${player+1} wins"
}
}
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #C.2B.2B | C++ |
#include <iostream>
using namespace std;
int main() {
int cnt = 0, cnt2, cnt3, tmp, binary[8];
for (int i = 3; cnt < 25; i++) {
tmp = i;
cnt2 = 0;
cnt3 = 0;
for (int j = 7; j > 0; j--) {
binary[j] = tmp % 2;
tmp /= 2;
}
binary[0] = tmp;
for (int j = 0; j < 8; j++) {
if (binary[j] == 1) {
cnt2++;
}
}
for (int j = 2; j <= (cnt2 / 2); j++) {
if (cnt2 % j == 0) {
cnt3++;
break;
}
}
if (cnt3 == 0 && cnt2 != 1) {
cout << i << endl;
cnt++;
}
}
cout << endl;
int binary2[31];
for (int i = 888888877; i <= 888888888; i++) {
tmp = i;
cnt2 = 0;
cnt3 = 0;
for (int j = 30; j > 0; j--) {
binary2[j] = tmp % 2;
tmp /= 2;
}
binary2[0] = tmp;
for (int j = 0; j < 31; j++) {
if (binary2[j] == 1) {
cnt2++;
}
}
for (int j = 2; j <= (cnt2 / 2); j++) {
if (cnt2 % j == 0) {
cnt3++;
break;
}
}
if (cnt3 == 0 && cnt2 != 1) {
cout << i << endl;
}
}
}
|
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Phix | Phix | with javascript_semantics
function get_rank(sequence l)
integer r = length(l)
sequence inv = repeat(0,r)
for i=1 to r do
inv[l[i]+1] = i-1
end for
integer res = 0, mul = 1
l = deep_copy(l)
for n=r to 2 by -1 do
integer s = l[n]
l[inv[n]+1] = s
inv[s+1] = inv[n]
res += s*mul
mul *= n
end for
return res
end function
puts(1,"rank->permute->rank:\n")
sequence l = tagset(2,0)
for n=1 to factorial(length(l)) do
sequence p = permute(n,l)
?{n-1,p,get_rank(p)}
end for
puts(1,"4 random individual samples of 12 items:\n")
l = tagset(11,0)
for i=1 to 4 do
?permute(rand(factorial(12)),l)
end for
|
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #M2000_Interpreter | M2000 Interpreter | Module Pierpoint_Primes {
Form 80
Set Fast !
const NPP=50
dim pier(1 to 2, 1 to NPP), np(1 to 2) = 0
def long x = 1, j
while np(1)<=NPP or np(2)<=NPP
x++
j = @is_pierpont(x)
if j>0 Else Continue
if j mod 2 = 1 then np(1)++ :if np(1) <= NPP then pier(1, np(1)) = x
if j > 1 then np(2)++ : if np(2) <= NPP then pier(2, np(2)) = x
end while
print "First ";NPP;" Pierpont primes of the first kind:"
for j = 1 to NPP
print pier(2, j),
next j
if pos>0 then print
print "First ";NPP;" Pierpont primes of the second kind:"
for j = 1 to NPP
print pier(1, j),
next j
if pos>0 then print
Set Fast
function is_prime(n as decimal)
if n < 2 then = false : exit function
if n <4 then = true : exit function
if n mod 2 = 0 then = false : exit function
local i as long
for i = 3 to int(sqrt(n))+1 step 2
if n mod i = 0 then = false : exit function
next i
= true
end function
function is_23(n as long)
while n mod 2 = 0
n = n div 2
end while
while n mod 3 = 0
n = n div 3
end while
if n = 1 then = true else = false
end function
function is_pierpont(n as long)
if not @is_prime(n) then = 0& : exit function 'not prime
Local p1 = @is_23(n+1), p2 = @is_23(n-1)
if p1 and p2 then = 3 : exit function 'pierpont prime of both kinds
if p1 then = 1 : exit function 'pierpont prime of the 1st kind
if p2 then = 2 : exit function 'pierpont prime of the 2nd kind
= 0 'prime, but not pierpont
end function
}
Pierpoint_Primes |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Elena | Elena | import extensions;
extension listOp
{
randomItem()
= self[randomGenerator.eval(self.Length)];
}
public program()
{
var item := new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
console.printLine("I picked element ",item.randomItem())
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Elixir | Elixir | iex(1)> list = Enum.to_list(1..20)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
iex(2)> Enum.random(list)
19
iex(3)> Enum.take_random(list,4)
[19, 20, 7, 15] |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Tiny_BASIC | Tiny BASIC | PRINT "ENTER A NUMBER "
INPUT P
GOSUB 100
IF Z = 1 THEN PRINT "It is prime."
IF Z = 0 THEN PRINT "It isn't prime."
END
100 REM PRIMALITY OF THE NUMBER P BY TRIAL DIVISION
IF P < 2 THEN RETURN
LET Z = 1
IF P < 4 THEN RETURN
LET I = 2
110 IF (P/I)*I = P THEN LET Z = 0
IF Z = 0 THEN RETURN
LET I = I + 1
IF I*I <= P THEN GOTO 110
RETURN |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Dyalect | Dyalect | let str = "rosetta code phrase reversal"
//or you can use a built-in method String.reverse
func reverse(str) {
let xs = []
for i in (str.Length()-1)^-1..0 {
xs.Add(str[i])
}
String.Concat(values: xs)
}
func reverseByWord(str) {
let words = str.Split(" ")
let xs = []
for w in words {
xs.Add(reverse(w))
xs.Add(" ")
}
String.Concat(values: xs)
}
func reverseWords(str) {
let words = str.Split(" ")
let xs = []
for i in (words.Length()-1)^-1..0 {
xs.Add(words[i])
xs.Add(" ")
}
String.Concat(values: xs)
}
print("1. \(reverse(str))")
print("2. \(reverseByWord(str))")
print("3. \(reverseWords(str))") |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #EchoLisp | EchoLisp |
(define (string-reverse string)
(list->string (reverse (string->list string))))
(define (task str)
(for-each writeln (list
(string-reverse str)
(string-join (map string-reverse (string-split str )))
(string-join (reverse (string-split str ))))))
(task "rosetta code phrase reversal")
"lasrever esarhp edoc attesor"
"attesor edoc esarhp lasrever"
"reversal phrase code rosetta"
|
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Bracmat | Bracmat | ( ( calculated-!n
= memo answ
. (memo==)
& ( !arg:0&1
| !arg:1&0
| !(memo.):? (!arg.?answ) ?&!answ
| (!arg+-1)
* (calculated-!n$(!arg+-1)+calculated-!n$(!arg+-2))
: ?answ
& (!arg.!answ) !(memo.):?(memo.)
& !answ
)
)
& ( counted-!n
= p P h H A Z L
. !arg:(%?p ?P.?H.?L)
& !H
: ?A
(%@?h:~!p)
(?Z&counted-!n$(!P.!A !Z.!h !L))
| !arg:(..?L)
& 1+!count:?count
& (!count.!L) !D:?D
& ~
)
& out$"Derangements of 1 2 3 4"
& :?D
& 0:?count
& ( counted-!n$(4 3 2 1.4 3 2 1.)
| out$!D
)
& ( pad
= len w
. @(!arg:? [?len)
& @(" ":? [!len ?w)
& !w !arg
)
& :?K
& -1:?N
& out$(str$(N pad$List pad$Calc))
& whl
' ( !N+1:<10:?N
& ( 0:?count
& :?D
& counted-!n$(!K.!K.)
| out$(str$(!N pad$!count pad$(calculated-!n$!N)))
)
& !N !K:?K
)
& out$("!20 =" calculated-!n$20)
& lst$calculated-!n
) |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #C.2B.2B | C++ |
#include <iostream>
#include <vector>
using namespace std;
vector<int> UpTo(int n, int offset = 0)
{
vector<int> retval(n);
for (int ii = 0; ii < n; ++ii)
retval[ii] = ii + offset;
return retval;
}
struct JohnsonTrotterState_
{
vector<int> values_;
vector<int> positions_; // size is n+1, first element is not used
vector<bool> directions_;
int sign_;
JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}
int LargestMobile() const // returns 0 if no mobile integer exists
{
for (int r = values_.size(); r > 0; --r)
{
const int loc = positions_[r] + (directions_[r] ? 1 : -1);
if (loc >= 0 && loc < values_.size() && values_[loc] < r)
return r;
}
return 0;
}
bool IsComplete() const { return LargestMobile() == 0; }
void operator++() // implement Johnson-Trotter algorithm
{
const int r = LargestMobile();
const int rLoc = positions_[r];
const int lLoc = rLoc + (directions_[r] ? 1 : -1);
const int l = values_[lLoc];
// do the swap
swap(values_[lLoc], values_[rLoc]);
swap(positions_[l], positions_[r]);
sign_ = -sign_;
// change directions
for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)
*pd = !*pd;
}
};
int main(void)
{
JohnsonTrotterState_ state(4);
do
{
for (auto v : state.values_)
cout << v << " ";
cout << "\n";
++state;
} while (!state.IsComplete());
}
|
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #D | D | import std.stdio, std.algorithm, std.array, combinations3;
auto permutationTest(T)(in T[] a, in T[] b) pure nothrow @safe {
immutable tObs = a.sum;
auto combs = combinations!false(a ~ b, a.length);
immutable under = combs.count!(perm => perm.sum <= tObs);
return under * 100.0 / combs.length;
}
void main() {
immutable treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97];
immutable controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98];
immutable under = permutationTest(treatmentGroup, controlGroup);
writefln("Under =%6.2f%%\nOver =%6.2f%%", under, 100.0 - under);
} |
http://rosettacode.org/wiki/Perlin_noise | Perlin noise | The Perlin noise is a kind of gradient noise invented by Ken Perlin around the end of the twentieth century and still currently heavily used in computer graphics, most notably to procedurally generate textures or heightmaps.
The Perlin noise is basically a pseudo-random mapping of
R
d
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #11l | 11l | V p = [-1] * 512
V permutation = [151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]
L(i) 256
p[256 + i] = p[i] = permutation[i]
F fade(t)
R t ^ 3 * (t * (t * 6 - 15) + 10)
F linerp(t, a, b)
R a + t * (b - a)
F grad(hash, x, y, z)
V h = hash [&] 15
V u = I h < 8 {x} E y
V v = I h < 4 {y} E (I h C (12, 14) {x} E z)
R (I (h [&] 1) == 0 {u} E -u) + (I (h [&] 2) == 0 {v} E -v)
F perlin_noise(=x, =y, =z)
V _x_ = Int(x) [&] 255
V Y = Int(y) [&] 255
V Z = Int(z) [&] 255
x -= Int(x)
y -= Int(y)
z -= Int(z)
V u = fade(x)
V v = fade(y)
V w = fade(z)
V A = :p[_x_] + Y
V AA = :p[A] + Z
V AB = :p[A + 1] + Z
V B = :p[_x_ + 1] + Y
V BA = :p[B] + Z
V BB = :p[B + 1] + Z
R linerp(w, linerp(v, linerp(u, grad(:p[AA], x, y, z),
grad(:p[BA], x - 1, y, z)),
linerp(u, grad(:p[AB], x, y - 1, z),
grad(:p[BB], x - 1, y - 1, z))),
linerp(v, linerp(u, grad(:p[AA + 1], x, y, z - 1),
grad(:p[BA + 1], x - 1, y, z - 1)),
linerp(u, grad(:p[AB + 1], x, y - 1, z - 1),
grad(:p[BB + 1], x - 1, y - 1, z - 1))))
print(‘#.17’.format(perlin_noise(3.14, 42, 7))) |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #APL | APL | (⊢(/⍨)((+/((1+.=⍳∨⊢)∘⊃,⊢)⍣(1=(⊃⊣)))=2∘×)¨)1↓⍳6000 |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #COBOL | COBOL | identification division.
program-id. playing-cards.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
77 card usage index.
01 deck.
05 cards occurs 52 times ascending key slot indexed by card.
10 slot pic 99.
10 hand pic 99.
10 suit pic 9.
10 symbol pic x(4).
10 rank pic 99.
01 filler.
05 suit-name pic x(8) occurs 4 times.
*> Unicode U+1F0Ax, Bx, Cx, Dx "f09f82a0" "82b0" "8380" "8390"
01 base-s constant as 4036985504.
01 base-h constant as 4036985520.
01 base-d constant as 4036985728.
01 base-c constant as 4036985744.
01 sym pic x(4) comp-x.
01 symx redefines sym pic x(4).
77 s pic 9.
77 r pic 99.
77 c pic 99.
77 hit pic 9.
77 limiter pic 9(6).
01 spades constant as 1.
01 hearts constant as 2.
01 diamonds constant as 3.
01 clubs constant as 4.
01 players constant as 3.
01 cards-per constant as 5.
01 deal pic 99.
01 player pic 99.
01 show-tally pic zz.
01 show-rank pic z(5).
01 arg pic 9(10).
procedure division.
cards-main.
perform seed
perform initialize-deck
perform shuffle-deck
perform deal-deck
perform display-hands
goback.
*> ********
seed.
accept arg from command-line
if arg not equal 0 then
move random(arg) to c
end-if
.
initialize-deck.
move "spades" to suit-name(spades)
move "hearts" to suit-name(hearts)
move "diamonds" to suit-name(diamonds)
move "clubs" to suit-name(clubs)
perform varying s from 1 by 1 until s > 4
after r from 1 by 1 until r > 13
compute c = (s - 1) * 13 + r
evaluate s
when spades compute sym = base-s + r
when hearts compute sym = base-h + r
when diamonds compute sym = base-d + r
when clubs compute sym = base-c + r
end-evaluate
if r > 11 then compute sym = sym + 1 end-if
move s to suit(c)
move r to rank(c)
move symx to symbol(c)
move zero to slot(c)
move zero to hand(c)
end-perform
.
shuffle-deck.
move zero to limiter
perform until exit
compute c = random() * 52.0 + 1.0
move zero to hit
perform varying tally from 1 by 1 until tally > 52
if slot(tally) equal c then
move 1 to hit
exit perform
end-if
if slot(tally) equal 0 then
if tally < 52 then move 1 to hit end-if
move c to slot(tally)
exit perform
end-if
end-perform
if hit equal zero then exit perform end-if
if limiter > 999999 then
display "too many shuffles, deck invalid" upon syserr
exit perform
end-if
add 1 to limiter
end-perform
sort cards ascending key slot
.
display-card.
>>IF ENGLISH IS DEFINED
move rank(tally) to show-rank
evaluate rank(tally)
when 1 display " ace" with no advancing
when 2 thru 10 display show-rank with no advancing
when 11 display " jack" with no advancing
when 12 display "queen" with no advancing
when 13 display " king" with no advancing
end-evaluate
display " of " suit-name(suit(tally)) with no advancing
>>ELSE
display symbol(tally) with no advancing
>>END-IF
.
display-deck.
perform varying tally from 1 by 1 until tally > 52
move tally to show-tally
display "Card: " show-tally
" currently in hand " hand(tally)
" is " with no advancing
perform display-card
display space
end-perform
.
display-hands.
perform varying player from 1 by 1 until player > players
move player to tally
display "Player " player ": " with no advancing
perform varying deal from 1 by 1 until deal > cards-per
perform display-card
add players to tally
end-perform
display space
end-perform
display "Stock: " with no advancing
subtract players from tally
add 1 to tally
perform varying tally from tally by 1 until tally > 52
perform display-card
>>IF ENGLISH IS DEFINED
display space
>>END-IF
end-perform
display space
.
deal-deck.
display "Dealing " cards-per " cards to " players " players"
move 1 to tally
perform varying deal from 1 by 1 until deal > cards-per
after player from 1 by 1 until player > players
move player to hand(tally)
add 1 to tally
end-perform
.
end program playing-cards.
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #C.23 | C# | using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
} |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra ° Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidi° Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
Example test cases;
1 -> 1 1
2 -> 1 18
29 -> 4 11
42 -> 5 6
57 -> 8 4
58 -> 8 5
72 -> 6 4
89 -> 9 4
Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
See also
the periodic table
This task was an idea from CompSciFact
The periodic table in ascii that was used as template
| #FreeBASIC | FreeBASIC | Sub MostarPos(N As Integer)
Dim As Integer M, I, R, C
Dim As Integer A(0 To 7) = { 1, 2, 5, 13, 57, 72, 89, 104} 'magic numbers
Dim As Integer B(0 To 7) = {-1, 15, 25, 35, 72, 21, 58, 7}
I = 7
While A(I) > N
I -= 1
Wend
M = N + B(I)
R = (M \ 18) +1
C = (M Mod 18) +1
Print Using "Atomic number ### -> #_, ##"; N; R; C
End Sub
Dim As Integer Element(0 To 12) = {1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113}
For I As Integer = 0 To Ubound(Element)
MostarPos(Element(I))
Next I |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Haskell | Haskell |
import System.Random (randomRIO)
data Score = Score { stack :: Int, score :: Int }
main :: IO ()
main = loop (Score 0 0) (Score 0 0)
loop :: Score -> Score -> IO ()
loop p1 p2 = do
putStrLn $ "\nPlayer 1 ~ " ++ show (score p1)
p1' <- askPlayer p1
if (score p1') >= 100
then putStrLn "P1 won!"
else do
putStrLn $ "\nPlayer 2 ~ " ++ show (score p2)
p2' <- askPlayer p2
if (score p2') >= 100
then putStrLn "P2 won!"
else loop p1' p2'
askPlayer :: Score -> IO Score
askPlayer (Score stack score) = do
putStr "\n(h)old or (r)oll? "
answer <- getChar
roll <- randomRIO (1,6)
case (answer, roll) of
('h', _) -> do
putStrLn $ " => Score = " ++ show (stack + score)
return $ Score 0 (stack + score)
('r', 1) -> do
putStrLn $ " => 1 => Sorry - stack was resetted"
return $ Score 0 score
('r', _) -> do
putStr $ " => " ++ show roll ++ " => current stack = " ++ show (stack + roll)
askPlayer $ Score (stack + roll) score
_ -> do
putStrLn "\nInvalid input - please try again."
askPlayer $ Score stack score
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Clojure | Clojure | (defn counting-numbers
([] (counting-numbers 1))
([n] (lazy-seq (cons n (counting-numbers (inc n))))))
(defn divisors [n] (filter #(zero? (mod n %)) (range 1 (inc n))))
(defn prime? [n] (= (divisors n) (list 1 n)))
(defn pernicious? [n]
(prime? (count (filter #(= % \1) (Integer/toString n 2)))))
(println (take 25 (filter pernicious? (counting-numbers))))
(println (filter pernicious? (range 888888877 888888889))) |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\displaystyle 0..(n-1)}
.
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of
n
{\displaystyle n}
items without duplicates when the total number of permutations is large. Remember that the total number of permutations of
n
{\displaystyle n}
items is given by
n
!
{\displaystyle n!}
which grows large very quickly: A 32 bit integer can only hold
12
!
{\displaystyle 12!}
, a 64 bit integer only
20
!
{\displaystyle 20!}
. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
Task
Create a function to generate a permutation from a rank.
Create the inverse function that given the permutation generates its rank.
Show that for
n
=
3
{\displaystyle n=3}
the two functions are indeed inverses of each other.
Compute and show here 4 random, individual, samples of permutations of 12 objects.
Stretch goal
State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
References
Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
Ranks on the DevData site.
Another answer on Stack Overflow to a different question that explains its algorithm in detail.
Related tasks
Factorial_base_numbers_indexing_permutations_of_a_collection
| #Python | Python | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1) |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be called "Pierpont primes of the first kind" on this page to distinguish them.
Task
Write a routine (function, procedure, whatever) to find Pierpont primes of the first & second kinds.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the first kind.
Use the routine to find and display here, on this page, the first 50 Pierpont primes of the second kind
If your language supports large integers, find and display here, on this page, the 250th Pierpont prime of the first kind and the 250th Pierpont prime of the second kind.
See also
Wikipedia - Pierpont primes
OEIS:A005109 - Class 1 -, or Pierpont primes
OEIS:A005105 - Class 1 +, or Pierpont primes of the second kind
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[FindUpToMax]
FindUpToMax[max_Integer, b_Integer] := Module[{res, num},
res = {};
Do[
num = 2^u 3^v + b;
If[PrimeQ[num], AppendTo[res, num]]
,
{u, 0, Ceiling@Log[2, max]}
,
{v, 0, Ceiling@Log[3, max]}
];
res //= Select[LessEqualThan[max]];
res //= Sort;
res
]
Print["Piermont primes of the first kind:"]
Take[FindUpToMax[10^10, +1], UpTo[50]]
Print["Piermont primes of the second kind:"]
Take[FindUpToMax[10^10, -1], UpTo[50]]
Print["250th Piermont prime of the first kind:"]
Part[FindUpToMax[10^34, +1], 250]
Print["250th Piermont prime of the second kind:"]
Part[FindUpToMax[10^34, -1], 250]
Print["1000th Piermont prime of the first kind:"]
Part[FindUpToMax[10^130, +1], 1000]
Print["1000th Piermont prime of the second kind:"]
Part[FindUpToMax[10^150, -1], 1000] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Emacs_Lisp | Emacs Lisp | (defun random-choice (items)
(nth (random (length items)) items))
(random-choice '("a" "b" "c"))
;; => "a" |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Erlang | Erlang | % Implemented by Arjun Sunel
-module(pick_random).
-export([main/0]).
main() ->
List =[1,2,3,4,5],
Index = rand:uniform(length(List)),
lists:nth(Index,List).
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #uBasic.2F4tH | uBasic/4tH | 10 LET n=0: LET p=0
20 INPUT "Enter number: ";n
30 LET p=0 : IF n>1 THEN GOSUB 1000
40 IF p=0 THEN PRINT n;" is not prime!"
50 IF p#0 THEN PRINT n;" is prime!"
60 GOTO 10
1000 REM ***************
1001 REM * PRIME CHECK *
1002 REM ***************
1010 LET p=0
1020 IF (n%2)=0 THEN RETURN
1030 LET p=1 : PUSH n,0 : GOSUB 9030
1040 FOR i=3 TO POP() STEP 2
1050 IF (n%i)=0 THEN LET p=0: PUSH n,0 : GOSUB 9030 : LET i=POP()
1060 NEXT i
1070 RETURN
9030 Push ((10^(Pop()*2))*Pop()) : @(255)=Tos()
9040 Push (@(255) + (Tos()/@(255)))/2
If Abs(@(255)-Tos())<2 Then @(255)=Pop() : If Pop() Then Push @(255) : Return
@(255) = Pop() : Goto 9040
REM ** This is an integer SQR subroutine. Output is scaled by 10^(TOS()). |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Elena | Elena | import extensions;
import extensions'text;
import system'routines;
public program()
{
var reverse := (s => s.toArray().sequenceReverse().summarize(new StringWriter()));
var phrase := "rosetta code phrase reversal";
console.printLine(phrase);
//Reverse the string
console.printLine(reverse(phrase));
//Reverse each individual word in the string, maintaining original string order.
console.printLine(phrase.splitBy:" ".selectBy:(s => reverse(s).add(" ")).summarize(new StringWriter()));
//Reverse the order of each word of the phrase, maintaining the order of characters in each word.
console.printLine(reverse(phrase.splitBy:" ".selectBy:(s => s + " ")))
} |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Elixir | Elixir | str = "rosetta code phrase reversal"
IO.puts String.reverse(str)
IO.puts String.split(str) |> Enum.map(&String.reverse(&1)) |> Enum.join(" ")
IO.puts String.split(str) |> Enum.reverse |> Enum.join(" ") |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C | C | #include <stdio.h>
typedef unsigned long long LONG;
LONG deranged(int depth, int len, int *d, int show)
{
int i;
char tmp;
LONG count = 0;
if (depth == len) {
if (show) {
for (i = 0; i < len; i++) putchar(d[i] + 'a');
putchar('\n');
}
return 1;
}
for (i = len - 1; i >= depth; i--) {
if (i == d[depth]) continue;
tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
count += deranged(depth + 1, len, d, show);
tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
}
return count;
}
LONG gen_n(int n, int show)
{
LONG i;
int a[1024]; /* 1024 ought to be big enough for anybody */
for (i = 0; i < n; i++) a[i] = i;
return deranged(0, n, a, show);
}
LONG sub_fact(int n)
{
return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1);
}
int main()
{
int i;
printf("Deranged Four:\n");
gen_n(4, 1);
printf("\nCompare list vs calc:\n");
for (i = 0; i < 10; i++)
printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i));
printf("\nfurther calc:\n");
for (i = 10; i <= 20; i++)
printf("%d: %llu\n", i, sub_fact(i));
return 0;
} |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.